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): score a canary batch from full session logs (#98335)

Thiago Salvatoredae27480b259
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.md
index 3b9cf6aaea8d..0c097d779668 100644
--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md
+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md
@@ -58,6 +58,13 @@ The agent inside the sandbox gets:
- Access to the **PostHog MCP server** for querying data
- **Code execution** capabilities within the sandbox
+### Run system prompts
+
+The run's `state.systemPrompt` is server-owned. Set it through trusted server-side run creation
+or state updates. The run PATCH endpoint silently ignores attempts to replace, remove, or append
+to this key, including requests from the sandbox itself. The run detail endpoint serves the prompt
+only to the task-bound sandbox, so it can initialize the agent session.
+
## Creating a sandboxed agent
Use `Task.create_and_run()` to launch a sandboxed agent from your product code:
diff --git a/products/data_catalog/evals/scorers.py b/products/data_catalog/evals/scorers.py
index defa95c0ba74..cc22a96112f8 100644
--- a/products/data_catalog/evals/scorers.py
+++ b/products/data_catalog/evals/scorers.py
@@ -41,12 +41,16 @@ __all__ = [
"MetricsCatalogBeforeDataDiscovery",
"MetricsCatalogNotQueried",
"GovernedBehaviorCorrectness",
+ "ClarificationAsked",
+ "ProposedMetricNotRun",
+ "MetricDescribeBeforeAdaptedSql",
]
SQL_TOOL = "execute-sql"
METRIC_LIST_TOOL = "metric-list"
METRIC_DESCRIBE_TOOL = "metric-describe"
METRIC_RUN_TOOL = "data-catalog-metric-run"
+QUESTION_TOOL = "askuserquestion"
CERTIFICATION_PROPOSE_TOOL = "data-catalog-certification-propose"
_INFO_SCHEMA = "information_schema"
_INFO_SYNTHETIC_PREFIX = "__info__:"
@@ -94,6 +98,10 @@ def _successful_catalog_lookups(parser: LogParser) -> list[ToolCall]:
)
+def _is_question_call(call: ToolCall) -> bool:
+ return call.name.replace("_", "").casefold() == QUESTION_TOOL
+
+
def _is_discovery(call: ToolCall) -> bool:
return _INFO_SCHEMA in _query_text(call)
@@ -519,6 +527,95 @@ class MetricsCatalogNotQueried(Scorer):
return Score(name=self._name(), score=0.0 if hits else 1.0, metadata={"catalog_lookups": len(hits)})
+class ClarificationAsked(Scorer):
+ """Binary: did the agent ask a catalog clarifying question before any data-bearing call?"""
+
+ def _name(self) -> str:
+ return "clarification_asked"
+
+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:
+ if not _requested(expected, self._name()):
+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})
+ parser = _parser_for(output)
+ if parser is None:
+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})
+
+ question_positions = [call.position for call in parser.get_tool_calls() if _is_question_call(call)]
+ if not question_positions:
+ return Score(name=self._name(), score=0.0, metadata={"reason": "no clarifying question was asked"})
+
+ first_question = min(question_positions)
+ premature = [
+ {"call_id": call.call_id, "tool": call.name}
+ for call in parser.get_tool_calls()
+ if _is_data_bearing(call) and not call.is_error and call.position <= first_question
+ ]
+ if premature:
+ return Score(
+ name=self._name(),
+ score=0.0,
+ metadata={"reason": "answered from data before asking", "offenders": premature},
+ )
+ return Score(name=self._name(), score=1.0, metadata={"question_position": first_question})
+
+
+class ProposedMetricNotRun(Scorer):
+ """Binary: the named non-approved metric must not have been run for the answer."""
+
+ def _name(self) -> str:
+ return "proposed_metric_not_run"
+
+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:
+ spec = expected.get(self._name()) if isinstance(expected, dict) else None
+ if spec is None:
+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})
+ metric_name = spec.get("metric_name") if isinstance(spec, dict) else None
+ if not isinstance(metric_name, str) or not metric_name:
+ return Score(name=self._name(), score=0.0, metadata={"reason": "metric_name is required"})
+ parser = _parser_for(output)
+ if parser is None:
+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})
+
+ runs = [
+ call
+ for call in parser.get_tool_calls(METRIC_RUN_TOOL)
+ if not call.is_error and call.input.get("name") == metric_name
+ ]
+ return Score(
+ name=self._name(),
+ score=0.0 if runs else 1.0,
+ metadata={"metric_name": metric_name, "runs": len(runs)},
+ )
+
+
+class MetricDescribeBeforeAdaptedSql(Scorer):
+ """Soft: SQL adapted from a catalog definition should follow a `metric-describe`."""
+
+ def _name(self) -> str:
+ return "metric_describe_before_adapted_sql"
+
+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:
+ if not _requested(expected, self._name()):
+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})
+ parser = _parser_for(output)
+ if parser is None:
+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})
+
+ analytical_sql = [call for call in _successful_sql(parser) if not _is_catalog_lookup(call)]
+ if not analytical_sql:
+ return Score(name=self._name(), score=1.0, metadata={"reason": "no adapted SQL"})
+ describe_positions = [call.position for call in parser.get_tool_calls(METRIC_DESCRIBE_TOOL)]
+ if not describe_positions:
+ return Score(name=self._name(), score=0.0, metadata={"reason": "adapted SQL without metric-describe"})
+ first_describe = min(describe_positions)
+ late = [call.call_id for call in analytical_sql if call.position < first_describe]
+ return Score(
+ name=self._name(),
+ score=0.0 if late else 1.0,
+ metadata={"sql_before_describe": late},
+ )
+
+
GOVERNED_BEHAVIOR_PROMPT = """\
You are grading whether an analytics agent honored a project's governed-metrics catalog rules.
@@ -768,3 +865,12 @@ class SemanticTrustDecisionCorrectness(JudgedScorer):
},
"expected": {"expected_behavior": spec["expected_behavior"]},
}
+
+
+CANARY_ROUTING_SCORERS: list[Scorer] = [
+ MetricsCatalogBeforeDataDiscovery(),
+ CanonicalMetricRun(),
+ ClarificationAsked(),
+ ProposedMetricNotRun(),
+ MetricDescribeBeforeAdaptedSql(),
+]
diff --git a/products/data_catalog/scripts/README.md b/products/data_catalog/scripts/README.md
index 3036f92419f1..6b69e1511f8c 100644
--- a/products/data_catalog/scripts/README.md
+++ b/products/data_catalog/scripts/README.md
@@ -82,6 +82,33 @@ The command exits with zero only when every case completes. It exits with one fo
The JSON output contains the run ID, pinned dataset revision, expected routing metadata, duration, status, conversation/trace correlation IDs, task ID, task-run ID, and direct task URLs. Failed attempts retain their task correlation when the open request succeeded. An agent failure starts a fresh attempt with new correlation and task IDs. An open request that fails before it returns a response is different: the retry reuses the same conversation ID, so a task the server created before the failure is resumed instead of duplicated. Stream rotation or a dropped connection resumes the same task run with `Last-Event-ID` and never resends the question.
-A turn completes when the task stream emits `_posthog/turn_complete`, asks a structured clarification question, or reaches a terminal completed state. Other permission requests and terminal failed/cancelled states fail the attempt. PostHog AI tasks remain open briefly for interactive follow-ups after a successful turn; the runner does not cancel them.
+A turn completes when the task stream emits `_posthog/turn_complete`, asks a structured clarification question, or reaches a terminal completed state. Other permission requests and terminal failed/cancelled states fail the attempt. PostHog AI tasks remain open briefly for interactive follow-ups after a successful turn; the runner does not cancel them, with one exception.
+
+A structured clarification question parks a permission request that stays open with no timeout. Anyone or anything that answers it later resumes the agent, and the run then continues past the question the canary was measuring. So the runner records the question text on the case result and cancels that run immediately. Scoring reads `clarification_questions` on the case; an empty list means the agent never asked.
+
+## 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:
+
+```bash
+POSTHOG_API_KEY=phx_... flox activate -- .venv/bin/python \
+ products/data_catalog/scripts/semantic_layer_canary_score.py \
+ --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`.
+
+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 |
+
+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.
+
+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.
Questions, assistant answers, streamed failure content, and exception messages are deliberately excluded from the output. Inspect the task run and its ACP session logs in PostHog to verify metric routing and answer quality. Keep local output under `.context/`, which is gitignored.
diff --git a/products/data_catalog/scripts/semantic_layer_canary.py b/products/data_catalog/scripts/semantic_layer_canary.py
index 173082161d29..f2f0a9b752c0 100644
--- a/products/data_catalog/scripts/semantic_layer_canary.py
+++ b/products/data_catalog/scripts/semantic_layer_canary.py
@@ -26,6 +26,8 @@ DEFAULT_DATASET_NAME = "semantic-layer-canaries-v1"
DEFAULT_MAX_CONCURRENCY = 3
DEFAULT_MAX_ATTEMPTS = 2
MAX_STREAM_RECONNECTS = 8
+MAX_CANCEL_ATTEMPTS = 3
+STOPPED_RUN_STATUSES = frozenset({"cancelled", "failed"})
DEFAULT_TIMEOUT_SECONDS = 1_900.0
DATASET_PAGE_SIZE = 25
BROWSER_HELPER_PATH = Path(__file__).with_name("browser_session_credentials.mjs")
@@ -52,6 +54,12 @@ class PermanentCanaryError(CanaryError):
pass
+class ClarificationRequested(CanaryError):
+ def __init__(self, questions: list[str]) -> None:
+ super().__init__("clarification_requested")
+ self.questions = questions
+
+
class _DatasetSummary(BaseModel):
id: str
name: str
@@ -151,6 +159,7 @@ class CanaryAttemptResult(BaseModel):
task_url: str | None
duration_ms: int
error: str | None = None
+ clarification_questions: list[str] = Field(default_factory=list)
class CanaryCaseResult(BaseModel):
@@ -167,11 +176,12 @@ class CanaryCaseResult(BaseModel):
task_id: str | None
task_run_id: str | None
task_url: str | None
+ clarification_questions: list[str] = Field(default_factory=list)
attempts: list[CanaryAttemptResult]
class CanaryRunResult(BaseModel):
- schema_version: Literal[2] = 2
+ schema_version: Literal[3] = 3
run_id: str
project_id: int
dataset_id: str
@@ -324,7 +334,22 @@ class PostHogCanaryClient:
raise RetryableCanaryError("invalid_open_response")
return opened
- async def wait_for_turn(self, opened: _ConversationOpenResponse) -> None:
+ async def cancel_run(self, opened: _ConversationOpenResponse) -> None:
+ for _attempt in range(MAX_CANCEL_ATTEMPTS):
+ try:
+ response = await self._client.post(
+ f"/api/projects/{self.project_id}/tasks/{opened.task_id}/runs/{opened.run_id}/cancel/",
+ json={"reason": "semantic-layer canary: agent asked a clarifying question"},
+ )
+ except (httpx.TimeoutException, httpx.TransportError):
+ continue
+ if _is_retryable_status(response.status_code):
+ continue
+ _raise_for_api_error(response)
+ return
+ await self._confirm_cancelled(opened)
+
+ async def wait_for_turn(self, opened: _ConversationOpenResponse) -> list[str]:
last_event_id: str | None = None
stream_path = f"/api/projects/{self.project_id}/tasks/{opened.task_id}/runs/{opened.run_id}/stream/"
@@ -338,7 +363,10 @@ class PostHogCanaryClient:
if "text/event-stream" not in response.headers.get("content-type", ""):
raise RetryableCanaryError("invalid_content_type")
await _consume_task_stream(response)
- return
+ return []
+ except ClarificationRequested as clarification:
+ await self.cancel_run(opened)
+ return clarification.questions
except TaskStreamReconnect as reconnect:
if reconnect.last_event_id is not None:
last_event_id = reconnect.last_event_id
@@ -346,14 +374,15 @@ class PostHogCanaryClient:
raise RetryableCanaryError("task_stream_reconnect_exhausted") from reconnect
except TaskStreamEnded:
await self._confirm_terminal_status(opened)
- return
+ return []
except CanaryError:
raise
except (httpx.TimeoutException, httpx.TransportError) as error:
if reconnect_number == MAX_STREAM_RECONNECTS:
raise RetryableCanaryError("task_stream_reconnect_exhausted") from error
+ return []
- async def _confirm_terminal_status(self, opened: _ConversationOpenResponse) -> None:
+ async def _read_run_status(self, opened: _ConversationOpenResponse) -> str:
try:
response = await self._client.get(
f"/api/projects/{self.project_id}/tasks/{opened.task_id}/runs/{opened.run_id}/"
@@ -362,15 +391,22 @@ class PostHogCanaryClient:
raise RetryableCanaryError("transport_error") from error
_raise_for_api_error(response)
try:
- task_run = _TaskRunResponse.model_validate(response.json())
+ return _TaskRunResponse.model_validate(response.json()).status
except (json.JSONDecodeError, ValidationError) as error:
raise RetryableCanaryError("invalid_task_run_response") from error
- if task_run.status == "completed":
+
+ async def _confirm_terminal_status(self, opened: _ConversationOpenResponse) -> None:
+ status = await self._read_run_status(opened)
+ if status == "completed":
return
- if task_run.status in {"failed", "cancelled"}:
- raise RetryableCanaryError(f"task_run_{task_run.status}")
+ if status in STOPPED_RUN_STATUSES:
+ raise RetryableCanaryError(f"task_run_{status}")
raise RetryableCanaryError("missing_turn_completion")
+ async def _confirm_cancelled(self, opened: _ConversationOpenResponse) -> None:
+ if await self._read_run_status(opened) not in STOPPED_RUN_STATUSES:
+ raise RetryableCanaryError("cancel_unconfirmed")
+
def task_url(self, task_id: str, task_run_id: str) -> str:
return f"{self.host}/project/{self.project_id}/tasks/{task_id}?runId={task_run_id}"
@@ -431,8 +467,12 @@ class TaskStreamEnded(CanaryError):
super().__init__("task_stream_ended")
+def _is_retryable_status(status_code: int) -> bool:
+ return status_code == 429 or status_code >= 500
+
+
def _raise_for_api_error(response: httpx.Response) -> None:
- if response.status_code == 429 or response.status_code >= 500:
+ if _is_retryable_status(response.status_code):
raise RetryableCanaryError(f"http_{response.status_code}")
if response.is_error:
raise PermanentCanaryError(f"http_{response.status_code}")
@@ -516,10 +556,18 @@ def _is_completed_turn(payload: dict[str, object]) -> bool:
raise PermanentCanaryError("permission_required")
questions = metadata.get("questions")
if metadata.get("codeToolKind") == "question" and isinstance(questions, list) and questions:
- return True
+ raise ClarificationRequested(_question_texts(questions))
raise PermanentCanaryError("permission_required")
+def _question_texts(questions: list[object]) -> list[str]:
+ texts: list[str] = []
+ for question in questions:
+ text = question.get("question") if isinstance(question, dict) else None
+ texts.append(text if isinstance(text, str) else "")
+ return texts
+
+
async def execute_canary(
client: PostHogCanaryClient,
config: CanaryRunConfig,
@@ -596,7 +644,7 @@ async def _execute_case(
conversation_id=conversation_id,
trace_id=trace_id,
)
- await client.wait_for_turn(opened)
+ clarification_questions = await client.wait_for_turn(opened)
except CanaryError as error:
unconfirmed_conversation_id = conversation_id if opened is None else None
attempts.append(
@@ -626,6 +674,7 @@ async def _execute_case(
task_run_id=opened.run_id,
task_url=client.task_url(opened.task_id, opened.run_id),
duration_ms=_duration_ms(attempt_started_at),
+ clarification_questions=clarification_questions,
)
)
return CanaryCaseResult(
@@ -642,6 +691,7 @@ async def _execute_case(
task_id=opened.task_id,
task_run_id=opened.run_id,
task_url=client.task_url(opened.task_id, opened.run_id),
+ clarification_questions=clarification_questions,
attempts=attempts,
)
diff --git a/products/data_catalog/scripts/semantic_layer_canary_score.py b/products/data_catalog/scripts/semantic_layer_canary_score.py
new file mode 100644
index 000000000000..e22e06f2937e
--- /dev/null
+++ b/products/data_catalog/scripts/semantic_layer_canary_score.py
@@ -0,0 +1,238 @@
+#!/usr/bin/env python3
+# 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.
+
+Usage:
+ python semantic_layer_canary_score.py --results run.json
+ python semantic_layer_canary_score.py --results - --emit
+
+Environment:
+ POSTHOG_API_KEY personal API key with task:read on the target project
+ POSTHOG_CAPTURE_TOKEN project API token, required only with --emit
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+import json
+import argparse
+from collections.abc import Sequence
+from datetime import UTC, datetime
+from typing import Any
+
+import httpx
+
+from products.data_catalog.evals.scorers import CANARY_ROUTING_SCORERS
+
+DEFAULT_HOST = "https://us.posthog.com"
+DEFAULT_PROJECT_ID = 2
+SESSION_LOG_PAGE_SIZE = 5_000
+MAX_SESSION_LOG_PAGES = 200
+REQUEST_TIMEOUT_SECONDS = 120.0
+EVALUATION_METRIC_NAME = "semantic_layer_canary_routing"
+
+CANONICAL_ROUTING = "canonical_metric"
+CLARIFY_ROUTING = "clarify"
+NO_MATCH_ROUTING = "no_match"
+DERIVE_ROUTING = "derive_from_approved"
+
+HARD_CHECKS = frozenset(
+ {
+ "metrics_catalog_before_data_discovery",
+ "canonical_metric_run",
+ "clarification_asked",
+ "proposed_metric_not_run",
+ }
+)
+
+
+class UnknownRouting(ValueError):
+ pass
+
+
+def expectations_for(routing: str, expected_metric: str | None) -> dict[str, Any]:
+ if routing == CLARIFY_ROUTING:
+ return {"clarification_asked": {}, "canonical_metric_run": {"outcome": "not_called"}}
+ if routing == NO_MATCH_ROUTING:
+ return {
+ "metrics_catalog_before_data_discovery": {},
+ "canonical_metric_run": {"outcome": "not_called"},
+ }
+ if routing in (CANONICAL_ROUTING, DERIVE_ROUTING):
+ if not expected_metric:
+ raise UnknownRouting(f"routing '{routing}' needs an expected_metric")
+ expectations: dict[str, Any] = {
+ "metrics_catalog_before_data_discovery": {},
+ "canonical_metric_run": {"metric_name": 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:
+ def __init__(self, *, host: str, project_id: int, api_key: str, transport: httpx.BaseTransport | None = None):
+ self.project_id = project_id
+ self._client = httpx.Client(
+ base_url=host.rstrip("/"),
+ headers={"Authorization": f"Bearer {api_key}"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ transport=transport,
+ )
+
+ def __enter__(self) -> SessionLogClient:
+ return self
+
+ def __exit__(self, *_exc: object) -> None:
+ self._client.close()
+
+ def read_full_log(self, task_id: str, run_id: str) -> str:
+ entries: list[dict] = []
+ offset = 0
+ for _page in range(MAX_SESSION_LOG_PAGES):
+ response = self._client.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}")
+ entries.extend(page)
+ if response.headers.get("X-Has-More") != "true" or not page:
+ break
+ 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)
+
+
+def score_case(case: dict[str, Any], raw_log: str) -> dict[str, Any]:
+ routing = case.get("expected_routing") or ""
+ row: dict[str, Any] = {
+ "case_id": case.get("case_id"),
+ "category": case.get("category"),
+ "expected_metric": case.get("expected_metric"),
+ "expected_routing": routing,
+ "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"}
+ try:
+ expectations = expectations_for(routing, case.get("expected_metric"))
+ except UnknownRouting as error:
+ return row | {"verdict": "unscored", "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}
+ 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 | {
+ "verdict": "fail" if failed_hard else "pass",
+ "checks": checks,
+ "failed_checks": failed_hard,
+ "advisory_checks": failed_soft,
+ "metadata": {score.name: score.metadata for score in scores if score.score is not None},
+ }
+
+
+def emit_evaluation_event(*, host: str, capture_token: str, run_id: str, row: dict[str, Any]) -> None:
+ if row["verdict"] == "unscored":
+ return
+ properties = {
+ "$ai_experiment_id": run_id,
+ "$ai_experiment_name": "semantic-layer-canary",
+ "$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,
+ }
+ 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(),
+ },
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ response.raise_for_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.add_argument("--host", default=DEFAULT_HOST)
+ parser.add_argument("--project-id", type=int, default=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)
+
+
+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)
+ return 2
+ capture_token = os.environ.get("POSTHOG_CAPTURE_TOKEN")
+ if args.emit and not capture_token:
+ 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,
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
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 20aafa394805..2ca5adbf9768 100644
--- a/products/data_catalog/scripts/test/test_semantic_layer_canary.py
+++ b/products/data_catalog/scripts/test/test_semantic_layer_canary.py
@@ -8,6 +8,7 @@ import pytest
import httpx
from products.data_catalog.scripts.semantic_layer_canary import (
+ MAX_CANCEL_ATTEMPTS,
BrowserSessionCredentials,
CanaryRunConfig,
PermanentCanaryError,
@@ -251,7 +252,7 @@ async def test_execute_canary_retries_with_new_correlation_ids_without_leaking_c
assert case_result.attempts[0].task_url == (
"https://us.posthog.test/project/2/tasks/task-failed?runId=task-run-failed"
)
- assert result.schema_version == 2
+ assert result.schema_version == 3
serialized = result.model_dump_json()
assert "Show weekly widget activations" not in serialized
assert "private failure" not in serialized
@@ -370,13 +371,31 @@ async def test_execute_canary_resumes_an_open_stream_without_resending_the_quest
assert [attempt.status for attempt in case_result.attempts] == ["completed"]
+ "cancel_status,run_status,expected_case_status,expected_cancel_attempts",
+ [
+ (200, "cancelled", "completed", 1),
+ (503, "cancelled", "completed", MAX_CANCEL_ATTEMPTS),
+ (429, "cancelled", "completed", MAX_CANCEL_ATTEMPTS),
+ (503, "in_progress", "failed", MAX_CANCEL_ATTEMPTS),
+ ],
+)
@pytest.mark.asyncio
-async def test_execute_canary_accepts_an_agent_clarification_question_as_a_completed_turn() -> None:
+async def test_execute_canary_cancels_the_run_behind_an_agent_clarification_question(
+ cancel_status: int, run_status: str, expected_case_status: str, expected_cancel_attempts: int
+) -> None:
+ cancelled: list[str] = []
+
async def handler(request: httpx.Request) -> httpx.Response:
if request.url.path.endswith("/datasets/"):
return _dataset_response()
if request.url.path.endswith("/dataset_items/"):
return _items_response([_dataset_item("ambiguous", question="How engaged are our workspaces?")])
+ if request.url.path.endswith("/cancel/"):
+ cancelled.append(request.url.path)
+ return httpx.Response(cancel_status, json={"id": "task-run-1", "status": "cancelled"})
+ if request.url.path.endswith("/runs/task-run-1/"):
+ return httpx.Response(200, json={"status": run_status})
if request.method == "POST":
payload = json.loads(request.content)
return _open_response(task_id="task-1", task_run_id="task-run-1", trace_id=str(payload["trace_id"]))
@@ -403,8 +422,13 @@ async def test_execute_canary_accepts_an_agent_clarification_question_as_a_compl
CanaryRunConfig(dataset_name="semantic-layer-canaries-v1", run_id="run-clarification", max_attempts=1),
)
- assert result.status == "completed"
- assert result.cases[0].task_run_id == "task-run-1"
+ assert result.cases[0].status == expected_case_status
+ assert len(cancelled) == expected_cancel_attempts
+ if expected_case_status == "completed":
+ assert result.cases[0].task_run_id == "task-run-1"
+ assert result.cases[0].clarification_questions == ["Which engagement window?"]
+ else:
+ assert result.cases[0].attempts[-1].error == "cancel_unconfirmed"
@pytest.mark.asyncio
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
new file mode 100644
index 000000000000..569bb951144d
--- /dev/null
+++ b/products/data_catalog/scripts/test/test_semantic_layer_canary_score.py
@@ -0,0 +1,237 @@
+import json
+
+import pytest
+
+import httpx
+
+from products.data_catalog.scripts.semantic_layer_canary_score import (
+ SessionLogClient,
+ UnknownRouting,
+ expectations_for,
+ score_case,
+)
+
+METRIC = "web_sessions_daily"
+
+
+def _entry(update: dict) -> dict:
+ return {
+ "timestamp": "2026-09-09T18:52:26.000Z",
+ "notification": {"method": "session/update", "params": {"update": update}},
+ }
+
+
+def _tool_call(call_id: str, tool_name: str, raw_input: dict) -> list[dict]:
+ return [
+ _entry(
+ {
+ "sessionUpdate": "tool_call",
+ "toolCallId": call_id,
+ "_meta": {"claudeCode": {"toolName": tool_name}},
+ "rawInput": raw_input,
+ }
+ ),
+ _entry(
+ {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": call_id,
+ "status": "completed",
+ "rawOutput": "{}",
+ }
+ ),
+ ]
+
+
+def _parallel_tool_calls(*calls: tuple[str, str, dict]) -> list[dict]:
+ opened = [
+ _entry(
+ {
+ "sessionUpdate": "tool_call",
+ "toolCallId": call_id,
+ "_meta": {"claudeCode": {"toolName": tool_name}},
+ "rawInput": raw_input,
+ }
+ )
+ for call_id, tool_name, raw_input in calls
+ ]
+ finished = [
+ _entry(
+ {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": call_id,
+ "status": "completed",
+ "rawOutput": "{}",
+ }
+ )
+ for call_id, _tool_name, _raw_input in calls
+ ]
+ return opened + finished
+
+
+def _log(*entry_groups: list[dict]) -> str:
+ return "\n".join(json.dumps(entry) for group in entry_groups for entry in group)
+
+
+def _case(**overrides: object) -> dict:
+ return {
+ "case_id": "web-sessions-daily",
+ "category": "direct_match",
+ "expected_metric": METRIC,
+ "expected_routing": "canonical_metric",
+ "status": "completed",
+ "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?",
+ } | overrides
+
+
+class TestExpectationsForRouting:
+ @pytest.mark.parametrize(
+ "routing,expected_keys",
+ [
+ ("clarify", {"clarification_asked", "canonical_metric_run"}),
+ ("no_match", {"metrics_catalog_before_data_discovery", "canonical_metric_run"}),
+ (
+ "canonical_metric",
+ {
+ "metrics_catalog_before_data_discovery",
+ "canonical_metric_run",
+ "metric_describe_before_adapted_sql",
+ },
+ ),
+ (
+ "derive_from_approved",
+ {
+ "metrics_catalog_before_data_discovery",
+ "canonical_metric_run",
+ "metric_describe_before_adapted_sql",
+ "proposed_metric_not_run",
+ },
+ ),
+ ],
+ )
+ 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_an_unknown_routing_is_rejected_rather_than_guessed(self) -> None:
+ with pytest.raises(UnknownRouting):
+ expectations_for("vibes", METRIC)
+
+
+class TestScoreCase:
+ def test_catalog_then_canonical_run_passes(self) -> None:
+ raw_log = _log(
+ _tool_call("call-1", "metric-list", {}),
+ _tool_call("call-2", "data-catalog-metric-run", {"name": METRIC}),
+ )
+
+ row = score_case(_case(), raw_log)
+
+ assert row["verdict"] == "pass"
+ assert row["failed_checks"] == []
+
+ def test_schema_discovery_before_the_catalog_fails(self) -> None:
+ raw_log = _log(
+ _tool_call("call-1", "read-data-schema", {"query": {"kind": "events"}}),
+ _tool_call("call-2", "execute-sql", {"query": "select count() from events"}),
+ )
+
+ row = score_case(_case(), raw_log)
+
+ assert row["verdict"] == "fail"
+ assert "metrics_catalog_before_data_discovery" in row["failed_checks"]
+ assert "canonical_metric_run" in row["failed_checks"]
+
+ def test_a_clarifying_question_before_any_data_call_passes(self) -> None:
+ raw_log = _log(
+ _tool_call("call-1", "metric-list", {}),
+ _tool_call("call-2", "AskUserQuestion", {"questions": [{"question": "Which customers?"}]}),
+ )
+
+ row = score_case(_case(expected_routing="clarify", expected_metric=None), raw_log)
+
+ assert row["verdict"] == "pass"
+
+ def test_answering_from_data_instead_of_asking_fails(self) -> None:
+ raw_log = _log(
+ _tool_call("call-1", "metric-list", {}),
+ _tool_call("call-2", "data-catalog-metric-run", {"name": METRIC}),
+ _tool_call("call-3", "AskUserQuestion", {"questions": [{"question": "Which customers?"}]}),
+ )
+
+ row = score_case(_case(expected_routing="clarify", expected_metric=None), raw_log)
+
+ assert row["verdict"] == "fail"
+ assert "clarification_asked" in row["failed_checks"]
+
+ def test_a_data_call_beside_the_question_in_one_message_fails(self) -> None:
+ raw_log = _log(
+ _tool_call("call-1", "metric-list", {}),
+ _parallel_tool_calls(
+ ("call-2", "execute-sql", {"query": "SELECT count() FROM events"}),
+ ("call-3", "AskUserQuestion", {"questions": [{"question": "Which customers?"}]}),
+ ),
+ )
+
+ row = score_case(_case(expected_routing="clarify", 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:
+ 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}),
+ )
+
+ row = score_case(_case(expected_routing="derive_from_approved"), raw_log)
+
+ assert row["verdict"] == "fail"
+ assert row["failed_checks"] == ["proposed_metric_not_run"]
+
+ def test_adapted_sql_without_describe_is_advisory_only(self) -> None:
+ raw_log = _log(
+ _tool_call("call-1", "metric-list", {}),
+ _tool_call("call-2", "data-catalog-metric-run", {"name": METRIC}),
+ _tool_call("call-3", "execute-sql", {"query": "select count() from events"}),
+ )
+
+ row = score_case(_case(), raw_log)
+
+ assert row["verdict"] == "pass"
+ assert row["advisory_checks"] == ["metric_describe_before_adapted_sql"]
+
+ def test_a_run_without_a_confirmed_terminal_status_is_not_scored(self) -> None:
+ row = score_case(_case(status="failed"), "")
+
+ assert row["verdict"] == "unscored"
+ assert "failed_checks" not in row
+
+
+class TestSessionLogClient:
+ def test_reads_every_page_before_scoring(self) -> None:
+ pages = [[{"page": 0}, {"page": 1}], [{"page": 2}]]
+ seen_offsets: list[str | None] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ offset = request.url.params.get("offset")
+ seen_offsets.append(offset)
+ index = int(offset or 0) // 2
+ return httpx.Response(
+ 200,
+ json=pages[index],
+ headers={"X-Has-More": "true" if index + 1 < len(pages) else "false"},
+ )
+
+ with SessionLogClient(
+ 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 seen_offsets == ["0", "2"]
+ assert raw_log.splitlines() == ['{"page": 0}', '{"page": 1}', '{"page": 2}']
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index bbb1af23c8dd..35500c97a2ab 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -2250,6 +2250,7 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(
"sandbox_memory_gb",
"sandbox_ttl_seconds",
"inactivity_timeout_seconds",
+ "systemPrompt",
"wizard_config",
"wizard_head_branch",
"use_modal_directory_resume_snapshots",
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index bbb500692b19..c62466367047 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -5626,6 +5626,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
def test_patch_cannot_mutate_protected_credential_state_keys(self, _mock_publish):
credential_target = self.create_organization_user("credential-target")
task = self.create_task()
+ system_prompt = {"type": "preset", "preset": "claude_code", "append": "Server-owned instructions"}
pending_external_followups = [
{
"message": "server queued message",
@@ -5644,6 +5645,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
status=TaskRun.Status.IN_PROGRESS,
state={
"github_credential_source": "caller_token",
+ "systemPrompt": system_prompt,
"claude_model_access": "own-subscription",
"claude_subscription_user_id": self.user.id,
"pr_authorship_mode": "user",
@@ -5703,6 +5705,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
{
"state": {
"github_credential_source": "server_integration",
+ "systemPrompt": "Caller-controlled instructions",
"claude_model_access": "posthog-gateway",
"claude_subscription_user_id": self.user.id + 1,
"pr_authorship_mode": "bot",
@@ -5814,6 +5817,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
assert run.state["analysis_target_custom_image_id"] == "img-real"
assert run.state["analysis_target_custom_image_name"] == "real-image"
assert run.state["scratch"] == "ok" # non-protected keys still merge
+ assert run.state["systemPrompt"] == system_prompt
# Nor can a caller remove a protected key to force a fallback or unguarded path.
response = self.client.patch(
@@ -5821,6 +5825,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
{
"state": {},
"state_remove_keys": [
+ "systemPrompt",
"claude_model_access",
"claude_subscription_user_id",
"github_credential_source",
@@ -5897,6 +5902,17 @@ class TestTaskRunAPI(BaseTaskAPITest):
assert run.state["analysis_target_custom_image_id"] == "img-real"
assert run.state["analysis_target_custom_image_name"] == "real-image"
assert "scratch" not in run.state # non-protected key removed
+ assert run.state["systemPrompt"] == system_prompt
+
+ response = self.client.patch(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",
+ {"state_append": {"systemPrompt": "Caller-controlled instructions", "scratch": "ok"}},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ run.refresh_from_db()
+ assert run.state["systemPrompt"] == system_prompt
+ assert run.state["scratch"] == ["ok"]
@patch("products.tasks.backend.facade.api.signal_workflow_completion")
def test_update_run_status_to_completed_signals_workflow(self, mock_signal):