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.

chore(data-catalog): rebuild a canary batch for scoring from the Tasks API (#98649)

Thiago Salvatore655414adb8dc
diff --git a/products/data_catalog/evals/scorers.py b/products/data_catalog/evals/scorers.py
index cc22a96112f8..1b93dd1d99fc 100644
--- a/products/data_catalog/evals/scorers.py
+++ b/products/data_catalog/evals/scorers.py
@@ -244,6 +244,14 @@ class MetricsCatalogBeforeDataDiscovery(Scorer):
return Score(name=self._name(), score=1.0, metadata={"failed_catalog_lookups": failed_catalog_lookups})
+def _expected_metric_names(metric_name: object) -> list[str]:
+ if isinstance(metric_name, str):
+ return [metric_name] if metric_name else []
+ if isinstance(metric_name, list) and all(isinstance(name, str) and name for name in metric_name):
+ return metric_name
+ return []
+
+
class CanonicalMetricRun(Scorer):
"""Binary: did the expected canonical metric run after discovery with the expected outcome?"""
@@ -277,11 +285,12 @@ class CanonicalMetricRun(Scorer):
)
metric_name = spec.get("metric_name")
- if not isinstance(metric_name, str) or not metric_name:
+ metric_names = _expected_metric_names(metric_name)
+ if not metric_names:
return Score(name=self._name(), score=0.0, metadata={"reason": "metric_name is required"})
called_names = [call.input.get("name") for call in run_calls]
- if any(name != metric_name for name in called_names):
+ if any(name not in metric_names for name in called_names):
return Score(
name=self._name(),
score=0.0,
@@ -293,14 +302,15 @@ class CanonicalMetricRun(Scorer):
post_catalog_runs = [
call
for call in run_calls
- if call.input.get("name") == metric_name
+ if call.input.get("name") in metric_names
and any(position < call.position for position in successful_catalog_positions)
]
matching_calls = [call for call in post_catalog_runs if call.is_error is expected_error]
contradicting_calls = [call for call in post_catalog_runs if call.is_error is not expected_error]
+ matched_names = {call.input.get("name") for call in matching_calls}
# Mixed outcomes (e.g. a failed run followed by a successful one) are contradictory —
# only accept when every canonical run agreed with the expected outcome.
- if matching_calls and not contradicting_calls:
+ if matched_names == set(metric_names) and not contradicting_calls:
return Score(
name=self._name(),
score=1.0,
@@ -523,7 +533,7 @@ class MetricsCatalogNotQueried(Scorer):
parser = _parser_for(output)
if parser is None:
return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})
- hits = [c for c in _successful_sql(parser) if _is_catalog_lookup(c)]
+ hits = _successful_catalog_lookups(parser)
return Score(name=self._name(), score=0.0 if hits else 1.0, metadata={"catalog_lookups": len(hits)})
@@ -869,8 +879,8 @@ class SemanticTrustDecisionCorrectness(JudgedScorer):
CANARY_ROUTING_SCORERS: list[Scorer] = [
MetricsCatalogBeforeDataDiscovery(),
+ MetricsCatalogNotQueried(),
CanonicalMetricRun(),
ClarificationAsked(),
- ProposedMetricNotRun(),
MetricDescribeBeforeAdaptedSql(),
]
diff --git a/products/data_catalog/scripts/README.md b/products/data_catalog/scripts/README.md
index 6b69e1511f8c..e5959f556fb0 100644
--- a/products/data_catalog/scripts/README.md
+++ b/products/data_catalog/scripts/README.md
@@ -88,26 +88,52 @@ A structured clarification question parks a permission request that stays open w
## Scoring a canary batch
-`semantic_layer_canary_score.py` grades a completed batch from the full ACP session log of each run, using the same scorers as the offline evals in `products/data_catalog/evals/`. It reads the runner's output, so score the file the runner just wrote:
+`semantic_layer_canary_score.py` grades a completed batch from the full ACP session log of each run, using the same scorers as the offline evals in `products/data_catalog/evals/`. It is the only scorer. The `signals-scout-semantic-layer-canary-report` scout reports the `$ai_evaluation` events this script emits; it does not grade session logs itself. A batch that was never scored here has no pass rate anywhere.
+
+Score the file the runner just wrote:
```bash
POSTHOG_API_KEY=phx_... flox activate -- .venv/bin/python \
- products/data_catalog/scripts/semantic_layer_canary_score.py \
+ -m products.data_catalog.scripts.semantic_layer_canary_score \
--results .context/semantic-layer-canary.json
```
-It prints one JSON verdict row per case on stdout and a batch summary on stderr. `--emit` additionally publishes an `$ai_evaluation` event per scored case, tagged with the canary run id, and needs `POSTHOG_CAPTURE_TOKEN`.
+Without the runner's file, rebuild the batch from the tasks the runner created. Pass the window of task creation times and the dataset revision that was run:
+
+```bash
+POSTHOG_API_KEY=phx_... flox activate -- .venv/bin/python \
+ -m products.data_catalog.scripts.semantic_layer_canary_score \
+ --batch 2026-09-10T16:54:23Z 2026-09-10T17:17:23Z --revision 42
+```
+
+`--batch` reads the pinned revision, then finds each enabled question's task among `origin_product=posthog_ai` tasks created inside the window. Only a task whose full description equals the question counts; there is no fuzzy matching. A case with no task in the window is `missing`; a case whose newest attempt is still running is `incomplete`; more than one completed attempt is `duplicate`; a failed attempt followed by a completed one scores the completed one. A run the runner cancelled behind a clarifying question is scored as completed, with the question text recovered from its log. The batch id is `tasks:<from>:<to>`, so scoring the same window twice publishes the same experiment id.
+
+The personal API key needs `task:read`, plus `dataset:read` for `--batch`.
+
+It prints one JSON verdict row per case on stdout and a batch summary on stderr. `--emit` additionally publishes an `$ai_evaluation` event per case, tagged with the batch id, and needs `POSTHOG_CAPTURE_TOKEN`. Unscored cases are emitted too, with `$ai_evaluation_applicable` false and the case status as the reasoning, so the scout can report coverage gaps without reading logs. Every event carries `task_id`, `task_run_id`, and `task_url` for the report's links.
Each case is graded against its dataset `expected_routing`:
-| `expected_routing` | Passes when |
-| ---------------------- | ---------------------------------------------------------------------------------------------- |
-| `canonical_metric` | the catalog was consulted before any data-bearing call, and `expected_metric` ran successfully |
-| `derive_from_approved` | the same, and the named metric was never run for the answer |
-| `clarify` | a question was asked before any data-bearing call, and no metric ran |
-| `no_match` | the catalog was consulted first, and no metric ran |
+| `expected_routing` | Passes when |
+| ------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
+| `canonical_metric`, `canonical_then_drilldown`, `approved_over_proposed`, `proposed_discovery_noncanonical_derivation` | the catalog was consulted before any data-bearing call, every metric in `expected_metric` ran successfully, and no other metric ran |
+| `clarify_before_execution` | a question was asked before any data-bearing call, and no metric ran |
+| `no_approved_match_then_noncanonical` | the catalog was consulted first, and no metric ran |
+| `schema_discovery_only`, `availability_query_only`, `source_discovery_only`, `row_level_debugging_only`, `query_diagnosis_only` | the catalog was never listed, described, or queried, and no metric ran |
+
+`expected_metric` names several metrics with `+` when a case must run more than one.
+
+### What the scorer checks
+
+The catalog tool surface is `metric-list` (paginated, no search parameter, not data-bearing), `metric-describe` (one stored definition, not data-bearing), `data-catalog-metric-run` (executes a governed metric; its response repeats `status` and `is_drifted`), and `execute-sql` over `system.information_schema.metrics`, which still counts as consulting the catalog. A data-bearing call is `execute-sql`, any `query-*` tool, `read-data-schema`, or a typed domain tool. Tool discovery (`info`, `search`, `schema`) is neither.
+
+- `metrics_catalog_before_data_discovery`: a successful catalog lookup precedes the first data-bearing call.
+- `metrics_catalog_not_queried`: a discovery-only routing never made a successful catalog lookup.
+- `canonical_metric_run`: `data-catalog-metric-run` ran `expected_metric` successfully, or was never called where the routing forbids it.
+- `clarification_asked`: a question tool call precedes any data-bearing call.
+- `metric_describe_before_adapted_sql`: advisory, see below.
-An unrecognized `expected_routing` and a run without a confirmed terminal status both come back as `unscored` rather than a guess. `metric_describe_before_adapted_sql` is advisory: it never fails a case on its own, because a run that listed the catalog and then wrote its own SQL did consult the catalog.
+An unrecognized `expected_routing`, a run without a confirmed terminal status, a session log the API would not serve, and a required check that produced no score all come back as `unscored` rather than a guess. `metric_describe_before_adapted_sql` is advisory: it never fails a case on its own, because a run that listed the catalog and then wrote its own SQL did consult the catalog.
It reads whole logs, paginating at 5000 entries from offset zero. A partial log cannot show what a run did before the slice, so there is no tail-reading mode.
diff --git a/products/data_catalog/scripts/semantic_layer_canary.py b/products/data_catalog/scripts/semantic_layer_canary.py
index f2f0a9b752c0..a64438117263 100644
--- a/products/data_catalog/scripts/semantic_layer_canary.py
+++ b/products/data_catalog/scripts/semantic_layer_canary.py
@@ -30,6 +30,8 @@ MAX_CANCEL_ATTEMPTS = 3
STOPPED_RUN_STATUSES = frozenset({"cancelled", "failed"})
DEFAULT_TIMEOUT_SECONDS = 1_900.0
DATASET_PAGE_SIZE = 25
+DATASETS_PATH = "/api/environments/{project_id}/datasets/"
+DATASET_ITEMS_PATH = "/api/environments/{project_id}/dataset_items/"
BROWSER_HELPER_PATH = Path(__file__).with_name("browser_session_credentials.mjs")
DEFAULT_BROWSER_PROFILE = Path(".context/semantic-layer-canary-browser")
DEFAULT_BROWSER_LOGIN_TIMEOUT_SECONDS = 600
@@ -60,14 +62,14 @@ class ClarificationRequested(CanaryError):
self.questions = questions
-class _DatasetSummary(BaseModel):
+class DatasetSummary(BaseModel):
id: str
name: str
current_revision: int | None
class _DatasetPage(BaseModel):
- results: list[_DatasetSummary]
+ results: list[DatasetSummary]
class CanaryCaseInput(BaseModel):
@@ -135,6 +137,12 @@ class DatasetSnapshot(BaseModel):
cases: list[CanaryCase]
+class ParsedDatasetItemPage(BaseModel):
+ cases: list[CanaryCase]
+ next_page: str | None
+ item_count: int
+
+
class CanaryRunConfig(BaseModel):
dataset_name: str = DEFAULT_DATASET_NAME
revision: int | None = Field(default=None, ge=1)
@@ -240,16 +248,14 @@ class PostHogCanaryClient:
async def load_dataset_snapshot(self, dataset_name: str, revision: int | None = None) -> DatasetSnapshot:
dataset_response = await self._client.get(
- f"/api/environments/{self.project_id}/datasets/",
- params={"search": dataset_name, "archived": "false"},
+ DATASETS_PATH.format(project_id=self.project_id),
+ params=dataset_search_params(dataset_name),
)
dataset_response.raise_for_status()
- dataset_page = _DatasetPage.model_validate(dataset_response.json())
- exact_matches = [dataset for dataset in dataset_page.results if dataset.name == dataset_name]
- if len(exact_matches) != 1:
- raise PermanentCanaryError("dataset_not_found")
-
- dataset = exact_matches[0]
+ try:
+ dataset = select_dataset(dataset_response.json(), dataset_name)
+ except ValueError as error:
+ raise RetryableCanaryError("invalid_dataset_response") from error
selected_revision = revision if revision is not None else dataset.current_revision
if selected_revision is None:
raise PermanentCanaryError("dataset_has_no_revision")
@@ -269,40 +275,18 @@ class PostHogCanaryClient:
while True:
response = await self._client.get(
- f"/api/environments/{self.project_id}/dataset_items/",
- params={
- "dataset": dataset_id,
- "revision": revision,
- "archived": "false",
- "limit": DATASET_PAGE_SIZE,
- "offset": offset,
- },
+ DATASET_ITEMS_PATH.format(project_id=self.project_id),
+ params=dataset_items_params(dataset_id, revision, offset),
)
response.raise_for_status()
- page = _DatasetItemPage.model_validate(response.json())
- for item in page.results:
- if not item.metadata.enabled:
- continue
- if item.metadata.case_id in seen_case_ids:
- raise PermanentCanaryError("duplicate_case_id")
- seen_case_ids.add(item.metadata.case_id)
- cases.append(
- CanaryCase(
- dataset_item_id=item.id,
- case_id=item.metadata.case_id,
- category=item.metadata.category,
- question=item.input.question,
- agent_mode=item.input.agent_mode,
- expected_metric=item.expected_output.expected_metric,
- expected_routing=item.expected_output.expected_routing,
- expected_behavior=item.expected_output.expected_behavior,
- )
- )
- if page.next is None:
+ try:
+ page = parse_dataset_item_page(response.json(), seen_case_ids)
+ except ValueError as error:
+ raise RetryableCanaryError("invalid_dataset_item_response") from error
+ cases.extend(page.cases)
+ if page.next_page is None:
return cases
- if not page.results:
- raise PermanentCanaryError("invalid_dataset_pagination")
- offset += len(page.results)
+ offset += page.item_count
async def open_turn(
self,
@@ -328,7 +312,7 @@ class PostHogCanaryClient:
_raise_for_api_error(response)
try:
opened = _ConversationOpenResponse.model_validate(response.json())
- except (json.JSONDecodeError, ValidationError) as error:
+ except ValueError as error:
raise RetryableCanaryError("invalid_open_response") from error
if opened.trace_id != trace_id:
raise RetryableCanaryError("invalid_open_response")
@@ -392,7 +376,7 @@ class PostHogCanaryClient:
_raise_for_api_error(response)
try:
return _TaskRunResponse.model_validate(response.json()).status
- except (json.JSONDecodeError, ValidationError) as error:
+ except ValueError as error:
raise RetryableCanaryError("invalid_task_run_response") from error
async def _confirm_terminal_status(self, opened: _ConversationOpenResponse) -> None:
@@ -411,6 +395,54 @@ class PostHogCanaryClient:
return f"{self.host}/project/{self.project_id}/tasks/{task_id}?runId={task_run_id}"
+def dataset_search_params(dataset_name: str) -> dict[str, str]:
+ return {"search": dataset_name, "archived": "false"}
+
+
+def dataset_items_params(dataset_id: str, revision: int, offset: int) -> dict[str, str | int]:
+ return {
+ "dataset": dataset_id,
+ "revision": revision,
+ "archived": "false",
+ "limit": DATASET_PAGE_SIZE,
+ "offset": offset,
+ }
+
+
+def select_dataset(page_json: object, dataset_name: str) -> DatasetSummary:
+ dataset_page = _DatasetPage.model_validate(page_json)
+ exact_matches = [dataset for dataset in dataset_page.results if dataset.name == dataset_name]
+ if len(exact_matches) != 1:
+ raise PermanentCanaryError("dataset_not_found")
+ return exact_matches[0]
+
+
+def parse_dataset_item_page(page_json: object, seen_case_ids: set[str]) -> ParsedDatasetItemPage:
+ page = _DatasetItemPage.model_validate(page_json)
+ if page.next is not None and not page.results:
+ raise PermanentCanaryError("invalid_dataset_pagination")
+ cases: list[CanaryCase] = []
+ for item in page.results:
+ if not item.metadata.enabled:
+ continue
+ if item.metadata.case_id in seen_case_ids:
+ raise PermanentCanaryError("duplicate_case_id")
+ seen_case_ids.add(item.metadata.case_id)
+ cases.append(
+ CanaryCase(
+ dataset_item_id=item.id,
+ case_id=item.metadata.case_id,
+ category=item.metadata.category,
+ question=item.input.question,
+ agent_mode=item.input.agent_mode,
+ expected_metric=item.expected_output.expected_metric,
+ expected_routing=item.expected_output.expected_routing,
+ expected_behavior=item.expected_output.expected_behavior,
+ )
+ )
+ return ParsedDatasetItemPage(cases=cases, next_page=page.next, item_count=len(page.results))
+
+
def parse_browser_credentials(raw_credentials: str) -> BrowserSessionCredentials:
try:
credentials = BrowserSessionCredentials.model_validate_json(raw_credentials)
@@ -506,7 +538,7 @@ async def _consume_task_stream(response: httpx.Response) -> None:
raise RetryableCanaryError("invalid_sse_json") from error
if not isinstance(payload, dict):
return False
- return _is_completed_turn(payload)
+ return is_completed_turn(payload)
try:
async for line in response.aiter_lines():
@@ -534,7 +566,7 @@ async def _consume_task_stream(response: httpx.Response) -> None:
raise TaskStreamReconnect(last_event_id)
-def _is_completed_turn(payload: dict[str, object]) -> bool:
+def is_completed_turn(payload: dict[str, object]) -> bool:
payload_type = payload.get("type")
if payload_type == "task_run_state":
status = payload.get("status")
diff --git a/products/data_catalog/scripts/semantic_layer_canary_score.py b/products/data_catalog/scripts/semantic_layer_canary_score.py
index e22e06f2937e..cd1939b639f0 100644
--- a/products/data_catalog/scripts/semantic_layer_canary_score.py
+++ b/products/data_catalog/scripts/semantic_layer_canary_score.py
@@ -2,16 +2,17 @@
# ruff: noqa: T201 allow print statements
"""Score a semantic-layer canary batch deterministically from its full session logs.
-Reads the runner's `CanaryRunResult` JSON, fetches every scored run's complete ACP session
-log, and grades each case with the same scorers the offline evals use. Emits one JSON verdict
-row per case, and optionally `$ai_evaluation` events tagged with the canary run id.
+Reads the runner's `CanaryRunResult` JSON, or rebuilds the batch from the Tasks API and a pinned
+dataset revision, fetches every scored run's complete ACP session log, and grades each case with
+the same scorers the offline evals use. Emits one JSON verdict row per case, and optionally
+`$ai_evaluation` events tagged with the batch id.
Usage:
python semantic_layer_canary_score.py --results run.json
- python semantic_layer_canary_score.py --results - --emit
+ python semantic_layer_canary_score.py --batch 2026-09-10T16:54:23Z 2026-09-10T17:17:23Z --revision 42 --emit
Environment:
- POSTHOG_API_KEY personal API key with task:read on the target project
+ POSTHOG_API_KEY personal API key with task:read, plus dataset:read for --batch
POSTHOG_CAPTURE_TOKEN project API token, required only with --emit
"""
@@ -21,32 +22,82 @@ import os
import sys
import json
import argparse
-from collections.abc import Sequence
+from collections.abc import Mapping, Sequence
from datetime import UTC, datetime
+from pathlib import Path
from typing import Any
import httpx
+from pydantic import BaseModel, ConfigDict, ValidationError, model_validator
from products.data_catalog.evals.scorers import CANARY_ROUTING_SCORERS
+from products.data_catalog.scripts.semantic_layer_canary import (
+ DATASET_ITEMS_PATH,
+ DATASETS_PATH,
+ DEFAULT_DATASET_NAME,
+ CanaryCase,
+ CanaryError,
+ ClarificationRequested,
+ DatasetSnapshot,
+ dataset_items_params,
+ dataset_search_params,
+ is_completed_turn,
+ parse_dataset_item_page,
+ select_dataset,
+)
DEFAULT_HOST = "https://us.posthog.com"
DEFAULT_PROJECT_ID = 2
SESSION_LOG_PAGE_SIZE = 5_000
MAX_SESSION_LOG_PAGES = 200
+TASK_LIST_PAGE_SIZE = 50
+TASK_RUN_PAGE_SIZE = 100
REQUEST_TIMEOUT_SECONDS = 120.0
+MAX_READ_TIMEOUT_RETRIES = 2
EVALUATION_METRIC_NAME = "semantic_layer_canary_routing"
+EXPERIMENT_NAME = "semantic-layer-canary"
+BATCH_ID_PREFIX = "tasks"
+CANARY_ORIGIN_PRODUCT = "posthog_ai"
+PERMISSION_REQUEST_METHOD = "session/request_permission"
+SESSION_UPDATE_METHOD = "session/update"
-CANONICAL_ROUTING = "canonical_metric"
-CLARIFY_ROUTING = "clarify"
-NO_MATCH_ROUTING = "no_match"
-DERIVE_ROUTING = "derive_from_approved"
+CANONICAL_ROUTINGS = frozenset(
+ {
+ "canonical_metric",
+ "canonical_then_drilldown",
+ "approved_over_proposed",
+ "proposed_discovery_noncanonical_derivation",
+ }
+)
+CLARIFY_ROUTINGS = frozenset({"clarify_before_execution"})
+NO_MATCH_ROUTINGS = frozenset({"no_approved_match_then_noncanonical"})
+NEGATIVE_CONTROL_ROUTINGS = frozenset(
+ {
+ "schema_discovery_only",
+ "availability_query_only",
+ "source_discovery_only",
+ "row_level_debugging_only",
+ "query_diagnosis_only",
+ }
+)
+EXPECTED_METRIC_SEPARATOR = " + "
+
+COMPLETED_STATUS = "completed"
+CANCELLED_STATUS = "cancelled"
+FAILED_STATUS = "failed"
+MISSING_STATUS = "missing"
+UNAVAILABLE_STATUS = "unavailable"
+INCOMPLETE_STATUS = "incomplete"
+DUPLICATE_STATUS = "duplicate"
+UNSCORED_VERDICT = "unscored"
+TERMINAL_RUN_STATUSES = frozenset({COMPLETED_STATUS, CANCELLED_STATUS, FAILED_STATUS})
HARD_CHECKS = frozenset(
{
"metrics_catalog_before_data_discovery",
+ "metrics_catalog_not_queried",
"canonical_metric_run",
"clarification_asked",
- "proposed_metric_not_run",
}
)
@@ -55,53 +106,129 @@ class UnknownRouting(ValueError):
pass
+class BatchWindow(BaseModel):
+ model_config = ConfigDict(frozen=True)
+
+ start: datetime
+ end: datetime
+
+ @model_validator(mode="after")
+ def _start_must_not_follow_end(self) -> BatchWindow:
+ if self.start > self.end:
+ raise ValueError("batch window start must not be after its end")
+ return self
+
+ @property
+ def batch_id(self) -> str:
+ return f"{BATCH_ID_PREFIX}:{_utc_iso(self.start)}:{_utc_iso(self.end)}"
+
+ def contains(self, moment: datetime) -> bool:
+ return self.start <= moment <= self.end
+
+
+class _TaskSummary(BaseModel):
+ id: str
+ description: str = ""
+ created_at: datetime
+
+
+class _TaskPage(BaseModel):
+ next: str | None = None
+ results: list[_TaskSummary]
+
+
+class _TaskRun(BaseModel):
+ id: str
+ status: str
+ created_at: datetime
+
+
+class _TaskRunPage(BaseModel):
+ next: str | None = None
+ results: list[_TaskRun]
+
+
+class _BatchAttempt(BaseModel):
+ task_id: str
+ run: _TaskRun
+
+
+def _utc_iso(moment: datetime) -> str:
+ return moment.astimezone(UTC).isoformat().replace("+00:00", "Z")
+
+
+def parse_batch_moment(raw: str) -> datetime:
+ moment = datetime.fromisoformat(raw.replace("Z", "+00:00"))
+ return moment if moment.tzinfo else moment.replace(tzinfo=UTC)
+
+
+def _expected_metric_names(expected_metric: str) -> str | list[str]:
+ names = [name.strip() for name in expected_metric.split(EXPECTED_METRIC_SEPARATOR) if name.strip()]
+ return names[0] if len(names) == 1 else names
+
+
def expectations_for(routing: str, expected_metric: str | None) -> dict[str, Any]:
- if routing == CLARIFY_ROUTING:
+ if routing in CLARIFY_ROUTINGS:
return {"clarification_asked": {}, "canonical_metric_run": {"outcome": "not_called"}}
- if routing == NO_MATCH_ROUTING:
+ if routing in NO_MATCH_ROUTINGS:
return {
"metrics_catalog_before_data_discovery": {},
"canonical_metric_run": {"outcome": "not_called"},
}
- if routing in (CANONICAL_ROUTING, DERIVE_ROUTING):
+ if routing in NEGATIVE_CONTROL_ROUTINGS:
+ return {"metrics_catalog_not_queried": {}, "canonical_metric_run": {"outcome": "not_called"}}
+ if routing in CANONICAL_ROUTINGS:
if not expected_metric:
raise UnknownRouting(f"routing '{routing}' needs an expected_metric")
- expectations: dict[str, Any] = {
+ return {
"metrics_catalog_before_data_discovery": {},
- "canonical_metric_run": {"metric_name": expected_metric, "outcome": "succeeded"},
+ "canonical_metric_run": {"metric_name": _expected_metric_names(expected_metric), "outcome": "succeeded"},
"metric_describe_before_adapted_sql": {},
}
- if routing == DERIVE_ROUTING:
- expectations["proposed_metric_not_run"] = {"metric_name": expected_metric}
- return expectations
raise UnknownRouting(routing)
-class SessionLogClient:
+class CanaryApiClient:
def __init__(self, *, host: str, project_id: int, api_key: str, transport: httpx.BaseTransport | None = None):
+ self.host = host.rstrip("/")
self.project_id = project_id
self._client = httpx.Client(
- base_url=host.rstrip("/"),
+ base_url=self.host,
headers={"Authorization": f"Bearer {api_key}"},
timeout=REQUEST_TIMEOUT_SECONDS,
transport=transport,
)
+ self._log_entries: dict[tuple[str, str], list[dict]] = {}
- def __enter__(self) -> SessionLogClient:
+ def __enter__(self) -> CanaryApiClient:
return self
def __exit__(self, *_exc: object) -> None:
self._client.close()
- def read_full_log(self, task_id: str, run_id: str) -> str:
+ def _get(self, url: str, params: Mapping[str, str | int] | None = None) -> httpx.Response:
+ for attempt in range(MAX_READ_TIMEOUT_RETRIES + 1):
+ try:
+ response = self._client.get(url, params=params)
+ except httpx.ReadTimeout:
+ if attempt == MAX_READ_TIMEOUT_RETRIES:
+ raise
+ continue
+ response.raise_for_status()
+ return response
+ raise AssertionError("unreachable")
+
+ def read_log_entries(self, task_id: str, run_id: str) -> list[dict]:
+ cached = self._log_entries.get((task_id, run_id))
+ if cached is not None:
+ return cached
entries: list[dict] = []
offset = 0
for _page in range(MAX_SESSION_LOG_PAGES):
- response = self._client.get(
+ response = self._get(
f"/api/projects/{self.project_id}/tasks/{task_id}/runs/{run_id}/session_logs/",
params={"limit": SESSION_LOG_PAGE_SIZE, "offset": offset},
)
- response.raise_for_status()
page = response.json()
if not isinstance(page, list):
raise ValueError(f"unexpected session_logs payload for run {run_id}")
@@ -111,31 +238,224 @@ class SessionLogClient:
offset += len(page)
else:
raise ValueError(f"session log for run {run_id} exceeded {MAX_SESSION_LOG_PAGES} pages")
- return "\n".join(json.dumps(entry) for entry in entries)
+ self._log_entries[(task_id, run_id)] = entries
+ return entries
+ def read_full_log(self, task_id: str, run_id: str) -> str:
+ return "\n".join(json.dumps(entry) for entry in self.read_log_entries(task_id, run_id))
-def score_case(case: dict[str, Any], raw_log: str) -> dict[str, Any]:
- routing = case.get("expected_routing") or ""
+ def load_dataset_snapshot(self, dataset_name: str, revision: int) -> DatasetSnapshot:
+ response = self._get(
+ DATASETS_PATH.format(project_id=self.project_id), params=dataset_search_params(dataset_name)
+ )
+ dataset = select_dataset(response.json(), dataset_name)
+ cases: list[CanaryCase] = []
+ seen_case_ids: set[str] = set()
+ offset = 0
+ while True:
+ items_response = self._get(
+ DATASET_ITEMS_PATH.format(project_id=self.project_id),
+ params=dataset_items_params(dataset.id, revision, offset),
+ )
+ page = parse_dataset_item_page(items_response.json(), seen_case_ids)
+ cases.extend(page.cases)
+ if page.next_page is None:
+ return DatasetSnapshot(dataset_id=dataset.id, dataset_name=dataset.name, revision=revision, cases=cases)
+ offset += page.item_count
+
+ def find_tasks(self, question: str, window: BatchWindow) -> list[_TaskSummary]:
+ matches: list[_TaskSummary] = []
+ url: str | None = f"/api/projects/{self.project_id}/tasks/"
+ params: dict[str, str | int] | None = {
+ "origin_product": CANARY_ORIGIN_PRODUCT,
+ "search": question,
+ "ordering": "-created_at",
+ "limit": TASK_LIST_PAGE_SIZE,
+ }
+ while url:
+ response = self._get(url, params=params)
+ page = _TaskPage.model_validate(response.json())
+ matches.extend(
+ task for task in page.results if task.description == question and window.contains(task.created_at)
+ )
+ reached_window_start = any(task.created_at < window.start for task in page.results)
+ url, params = (None, None) if reached_window_start else (page.next, None)
+ return matches
+
+ def list_runs(self, task_id: str) -> list[_TaskRun]:
+ runs: list[_TaskRun] = []
+ url: str | None = f"/api/projects/{self.project_id}/tasks/{task_id}/runs/"
+ params: Mapping[str, str | int] | None = {"limit": TASK_RUN_PAGE_SIZE}
+ while url:
+ page = _TaskRunPage.model_validate(self._get(url, params).json())
+ runs.extend(page.results)
+ url, params = page.next, None
+ return runs
+
+ def task_url(self, task_id: str, run_id: str) -> str:
+ return f"{self.host}/project/{self.project_id}/tasks/{task_id}?runId={run_id}"
+
+
+def _as_stream_payload(entry: dict) -> dict:
+ notification = entry.get("notification")
+ if not isinstance(notification, dict) or notification.get("method") != PERMISSION_REQUEST_METHOD:
+ return entry
+ return {"type": "permission_request", **(notification.get("params") or {})}
+
+
+def _is_agent_activity(entry: dict) -> bool:
+ notification = entry.get("notification")
+ return isinstance(notification, dict) and notification.get("method") == SESSION_UPDATE_METHOD
+
+
+def clarification_questions(entries: Sequence[dict]) -> list[str] | None:
+ for index in reversed(range(len(entries))):
+ try:
+ is_completed_turn(_as_stream_payload(entries[index]))
+ except ClarificationRequested as clarification:
+ if any(_is_agent_activity(entry) for entry in entries[index + 1 :]):
+ return None
+ return clarification.questions
+ except CanaryError:
+ continue
+ return None
+
+
+def _winning_attempts(
+ client: CanaryApiClient, attempts: Sequence[_BatchAttempt]
+) -> list[tuple[_BatchAttempt, list[str]]]:
+ winners: list[tuple[_BatchAttempt, list[str]]] = []
+ for attempt in attempts:
+ if attempt.run.status == COMPLETED_STATUS:
+ winners.append((attempt, []))
+ elif attempt.run.status == CANCELLED_STATUS:
+ questions = clarification_questions(client.read_log_entries(attempt.task_id, attempt.run.id))
+ if questions is not None:
+ winners.append((attempt, questions))
+ return winners
+
+
+def _attempt_fields(client: CanaryApiClient, attempt: _BatchAttempt) -> dict[str, Any]:
+ return {
+ "task_id": attempt.task_id,
+ "task_run_id": attempt.run.id,
+ "task_url": client.task_url(attempt.task_id, attempt.run.id),
+ }
+
+
+def reconstruct_case(client: CanaryApiClient, case: CanaryCase, window: BatchWindow) -> dict[str, Any]:
row: dict[str, Any] = {
+ "case_id": case.case_id,
+ "category": case.category,
+ "expected_metric": case.expected_metric,
+ "expected_routing": case.expected_routing,
+ "question": case.question,
+ "task_id": None,
+ "task_run_id": None,
+ "task_url": None,
+ "clarification_questions": [],
+ }
+ attempts = sorted(
+ (
+ _BatchAttempt(task_id=task.id, run=run)
+ for task in client.find_tasks(case.question, window)
+ for run in client.list_runs(task.id)
+ ),
+ key=lambda attempt: attempt.run.created_at,
+ )
+ if not attempts:
+ return row | {"status": MISSING_STATUS}
+ winners = _winning_attempts(client, attempts)
+ if len(winners) > 1:
+ return row | _attempt_fields(client, winners[-1][0]) | {"status": DUPLICATE_STATUS}
+ if len(winners) == 1:
+ attempt, questions = winners[0]
+ return (
+ row | _attempt_fields(client, attempt) | {"status": COMPLETED_STATUS, "clarification_questions": questions}
+ )
+ still_running = any(attempt.run.status not in TERMINAL_RUN_STATUSES for attempt in attempts)
+ status = INCOMPLETE_STATUS if still_running else FAILED_STATUS
+ return row | _attempt_fields(client, attempts[-1]) | {"status": status}
+
+
+def _reconstruct_case_or_mark_unavailable(
+ client: CanaryApiClient, case: CanaryCase, window: BatchWindow
+) -> dict[str, Any]:
+ try:
+ return reconstruct_case(client, case, window)
+ except (httpx.HTTPError, ValueError) as error:
+ return {
+ "case_id": case.case_id,
+ "category": case.category,
+ "expected_metric": case.expected_metric,
+ "expected_routing": case.expected_routing,
+ "question": case.question,
+ "task_id": None,
+ "task_run_id": None,
+ "task_url": None,
+ "clarification_questions": [],
+ "status": UNAVAILABLE_STATUS,
+ "status_detail": str(error),
+ }
+
+
+def reconstruct_batch(
+ client: CanaryApiClient,
+ *,
+ dataset_name: str,
+ revision: int,
+ window: BatchWindow,
+ case_ids: Sequence[str] = (),
+) -> dict[str, Any]:
+ snapshot = client.load_dataset_snapshot(dataset_name, revision)
+ return {
+ "run_id": window.batch_id,
+ "dataset_revision": snapshot.revision,
+ "cases": [
+ _reconstruct_case_or_mark_unavailable(client, case, window)
+ for case in snapshot.cases
+ if not case_ids or case.case_id in case_ids
+ ],
+ }
+
+
+def _case_row(case: dict[str, Any]) -> dict[str, Any]:
+ return {
"case_id": case.get("case_id"),
"category": case.get("category"),
"expected_metric": case.get("expected_metric"),
- "expected_routing": routing,
+ "expected_routing": case.get("expected_routing") or "",
+ "status": case.get("status"),
"task_id": case.get("task_id"),
"task_run_id": case.get("task_run_id"),
"task_url": case.get("task_url"),
"clarification_questions": case.get("clarification_questions") or [],
}
- if case.get("status") != "completed":
- return row | {"verdict": "unscored", "reason": "run did not reach a confirmed terminal status"}
+
+
+def unscored_case(case: dict[str, Any], reason: str) -> dict[str, Any]:
+ return _case_row(case) | {"verdict": UNSCORED_VERDICT, "reason": reason}
+
+
+def score_case(case: dict[str, Any], raw_log: str) -> dict[str, Any]:
+ routing = case.get("expected_routing") or ""
+ status = case.get("status")
+ row = _case_row(case)
+ if status != COMPLETED_STATUS:
+ detail = case.get("status_detail")
+ reason = f"case status is {status}, not {COMPLETED_STATUS}"
+ return row | {"verdict": UNSCORED_VERDICT, "reason": f"{reason}: {detail}" if detail else reason}
try:
expectations = expectations_for(routing, case.get("expected_metric"))
except UnknownRouting as error:
- return row | {"verdict": "unscored", "reason": f"unrecognized expected_routing: {error}"}
+ return row | {"verdict": UNSCORED_VERDICT, "reason": f"unrecognized expected_routing: {error}"}
output = {"raw_log": raw_log, "prompt": case.get("question", "") or ""}
scores = [scorer.eval(output, expectations) for scorer in CANARY_ROUTING_SCORERS]
checks = {score.name: score.score for score in scores if score.score is not None}
+ unscored_hard = sorted((set(expectations) & HARD_CHECKS) - set(checks))
+ if unscored_hard:
+ return row | {"verdict": UNSCORED_VERDICT, "reason": f"required checks returned no score: {unscored_hard}"}
failed_hard = sorted(name for name, value in checks.items() if name in HARD_CHECKS and value < 1.0)
failed_soft = sorted(name for name, value in checks.items() if name not in HARD_CHECKS and value < 1.0)
return row | {
@@ -147,56 +467,134 @@ def score_case(case: dict[str, Any], raw_log: str) -> dict[str, Any]:
}
-def emit_evaluation_event(*, host: str, capture_token: str, run_id: str, row: dict[str, Any]) -> None:
- if row["verdict"] == "unscored":
- return
- properties = {
+def score_results(
+ client: CanaryApiClient, results: dict[str, Any], case_ids: Sequence[str] = ()
+) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ for case in results["cases"]:
+ if case_ids and case["case_id"] not in case_ids:
+ continue
+ task_id, run_id = case.get("task_id"), case.get("task_run_id")
+ scorable = case.get("status") == COMPLETED_STATUS and task_id and run_id
+ try:
+ raw_log = client.read_full_log(task_id, run_id) if scorable else ""
+ except (httpx.HTTPError, ValueError) as error:
+ rows.append(unscored_case(case, f"session log could not be read: {error}"))
+ continue
+ rows.append(score_case(case, raw_log))
+ return rows
+
+
+def evaluation_event(*, run_id: str, dataset_revision: int | None, row: dict[str, Any]) -> dict[str, Any]:
+ scored = row["verdict"] != UNSCORED_VERDICT
+ properties: dict[str, Any] = {
"$ai_experiment_id": run_id,
- "$ai_experiment_name": "semantic-layer-canary",
+ "$ai_experiment_name": EXPERIMENT_NAME,
"$ai_experiment_item_id": f"{run_id}:{row['case_id']}",
"$ai_experiment_item_name": row["case_id"],
"$ai_metric_name": EVALUATION_METRIC_NAME,
"$ai_metric_version": "1",
"$ai_status": "completed",
"$ai_result_type": "boolean",
- "$ai_reasoning": json.dumps({"failed": row["failed_checks"], "advisory": row["advisory_checks"]}),
"$ai_expected": row["expected_routing"],
- "$ai_score": 1 if row["verdict"] == "pass" else 0,
- "$ai_score_min": 0,
- "$ai_score_max": 1,
- "$ai_evaluation_applicable": True,
+ "$ai_evaluation_applicable": scored,
+ "$ai_reasoning": (
+ json.dumps({"failed": row["failed_checks"], "advisory": row["advisory_checks"]})
+ if scored
+ else row["reason"]
+ ),
+ "batch_id": run_id,
+ "case_status": row["status"],
+ "category": row["category"],
+ "dataset_revision": dataset_revision,
+ "task_id": row["task_id"],
+ "task_run_id": row["task_run_id"],
+ "task_url": row["task_url"],
}
+ if scored:
+ properties |= {"$ai_score": 1 if row["verdict"] == "pass" else 0, "$ai_score_min": 0, "$ai_score_max": 1}
+ return {
+ "event": "$ai_evaluation",
+ "distinct_id": f"{EXPERIMENT_NAME}:{run_id}",
+ "properties": properties,
+ "timestamp": datetime.now(UTC).isoformat(),
+ }
+
+
+def emit_evaluation_event(*, host: str, capture_token: str, event: dict[str, Any]) -> None:
response = httpx.post(
f"{host.replace('us.posthog.com', 'us.i.posthog.com').rstrip('/')}/i/v0/e/",
- json={
- "api_key": capture_token,
- "event": "$ai_evaluation",
- "distinct_id": f"semantic-layer-canary:{run_id}",
- "properties": properties,
- "timestamp": datetime.now(UTC).isoformat(),
- },
+ json=event | {"api_key": capture_token},
timeout=REQUEST_TIMEOUT_SECONDS,
)
response.raise_for_status()
+def summarize(run_id: str, rows: Sequence[dict[str, Any]]) -> dict[str, Any]:
+ scored = [row for row in rows if row["verdict"] != UNSCORED_VERDICT]
+ passed = sum(row["verdict"] == "pass" for row in scored)
+ unscored_by_status: dict[str, int] = {}
+ for row in rows:
+ if row["verdict"] == UNSCORED_VERDICT:
+ unscored_by_status[str(row["status"])] = unscored_by_status.get(str(row["status"]), 0) + 1
+ return {
+ "run_id": run_id,
+ "scored": len(scored),
+ "passed": passed,
+ "failed": len(scored) - passed,
+ "unscored": len(rows) - len(scored),
+ "unscored_by_status": unscored_by_status,
+ }
+
+
def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--results", required=True, help="Runner result JSON, or - for stdin")
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ source = parser.add_mutually_exclusive_group(required=True)
+ source.add_argument("--results", help="Runner result JSON, or - for stdin")
+ source.add_argument(
+ "--batch",
+ nargs=2,
+ metavar=("FROM", "TO"),
+ help="Rebuild the batch from tasks created in this ISO-8601 window instead of a results file",
+ )
+ parser.add_argument("--revision", type=int, help="Dataset revision to score against; required with --batch")
+ parser.add_argument("--dataset-name", default=DEFAULT_DATASET_NAME)
parser.add_argument("--host", default=DEFAULT_HOST)
- parser.add_argument("--project-id", type=int, default=DEFAULT_PROJECT_ID)
+ parser.add_argument(
+ "--project-id",
+ type=int,
+ help=f"Overrides the result file's project_id; defaults to {DEFAULT_PROJECT_ID}",
+ )
parser.add_argument("--case-id", action="append", dest="case_ids", default=[])
- parser.add_argument("--emit", action="store_true", help="Publish an $ai_evaluation event per scored case")
- return parser.parse_args(argv)
+ parser.add_argument("--emit", action="store_true", help="Publish an $ai_evaluation event per case")
+ args = parser.parse_args(argv)
+ args.window = None
+ if args.batch:
+ if args.revision is None:
+ parser.error("--batch requires --revision")
+ try:
+ args.window = BatchWindow(start=parse_batch_moment(args.batch[0]), end=parse_batch_moment(args.batch[1]))
+ except ValidationError as error:
+ parser.error(f"--batch window is invalid: {error}")
+ return args
+
+
+def read_results_file(args: argparse.Namespace) -> dict[str, Any] | None:
+ if args.batch:
+ return None
+ raw_results = sys.stdin.read() if args.results == "-" else Path(args.results).read_text()
+ return json.loads(raw_results)
+
+
+def resolve_project_id(args: argparse.Namespace, results: dict[str, Any] | None) -> int:
+ if args.project_id is not None:
+ return args.project_id
+ recorded = (results or {}).get("project_id")
+ return recorded if isinstance(recorded, int) else DEFAULT_PROJECT_ID
def main(argv: Sequence[str] | None = None) -> int:
args = _parse_args(argv)
- raw_results = sys.stdin.read() if args.results == "-" else open(args.results).read()
- results = json.loads(raw_results)
- run_id = results["run_id"]
- cases = [case for case in results["cases"] if not args.case_ids or case["case_id"] in args.case_ids]
-
api_key = os.environ.get("POSTHOG_API_KEY")
if not api_key:
print("POSTHOG_API_KEY is required", file=sys.stderr)
@@ -206,31 +604,25 @@ def main(argv: Sequence[str] | None = None) -> int:
print("POSTHOG_CAPTURE_TOKEN is required with --emit", file=sys.stderr)
return 2
- rows: list[dict[str, Any]] = []
- with SessionLogClient(host=args.host, project_id=args.project_id, api_key=api_key) as client:
- for case in cases:
- task_id, run = case.get("task_id"), case.get("task_run_id")
- raw_log = client.read_full_log(task_id, run) if task_id and run else ""
- row = score_case(case, raw_log)
- rows.append(row)
- print(json.dumps(row))
- if args.emit and capture_token:
- emit_evaluation_event(host=args.host, capture_token=capture_token, run_id=run_id, row=row)
-
- scored = [row for row in rows if row["verdict"] != "unscored"]
- passed = sum(row["verdict"] == "pass" for row in scored)
- print(
- json.dumps(
- {
- "run_id": run_id,
- "scored": len(scored),
- "passed": passed,
- "failed": len(scored) - passed,
- "unscored": len(rows) - len(scored),
- }
- ),
- file=sys.stderr,
- )
+ results = read_results_file(args)
+ with CanaryApiClient(host=args.host, project_id=resolve_project_id(args, results), api_key=api_key) as client:
+ if results is None:
+ results = reconstruct_batch(
+ client,
+ dataset_name=args.dataset_name,
+ revision=args.revision,
+ window=args.window,
+ case_ids=args.case_ids,
+ )
+ rows = score_results(client, results, args.case_ids)
+
+ run_id = results["run_id"]
+ for row in rows:
+ print(json.dumps(row))
+ if args.emit and capture_token:
+ event = evaluation_event(run_id=run_id, dataset_revision=results.get("dataset_revision"), row=row)
+ emit_evaluation_event(host=args.host, capture_token=capture_token, event=event)
+ print(json.dumps(summarize(run_id, rows)), file=sys.stderr)
return 0
diff --git a/products/data_catalog/scripts/test/test_semantic_layer_canary.py b/products/data_catalog/scripts/test/test_semantic_layer_canary.py
index 2ca5adbf9768..6f70bc8c0011 100644
--- a/products/data_catalog/scripts/test/test_semantic_layer_canary.py
+++ b/products/data_catalog/scripts/test/test_semantic_layer_canary.py
@@ -10,6 +10,7 @@ import httpx
from products.data_catalog.scripts.semantic_layer_canary import (
MAX_CANCEL_ATTEMPTS,
BrowserSessionCredentials,
+ CanaryError,
CanaryRunConfig,
PermanentCanaryError,
PostHogCanaryClient,
@@ -186,6 +187,38 @@ async def test_execute_canary_rejects_dataset_without_enabled_cases() -> None:
await execute_canary(client, CanaryRunConfig())
+ "malformed_path,content,expected_code",
+ [
+ ("/datasets/", b"<html>gateway error</html>", "invalid_dataset_response"),
+ ("/dataset_items/", b"<html>gateway error</html>", "invalid_dataset_item_response"),
+ ("/datasets/", b'{"results": "caf\xe9"}', "invalid_dataset_response"),
+ ],
+ ids=["dataset_page_not_json", "item_page_not_json", "dataset_page_not_utf8"],
+)
+async def test_execute_canary_reports_an_unparseable_dataset_response_as_a_canary_error(
+ malformed_path: str, content: bytes, expected_code: str
+) -> None:
+ async def handler(request: httpx.Request) -> httpx.Response:
+ if request.url.path.endswith(malformed_path):
+ return httpx.Response(200, content=content)
+ if request.url.path.endswith("/datasets/"):
+ return _dataset_response()
+ return _items_response([_dataset_item("ambiguous")])
+
+ async with PostHogCanaryClient(
+ host="https://us.posthog.test",
+ project_id=2,
+ browser_credentials=_browser_credentials(),
+ transport=httpx.MockTransport(handler),
+ ) as client:
+ with pytest.raises(CanaryError) as caught:
+ await execute_canary(client, CanaryRunConfig())
+
+ assert caught.value.code == expected_code
+
+
@pytest.mark.asyncio
async def test_execute_canary_retries_with_new_correlation_ids_without_leaking_content() -> None:
post_payloads: list[dict[str, object]] = []
diff --git a/products/data_catalog/scripts/test/test_semantic_layer_canary_score.py b/products/data_catalog/scripts/test/test_semantic_layer_canary_score.py
index 569bb951144d..14dd61ed8736 100644
--- a/products/data_catalog/scripts/test/test_semantic_layer_canary_score.py
+++ b/products/data_catalog/scripts/test/test_semantic_layer_canary_score.py
@@ -1,17 +1,35 @@
+import re
import json
+from datetime import UTC, datetime
import pytest
import httpx
from products.data_catalog.scripts.semantic_layer_canary_score import (
- SessionLogClient,
+ DEFAULT_PROJECT_ID,
+ BatchWindow,
+ CanaryApiClient,
UnknownRouting,
+ _parse_args,
+ evaluation_event,
expectations_for,
+ reconstruct_batch,
+ resolve_project_id,
score_case,
+ score_results,
)
METRIC = "web_sessions_daily"
+QUESTION = "How many sessions did the site get each day?"
+DATASET_ID = "dataset-1"
+REVISION = 42
+WINDOW = BatchWindow(
+ start=datetime(2026, 9, 10, 16, 54, 23, tzinfo=UTC),
+ end=datetime(2026, 9, 10, 17, 17, 23, tzinfo=UTC),
+)
+INSIDE_WINDOW = "2026-09-10T17:00:00Z"
+BEFORE_WINDOW = "2026-09-10T10:00:00Z"
def _entry(update: dict) -> dict:
@@ -82,16 +100,97 @@ def _case(**overrides: object) -> dict:
"task_id": "task-1",
"task_run_id": "run-1",
"task_url": "https://us.posthog.test/project/2/tasks/task-1?runId=run-1",
- "question": "How many sessions did the site get each day?",
+ "question": QUESTION,
} | overrides
+def _question_permission_request(question: str) -> list[dict]:
+ return [
+ {
+ "timestamp": "2026-09-10T17:01:00.000Z",
+ "notification": {
+ "method": "session/request_permission",
+ "params": {
+ "toolCall": {
+ "toolCallId": "call-q",
+ "_meta": {"codeToolKind": "question", "questions": [{"question": question}]},
+ }
+ },
+ },
+ }
+ ]
+
+
+def _dataset_item(expected_routing: str = "canonical_metric") -> dict:
+ return {
+ "id": "item-1",
+ "input": {"question": QUESTION},
+ "expected_output": {
+ "expected_metric": METRIC,
+ "expected_routing": expected_routing,
+ "expected_behavior": "Run the approved metric and summarize its output.",
+ },
+ "metadata": {"case_id": "web-sessions-daily", "category": "direct_match", "enabled": True},
+ }
+
+
+def _task(task_id: str, *, description: str = QUESTION, created_at: str = INSIDE_WINDOW) -> dict:
+ return {"id": task_id, "description": description, "created_at": created_at, "title": description}
+
+
+def _run(run_id: str, status: str, *, created_at: str = INSIDE_WINDOW) -> dict:
+ return {"id": run_id, "status": status, "created_at": created_at}
+
+
+def _batch_client(
+ *,
+ tasks: list[dict],
+ runs_by_task: dict[str, list[dict]],
+ logs_by_run: dict[str, list[dict]],
+ expected_routing: str = "canonical_metric",
+ unreadable_logs: frozenset[str] = frozenset(),
+) -> CanaryApiClient:
+ def handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ if path.endswith("/datasets/"):
+ return httpx.Response(
+ 200,
+ json={"results": [{"id": DATASET_ID, "name": "semantic-layer-canaries-v1", "current_revision": 7}]},
+ )
+ if path.endswith("/dataset_items/"):
+ assert request.url.params["revision"] == str(REVISION)
+ return httpx.Response(200, json={"next": None, "results": [_dataset_item(expected_routing)]})
+ if path.endswith("/tasks/"):
+ assert request.url.params["origin_product"] == "posthog_ai"
+ return httpx.Response(200, json={"next": None, "results": tasks})
+ runs_match = re.fullmatch(r".*/tasks/([^/]+)/runs/", path)
+ if runs_match:
+ return httpx.Response(200, json={"results": runs_by_task[runs_match.group(1)]})
+ log_match = re.fullmatch(r".*/tasks/[^/]+/runs/([^/]+)/session_logs/", path)
+ assert log_match, path
+ if log_match.group(1) in unreadable_logs:
+ return httpx.Response(500, json={"error": "session log unavailable"})
+ return httpx.Response(200, json=logs_by_run[log_match.group(1)], headers={"X-Has-More": "false"})
+
+ return CanaryApiClient(
+ host="https://us.posthog.test", project_id=2, api_key="key", transport=httpx.MockTransport(handler)
+ )
+
+
+def _score_batch(client: CanaryApiClient) -> tuple[dict, dict]:
+ results = reconstruct_batch(client, dataset_name="semantic-layer-canaries-v1", revision=REVISION, window=WINDOW)
+ rows = score_results(client, results)
+ assert len(rows) == 1
+ return results, rows[0]
+
+
class TestExpectationsForRouting:
@pytest.mark.parametrize(
"routing,expected_keys",
[
- ("clarify", {"clarification_asked", "canonical_metric_run"}),
- ("no_match", {"metrics_catalog_before_data_discovery", "canonical_metric_run"}),
+ ("clarify_before_execution", {"clarification_asked", "canonical_metric_run"}),
+ ("no_approved_match_then_noncanonical", {"metrics_catalog_before_data_discovery", "canonical_metric_run"}),
+ ("schema_discovery_only", {"metrics_catalog_not_queried", "canonical_metric_run"}),
(
"canonical_metric",
{
@@ -101,12 +200,11 @@ class TestExpectationsForRouting:
},
),
(
- "derive_from_approved",
+ "canonical_then_drilldown",
{
"metrics_catalog_before_data_discovery",
"canonical_metric_run",
"metric_describe_before_adapted_sql",
- "proposed_metric_not_run",
},
),
],
@@ -114,6 +212,11 @@ class TestExpectationsForRouting:
def test_known_routings_map_to_their_checks(self, routing: str, expected_keys: set[str]) -> None:
assert set(expectations_for(routing, METRIC)) == expected_keys
+ def test_two_expected_metrics_become_a_list(self) -> None:
+ expectations = expectations_for("canonical_then_drilldown", f"{METRIC} + mrr_monthly")
+
+ assert expectations["canonical_metric_run"]["metric_name"] == [METRIC, "mrr_monthly"]
+
def test_an_unknown_routing_is_rejected_rather_than_guessed(self) -> None:
with pytest.raises(UnknownRouting):
expectations_for("vibes", METRIC)
@@ -149,7 +252,7 @@ class TestScoreCase:
_tool_call("call-2", "AskUserQuestion", {"questions": [{"question": "Which customers?"}]}),
)
- row = score_case(_case(expected_routing="clarify", expected_metric=None), raw_log)
+ row = score_case(_case(expected_routing="clarify_before_execution", expected_metric=None), raw_log)
assert row["verdict"] == "pass"
@@ -160,7 +263,7 @@ class TestScoreCase:
_tool_call("call-3", "AskUserQuestion", {"questions": [{"question": "Which customers?"}]}),
)
- row = score_case(_case(expected_routing="clarify", expected_metric=None), raw_log)
+ row = score_case(_case(expected_routing="clarify_before_execution", expected_metric=None), raw_log)
assert row["verdict"] == "fail"
assert "clarification_asked" in row["failed_checks"]
@@ -174,22 +277,38 @@ class TestScoreCase:
),
)
- row = score_case(_case(expected_routing="clarify", expected_metric=None), raw_log)
+ row = score_case(_case(expected_routing="clarify_before_execution", expected_metric=None), raw_log)
assert row["verdict"] == "fail"
assert "clarification_asked" in row["failed_checks"]
- def test_running_the_proposed_metric_fails_a_derive_case(self) -> None:
+ def test_a_negative_control_that_lists_the_catalog_fails(self) -> None:
raw_log = _log(
_tool_call("call-1", "metric-list", {}),
- _tool_call("call-2", "metric-describe", {"name": METRIC}),
- _tool_call("call-3", "data-catalog-metric-run", {"name": METRIC}),
+ _tool_call("call-2", "read-data-schema", {"query": {"kind": "events"}}),
)
- row = score_case(_case(expected_routing="derive_from_approved"), raw_log)
+ row = score_case(_case(expected_routing="schema_discovery_only", expected_metric=None), raw_log)
assert row["verdict"] == "fail"
- assert row["failed_checks"] == ["proposed_metric_not_run"]
+ assert row["failed_checks"] == ["metrics_catalog_not_queried"]
+
+ @pytest.mark.parametrize(
+ "metrics_run,verdict",
+ [([METRIC], "fail"), ([METRIC, "mrr_monthly"], "pass")],
+ ids=["one_of_two", "both"],
+ )
+ def test_every_expected_metric_must_run(self, metrics_run: list[str], verdict: str) -> None:
+ raw_log = _log(
+ _tool_call("call-1", "metric-list", {}),
+ *(_tool_call(f"run-{name}", "data-catalog-metric-run", {"name": name}) for name in metrics_run),
+ )
+
+ row = score_case(
+ _case(expected_routing="canonical_then_drilldown", expected_metric=f"{METRIC} + mrr_monthly"), raw_log
+ )
+
+ assert row["verdict"] == verdict
def test_adapted_sql_without_describe_is_advisory_only(self) -> None:
raw_log = _log(
@@ -209,8 +328,184 @@ class TestScoreCase:
assert row["verdict"] == "unscored"
assert "failed_checks" not in row
+ def test_a_completed_run_with_an_empty_log_is_not_scored_as_a_pass(self) -> None:
+ row = score_case(_case(), "")
+
+ assert row["verdict"] == "unscored"
+ assert "required checks returned no score" in row["reason"]
+
+
+class TestBatchReconstruction:
+ def test_scores_the_single_completed_run_from_its_full_log(self) -> None:
+ client = _batch_client(
+ tasks=[_task("task-1")],
+ runs_by_task={"task-1": [_run("run-1", "completed")]},
+ logs_by_run={
+ "run-1": _tool_call("call-1", "metric-list", {})
+ + _tool_call("call-2", "data-catalog-metric-run", {"name": METRIC})
+ },
+ )
+
+ results, row = _score_batch(client)
+
+ assert results["run_id"] == "tasks:2026-09-10T16:54:23Z:2026-09-10T17:17:23Z"
+ assert results["dataset_revision"] == REVISION
+ assert row["verdict"] == "pass"
+ assert row["task_url"] == "https://us.posthog.test/project/2/tasks/task-1?runId=run-1"
+
+ @pytest.mark.parametrize(
+ "task",
+ [
+ _task("task-1", description=f"{QUESTION} Please."),
+ _task("task-1", created_at=BEFORE_WINDOW),
+ ],
+ ids=["inexact_description", "outside_window"],
+ )
+ def test_ignores_tasks_that_are_not_an_exact_match_inside_the_window(self, task: dict) -> None:
+ client = _batch_client(tasks=[task], runs_by_task={"task-1": [_run("run-1", "completed")]}, logs_by_run={})
+
+ _results, row = _score_batch(client)
-class TestSessionLogClient:
+ assert row["status"] == "missing"
+ assert row["verdict"] == "unscored"
+ assert row["task_id"] is None
+
+ @pytest.mark.parametrize(
+ "runs,expected_status,expected_run_id",
+ [
+ (
+ [
+ _run("run-1", "failed", created_at="2026-09-10T17:00:00Z"),
+ _run("run-2", "completed", created_at="2026-09-10T17:05:00Z"),
+ ],
+ "completed",
+ "run-2",
+ ),
+ ([_run("run-1", "completed"), _run("run-2", "completed")], "duplicate", "run-2"),
+ (
+ [
+ _run("run-1", "completed", created_at="2026-09-10T17:00:00Z"),
+ _run("run-2", "completed", created_at="2026-09-10T17:05:00Z"),
+ _run("run-3", "failed", created_at="2026-09-10T17:10:00Z"),
+ ],
+ "duplicate",
+ "run-2",
+ ),
+ ([_run("run-1", "in_progress")], "incomplete", "run-1"),
+ ([_run("run-1", "failed")], "failed", "run-1"),
+ ],
+ ids=[
+ "retry_then_completed",
+ "two_completed",
+ "two_completed_then_failed",
+ "still_running",
+ "all_failed",
+ ],
+ )
+ def test_classifies_attempts_by_terminal_status(
+ self, runs: list[dict], expected_status: str, expected_run_id: str
+ ) -> None:
+ client = _batch_client(
+ tasks=[_task("task-1")],
+ runs_by_task={"task-1": runs},
+ logs_by_run={expected_run_id: _tool_call("call-1", "metric-list", {})},
+ )
+
+ _results, row = _score_batch(client)
+
+ assert row["status"] == expected_status
+ assert row["task_run_id"] == expected_run_id
+ assert (row["verdict"] == "unscored") == (expected_status != "completed")
+
+ def test_a_session_log_the_api_will_not_serve_leaves_the_case_unscored(self) -> None:
+ client = _batch_client(
+ tasks=[_task("task-1")],
+ runs_by_task={"task-1": [_run("run-1", "completed")]},
+ logs_by_run={},
+ unreadable_logs=frozenset({"run-1"}),
+ )
+
+ _results, row = _score_batch(client)
+
+ assert row["status"] == "completed"
+ assert row["verdict"] == "unscored"
+ assert "session log could not be read" in row["reason"]
+
+ def test_a_run_cancelled_behind_a_clarifying_question_is_scored_as_a_clarification(self) -> None:
+ client = _batch_client(
+ tasks=[_task("task-1")],
+ runs_by_task={"task-1": [_run("run-1", "cancelled")]},
+ logs_by_run={
+ "run-1": _tool_call("call-1", "metric-list", {})
+ + _tool_call("call-2", "AskUserQuestion", {"questions": [{"question": "Which customers?"}]})
+ + _question_permission_request("Which customers?")
+ },
+ expected_routing="clarify_before_execution",
+ )
+
+ _results, row = _score_batch(client)
+
+ assert row["status"] == "completed"
+ assert row["verdict"] == "pass"
+ assert row["clarification_questions"] == ["Which customers?"]
+
+
+class TestCliArguments:
+ @pytest.mark.parametrize(
+ "argv,results,expected",
+ [
+ (["--results", "run.json"], {"project_id": 77}, 77),
+ (["--results", "run.json"], {}, DEFAULT_PROJECT_ID),
+ (["--results", "run.json", "--project-id", "5"], {"project_id": 77}, 5),
+ ],
+ ids=["from_results", "no_recorded_project", "explicit_override"],
+ )
+ def test_project_id_prefers_an_override_then_the_results_file(
+ self, argv: list[str], results: dict, expected: int
+ ) -> None:
+ assert resolve_project_id(_parse_args(argv), results) == expected
+
+ def test_a_reversed_batch_window_is_rejected(self) -> None:
+ with pytest.raises(SystemExit):
+ _parse_args(["--batch", "2026-09-10T17:17:23Z", "2026-09-10T16:54:23Z", "--revision", "42"])
+
+
+class TestEvaluationEvent:
+ @pytest.mark.parametrize(
+ "row,applicable,score,reasoning",
+ [
+ (
+ {"verdict": "pass", "failed_checks": [], "advisory_checks": []},
+ True,
+ 1,
+ '{"failed": [], "advisory": []}',
+ ),
+ (
+ {"verdict": "unscored", "reason": "case status is missing, not completed"},
+ False,
+ None,
+ "case status is missing, not completed",
+ ),
+ ],
+ ids=["scored", "unscored"],
+ )
+ def test_marks_applicability_and_carries_the_task_link(
+ self, row: dict, applicable: bool, score: int | None, reasoning: str
+ ) -> None:
+ base = _case(status="missing" if row["verdict"] == "unscored" else "completed")
+
+ event = evaluation_event(run_id="tasks:a:b", dataset_revision=REVISION, row=base | row)
+
+ properties = event["properties"]
+ assert properties["$ai_evaluation_applicable"] is applicable
+ assert properties.get("$ai_score") == score
+ assert properties["$ai_reasoning"] == reasoning
+ assert properties["batch_id"] == "tasks:a:b"
+ assert properties["task_url"] == base["task_url"]
+ assert "api_key" not in event
+
+
+class TestCanaryApiClient:
def test_reads_every_page_before_scoring(self) -> None:
pages = [[{"page": 0}, {"page": 1}], [{"page": 2}]]
seen_offsets: list[str | None] = []
@@ -225,7 +520,7 @@ class TestSessionLogClient:
headers={"X-Has-More": "true" if index + 1 < len(pages) else "false"},
)
- with SessionLogClient(
+ with CanaryApiClient(
host="https://us.posthog.test",
project_id=2,
api_key="key",
@@ -235,3 +530,21 @@ class TestSessionLogClient:
assert seen_offsets == ["0", "2"]
assert raw_log.splitlines() == ['{"page": 0}', '{"page": 1}', '{"page": 2}']
+
+ def test_retries_a_page_that_times_out_on_read(self) -> None:
+ attempts = 0
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ raise httpx.ReadTimeout("slow page", request=request)
+ return httpx.Response(200, json=[{"page": 0}], headers={"X-Has-More": "false"})
+
+ with CanaryApiClient(
+ host="https://us.posthog.test", project_id=2, api_key="key", transport=httpx.MockTransport(handler)
+ ) as client:
+ raw_log = client.read_full_log("task-1", "run-1")
+
+ assert attempts == 2
+ assert raw_log == '{"page": 0}'