Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-quality): add jev question execution foundation (#113446)

Jovan Sakovic5cb6dfe61cb4
diff --git a/docs/internal/data-quality-checks.md b/docs/internal/data-quality-checks.md
index 9421607a0f50..c18dc4557a0d 100644
--- a/docs/internal/data-quality-checks.md
+++ b/docs/internal/data-quality-checks.md
@@ -32,6 +32,52 @@ The family scope `warehouse_objects` reaches every warehouse kind. A per-kind sc
The table above applies to the REST routes only. The MCP tools declare `query:read` alone, because a tool's scope list must be met in full and the two subject families are authorized independently; a token with no subject family is refused by the route. A raw HogQL query against `system.information_schema.data_quality_*` needs `query:read` and no other scope. The user's own permissions still apply to each row. A token with `query:read` reads metric checks only if its user has catalog access.
+## Question execution foundation
+
+The question execution primitives in `products/data_quality/backend/logic/jev_*.py` are not yet registered as an authorable check type.
+They provide the warehouse-table execution foundation before the check registry, Temporal orchestration, durable run checkpoints, previews, and editor are wired.
+`WarehouseQuestionExecutor` connects source preparation, manifests, Redis, and the gateway.
+Its caller supplies atomic persistence callbacks for manifest selection and checkpoints, plus a durable reservation for inference inputs.
+Query and inference tags carry check and run identifiers without source values.
+
+`QuestionConfig` accepts a column input or explicitly selected row fields, a yes/no assertion, an inclusive minimum probability (default 0.8), and an inclusive allowed failure rate (default 0).
+Row fields are sorted by label and serialized with their types and explicit null values.
+NaN and infinities serialize as quoted strings, so they stay distinct from null.
+Column nulls contribute deterministic row failures without inference.
+Nulls do not contribute to the decision counters.
+Warehouse fields must appear in the subject's column catalog, and the projection is compiled as the executing user after checking subject access.
+
+The source query groups exact evaluator inputs and preserves their row multiplicities without a row limit.
+It streams bounded chunks into the configured object store and publishes a manifest only after the source stream completes.
+ClickHouse overflow settings throw instead of returning partial results.
+A response that ends before the Arrow end-of-stream marker, or has data after it, fails before any manifest is published.
+A subject that exceeds the limit on frozen inputs fails before any manifest is published.
+A manifest freezes the definition, the explicitly supplied model revision, and the evaluator contract version.
+A deployment with a different evaluator version rejects the manifest and its checkpoints.
+A retry must reuse that manifest; a new run must prepare a new one.
+Empty manifests skip.
+
+Redis keys are project-scoped hashes of the exact input, question schema, model id, immutable model or deployment revision, and evaluator contract version.
+Thresholds are excluded.
+Only validated probabilities and their revision, evaluator version, and timestamp enter the cache.
+The default TTL is 30 days and reads do not renew it.
+Malformed or expired entries miss; Redis errors stop evaluation.
+Leases use ownership tokens, bounded renewal that outlasts the inference wait, and atomic publication and release.
+A crash between the model response and cache publication can still cause duplicate billed inference.
+So can a failed gateway batch: the runner waits for every batch in a chunk, so one failure discards the decisions the other batches already returned and the retry pays for them again.
+
+The chunk evaluator reuses `PromptJevRunner` and the billed gateway.
+Chunk limits, an inference input budget, and execution deadlines raise errors with incomplete coverage; they never produce a successful result from fewer rows.
+Checkpoint callbacks must atomically retain the first result under `(run, chunk)`.
+Finalization counts each checkpoint once and verifies total row and input coverage before evaluating the failure rate.
+
+Before enabling this path in the checks system, persist manifest references and chunk checkpoints through the checks models, reserve the inference budget durably across activity retries, and add object-store lifecycle cleanup for expired or abandoned prefixes.
+The caller must resolve an immutable model revision, or configure a deployment revision that changes with the served model.
+Authorization must run before replaying any checkpoint or reading decisions.
+The run deadline is checked before every chunk and before the final result, so a replayed checkpoint or a fully cached chunk cannot outlast it.
+An inference reservation is spent only after the gateway accepts the run, so a disabled flag, an exhausted credit budget, or a missing gateway leaves the allowance untouched.
+Staged views, PostHog tables, warning-only authoring, and results UI require the subsequent integration.
+
## Lookback window
A check may carry `lookback_hours`, which counts only the rows from the last N hours by the subject's own time column.
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 9492c5acae3a..be155f1c23f7 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -542,6 +542,7 @@ class QueryTags(BaseModel):
# data quality
data_quality_check_id: Optional[str] = None
+ data_quality_run_id: Optional[str] = None
data_quality_check_type: Optional[str] = None # not_null, unique, freshness, custom_sql, ...
data_quality_subject_type: Optional[str] = None # table or view
data_quality_subject_id: Optional[str] = None
diff --git a/products/data_quality/backend/logic/jev_cache.py b/products/data_quality/backend/logic/jev_cache.py
new file mode 100644
index 000000000000..86ab00842294
--- /dev/null
+++ b/products/data_quality/backend/logic/jev_cache.py
@@ -0,0 +1,257 @@
+import json
+import math
+from collections.abc import Iterator, Sequence
+from contextlib import contextmanager
+from dataclasses import field
+from datetime import UTC, datetime
+from hashlib import sha256
+from threading import Event, Thread
+from typing import TYPE_CHECKING
+from uuid import uuid4
+
+from pydantic import BaseModel, ConfigDict, Field, ValidationError
+from redis.exceptions import RedisError
+
+from posthog.dataclasses import frozen
+
+if TYPE_CHECKING:
+ from redis import Redis
+
+# Bump when PromptJevRunner's prompt/batching contract or question input serialization changes.
+EVALUATOR_VERSION = 1
+DEFAULT_TTL_SECONDS = 30 * 24 * 60 * 60
+MAX_CACHE_BATCH = 256
+DEFAULT_LEASE_SECONDS = 60
+# Renewal runs every half lease, so the default covers 60 + 6 * 30 = 240 seconds. Coverage must outlast
+# the chunk evaluator's inference wait, or a slow batch loses its lease and the retry pays for it again.
+DEFAULT_MAX_RENEWALS = 6
+
+
+class DecisionCacheUnavailable(RuntimeError):
+ pass
+
+
+@frozen
+class DecisionRequest:
+ input: str = field(repr=False)
+ question_schema: str = field(repr=False)
+ model_id: str
+ model_revision: str
+ evaluator_version: int = EVALUATOR_VERSION
+
+ def key(self, team_id: int) -> str:
+ if team_id <= 0 or not self.model_id.strip() or not self.model_revision.strip() or self.evaluator_version < 1:
+ raise ValueError("A decision needs a project, immutable model revision, and evaluator version.")
+ canonical = json.dumps(
+ {
+ "input": self.input,
+ "question_schema": json.loads(self.question_schema),
+ "model_id": self.model_id,
+ "model_revision": self.model_revision,
+ "evaluator_version": self.evaluator_version,
+ },
+ sort_keys=True,
+ ensure_ascii=False,
+ separators=(",", ":"),
+ allow_nan=False,
+ )
+ return f"dq:jev:v1:{team_id}:{sha256(canonical.encode()).hexdigest()}"
+
+
+class CachedDecision(BaseModel):
+ model_config = ConfigDict(extra="forbid", strict=True)
+
+ probability: float = Field(ge=0, le=1, allow_inf_nan=False)
+ model_revision: str = Field(min_length=1)
+ evaluator_version: int = Field(ge=1)
+ evaluated_at: datetime
+
+
+@frozen
+class DecisionLease:
+ key: str
+ token: str
+ renewals: int = 0
+
+
+_RELEASE = """
+if redis.call('GET', KEYS[1]) == ARGV[1] then
+ return redis.call('DEL', KEYS[1])
+end
+return 0
+"""
+
+_RENEW = """
+if redis.call('GET', KEYS[1]) == ARGV[1] then
+ return redis.call('EXPIRE', KEYS[1], ARGV[2])
+end
+return 0
+"""
+
+_PUBLISH = """
+if redis.call('GET', KEYS[1]) ~= ARGV[1] then
+ return 0
+end
+redis.call('SET', KEYS[2], ARGV[2], 'EX', ARGV[3])
+redis.call('DEL', KEYS[1])
+return 1
+"""
+
+
+class JevDecisionCache:
+ def __init__(
+ self,
+ client: "Redis",
+ *,
+ team_id: int,
+ ttl_seconds: int = DEFAULT_TTL_SECONDS,
+ lease_seconds: int = DEFAULT_LEASE_SECONDS,
+ max_renewals: int = DEFAULT_MAX_RENEWALS,
+ ) -> None:
+ if team_id <= 0 or ttl_seconds <= 0 or lease_seconds <= 0 or max_renewals < 0:
+ raise ValueError("Invalid decision cache configuration.")
+ self.client = client
+ self.team_id = team_id
+ self.ttl_seconds = ttl_seconds
+ self.lease_seconds = lease_seconds
+ self.max_renewals = max_renewals
+
+ def read(self, requests: Sequence[DecisionRequest]) -> dict[str, float]:
+ decisions: dict[str, float] = {}
+ try:
+ for start in range(0, len(requests), MAX_CACHE_BATCH):
+ batch = requests[start : start + MAX_CACHE_BATCH]
+ keys = [request.key(self.team_id) for request in batch]
+ values = self.client.mget(keys)
+ for request, key, value in zip(batch, keys, values, strict=True):
+ if value is None:
+ continue
+ try:
+ decision = CachedDecision.model_validate_json(value)
+ except (ValidationError, ValueError, TypeError):
+ continue
+ if (
+ decision.model_revision == request.model_revision
+ and decision.evaluator_version == request.evaluator_version
+ and decision.evaluated_at.tzinfo is not None
+ ):
+ decisions[key] = decision.probability
+ except RedisError as error:
+ raise DecisionCacheUnavailable("Redis decision cache is unavailable.") from error
+ return decisions
+
+ def acquire(self, requests: Sequence[DecisionRequest]) -> dict[str, DecisionLease]:
+ leases: dict[str, DecisionLease] = {}
+ try:
+ for start in range(0, len(requests), MAX_CACHE_BATCH):
+ batch = requests[start : start + MAX_CACHE_BATCH]
+ candidates = {
+ request.key(self.team_id): DecisionLease(key=request.key(self.team_id), token=uuid4().hex)
+ for request in batch
+ }
+ with self.client.pipeline(transaction=False) as pipeline:
+ for lease in candidates.values():
+ pipeline.set(lease.key + ":lease", lease.token, nx=True, ex=self.lease_seconds)
+ acquired = pipeline.execute()
+ for lease, owned in zip(candidates.values(), acquired, strict=True):
+ if owned:
+ leases[lease.key] = lease
+ except RedisError as error:
+ # Leases from an interrupted pipeline expire without requiring cleanup to succeed.
+ raise DecisionCacheUnavailable("Redis decision cache is unavailable.") from error
+ return leases
+
+ def renew(self, lease: DecisionLease) -> DecisionLease | None:
+ return self.renew_many([lease]).get(lease.key)
+
+ def renew_many(self, leases: Sequence[DecisionLease]) -> dict[str, DecisionLease]:
+ renewable = [lease for lease in leases if lease.renewals < self.max_renewals]
+ renewed: dict[str, DecisionLease] = {}
+ try:
+ for start in range(0, len(renewable), MAX_CACHE_BATCH):
+ batch = renewable[start : start + MAX_CACHE_BATCH]
+ with self.client.pipeline(transaction=False) as pipeline:
+ for lease in batch:
+ pipeline.eval(_RENEW, 1, lease.key + ":lease", lease.token, self.lease_seconds)
+ results = pipeline.execute()
+ renewed.update(
+ {
+ lease.key: DecisionLease(key=lease.key, token=lease.token, renewals=lease.renewals + 1)
+ for lease, owned in zip(batch, results, strict=True)
+ if owned
+ }
+ )
+ except RedisError as error:
+ raise DecisionCacheUnavailable("Redis decision cache is unavailable.") from error
+ return renewed
+
+ @contextmanager
+ def maintain(self, leases: Sequence[DecisionLease]) -> Iterator[None]:
+ stopped = Event()
+ errors: list[DecisionCacheUnavailable] = []
+
+ def renew_while_evaluating() -> None:
+ active = list(leases)
+ while active and not stopped.wait(self.lease_seconds / 2):
+ try:
+ active = list(self.renew_many(active).values())
+ except DecisionCacheUnavailable as error:
+ errors.append(error)
+ break
+
+ worker = Thread(target=renew_while_evaluating, name="dq-jev-lease", daemon=True)
+ worker.start()
+ try:
+ yield
+ finally:
+ stopped.set()
+ worker.join()
+ if errors:
+ raise errors[0]
+
+ def publish(self, decisions: Sequence[tuple[DecisionLease, DecisionRequest, float]]) -> set[str]:
+ published: set[str] = set()
+ # Validate the whole batch before writing any of it.
+ values: list[str] = []
+ for lease, request, probability in decisions:
+ if lease.key != request.key(self.team_id) or type(probability) not in (int, float):
+ raise ValueError("Invalid decision publication.")
+ if not math.isfinite(probability) or not 0 <= probability <= 1:
+ raise ValueError("Jev returned an invalid probability.")
+ values.append(
+ CachedDecision(
+ probability=float(probability),
+ model_revision=request.model_revision,
+ evaluator_version=request.evaluator_version,
+ evaluated_at=datetime.now(UTC),
+ ).model_dump_json()
+ )
+ try:
+ for start in range(0, len(decisions), MAX_CACHE_BATCH):
+ batch = decisions[start : start + MAX_CACHE_BATCH]
+ with self.client.pipeline(transaction=False) as pipeline:
+ for (lease, _, _), value in zip(batch, values[start : start + MAX_CACHE_BATCH], strict=True):
+ pipeline.eval(
+ _PUBLISH,
+ 2,
+ lease.key + ":lease",
+ lease.key,
+ lease.token,
+ value,
+ self.ttl_seconds,
+ )
+ results = pipeline.execute()
+ published.update(lease.key for (lease, _, _), owned in zip(batch, results, strict=True) if owned)
+ except RedisError as error:
+ raise DecisionCacheUnavailable("Redis decision cache is unavailable.") from error
+ return published
+
+ def release(self, leases: Sequence[DecisionLease]) -> None:
+ try:
+ for start in range(0, len(leases), MAX_CACHE_BATCH):
+ with self.client.pipeline(transaction=False) as pipeline:
+ for lease in leases[start : start + MAX_CACHE_BATCH]:
+ pipeline.eval(_RELEASE, 1, lease.key + ":lease", lease.token)
+ pipeline.execute()
+ except RedisError as error:
+ raise DecisionCacheUnavailable("Redis decision cache is unavailable.") from error
diff --git a/products/data_quality/backend/logic/jev_evaluator.py b/products/data_quality/backend/logic/jev_evaluator.py
new file mode 100644
index 000000000000..ceecfbb00a68
--- /dev/null
+++ b/products/data_quality/backend/logic/jev_evaluator.py
@@ -0,0 +1,53 @@
+from typing import TYPE_CHECKING, cast
+
+from posthog.hogql import ast
+from posthog.hogql.functions.prompt_jev import PromptJevCall
+from posthog.hogql.transforms.prompt_jev import PromptJevRunner, validate_prompt_jev_access
+
+from posthog.llm.system_one import NoulQuestion
+from posthog.llm.system_one_client import GatewaySystemOneClient, build_system_one_client
+
+if TYPE_CHECKING:
+ from posthog.models.team import Team
+
+
+class QuestionGatewayEvaluator:
+ def __init__(
+ self,
+ *,
+ team: "Team",
+ model_id: str,
+ question: str,
+ check_id: str,
+ run_id: str,
+ distinct_id: str | None,
+ ) -> None:
+ validate_prompt_jev_access(team)
+ self.team = team
+ self.distinct_id = distinct_id
+ self.spec = PromptJevCall(
+ input=ast.Constant(value=None),
+ question=NoulQuestion(instructions=question),
+ batch_size=16,
+ model="jeeves",
+ )
+ client = build_system_one_client(
+ model=model_id,
+ ai_product="hogql_decide",
+ team_id=team.pk,
+ distinct_id=distinct_id,
+ trace_id=run_id,
+ properties={"data_quality_check_id": check_id, "data_quality_run_id": run_id},
+ )
+ if not isinstance(client, GatewaySystemOneClient):
+ raise ValueError("Question checks require the billed AI gateway.")
+ self.client = client
+
+ def __call__(self, inputs: list[str]) -> list[float]:
+ # Each manifest chunk gets Jev's existing byte, concurrency, row-isolation and time budgets.
+ runner = PromptJevRunner(team_id=self.team.pk, distinct_id=self.distinct_id)
+ runner.clients[self.spec.model] = self.client
+ decisions = runner.evaluate(self.spec, list(inputs))
+ if any(type(decision) not in (int, float) for decision in decisions):
+ raise ValueError("Jev returned an invalid probability.")
+ return [float(cast(float, decision)) for decision in decisions]
diff --git a/products/data_quality/backend/logic/jev_manifest.py b/products/data_quality/backend/logic/jev_manifest.py
new file mode 100644
index 000000000000..0085d021884a
--- /dev/null
+++ b/products/data_quality/backend/logic/jev_manifest.py
@@ -0,0 +1,358 @@
+import asyncio
+from collections.abc import AsyncIterator, Callable, Sequence
+from datetime import UTC, datetime, timedelta
+from typing import TYPE_CHECKING
+from uuid import uuid4
+
+import pyarrow as pa
+from pydantic import BaseModel, ConfigDict, Field
+
+from posthog.schema import HogQLQueryModifiers
+
+from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.modifiers import create_default_modifiers_for_team
+from posthog.hogql.printer import prepare_and_print_ast
+
+from posthog.storage import object_storage
+from posthog.sync import database_sync_to_async_pool
+from posthog.temporal.common.asyncpa import AsyncRecordBatchReader
+from posthog.temporal.common.clickhouse import ChunkBytesAsyncStreamIterator, get_client
+
+from ..facade.enums import CheckRunStatus, SubjectType
+from .contracts import SubjectRef
+from .jev_cache import EVALUATOR_VERSION
+from .jev_question import (
+ QuestionChunkEvaluator,
+ QuestionChunkResult,
+ QuestionConfig,
+ WeightedInput,
+ question_input_query,
+)
+from .permissions import sql_denial_context
+from .subjects import subject_column_type
+
+if TYPE_CHECKING:
+ from posthog.models.team import Team
+ from posthog.models.user import User
+
+CHUNK_INPUTS = 128
+MAX_INPUT_BYTES = 8192
+# Freezing writes to the shared object store before any inference budget applies, so a subject with
+# more distinct inputs than a run can evaluate must fail closed rather than stream without a bound.
+MAX_FROZEN_INPUTS = 100_000
+# Arrow IPC end-of-stream marker: continuation bytes followed by a zero metadata length.
+ARROW_END_OF_STREAM_BYTES = 8
+
+
+class ManifestInput(BaseModel):
+ model_config = ConfigDict(extra="forbid", strict=True)
+ text: str | None
+ row_count: int = Field(ge=1)
+
+
+class ManifestChunk(BaseModel):
+ model_config = ConfigDict(extra="forbid", strict=True)
+ inputs: list[ManifestInput] = Field(max_length=CHUNK_INPUTS)
+
+
+class QuestionManifest(BaseModel):
+ model_config = ConfigDict(extra="forbid", strict=True)
+ prefix: str
+ team_id: int = Field(gt=0)
+ run_id: str
+ subject_uuid: str
+ model_id: str
+ model_revision: str
+ evaluator_version: int = Field(ge=1)
+ question_config: QuestionConfig
+ column_name: str
+ chunk_count: int = Field(ge=0)
+ examined_row_count: int = Field(ge=0)
+ unique_input_count: int = Field(ge=0)
+ created_at: datetime
+ expires_at: datetime
+
+
+class QuestionResult(BaseModel):
+ model_config = ConfigDict(extra="forbid", strict=True)
+ status: CheckRunStatus
+ examined_row_count: int = Field(ge=0)
+ failed_row_count: int = Field(ge=0)
+ failure_rate: float | None
+ unique_input_count: int = Field(ge=0)
+ reused_decision_count: int = Field(ge=0)
+ new_decision_count: int = Field(ge=0)
+ completed_chunk_count: int = Field(ge=0)
+ total_chunk_count: int = Field(ge=0)
+ coverage_complete: bool
+
+
+class QuestionManifestStore:
+ def write_chunk(self, prefix: str, index: int, inputs: Sequence[WeightedInput]) -> None:
+ chunk = ManifestChunk(inputs=[ManifestInput(text=item.text, row_count=item.row_count) for item in inputs])
+ object_storage.write(f"{prefix}/chunks/{index}.json", chunk.model_dump_json())
+
+ def read_chunk(self, manifest: QuestionManifest, index: int) -> list[WeightedInput]:
+ if not 0 <= index < manifest.chunk_count:
+ raise ValueError("Question manifest chunk is outside the frozen input set.")
+ content = object_storage.read(f"{manifest.prefix}/chunks/{index}.json")
+ if content is None:
+ raise ValueError("Question manifest is incomplete.")
+ chunk = ManifestChunk.model_validate_json(content)
+ return [WeightedInput(text=item.text, row_count=item.row_count) for item in chunk.inputs]
+
+ def write_manifest(self, manifest: QuestionManifest) -> str:
+ key = f"{manifest.prefix}/manifest.json"
+ object_storage.write(key, manifest.model_dump_json())
+ return key
+
+ def read_manifest(self, key: str, *, team_id: int, run_id: str) -> QuestionManifest:
+ content = object_storage.read(key)
+ if content is None:
+ raise ValueError("Question manifest is unavailable.")
+ manifest = QuestionManifest.model_validate_json(content)
+ if manifest.team_id != team_id or manifest.run_id != run_id or manifest.expires_at <= datetime.now(UTC):
+ raise ValueError("Question manifest does not belong to this run or has expired.")
+ return manifest
+
+ def delete(self, manifest: QuestionManifest) -> None:
+ for start in range(0, manifest.chunk_count, 128):
+ object_storage.delete_objects(
+ [
+ f"{manifest.prefix}/chunks/{index}.json"
+ for index in range(start, min(start + 128, manifest.chunk_count))
+ ]
+ )
+ object_storage.delete(f"{manifest.prefix}/manifest.json")
+
+
+async def freeze_question_inputs(
+ *,
+ inputs: AsyncIterator[WeightedInput],
+ store: QuestionManifestStore,
+ team_id: int,
+ run_id: str,
+ subject_uuid: str,
+ model_id: str,
+ model_revision: str,
+ config: QuestionConfig,
+ column_name: str,
+ retention_hours: int = 24,
+ max_inputs: int = MAX_FROZEN_INPUTS,
+) -> QuestionManifest:
+ if not model_id.strip() or not model_revision.strip() or retention_hours < 1 or max_inputs < 1:
+ raise ValueError("A snapshot needs a pinned model revision and a positive lifetime.")
+ config.input_columns(column_name)
+ # Attempts use separate prefixes. Only a complete manifest may be published as the run's snapshot.
+ prefix = f"data_quality/jev/{team_id}/{uuid4().hex}"
+ chunk: list[WeightedInput] = []
+ chunks = rows = unique = 0
+ try:
+ async for item in inputs:
+ if item.text is not None and len(item.text.encode()) > MAX_INPUT_BYTES:
+ raise ValueError("A question input exceeds 8 KiB; no input was truncated.")
+ if chunks * CHUNK_INPUTS + len(chunk) >= max_inputs:
+ raise ValueError("The question subject exceeds the limit on frozen inputs.")
+ chunk.append(item)
+ rows += item.row_count
+ unique += item.text is not None
+ if len(chunk) == CHUNK_INPUTS:
+ await asyncio.to_thread(store.write_chunk, prefix, chunks, chunk)
+ chunk = []
+ chunks += 1
+ if chunk:
+ await asyncio.to_thread(store.write_chunk, prefix, chunks, chunk)
+ chunks += 1
+ created_at = datetime.now(UTC)
+ manifest = QuestionManifest(
+ prefix=prefix,
+ team_id=team_id,
+ run_id=run_id,
+ subject_uuid=subject_uuid,
+ model_id=model_id,
+ model_revision=model_revision,
+ evaluator_version=EVALUATOR_VERSION,
+ question_config=config.model_copy(deep=True),
+ column_name=column_name,
+ chunk_count=chunks,
+ examined_row_count=rows,
+ unique_input_count=unique,
+ created_at=created_at,
+ expires_at=created_at + timedelta(hours=retention_hours),
+ )
+ await asyncio.to_thread(store.write_manifest, manifest)
+ return manifest
+ except BaseException:
+ # A failed scan must never publish a partial manifest. Cleanup is best effort; expired
+ # attempt prefixes also need the object store's lifecycle policy before production rollout.
+ for index in range(chunks + 1):
+ try:
+ await asyncio.to_thread(object_storage.delete, f"{prefix}/chunks/{index}.json")
+ except Exception:
+ pass
+ raise
+
+
+def authorize_warehouse_question_subject(
+ team: "Team", user: "User", subject: SubjectRef, config: QuestionConfig, column_name: str
+) -> tuple[Database, HogQLQueryModifiers]:
+ """Every chunk repeats this, so a grant revoked mid-run stops the rest of the evaluation."""
+ if not subject.exists or subject.subject_type != SubjectType.TABLE:
+ raise ValueError("The initial question executor supports resolved warehouse tables only.")
+ if config.lookback_hours is not None:
+ raise ValueError("Warehouse tables have no lookback time column.")
+ for name in config.input_columns(column_name):
+ if subject_column_type(team.id, subject.subject_type, subject.subject_uuid, name) is None:
+ raise ValueError("A selected question field is not available on the subject.")
+ modifiers = create_default_modifiers_for_team(team)
+ database = Database.create_for(team=team, user=user, modifiers=modifiers)
+ if not sql_denial_context(team.id, database).readable.contains(subject.subject_type, subject.subject_uuid):
+ raise ValueError("The executing user cannot read the question check's subject.")
+ return database, modifiers
+
+
+def prepare_warehouse_question_inputs(
+ team: "Team", user: "User", subject: SubjectRef, config: QuestionConfig, column_name: str
+) -> tuple[str, HogQLContext]:
+ database, modifiers = authorize_warehouse_question_subject(team, user, subject, config, column_name)
+ context = HogQLContext(
+ team=team,
+ team_id=team.id,
+ user=user,
+ database=database,
+ modifiers=modifiers,
+ enable_select_queries=True,
+ limit_top_select=False,
+ output_format="ArrowStream",
+ )
+ # Overflow must throw: even a cleanly terminated partial stream is incomplete coverage.
+ settings = HogQLGlobalSettings(max_execution_time=300, timeout_overflow_mode="throw", read_overflow_mode="throw")
+ query = question_input_query(subject, config, column_name)
+ sql, prepared = prepare_and_print_ast(query, context=context, dialect="clickhouse", settings=settings)
+ if prepared is None:
+ raise ValueError("The question input query could not be prepared.")
+ return sql, context
+
+
+class _ResponseBytes:
+ def __init__(self, chunks: AsyncIterator[bytes]) -> None:
+ self.chunks = chunks
+ self.received = 0
+ self.ended = False
+
+ def __aiter__(self) -> "_ResponseBytes":
+ return self
+
+ async def __anext__(self) -> bytes:
+ try:
+ chunk = await anext(self.chunks)
+ except StopAsyncIteration:
+ self.ended = True
+ raise
+ self.received += len(chunk)
+ return chunk
+
+
+async def strict_arrow_batches(chunks: AsyncIterator[bytes]) -> AsyncIterator[pa.RecordBatch]:
+ """Arrow batches from a response that must reach the end-of-stream marker and carry nothing after it."""
+ body = _ResponseBytes(chunks)
+ reader = AsyncRecordBatchReader(body)
+ async for batch in reader:
+ yield batch
+ # The shared reader also stops quietly when the response ends between or inside messages.
+ if body.ended:
+ raise ValueError("The question input stream ended before its end marker.")
+ async for _ in body:
+ pass
+ if body.received != reader.bytes_consumed + ARROW_END_OF_STREAM_BYTES:
+ raise ValueError("The question input stream has data after its end marker.")
+
+
+async def warehouse_question_inputs(
+ *, team: "Team", user: "User", subject: SubjectRef, config: QuestionConfig, column_name: str
+) -> AsyncIterator[WeightedInput]:
+ sql, context = await database_sync_to_async_pool(prepare_warehouse_question_inputs)(
+ team, user, subject, config, column_name
+ )
+ async with get_client(
+ team_id=team.id,
+ max_block_size=CHUNK_INPUTS,
+ result_overflow_mode="throw",
+ group_by_overflow_mode="throw",
+ max_result_rows=0,
+ max_result_bytes=0,
+ # toJSONString writes NaN and infinities as null by default, which merges them with SQL NULL in row inputs.
+ output_format_json_quote_denormals=1,
+ ) as client:
+ async with client.apost_query(
+ sql,
+ query_parameters=context.values,
+ query_id=None,
+ external_tables=list(context.external_tables.values()),
+ ) as response:
+ async for batch in strict_arrow_batches(ChunkBytesAsyncStreamIterator(response.content)):
+ for item in batch.to_pylist():
+ yield WeightedInput(text=item["input"], row_count=item["row_count"])
+
+
+def evaluate_question_manifest(
+ *,
+ manifest: QuestionManifest,
+ store: QuestionManifestStore,
+ evaluator: QuestionChunkEvaluator,
+ authorize: Callable[[], None],
+ load_checkpoint: Callable[[int], QuestionChunkResult | None],
+ save_checkpoint: Callable[[int, QuestionChunkResult], QuestionChunkResult],
+) -> QuestionResult:
+ """Checkpoint callbacks must persist the first result atomically under (run, chunk)."""
+ if (
+ manifest.team_id != evaluator.cache.team_id
+ or manifest.model_id != evaluator.model_id
+ or manifest.model_revision != evaluator.model_revision
+ or manifest.evaluator_version != EVALUATOR_VERSION
+ or manifest.question_config != evaluator.config
+ ):
+ raise ValueError("The frozen run and decision evaluator do not match.")
+ examined = failed = unique = reused = new = completed = 0
+ authorize()
+ evaluator.check_deadline()
+ if manifest.expires_at <= datetime.now(UTC):
+ raise ValueError("Question manifest expired with incomplete coverage.")
+ for index in range(manifest.chunk_count):
+ if manifest.expires_at <= datetime.now(UTC):
+ raise ValueError("Question manifest expired with incomplete coverage.")
+ authorize()
+ # Replaying a checkpoint skips the evaluator, so the run deadline is enforced here too.
+ evaluator.check_deadline()
+ result = load_checkpoint(index)
+ if result is None:
+ result = save_checkpoint(index, evaluator.run(store.read_chunk(manifest, index)))
+ examined += result.examined_row_count
+ failed += result.failed_row_count
+ unique += result.unique_input_count
+ reused += result.reused_decision_count
+ new += result.new_decision_count
+ completed += 1
+ evaluator.check_deadline()
+ if examined != manifest.examined_row_count or unique != manifest.unique_input_count:
+ raise ValueError("Question manifest coverage is incomplete.")
+ rate = failed / examined if examined else None
+ status = (
+ CheckRunStatus.SKIPPED
+ if rate is None
+ else (CheckRunStatus.PASSED if rate <= evaluator.config.max_failure_rate else CheckRunStatus.FAILED)
+ )
+ return QuestionResult(
+ status=status,
+ examined_row_count=examined,
+ failed_row_count=failed,
+ failure_rate=rate,
+ unique_input_count=unique,
+ reused_decision_count=reused,
+ new_decision_count=new,
+ completed_chunk_count=completed,
+ total_chunk_count=manifest.chunk_count,
+ coverage_complete=True,
+ )
diff --git a/products/data_quality/backend/logic/jev_question.py b/products/data_quality/backend/logic/jev_question.py
new file mode 100644
index 000000000000..3d06a44a4c61
--- /dev/null
+++ b/products/data_quality/backend/logic/jev_question.py
@@ -0,0 +1,256 @@
+import json
+import time
+from collections.abc import Callable, Sequence
+from dataclasses import field
+from typing import Literal, Self
+
+from pydantic import Field, field_validator, model_validator
+
+from posthog.hogql import ast
+
+from posthog.dataclasses import frozen
+from posthog.llm.system_one import NoulQuestion
+
+from .contracts import SubjectRef
+from .jev_cache import DecisionRequest, JevDecisionCache
+from .spec import CheckConfig
+from .types.common import column, subject_source
+
+
+class QuestionConfig(CheckConfig):
+ input_mode: Literal["column", "row"] = "column"
+ question: str = Field(
+ min_length=1, description="Yes/no question describing valid data. Yes is the expected answer."
+ )
+ columns: list[str] = Field(default_factory=list, description="Fields evaluated together in row mode.")
+ min_probability: float = Field(default=0.8, ge=0, le=1, allow_inf_nan=False)
+ max_failure_rate: float = Field(default=0, ge=0, le=1, allow_inf_nan=False)
+
+ @field_validator("question")
+ @classmethod
+ def nonempty_question(cls, value: str) -> str:
+ if not value.strip() or len(value.encode()) > 8192:
+ raise ValueError("The question must be non-empty and at most 8 KiB.")
+ return value
+
+ @model_validator(mode="after")
+ def selected_columns(self) -> Self:
+ if self.input_mode == "column" and self.columns:
+ raise ValueError("Column mode uses column_name, not columns.")
+ if self.input_mode == "row" and (
+ not self.columns
+ or any(not name.strip() for name in self.columns)
+ or len(set(self.columns)) != len(self.columns)
+ ):
+ raise ValueError("Row mode needs a non-empty list of distinct columns.")
+ self.columns = sorted(self.columns)
+ return self
+
+ def input_columns(self, column_name: str) -> list[str]:
+ if self.input_mode == "column":
+ if not column_name:
+ raise ValueError("Column mode needs column_name.")
+ return [column_name]
+ if column_name:
+ raise ValueError("Row mode takes no column_name.")
+ return self.columns
+
+ def question_schema(self) -> str:
+ return json.dumps(NoulQuestion(instructions=self.question).to_json(), sort_keys=True, separators=(",", ":"))
+
+
+def question_input_query(subject: SubjectRef, config: QuestionConfig, column_name: str) -> ast.SelectQuery:
+ """One exhaustive projection, grouped by the exact evaluator input with source multiplicities."""
+ names = config.input_columns(column_name)
+ if config.input_mode == "column":
+ input_expression: ast.Expr = ast.Call(name="toString", args=[column(names[0])])
+ else:
+ # Serializing each field first lets mixed column types share an Array(String), while the
+ # final JSON preserves native values and nulls rather than coercing every field to text.
+ fields: list[ast.Expr] = [
+ ast.Call(
+ name="toJSONString",
+ args=[
+ ast.Tuple(
+ exprs=[ast.Constant(value=name), ast.Call(name="toTypeName", args=[column(name)]), column(name)]
+ )
+ ],
+ )
+ for name in names
+ ]
+ input_expression = ast.Call(
+ name="concat",
+ args=[
+ ast.Constant(value="["),
+ ast.Call(name="arrayStringConcat", args=[ast.Array(exprs=fields), ast.Constant(value=",")]),
+ ast.Constant(value="]"),
+ ],
+ )
+ input_rows = ast.SelectQuery(
+ select=[ast.Alias(alias="input", expr=input_expression)],
+ select_from=subject_source(subject),
+ )
+ return ast.SelectQuery(
+ select=[ast.Field(chain=["input"]), ast.Alias(alias="row_count", expr=ast.Call(name="count", args=[]))],
+ select_from=ast.JoinExpr(table=input_rows),
+ group_by=[ast.Field(chain=["input"])],
+ )
+
+
+@frozen
+class WeightedInput:
+ text: str | None = field(repr=False)
+ row_count: int
+
+ def __post_init__(self) -> None:
+ if type(self.row_count) is not int or self.row_count < 1:
+ raise ValueError("An input must represent at least one row.")
+ if self.text is not None and not isinstance(self.text, str):
+ raise ValueError("A question input must be text or null.")
+
+
+@frozen
+class QuestionChunkResult:
+ examined_row_count: int
+ failed_row_count: int
+ unique_input_count: int
+ reused_decision_count: int
+ new_decision_count: int
+
+ def __post_init__(self) -> None:
+ counts = (
+ self.examined_row_count,
+ self.failed_row_count,
+ self.unique_input_count,
+ self.reused_decision_count,
+ self.new_decision_count,
+ )
+ if (
+ any(type(count) is not int or count < 0 for count in counts)
+ or self.failed_row_count > self.examined_row_count
+ or self.reused_decision_count + self.new_decision_count != self.unique_input_count
+ ):
+ raise ValueError("Question chunk counts are inconsistent.")
+
+
+class QuestionChunkEvaluator:
+ def __init__(
+ self,
+ *,
+ cache: JevDecisionCache,
+ config: QuestionConfig,
+ model_id: str,
+ model_revision: str,
+ evaluate: Callable[[list[str]], list[float]],
+ max_input_bytes: int = 8192,
+ max_chunk_inputs: int = 256,
+ wait_seconds: float = 180,
+ max_inference_inputs: int = 10_000,
+ max_run_seconds: float = 900,
+ clock: Callable[[], float] = time.monotonic,
+ wait: Callable[[float], None] = time.sleep,
+ ) -> None:
+ if (
+ not model_id.strip()
+ or not model_revision.strip()
+ or max_input_bytes < 1
+ or max_chunk_inputs < 1
+ or wait_seconds <= 0
+ or max_inference_inputs < 0
+ or max_run_seconds <= 0
+ ):
+ raise ValueError("Invalid question evaluator configuration.")
+ self.cache = cache
+ self.config = config.model_copy(deep=True)
+ self.model_id = model_id
+ self.model_revision = model_revision
+ self.evaluate = evaluate
+ self.max_input_bytes = max_input_bytes
+ self.max_chunk_inputs = max_chunk_inputs
+ self.wait_seconds = wait_seconds
+ self.clock = clock
+ self.wait = wait
+ self.max_inference_inputs = max_inference_inputs
+ self.inference_inputs = 0
+ self.run_deadline = clock() + max_run_seconds
+
+ def check_deadline(self) -> None:
+ """Every path that can advance coverage checks this, including ones that never call inference."""
+ if self.clock() >= self.run_deadline:
+ raise RuntimeError("Question evaluation timed out with incomplete coverage.")
+
+ def run(self, inputs: Sequence[WeightedInput]) -> QuestionChunkResult:
+ self.check_deadline()
+ if len(inputs) > self.max_chunk_inputs:
+ raise ValueError("Question manifest chunk exceeds its input limit.")
+ requests: dict[str, DecisionRequest] = {}
+ weights: dict[str, int] = {}
+ null_rows = 0
+ for item in inputs:
+ if item.text is None:
+ if self.config.input_mode != "column":
+ raise ValueError("Row inputs must retain labeled null fields.")
+ null_rows += item.row_count
+ continue
+ if len(item.text.encode()) > self.max_input_bytes:
+ raise ValueError("A question input exceeds 8 KiB; no input was truncated.")
+ request = DecisionRequest(
+ input=item.text,
+ question_schema=self.config.question_schema(),
+ model_id=self.model_id,
+ model_revision=self.model_revision,
+ )
+ key = request.key(self.cache.team_id)
+ requests[key] = request
+ weights[key] = weights.get(key, 0) + item.row_count
+ decisions = self.cache.read(list(requests.values()))
+ new: set[str] = set()
+ deadline = min(self.clock() + self.wait_seconds, self.run_deadline)
+ while missing := {key: request for key, request in requests.items() if key not in decisions}:
+ if self.clock() >= deadline:
+ raise RuntimeError("Question evaluation timed out with incomplete coverage.")
+ leases = self.cache.acquire(list(missing.values()))
+ try:
+ # A winner can publish between our first read and SET NX. Recheck before spending credits.
+ decisions.update(self.cache.read(list(missing.values())))
+ owned = [key for key in leases if key not in decisions]
+ if owned:
+ if self.inference_inputs + len(owned) > self.max_inference_inputs:
+ raise RuntimeError(
+ "Question evaluation exhausted its inference budget with incomplete coverage."
+ )
+ self.inference_inputs += len(owned)
+ with self.cache.maintain([leases[key] for key in owned]):
+ probabilities = self.evaluate([requests[key].input for key in owned])
+ if len(probabilities) != len(owned):
+ raise ValueError("Jev returned an incomplete decision batch.")
+ if self.clock() >= deadline:
+ raise RuntimeError("Question evaluation timed out with incomplete coverage.")
+ published = self.cache.publish(
+ [
+ (leases[key], requests[key], probability)
+ for key, probability in zip(owned, probabilities, strict=True)
+ ]
+ )
+ new.update(published)
+ decisions.update(
+ {
+ key: probability
+ for key, probability in zip(owned, probabilities, strict=True)
+ if key in published
+ }
+ )
+ decisions.update(self.cache.read(list(missing.values())))
+ finally:
+ self.cache.release(list(leases.values()))
+ if len(decisions) != len(requests):
+ self.wait(min(0.25, max(0, deadline - self.clock())))
+ self.check_deadline()
+ return QuestionChunkResult(
+ examined_row_count=null_rows + sum(weights.values()),
+ failed_row_count=null_rows
+ + sum(count for key, count in weights.items() if decisions[key] < self.config.min_probability),
+ unique_input_count=len(requests),
+ reused_decision_count=len(requests) - len(new),
+ new_decision_count=len(new),
+ )
diff --git a/products/data_quality/backend/logic/jev_warehouse.py b/products/data_quality/backend/logic/jev_warehouse.py
new file mode 100644
index 000000000000..85e27e0bdf1a
--- /dev/null
+++ b/products/data_quality/backend/logic/jev_warehouse.py
@@ -0,0 +1,145 @@
+from collections.abc import Callable
+from typing import TYPE_CHECKING
+
+from asgiref.sync import async_to_sync
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.redis import get_client
+
+from .contracts import SubjectRef
+from .jev_cache import JevDecisionCache
+from .jev_evaluator import QuestionGatewayEvaluator
+from .jev_manifest import (
+ QuestionManifest,
+ QuestionManifestStore,
+ QuestionResult,
+ authorize_warehouse_question_subject,
+ evaluate_question_manifest,
+ freeze_question_inputs,
+ warehouse_question_inputs,
+)
+from .jev_question import QuestionChunkEvaluator, QuestionChunkResult, QuestionConfig
+
+if TYPE_CHECKING:
+ from posthog.models.team import Team
+ from posthog.models.user import User
+
+
+class WarehouseQuestionExecutor:
+ def __init__(
+ self,
+ *,
+ team: "Team",
+ user: "User",
+ subject: SubjectRef,
+ config: QuestionConfig,
+ column_name: str,
+ model_id: str,
+ model_revision: str,
+ check_id: str,
+ run_id: str,
+ reserve_inference_inputs: Callable[[int], None],
+ ) -> None:
+ if not model_id.strip() or not model_revision.strip():
+ raise ValueError("Question checks require an immutable model or deployment revision.")
+ config.input_columns(column_name)
+ self.team = team
+ self.user = user
+ self.subject = subject
+ self.config = config.model_copy(deep=True)
+ self.column_name = column_name
+ self.model_id = model_id
+ self.model_revision = model_revision
+ self.check_id = check_id
+ self.run_id = run_id
+ self.reserve_inference_inputs = reserve_inference_inputs
+ self.store = QuestionManifestStore()
+ self.gateway: QuestionGatewayEvaluator | None = None
+
+ def _authorize(self) -> None:
+ authorize_warehouse_question_subject(self.team, self.user, self.subject, self.config, self.column_name)
+
+ def _evaluate(self, inputs: list[str]) -> list[float]:
+ # The reservation has no release callback, so it is spent only once inference can actually run.
+ if self.gateway is None:
+ self.gateway = QuestionGatewayEvaluator(
+ team=self.team,
+ model_id=self.model_id,
+ question=self.config.question,
+ check_id=self.check_id,
+ run_id=self.run_id,
+ distinct_id=self.user.distinct_id,
+ )
+ self.reserve_inference_inputs(len(inputs))
+ return self.gateway(inputs)
+
+ def _manifest(self, key: str | None, save_manifest: Callable[[str], str]) -> QuestionManifest:
+ self._authorize()
+ if key is not None:
+ manifest = self.store.read_manifest(key, team_id=self.team.id, run_id=self.run_id)
+ else:
+ manifest = async_to_sync(freeze_question_inputs)(
+ inputs=warehouse_question_inputs(
+ team=self.team,
+ user=self.user,
+ subject=self.subject,
+ config=self.config,
+ column_name=self.column_name,
+ ),
+ store=self.store,
+ team_id=self.team.id,
+ run_id=self.run_id,
+ subject_uuid=self.subject.subject_uuid,
+ model_id=self.model_id,
+ model_revision=self.model_revision,
+ config=self.config,
+ column_name=self.column_name,
+ )
+ proposed_key = f"{manifest.prefix}/manifest.json"
+ winning_key = save_manifest(proposed_key)
+ if winning_key != proposed_key:
+ self.store.delete(manifest)
+ manifest = self.store.read_manifest(winning_key, team_id=self.team.id, run_id=self.run_id)
+ if manifest.subject_uuid != self.subject.subject_uuid or manifest.column_name != self.column_name:
+ raise ValueError("The question manifest does not match its subject or input selection.")
+ return manifest
+
+ def run(
+ self,
+ *,
+ manifest_key: str | None,
+ save_manifest: Callable[[str], str],
+ load_checkpoint: Callable[[int], QuestionChunkResult | None],
+ save_checkpoint: Callable[[int, QuestionChunkResult], QuestionChunkResult],
+ ) -> QuestionResult:
+ """Callbacks must atomically persist the first manifest and checkpoints for this run."""
+ try:
+ with tags_context(
+ product=Product.DATA_QUALITY,
+ feature=Feature.DATA_QUALITY_CHECK,
+ data_quality_check_id=self.check_id,
+ data_quality_run_id=self.run_id,
+ data_quality_check_type="question",
+ data_quality_subject_type=self.subject.subject_type,
+ data_quality_subject_id=self.subject.subject_uuid,
+ ):
+ manifest = self._manifest(manifest_key, save_manifest)
+ cache = JevDecisionCache(get_client(socket_timeout=5, socket_connect_timeout=5), team_id=self.team.id)
+ evaluator = QuestionChunkEvaluator(
+ cache=cache,
+ config=self.config,
+ model_id=self.model_id,
+ model_revision=self.model_revision,
+ evaluate=self._evaluate,
+ )
+ return evaluate_question_manifest(
+ manifest=manifest,
+ store=self.store,
+ evaluator=evaluator,
+ authorize=self._authorize,
+ load_checkpoint=load_checkpoint,
+ save_checkpoint=save_checkpoint,
+ )
+ except Exception:
+ # Database and decoder errors can contain source values, so callers receive no raw cause.
+ raise RuntimeError("Question execution failed with incomplete coverage.") from None
diff --git a/products/data_quality/backend/tests/test_jev_question.py b/products/data_quality/backend/tests/test_jev_question.py
new file mode 100644
index 000000000000..fb004dadf17d
--- /dev/null
+++ b/products/data_quality/backend/tests/test_jev_question.py
@@ -0,0 +1,859 @@
+import json
+from collections.abc import AsyncIterator, Callable, Iterator
+from contextlib import contextmanager
+from dataclasses import replace
+from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
+from typing import cast
+from uuid import UUID
+
+import pytest
+from unittest.mock import AsyncMock, patch
+
+from django.test import override_settings
+
+import httpx
+import pyarrow as pa
+import fakeredis
+from asgiref.sync import async_to_sync
+from pydantic import ValidationError
+from redis.exceptions import ConnectionError
+
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.errors import QueryError
+from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql.transforms.prompt_jev import PromptJevColumn, PromptJevTable
+
+from posthog.models.team import Team
+from posthog.models.user import User
+
+from products.data_quality.backend.facade.enums import CheckRunStatus, SubjectType
+from products.data_quality.backend.logic.compiler import print_check_query
+from products.data_quality.backend.logic.contracts import SubjectRef
+from products.data_quality.backend.logic.jev_cache import (
+ EVALUATOR_VERSION,
+ DecisionCacheUnavailable,
+ DecisionRequest,
+ JevDecisionCache,
+)
+from products.data_quality.backend.logic.jev_evaluator import QuestionGatewayEvaluator
+from products.data_quality.backend.logic.jev_manifest import (
+ QuestionManifest,
+ QuestionManifestStore,
+ QuestionResult,
+ evaluate_question_manifest,
+ freeze_question_inputs,
+ strict_arrow_batches,
+ warehouse_question_inputs,
+)
+from products.data_quality.backend.logic.jev_question import (
+ QuestionChunkEvaluator,
+ QuestionChunkResult,
+ QuestionConfig,
+ WeightedInput,
+ question_input_query,
+)
+from products.data_quality.backend.logic.jev_warehouse import WarehouseQuestionExecutor
+
+
+def request(text: str = "input") -> DecisionRequest:
+ return DecisionRequest(
+ input=text,
+ question_schema=QuestionConfig(question="Is this valid?").question_schema(),
+ model_id="example-model",
+ model_revision="immutable-revision-1",
+ )
+
+
+def evaluator(
+ cache: JevDecisionCache, evaluate: Callable[[list[str]], list[float]], **config: float
+) -> QuestionChunkEvaluator:
+ return QuestionChunkEvaluator(
+ cache=cache,
+ config=QuestionConfig(question="Is this valid?", **config),
+ model_id="example-model",
+ model_revision="immutable-revision-1",
+ evaluate=evaluate,
+ wait_seconds=10_000,
+ )
+
+
+ "changed",
+ [
+ replace(request(), input="input "),
+ replace(request(), question_schema='{"type":"noul","instructions":"Different?"}'),
+ replace(request(), model_revision="immutable-revision-2"),
+ replace(request(), model_id="other-model"),
+ replace(request(), evaluator_version=2),
+ replace(request(), input='[["field", "String", "1"]]'),
+ replace(request(), input='[["field", "Int64", 1]]'),
+ replace(request(), input='[["other", "String", "1"]]'),
+ replace(request(), input='[["field", "Nullable(String)", null]]'),
+ ],
+)
+def test_cache_identity(changed: DecisionRequest) -> None:
+ original = request()
+ assert changed.key(1) != original.key(1)
+ assert original.key(2) != original.key(1)
+ assert "input" not in original.key(1)
+
+
+def test_expired_owner_cannot_publish_or_release_winning_lease() -> None:
+ client = fakeredis.FakeRedis()
+ cache = JevDecisionCache(client, team_id=1)
+ decision = request()
+ key = decision.key(1)
+ loser = cache.acquire([decision])[key]
+ client.delete(key + ":lease")
+ winner = cache.acquire([decision])[key]
+ assert cache.publish([(loser, decision, 0.1)]) == set()
+ cache.release([loser])
+ winning_token = client.get(key + ":lease")
+ assert winning_token is not None
+ assert winning_token.decode() == winner.token
+ assert cache.publish([(winner, decision, 0.9)]) == {key}
+ assert cache.read([decision]) == {key: 0.9}
+ stored = client.get(key)
+ assert stored is not None
+ assert set(json.loads(stored)) == {"probability", "model_revision", "evaluator_version", "evaluated_at"}
+
+
+def test_renewal_is_bounded_and_reads_do_not_extend_ttl() -> None:
+ client = fakeredis.FakeRedis()
+ cache = JevDecisionCache(client, team_id=1, max_renewals=1)
+ decision = request()
+ key = decision.key(1)
+ lease = cache.acquire([decision])[key]
+ renewed = cache.renew(lease)
+ assert renewed is not None
+ assert cache.renew(renewed) is None
+ cache.publish([(renewed, decision, 0.9)])
+ client.expire(key, 100)
+ cache.read([decision])
+ assert 0 < client.ttl(key) <= 100
+ client.delete(key)
+ assert cache.read([decision]) == {}
+
+
[email protected]("unavailable", [False, True])
+def test_evaluation_lease_renewal_preserves_ownership_or_errors(unavailable: bool) -> None:
+ client = fakeredis.FakeRedis()
+ cache = JevDecisionCache(client, team_id=1)
+ decision = request()
+ key = decision.key(1)
+ lease = cache.acquire([decision])[key]
+ client.expire(key + ":lease", 1)
+ with patch("products.data_quality.backend.logic.jev_cache.Event") as stopped:
+ stopped.return_value.wait.side_effect = [False, True]
+ if unavailable:
+ with patch.object(client, "pipeline", side_effect=ConnectionError()):
+ with pytest.raises(DecisionCacheUnavailable, match="unavailable"):
+ with cache.maintain([lease]):
+ pass
+ else:
+ with cache.maintain([lease]):
+ pass
+ assert client.ttl(key + ":lease") > 1
+ assert cache.publish([(lease, decision, 0.9)]) == {key}
+
+
[email protected]("probability", [float("nan"), float("inf"), -0.1, 1.1, True])
+def test_invalid_probability_never_enters_cache(probability: float) -> None:
+ client = fakeredis.FakeRedis()
+ cache = JevDecisionCache(client, team_id=1)
+ decision = request()
+ lease = cache.acquire([decision])[decision.key(1)]
+ with pytest.raises(ValueError):
+ cache.publish([(lease, decision, probability)])
+ assert cache.read([decision]) == {}
+
+
+ "content",
+ [
+ "not json",
+ '{"probability":0.5}',
+ '{"probability":NaN,"model_revision":"immutable-revision-1","evaluator_version":1,"evaluated_at":"2026-01-01T00:00:00Z"}',
+ '{"probability":0.5,"model_revision":"wrong","evaluator_version":1,"evaluated_at":"2026-01-01T00:00:00Z"}',
+ '{"probability":0.5,"model_revision":"immutable-revision-1","evaluator_version":1,"evaluated_at":"2026-01-01T00:00:00"}',
+ ],
+)
+def test_malformed_cache_entry_is_replaced(content: str) -> None:
+ client = fakeredis.FakeRedis()
+ cache = JevDecisionCache(client, team_id=1)
+ client.set(request().key(1), content)
+ result = evaluator(cache, lambda inputs: [0.9] * len(inputs)).run([WeightedInput(text="input", row_count=1)])
+ assert result.new_decision_count == 1
+ assert cache.read([request()]) == {request().key(1): 0.9}
+
+
+def test_redis_outage_does_not_fall_back_to_inference() -> None:
+ client = fakeredis.FakeRedis()
+ calls: list[str] = []
+
+ def evaluate(inputs: list[str]) -> list[float]:
+ calls.extend(inputs)
+ return [0.9] * len(inputs)
+
+ with patch.object(client, "mget", side_effect=ConnectionError()):
+ with pytest.raises(DecisionCacheUnavailable, match="unavailable"):
+ evaluator(JevDecisionCache(client, team_id=1), evaluate).run([WeightedInput(text="input", row_count=1)])
+ assert calls == []
+
+
+def test_threshold_change_reuses_decisions_and_nulls_fail_without_inference() -> None:
+ client = fakeredis.FakeRedis()
+ cache = JevDecisionCache(client, team_id=1)
+ calls: list[str] = []
+
+ def evaluate(inputs: list[str]) -> list[float]:
+ calls.extend(inputs)
+ return [0.8] * len(inputs)
+
+ inputs = [
+ WeightedInput(text="a", row_count=3),
+ WeightedInput(text="a", row_count=2),
+ WeightedInput(text=None, row_count=4),
+ ]
+ cold = evaluator(cache, evaluate).run(inputs)
+ assert (cold.examined_row_count, cold.failed_row_count, cold.new_decision_count) == (9, 4, 1)
+ warm = evaluator(cache, evaluate, min_probability=0.9).run(inputs)
+ assert (warm.examined_row_count, warm.failed_row_count, warm.reused_decision_count, warm.new_decision_count) == (
+ 9,
+ 9,
+ 1,
+ 0,
+ )
+ assert calls == ["a"]
+
+
+ "config,column_name",
+ [
+ ({"question": " "}, "description"),
+ ({"question": "Valid?", "min_probability": float("nan")}, "description"),
+ ({"question": "Valid?", "max_failure_rate": 1.1}, "description"),
+ ({"question": "Valid?", "input_mode": "row", "columns": []}, ""),
+ ({"question": "Valid?", "input_mode": "row", "columns": ["a", "a"]}, ""),
+ ({"question": "Valid?", "input_mode": "row", "columns": ["a"]}, "description"),
+ ({"question": "Valid?", "columns": ["a"]}, "description"),
+ ({"question": "Valid?"}, ""),
+ ],
+)
+def test_modes_and_thresholds_are_validated(config: dict[str, object], column_name: str) -> None:
+ with pytest.raises((ValueError, ValidationError)):
+ QuestionConfig(**config).input_columns(column_name)
+
+
+def test_exhaustive_question_projection_has_typed_fields_and_no_limit() -> None:
+ subject = SubjectRef(SubjectType.TABLE, "example-table", "orders", "orders", exists=True)
+ config = QuestionConfig(input_mode="row", question="Valid?", columns=["description", "amount"])
+ printed = print_check_query(question_input_query(subject, config, ""))
+ assert "LIMIT" not in printed
+ assert "GROUP BY" in printed
+ assert "toTypeName(amount)" in printed
+ assert "toTypeName(description)" in printed
+ assert printed.index("'amount'") < printed.index("'description'")
+ context = HogQLContext(
+ team_id=999,
+ team=Team(id=999, project_id=999),
+ database=Database(include_posthog_tables=False),
+ enable_select_queries=True,
+ limit_top_select=False,
+ restricted_properties=set(),
+ use_new_events_schema=False,
+ )
+ PromptJevTable(
+ name="orders",
+ columns=[
+ PromptJevColumn(name="amount", clickhouse_type="Int64"),
+ PromptJevColumn(name="description", clickhouse_type="String"),
+ ],
+ rows=[],
+ ).register(context)
+ sql, prepared = prepare_and_print_ast(
+ question_input_query(subject, config, ""), context=context, dialect="clickhouse"
+ )
+ assert prepared is not None
+ assert "LIMIT" not in sql
+ assert sql.count("toJSONString(tuple(") == 2
+ assert "arrayStringConcat" in sql
+
+
+def _arrow_stream(*texts: str) -> bytes:
+ fields: list[pa.Field] = [pa.field("input", pa.string()), pa.field("row_count", pa.uint64())]
+ schema = pa.schema(fields)
+ sink = pa.BufferOutputStream()
+ with pa.ipc.new_stream(sink, schema) as writer:
+ for text in texts:
+ writer.write_batch(pa.record_batch([[text], [1]], schema=schema))
+ return sink.getvalue().to_pybytes()
+
+
+ONE_BATCH_WITHOUT_END = _arrow_stream("first")[:-8]
+
+
+ "body,error",
+ [
+ (_arrow_stream("first", "second"), None),
+ (ONE_BATCH_WITHOUT_END, "before its end marker"),
+ (_arrow_stream("first", "second")[: len(ONE_BATCH_WITHOUT_END) + 24], "before its end marker"),
+ (_arrow_stream("first", "second") + b"Code: 241. DB::Exception: example", "after its end marker"),
+ ],
+ ids=["complete", "cut_at_batch_boundary", "cut_inside_batch", "trailing_error"],
+)
+def test_arrow_input_stream_must_end_at_its_end_marker(body: bytes, error: str | None) -> None:
+ async def chunks() -> AsyncIterator[bytes]:
+ for start in range(0, len(body), 7):
+ yield body[start : start + 7]
+
+ async def collect() -> list[str]:
+ return [row["input"] async for batch in strict_arrow_batches(chunks()) for row in batch.to_pylist()]
+
+ if error is None:
+ assert async_to_sync(collect)() == ["first", "second"]
+ else:
+ with pytest.raises(ValueError, match=error):
+ async_to_sync(collect)()
+
+
[email protected]("clickhouse_database")
+def test_row_inputs_keep_null_and_non_finite_numbers_distinct() -> None:
+ subject = SubjectRef(SubjectType.TABLE, "example-table", "orders", "orders", exists=True)
+ config = QuestionConfig(input_mode="row", question="Valid?", columns=["amount"])
+ team = Team(id=999, project_id=999)
+ context = HogQLContext(
+ team_id=999,
+ team=team,
+ database=Database(include_posthog_tables=False),
+ enable_select_queries=True,
+ limit_top_select=False,
+ restricted_properties=set(),
+ use_new_events_schema=False,
+ output_format="ArrowStream",
+ )
+ PromptJevTable(
+ name="orders",
+ columns=[PromptJevColumn(name="amount", clickhouse_type="Nullable(Float64)")],
+ rows=[[None], [float("nan")], [float("inf")], [float("-inf")]],
+ ).register(context)
+ sql, _ = prepare_and_print_ast(question_input_query(subject, config, ""), context=context, dialect="clickhouse")
+
+ async def collect() -> list[WeightedInput]:
+ return [
+ item
+ async for item in warehouse_question_inputs(
+ team=team, user=cast(User, SimpleNamespace()), subject=subject, config=config, column_name=""
+ )
+ ]
+
+ with patch(
+ "products.data_quality.backend.logic.jev_manifest.prepare_warehouse_question_inputs",
+ return_value=(sql, context),
+ ):
+ inputs = async_to_sync(collect)()
+ assert sorted((item.text or "", item.row_count) for item in inputs) == [
+ ('[["amount","Nullable(Float64)","-inf"]]', 1),
+ ('[["amount","Nullable(Float64)","inf"]]', 1),
+ ('[["amount","Nullable(Float64)","nan"]]', 1),
+ ('[["amount","Nullable(Float64)",null]]', 1),
+ ]
+
+
+def test_full_manifest_coverage_cold_warm_and_retry() -> None:
+ objects: dict[str, str] = {}
+ checkpoints: dict[int, QuestionChunkResult] = {}
+ store = QuestionManifestStore()
+ cache = JevDecisionCache(fakeredis.FakeRedis(), team_id=1)
+ calls: list[str] = []
+
+ async def source() -> AsyncIterator[WeightedInput]:
+ for index in range(500):
+ yield WeightedInput(text=str(index), row_count=40)
+
+ def evaluate(inputs: list[str]) -> list[float]:
+ calls.extend(inputs)
+ return [0.1 if text == "0" else 0.8 for text in inputs]
+
+ with (
+ patch(
+ "posthog.storage.object_storage.write", side_effect=lambda key, content: objects.__setitem__(key, content)
+ ),
+ patch("posthog.storage.object_storage.read", side_effect=lambda key: objects.get(key)),
+ ):
+ manifest = async_to_sync(freeze_question_inputs)(
+ inputs=source(),
+ store=store,
+ team_id=1,
+ run_id="example-run",
+ subject_uuid="example-table",
+ model_id="example-model",
+ model_revision="immutable-revision-1",
+ config=QuestionConfig(question="Is this valid?"),
+ column_name="description",
+ )
+ assert manifest.chunk_count == 4
+
+ def save(index: int, result: QuestionChunkResult) -> QuestionChunkResult:
+ if index == 2:
+ raise RuntimeError("checkpoint unavailable")
+ return checkpoints.setdefault(index, result)
+
+ def run(save_checkpoint: Callable[[int, QuestionChunkResult], QuestionChunkResult]) -> QuestionResult:
+ return evaluate_question_manifest(
+ manifest=manifest,
+ store=store,
+ evaluator=evaluator(cache, evaluate),
+ authorize=lambda: None,
+ load_checkpoint=checkpoints.get,
+ save_checkpoint=save_checkpoint,
+ )
+
+ with pytest.raises(RuntimeError, match="checkpoint unavailable"):
+ run(save)
+ assert len(checkpoints) == 2
+ cold = run(lambda index, result: checkpoints.setdefault(index, result))
+ assert cold.status == CheckRunStatus.FAILED
+ assert (cold.examined_row_count, cold.failed_row_count, cold.unique_input_count) == (20_000, 40, 500)
+ assert cold.coverage_complete
+ assert len(calls) == 500
+ checkpoints.clear()
+ warm = run(lambda index, result: checkpoints.setdefault(index, result))
+ assert (warm.examined_row_count, warm.reused_decision_count, warm.new_decision_count) == (20_000, 500, 0)
+ assert len(calls) == 500
+
+
+ "texts,max_inputs,message",
+ [(["a" * 8193], 200, "8 KiB"), ([str(index) for index in range(200)], 130, "frozen inputs")],
+)
+def test_oversized_freeze_fails_closed_and_publishes_nothing(texts: list[str], max_inputs: int, message: str) -> None:
+ objects: dict[str, str] = {}
+
+ async def source() -> AsyncIterator[WeightedInput]:
+ for text in texts:
+ yield WeightedInput(text=text, row_count=1)
+
+ with (
+ patch(
+ "posthog.storage.object_storage.write", side_effect=lambda key, content: objects.__setitem__(key, content)
+ ),
+ patch("posthog.storage.object_storage.delete", side_effect=lambda key: objects.pop(key, None)),
+ pytest.raises(ValueError, match=message),
+ ):
+ async_to_sync(freeze_question_inputs)(
+ inputs=source(),
+ store=QuestionManifestStore(),
+ team_id=1,
+ run_id="example-run",
+ subject_uuid="example-table",
+ model_id="example-model",
+ model_revision="immutable-revision-1",
+ config=QuestionConfig(question="Is this valid?"),
+ column_name="description",
+ max_inputs=max_inputs,
+ )
+ assert objects == {}
+
+
+def test_manifest_checkpoint_coverage_mismatch_and_permission_revocation_fail_closed() -> None:
+ store = QuestionManifestStore()
+ cache = JevDecisionCache(fakeredis.FakeRedis(), team_id=1)
+
+ async def source() -> AsyncIterator[WeightedInput]:
+ yield WeightedInput(text="input", row_count=10)
+
+ with patch("posthog.storage.object_storage.write"):
+ manifest = async_to_sync(freeze_question_inputs)(
+ inputs=source(),
+ store=store,
+ team_id=1,
+ run_id="example-run",
+ subject_uuid="example-table",
+ model_id="example-model",
+ model_revision="immutable-revision-1",
+ config=QuestionConfig(question="Is this valid?"),
+ column_name="description",
+ )
+
+ def run(
+ frozen: QuestionManifest, authorize: Callable[[], None], checkpoint: QuestionChunkResult | None = None
+ ) -> QuestionResult:
+ return evaluate_question_manifest(
+ manifest=frozen,
+ store=store,
+ evaluator=evaluator(cache, lambda inputs: [0.9]),
+ authorize=authorize,
+ load_checkpoint=lambda index: checkpoint,
+ save_checkpoint=lambda index, result: result,
+ )
+
+ def deny() -> None:
+ raise PermissionError()
+
+ with pytest.raises(PermissionError):
+ run(manifest, deny)
+ expired = manifest.model_copy(update={"expires_at": datetime.now(UTC) - timedelta(hours=1)})
+ with pytest.raises(ValueError, match="expired"):
+ run(expired, lambda: None)
+ with pytest.raises(ValueError, match="coverage is incomplete"):
+ run(
+ manifest,
+ lambda: None,
+ QuestionChunkResult(
+ examined_row_count=9,
+ failed_row_count=0,
+ unique_input_count=1,
+ reused_decision_count=1,
+ new_decision_count=0,
+ ),
+ )
+ for update in (
+ {"question_config": QuestionConfig(question="A different question?")},
+ {"evaluator_version": EVALUATOR_VERSION + 1},
+ ):
+ with pytest.raises(ValueError, match="do not match"):
+ run(manifest.model_copy(update=update), lambda: None)
+
+
+def test_inference_budget_errors_on_partial_coverage_but_allows_warm_decisions() -> None:
+ cache = JevDecisionCache(fakeredis.FakeRedis(), team_id=1)
+ runner = QuestionChunkEvaluator(
+ cache=cache,
+ config=QuestionConfig(question="Is this valid?"),
+ model_id="example-model",
+ model_revision="immutable-revision-1",
+ evaluate=lambda inputs: [0.9] * len(inputs),
+ max_inference_inputs=1,
+ max_run_seconds=10_000,
+ )
+ first = runner.run([WeightedInput(text="a", row_count=1)])
+ assert first.new_decision_count == 1
+ with pytest.raises(RuntimeError, match="inference budget.*incomplete coverage"):
+ runner.run([WeightedInput(text="b", row_count=1)])
+ assert runner.run([WeightedInput(text="a", row_count=1)]).reused_decision_count == 1
+
+
+ "rows,allowed_rate,status",
+ [(0, 0, CheckRunStatus.SKIPPED), (10, 0.1, CheckRunStatus.PASSED), (10, 0, CheckRunStatus.FAILED)],
+)
+def test_empty_scope_and_failure_rate_equality(rows: int, allowed_rate: float, status: CheckRunStatus) -> None:
+ async def source() -> AsyncIterator[WeightedInput]:
+ if rows:
+ yield WeightedInput(text=None, row_count=1)
+ yield WeightedInput(text="valid", row_count=rows - 1)
+
+ store = QuestionManifestStore()
+ config = QuestionConfig(question="Is this valid?", max_failure_rate=allowed_rate)
+ objects: dict[str, str] = {}
+ with (
+ patch(
+ "posthog.storage.object_storage.write", side_effect=lambda key, content: objects.__setitem__(key, content)
+ ),
+ patch("posthog.storage.object_storage.read", side_effect=lambda key: objects.get(key)),
+ ):
+ manifest = async_to_sync(freeze_question_inputs)(
+ inputs=source(),
+ store=store,
+ team_id=1,
+ run_id="example-run",
+ subject_uuid="example-table",
+ model_id="example-model",
+ model_revision="immutable-revision-1",
+ config=config,
+ column_name="description",
+ )
+ runner = evaluator(
+ JevDecisionCache(fakeredis.FakeRedis(), team_id=1),
+ lambda inputs: [0.9] * len(inputs),
+ max_failure_rate=allowed_rate,
+ )
+ result = evaluate_question_manifest(
+ manifest=manifest,
+ store=store,
+ evaluator=runner,
+ authorize=lambda: None,
+ load_checkpoint=lambda index: None,
+ save_checkpoint=lambda index, result: result,
+ )
+ assert result.status == status
+ assert result.examined_row_count == rows
+
+
[email protected]("enabled", [True, False])
+def test_gateway_access_and_attribution(enabled: bool) -> None:
+ team = cast(
+ "Team", SimpleNamespace(pk=42, id=42, uuid=UUID(int=42), organization_id=7, api_token="example-api-token")
+ )
+ with (
+ override_settings(
+ AI_GATEWAY_URL="https://ai-gateway.example.com/v1",
+ AI_GATEWAY_API_KEY="phs_test",
+ CLICKHOUSE_USE_HTTP=False,
+ CLICKHOUSE_USE_HTTP_PER_TEAM=[],
+ ),
+ patch("posthog.hogql.transforms.prompt_jev.feature_enabled_or_false", return_value=enabled),
+ patch("ee.billing.quota_limiting.is_team_over_ai_credit_budget", return_value=False),
+ patch.object(
+ httpx.AsyncClient,
+ "send",
+ new_callable=AsyncMock,
+ return_value=httpx.Response(200, json={"model": "example-model", "answers": {"row_0": {"noul": 0.9}}}),
+ ) as send,
+ ):
+ if not enabled:
+ with pytest.raises(QueryError, match="not enabled"):
+ QuestionGatewayEvaluator(
+ team=team,
+ model_id="example-model",
+ question="Is this valid?",
+ check_id="example-check",
+ run_id="example-run",
+ distinct_id="example-user",
+ )
+ assert not send.called
+ return
+ runner = QuestionGatewayEvaluator(
+ team=team,
+ model_id="example-model",
+ question="Is this valid?",
+ check_id="example-check",
+ run_id="example-run",
+ distinct_id="example-user",
+ )
+ assert runner(["example input"]) == [0.9]
+ gateway_request = send.call_args.args[0]
+ properties = json.loads(gateway_request.headers["X-PostHog-Properties"])
+ assert properties["team_id"] == "42"
+ assert properties["data_quality_check_id"] == "example-check"
+ assert properties["data_quality_run_id"] == "example-run"
+ assert gateway_request.headers["X-PostHog-Trace-Id"] == "example-run"
+ assert gateway_request.headers["X-PostHog-Distinct-Id"] == "example-user"
+ assert "example input" not in str(gateway_request.headers)
+ assert json.loads(gateway_request.content)["model"] == "example-model"
+
+
+WAREHOUSE = "products.data_quality.backend.logic.jev_warehouse"
+
+
+def _manifest(**overrides: object) -> QuestionManifest:
+ created_at = datetime.now(UTC)
+ fields: dict[str, object] = {
+ "prefix": "data_quality/jev/1/example",
+ "team_id": 1,
+ "run_id": "example-run",
+ "subject_uuid": "example-table",
+ "model_id": "example-model",
+ "model_revision": "immutable-revision-1",
+ "evaluator_version": EVALUATOR_VERSION,
+ "question_config": QuestionConfig(question="Is this valid?"),
+ "column_name": "description",
+ "chunk_count": 3,
+ "examined_row_count": 3,
+ "unique_input_count": 3,
+ "created_at": created_at,
+ "expires_at": created_at + timedelta(hours=1),
+ }
+ return QuestionManifest(**(fields | overrides)) # type: ignore[arg-type]
+
+
+def test_run_deadline_stops_replaying_checkpoints() -> None:
+ clock = [0.0]
+
+ def load_checkpoint(index: int) -> QuestionChunkResult:
+ clock[0] += 600
+ return QuestionChunkResult(
+ examined_row_count=1,
+ failed_row_count=0,
+ unique_input_count=1,
+ reused_decision_count=1,
+ new_decision_count=0,
+ )
+
+ def refuse(inputs: list[str]) -> list[float]:
+ raise AssertionError("A replayed checkpoint must not reach inference.")
+
+ runner = QuestionChunkEvaluator(
+ cache=JevDecisionCache(fakeredis.FakeRedis(), team_id=1),
+ config=QuestionConfig(question="Is this valid?"),
+ model_id="example-model",
+ model_revision="immutable-revision-1",
+ evaluate=refuse,
+ max_run_seconds=900,
+ clock=lambda: clock[0],
+ )
+ with pytest.raises(RuntimeError, match="timed out with incomplete coverage"):
+ evaluate_question_manifest(
+ manifest=_manifest(),
+ store=QuestionManifestStore(),
+ evaluator=runner,
+ authorize=lambda: None,
+ load_checkpoint=load_checkpoint,
+ save_checkpoint=lambda index, result: result,
+ )
+ assert clock[0] == 1200
+
+
+def test_run_deadline_stops_a_chunk_served_entirely_from_cache() -> None:
+ clock = [0.0]
+ cache = JevDecisionCache(fakeredis.FakeRedis(), team_id=1)
+ inputs = [WeightedInput(text="input", row_count=1)]
+ assert evaluator(cache, lambda texts: [0.9] * len(texts)).run(inputs).new_decision_count == 1
+
+ def refuse(texts: list[str]) -> list[float]:
+ raise AssertionError("A cached decision must not reach inference.")
+
+ runner = QuestionChunkEvaluator(
+ cache=cache,
+ config=QuestionConfig(question="Is this valid?"),
+ model_id="example-model",
+ model_revision="immutable-revision-1",
+ evaluate=refuse,
+ max_run_seconds=900,
+ clock=lambda: clock[0],
+ )
+ read = cache.read
+
+ def slow_read(requests: list[DecisionRequest]) -> dict[str, float]:
+ clock[0] += 1000
+ return read(requests)
+
+ with patch.object(cache, "read", side_effect=slow_read):
+ with pytest.raises(RuntimeError, match="timed out with incomplete coverage"):
+ runner.run(inputs)
+
+
+def _executor(reserve: Callable[[int], None]) -> WarehouseQuestionExecutor:
+ return WarehouseQuestionExecutor(
+ team=cast("Team", SimpleNamespace(id=1, pk=1)),
+ user=cast("User", SimpleNamespace(distinct_id="example-user")),
+ subject=SubjectRef(SubjectType.TABLE, "example-table", "orders", "orders", exists=True),
+ config=QuestionConfig(question="Is this valid?"),
+ column_name="description",
+ model_id="example-model",
+ model_revision="immutable-revision-1",
+ check_id="example-check",
+ run_id="example-run",
+ reserve_inference_inputs=reserve,
+ )
+
+
+@contextmanager
+def _warehouse_question_environment(
+ objects: dict[str, str], redis: fakeredis.FakeRedis, build_gateway: Callable[..., object]
+) -> Iterator[None]:
+ async def source() -> AsyncIterator[WeightedInput]:
+ yield WeightedInput(text="input", row_count=10)
+ yield WeightedInput(text=None, row_count=1)
+
+ with (
+ patch(
+ "posthog.storage.object_storage.write", side_effect=lambda key, content: objects.__setitem__(key, content)
+ ),
+ patch("posthog.storage.object_storage.read", side_effect=lambda key: objects.get(key)),
+ patch("posthog.storage.object_storage.delete", side_effect=lambda key: objects.pop(key, None)),
+ patch(
+ "posthog.storage.object_storage.delete_objects",
+ side_effect=lambda keys: [objects.pop(key, None) for key in keys],
+ ),
+ patch(f"{WAREHOUSE}.authorize_warehouse_question_subject"),
+ patch(f"{WAREHOUSE}.warehouse_question_inputs", side_effect=lambda **arguments: source()),
+ patch(f"{WAREHOUSE}.get_client", return_value=redis),
+ patch(f"{WAREHOUSE}.QuestionGatewayEvaluator", side_effect=build_gateway),
+ ):
+ yield
+
+
+def _gateway(calls: list[str]) -> Callable[..., Callable[[list[str]], list[float]]]:
+ def build(**arguments: object) -> Callable[[list[str]], list[float]]:
+ def evaluate(inputs: list[str]) -> list[float]:
+ calls.extend(inputs)
+ return [0.9] * len(inputs)
+
+ return evaluate
+
+ return build
+
+
+def test_executor_freezes_reuses_and_discards_a_losing_manifest() -> None:
+ objects: dict[str, str] = {}
+ redis = fakeredis.FakeRedis()
+ calls: list[str] = []
+ reserved: list[int] = []
+ won: list[str] = []
+ lost: list[str] = []
+
+ def run(manifest_key: str | None, save_manifest: Callable[[str], str]) -> QuestionResult:
+ return _executor(reserved.append).run(
+ manifest_key=manifest_key,
+ save_manifest=save_manifest,
+ load_checkpoint=lambda index: None,
+ save_checkpoint=lambda index, result: result,
+ )
+
+ def win(key: str) -> str:
+ won.append(key)
+ return key
+
+ def lose(key: str) -> str:
+ lost.append(key)
+ return won[0]
+
+ with _warehouse_question_environment(objects, redis, _gateway(calls)):
+ first = run(None, win)
+ # The null row fails without inference, which exceeds the default allowed failure rate.
+ assert first.status == CheckRunStatus.FAILED
+ assert (first.examined_row_count, first.failed_row_count, first.new_decision_count) == (11, 1, 1)
+ replayed = run(won[0], win)
+ assert (replayed.examined_row_count, replayed.reused_decision_count, replayed.new_decision_count) == (11, 1, 0)
+ discarded = run(None, lose)
+ assert discarded.examined_row_count == 11
+ assert won == [won[0]]
+ assert calls == ["input"]
+ assert reserved == [1]
+ losing_prefix = lost[0].removesuffix("/manifest.json")
+ assert [key for key in objects if key.startswith(losing_prefix)] == []
+ assert won[0] in objects
+
+
[email protected]("callback", ["save_manifest", "save_checkpoint"])
+def test_executor_hides_persistence_failures_behind_incomplete_coverage(callback: str) -> None:
+ reserved: list[int] = []
+
+ def fail(*arguments: object) -> str:
+ raise RuntimeError("durable store names a row")
+
+ callbacks: dict[str, object] = {
+ "save_manifest": lambda key: key,
+ "load_checkpoint": lambda index: None,
+ "save_checkpoint": lambda index, result: result,
+ callback: fail,
+ }
+ with _warehouse_question_environment({}, fakeredis.FakeRedis(), _gateway([])):
+ with pytest.raises(RuntimeError) as failure:
+ _executor(reserved.append).run(manifest_key=None, **callbacks) # type: ignore[arg-type]
+ assert str(failure.value) == "Question execution failed with incomplete coverage."
+ assert failure.value.__cause__ is None
+ assert "durable store names a row" not in str(failure.value)
+ assert reserved == ([] if callback == "save_manifest" else [1])
+
+
+def test_executor_reserves_no_inference_when_the_gateway_refuses_the_run() -> None:
+ reserved: list[int] = []
+
+ def refuse(**arguments: object) -> object:
+ raise QueryError("Jev is not enabled for this project.")
+
+ with _warehouse_question_environment({}, fakeredis.FakeRedis(), refuse):
+ with pytest.raises(RuntimeError, match="incomplete coverage"):
+ _executor(reserved.append).run(
+ manifest_key=None,
+ save_manifest=lambda key: key,
+ load_checkpoint=lambda index: None,
+ save_checkpoint=lambda index, result: result,
+ )
+ assert reserved == []