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): restore the semantic-layer canary runner (#97596)

Thiago Salvatore95896cefbe7a
diff --git a/.gitignore b/.gitignore
index d9030ae940aa..9b663214defa 100644
--- a/.gitignore
+++ b/.gitignore
@@ -239,3 +239,7 @@ corpora/
.test_durations.*
/context.md
+
+# Agent workspace scratch directory. Holds live browser profiles and run output
+# for local scripts, so it must never reach a commit.
+/.context/
diff --git a/products/data_catalog/docs/production-monitoring.md b/products/data_catalog/docs/production-monitoring.md
index 8e1bd605ebf0..87c2bc7dba85 100644
--- a/products/data_catalog/docs/production-monitoring.md
+++ b/products/data_catalog/docs/production-monitoring.md
@@ -6,6 +6,10 @@ All of this lives in PostHog's internal telemetry project (US project 2), where
The division of labor follows one rule: **the judges decide what a session was trying to do; deterministic code only measures what mechanically happened.** A keyword list can never enumerate every way a person asks a metric question (measured coverage of the tile keywords: ~6.5% of SQL sessions), so any check that starts with "was this a metric question?" belongs to a judge. The tiles keep the keyword heuristic as a cheap trend signal, and the judges measure what it misses.
+## Local semantic-layer canary
+
+The first canary dispatcher is the local [`semantic_layer_canary.py`](../scripts/semantic_layer_canary.py) runner. A local ChatGPT session invokes it on demand against a versioned LLM Analytics dataset through the task-backed Conversations API. It deliberately has no Dagster schedule or event publishing. A separate Signals Scout reads the resulting PostHog AI task runs and ACP session logs to score routing and answer quality. See the [scripts runbook](../scripts/README.md) for the dataset contract, browser authentication, smoke command, and task/run correlation output.
+
## 1. Dashboard tiles (HogQL over existing telemetry)
Tile group `7 · Agent behavior` on the "Data catalog usage" dashboard (project 2, dashboard 1902365):
diff --git a/products/data_catalog/package.json b/products/data_catalog/package.json
index 65818f70acf4..8af6e51b81e3 100644
--- a/products/data_catalog/package.json
+++ b/products/data_catalog/package.json
@@ -1,7 +1,7 @@
{
"name": "@posthog/products-data-catalog",
"scripts": {
- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests scripts/ -v --tb=short"
},
"dependencies": {
"kea": "catalog:",
diff --git a/products/data_catalog/scripts/README.md b/products/data_catalog/scripts/README.md
new file mode 100644
index 000000000000..3036f92419f1
--- /dev/null
+++ b/products/data_catalog/scripts/README.md
@@ -0,0 +1,87 @@
+# Data Catalog scripts
+
+## Semantic-layer canary
+
+`semantic_layer_canary.py` is the local runner for the Data Catalog semantic-layer canary. A local ChatGPT session invokes the script on demand or from its daily workflow. The runner itself does not use Dagster or a server-side scheduler; a separate Signals Scout scores the resulting task runs.
+
+The runner reads a pinned revision of a PostHog LLM Analytics dataset, opens each enabled question through the task-backed PostHog Conversations API, waits for the agent turn to finish, and writes task/run correlation metadata for later inspection. It does not evaluate answers or publish PostHog events.
+
+### Access
+
+The runner authenticates through a dedicated PostHog browser session because the task-backed Conversations endpoint uses web-session authentication. It does not use a personal API key.
+
+Create the reusable browser profile once:
+
+```bash
+flox activate -- .venv/bin/python products/data_catalog/scripts/semantic_layer_canary.py --browser-login
+```
+
+A dedicated Chrome window opens. Sign in to PostHog and leave the window open until the command confirms authentication. The profile is stored at `.context/semantic-layer-canary-browser` by default and is reused by headless runs. That directory holds live session state, so treat it as a credential: keep it inside `.context/`, which the repository ignores, and do not copy it between machines or workspaces. The browser helper returns only the session and CSRF cookies directly to the runner in process memory; they are never included in the command, output, dataset item, or workflow response.
+
+If a run reports `auth_required`, repeat the login command and retry the original run. For an interactive run, `--browser-login-if-needed` can open the login window automatically when the saved session has expired. Do not use that option in an unattended workflow because it waits for a person to complete login.
+
+The defaults target `https://us.posthog.com`, project `2`, and dataset `semantic-layer-canaries-v1`. Override the host or project explicitly when needed.
+
+### Trust boundary
+
+The runner sends each dataset question to an agent that runs with the signed-in operator's own PostHog access, under `initial_permission_mode: auto`, with nobody reviewing tool calls. The dataset is therefore a trusted input, not user input: anyone who can edit the selected revision can direct that agent. Two consequences follow.
+
+- Treat dataset write access to the canary dataset as equivalent to acting as the operator.
+- Pin a reviewed revision with `--revision N` for an unattended run, rather than taking whichever revision is current.
+
+### Dataset contract
+
+Each dataset item must use this shape:
+
+```json
+{
+ "input": {
+ "question": "Show weekly widget activations for the last quarter.",
+ "agent_mode": "product_analytics"
+ },
+ "expected_output": {
+ "expected_metric": "Weekly widget activations",
+ "expected_routing": "canonical_metric",
+ "expected_behavior": "Run the approved metric and summarize its output."
+ },
+ "metadata": {
+ "case_id": "direct-canonical-mrr",
+ "category": "direct_match",
+ "enabled": true
+ }
+}
+```
+
+`agent_mode` accepts `product_analytics` or `sql` as expectation metadata for existing dataset revisions. The task-backed runtime chooses its own tools, so the runner does not send this legacy field to the Conversations API. A negative control can set `expected_metric` to `null`. `case_id` must be unique among the enabled items of the selected revision. Disabled items remain in the versioned dataset but do not run.
+
+### Run from local ChatGPT
+
+Ask ChatGPT to run this command from the PostHog repository:
+
+```bash
+flox activate -- .venv/bin/python products/data_catalog/scripts/semantic_layer_canary.py \
+ --case 01 \
+ --case 21 \
+ --case 38 \
+ --output .context/semantic-layer-canary-smoke.json
+```
+
+Remove the `--case` options to run every enabled item. Use `--revision N` to replay an exact historical dataset revision. The default concurrency is three and the default is one retry per case:
+
+```bash
+flox activate -- .venv/bin/python products/data_catalog/scripts/semantic_layer_canary.py \
+ --revision 7 \
+ --max-concurrency 3 \
+ --max-attempts 2 \
+ --output .context/semantic-layer-canary.json
+```
+
+The command exits with zero only when every case completes. It exits with one for partial runs, failed runs, invalid dataset contents, missing cases, or API/configuration errors.
+
+### Output and inspection
+
+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.
+
+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/browser_session_credentials.mjs b/products/data_catalog/scripts/browser_session_credentials.mjs
new file mode 100644
index 000000000000..f1867147c32b
--- /dev/null
+++ b/products/data_catalog/scripts/browser_session_credentials.mjs
@@ -0,0 +1,64 @@
+import process from 'node:process'
+import { chromium } from 'playwright'
+
+const AUTH_REQUIRED_EXIT = 2
+const DEFAULT_LOGIN_TIMEOUT_SECONDS = 600
+const SESSION_COOKIE_NAME = 'sessionid'
+const CSRF_COOKIE_NAME = 'posthog_csrftoken'
+
+const [mode, host, profilePath, rawTimeoutSeconds] = process.argv.slice(2)
+const timeoutSeconds = Number(rawTimeoutSeconds || DEFAULT_LOGIN_TIMEOUT_SECONDS)
+
+if (!['cookies', 'login'].includes(mode) || !host || !profilePath || !Number.isFinite(timeoutSeconds)) {
+ process.exit(1)
+}
+
+const context = await chromium.launchPersistentContext(profilePath, {
+ channel: 'chrome',
+ headless: mode === 'cookies',
+})
+
+const page = context.pages()[0] ?? (await context.newPage())
+
+async function isAuthenticated() {
+ try {
+ const response = await context.request.get(`${host}/api/users/@me/`)
+ return response.ok()
+ } catch {
+ return false
+ }
+}
+
+async function waitForAuthentication() {
+ const deadline = Date.now() + timeoutSeconds * 1000
+ while (Date.now() < deadline) {
+ if (await isAuthenticated()) {
+ return true
+ }
+ await page.waitForTimeout(1000)
+ }
+ return false
+}
+
+async function credentials() {
+ const cookies = await context.cookies(host)
+ const session = cookies.find((cookie) => cookie.name === SESSION_COOKIE_NAME)?.value
+ const csrf = cookies.find((cookie) => cookie.name === CSRF_COOKIE_NAME)?.value
+ if (!session || !csrf) {
+ return null
+ }
+ return { session_id: session, csrf_token: csrf }
+}
+
+try {
+ await page.goto(host, { waitUntil: 'domcontentloaded' })
+ const authenticated = mode === 'login' ? await waitForAuthentication() : await isAuthenticated()
+ const browserCredentials = authenticated ? await credentials() : null
+ if (!browserCredentials) {
+ process.exitCode = AUTH_REQUIRED_EXIT
+ } else {
+ process.stdout.write(JSON.stringify(browserCredentials))
+ }
+} finally {
+ await context.close()
+}
diff --git a/products/data_catalog/scripts/semantic_layer_canary.py b/products/data_catalog/scripts/semantic_layer_canary.py
new file mode 100644
index 000000000000..173082161d29
--- /dev/null
+++ b/products/data_catalog/scripts/semantic_layer_canary.py
@@ -0,0 +1,756 @@
+#!/usr/bin/env python3
+# ruff: noqa: T201 allow print statements
+"""Run Data Catalog semantic-layer canaries through the PostHog AI API."""
+
+from __future__ import annotations
+
+import sys
+import json
+import time
+import shutil
+import asyncio
+import argparse
+from collections.abc import Callable, Sequence
+from datetime import UTC, datetime
+from pathlib import Path
+from types import TracebackType
+from typing import Literal
+from uuid import UUID, uuid4
+
+import httpx
+from pydantic import BaseModel, ConfigDict, Field, SecretStr, ValidationError
+
+DEFAULT_HOST = "https://us.posthog.com"
+DEFAULT_PROJECT_ID = 2
+DEFAULT_DATASET_NAME = "semantic-layer-canaries-v1"
+DEFAULT_MAX_CONCURRENCY = 3
+DEFAULT_MAX_ATTEMPTS = 2
+MAX_STREAM_RECONNECTS = 8
+DEFAULT_TIMEOUT_SECONDS = 1_900.0
+DATASET_PAGE_SIZE = 25
+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
+
+AgentMode = Literal["product_analytics", "sql"]
+AttemptStatus = Literal["completed", "failed"]
+CaseStatus = Literal["completed", "failed"]
+RunStatus = Literal["completed", "partial", "failed"]
+
+
+class CanaryError(RuntimeError):
+ def __init__(self, code: str) -> None:
+ super().__init__(code)
+ self.code = code
+
+
+class RetryableCanaryError(CanaryError):
+ pass
+
+
+class PermanentCanaryError(CanaryError):
+ pass
+
+
+class _DatasetSummary(BaseModel):
+ id: str
+ name: str
+ current_revision: int | None
+
+
+class _DatasetPage(BaseModel):
+ results: list[_DatasetSummary]
+
+
+class CanaryCaseInput(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ question: str = Field(min_length=1)
+ agent_mode: AgentMode = "product_analytics"
+
+
+class CanaryExpectedOutput(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ expected_metric: str | None
+ expected_routing: str = Field(min_length=1)
+ expected_behavior: str = Field(min_length=1)
+
+
+class CanaryCaseMetadata(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ case_id: str = Field(min_length=1)
+ category: str = Field(min_length=1)
+ enabled: bool
+
+
+class _DatasetItem(BaseModel):
+ id: str
+ input: CanaryCaseInput
+ expected_output: CanaryExpectedOutput
+ metadata: CanaryCaseMetadata
+
+
+class _DatasetItemPage(BaseModel):
+ next: str | None
+ results: list[_DatasetItem]
+
+
+class _ConversationOpenResponse(BaseModel):
+ task_id: str
+ run_id: str
+ trace_id: str | None
+ run_status: str
+ just_created_run: bool
+
+
+class _TaskRunResponse(BaseModel):
+ status: str
+
+
+class CanaryCase(BaseModel):
+ dataset_item_id: str
+ case_id: str
+ category: str
+ question: str
+ agent_mode: AgentMode
+ expected_metric: str | None
+ expected_routing: str
+ expected_behavior: str
+
+
+class DatasetSnapshot(BaseModel):
+ dataset_id: str
+ dataset_name: str
+ revision: int
+ cases: list[CanaryCase]
+
+
+class CanaryRunConfig(BaseModel):
+ dataset_name: str = DEFAULT_DATASET_NAME
+ revision: int | None = Field(default=None, ge=1)
+ run_id: str = Field(default_factory=lambda: str(uuid4()), min_length=1)
+ case_ids: tuple[str, ...] = ()
+ max_concurrency: int = Field(default=DEFAULT_MAX_CONCURRENCY, ge=1)
+ max_attempts: int = Field(default=DEFAULT_MAX_ATTEMPTS, ge=1)
+
+
+class BrowserSessionCredentials(BaseModel):
+ session_id: SecretStr
+ csrf_token: SecretStr
+
+
+class CanaryAttemptResult(BaseModel):
+ attempt: int
+ status: AttemptStatus
+ trace_id: str
+ conversation_id: str
+ task_id: str | None
+ task_run_id: str | None
+ task_url: str | None
+ duration_ms: int
+ error: str | None = None
+
+
+class CanaryCaseResult(BaseModel):
+ case_id: str
+ category: str
+ expected_metric: str | None
+ expected_routing: str
+ expected_behavior: str
+ agent_mode: AgentMode
+ status: CaseStatus
+ duration_ms: int
+ trace_id: str | None
+ conversation_id: str | None
+ task_id: str | None
+ task_run_id: str | None
+ task_url: str | None
+ attempts: list[CanaryAttemptResult]
+
+
+class CanaryRunResult(BaseModel):
+ schema_version: Literal[2] = 2
+ run_id: str
+ project_id: int
+ dataset_id: str
+ dataset_name: str
+ dataset_revision: int
+ started_at: datetime
+ completed_at: datetime
+ status: RunStatus
+ total_cases: int
+ completed_cases: int
+ failed_cases: int
+ cases: list[CanaryCaseResult]
+
+
+class PostHogCanaryClient:
+ def __init__(
+ self,
+ *,
+ host: str,
+ project_id: int,
+ browser_credentials: BrowserSessionCredentials,
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
+ transport: httpx.AsyncBaseTransport | None = None,
+ ) -> None:
+ self.host = host.rstrip("/")
+ self.project_id = project_id
+ csrf_token = browser_credentials.csrf_token.get_secret_value()
+ headers = {
+ "X-CSRFToken": csrf_token,
+ "Origin": self.host,
+ "Referer": f"{self.host}/",
+ }
+ cookies = {
+ "sessionid": browser_credentials.session_id.get_secret_value(),
+ "posthog_csrftoken": csrf_token,
+ }
+ self._client = httpx.AsyncClient(
+ base_url=self.host,
+ headers=headers,
+ cookies=cookies,
+ timeout=httpx.Timeout(timeout_seconds, connect=30.0),
+ transport=transport,
+ follow_redirects=True,
+ )
+
+ async def __aenter__(self) -> PostHogCanaryClient:
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> None:
+ await self._client.aclose()
+
+ 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"},
+ )
+ 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]
+ selected_revision = revision if revision is not None else dataset.current_revision
+ if selected_revision is None:
+ raise PermanentCanaryError("dataset_has_no_revision")
+
+ cases = await self._load_cases(dataset.id, selected_revision)
+ return DatasetSnapshot(
+ dataset_id=dataset.id,
+ dataset_name=dataset.name,
+ revision=selected_revision,
+ cases=cases,
+ )
+
+ async def _load_cases(self, dataset_id: str, revision: int) -> list[CanaryCase]:
+ cases: list[CanaryCase] = []
+ seen_case_ids: set[str] = set()
+ offset = 0
+
+ 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,
+ },
+ )
+ 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:
+ return cases
+ if not page.results:
+ raise PermanentCanaryError("invalid_dataset_pagination")
+ offset += len(page.results)
+
+ async def open_turn(
+ self,
+ *,
+ run_id: str,
+ case: CanaryCase,
+ conversation_id: str,
+ trace_id: str,
+ ) -> _ConversationOpenResponse:
+ try:
+ response = await self._client.post(
+ f"/api/projects/{self.project_id}/conversations/{conversation_id}/open/",
+ headers={"X-POSTHOG-SESSION-ID": f"semantic-canary:{run_id}"},
+ json={
+ "content": case.question,
+ "trace_id": trace_id,
+ "initial_permission_mode": "auto",
+ },
+ )
+ except (httpx.TimeoutException, httpx.TransportError) as error:
+ raise RetryableCanaryError("transport_error") from error
+
+ _raise_for_api_error(response)
+ try:
+ opened = _ConversationOpenResponse.model_validate(response.json())
+ except (json.JSONDecodeError, ValidationError) as error:
+ raise RetryableCanaryError("invalid_open_response") from error
+ if opened.trace_id != trace_id:
+ raise RetryableCanaryError("invalid_open_response")
+ return opened
+
+ async def wait_for_turn(self, opened: _ConversationOpenResponse) -> None:
+ last_event_id: str | None = None
+ stream_path = f"/api/projects/{self.project_id}/tasks/{opened.task_id}/runs/{opened.run_id}/stream/"
+
+ for reconnect_number in range(MAX_STREAM_RECONNECTS + 1):
+ headers = {"Accept": "text/event-stream"}
+ if last_event_id is not None:
+ headers["Last-Event-ID"] = last_event_id
+ try:
+ async with self._client.stream("GET", stream_path, headers=headers) as response:
+ _raise_for_api_error(response)
+ if "text/event-stream" not in response.headers.get("content-type", ""):
+ raise RetryableCanaryError("invalid_content_type")
+ await _consume_task_stream(response)
+ return
+ except TaskStreamReconnect as reconnect:
+ if reconnect.last_event_id is not None:
+ last_event_id = reconnect.last_event_id
+ if reconnect_number == MAX_STREAM_RECONNECTS:
+ raise RetryableCanaryError("task_stream_reconnect_exhausted") from reconnect
+ except TaskStreamEnded:
+ await self._confirm_terminal_status(opened)
+ 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
+
+ async def _confirm_terminal_status(self, opened: _ConversationOpenResponse) -> None:
+ try:
+ response = await self._client.get(
+ f"/api/projects/{self.project_id}/tasks/{opened.task_id}/runs/{opened.run_id}/"
+ )
+ except (httpx.TimeoutException, httpx.TransportError) as error:
+ raise RetryableCanaryError("transport_error") from error
+ _raise_for_api_error(response)
+ try:
+ task_run = _TaskRunResponse.model_validate(response.json())
+ except (json.JSONDecodeError, ValidationError) as error:
+ raise RetryableCanaryError("invalid_task_run_response") from error
+ if task_run.status == "completed":
+ return
+ if task_run.status in {"failed", "cancelled"}:
+ raise RetryableCanaryError(f"task_run_{task_run.status}")
+ raise RetryableCanaryError("missing_turn_completion")
+
+ 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}"
+
+
+def parse_browser_credentials(raw_credentials: str) -> BrowserSessionCredentials:
+ try:
+ credentials = BrowserSessionCredentials.model_validate_json(raw_credentials)
+ except ValidationError as error:
+ raise PermanentCanaryError("auth_required") from error
+ if not credentials.session_id.get_secret_value().strip() or not credentials.csrf_token.get_secret_value().strip():
+ raise PermanentCanaryError("auth_required")
+ return credentials
+
+
+async def load_browser_credentials(
+ *,
+ host: str,
+ profile_path: Path,
+ login: bool,
+ login_timeout_seconds: int,
+) -> BrowserSessionCredentials:
+ node_path = shutil.which("node")
+ if node_path is None:
+ raise PermanentCanaryError("browser_runtime_missing")
+ if not BROWSER_HELPER_PATH.is_file():
+ raise PermanentCanaryError("browser_helper_missing")
+
+ profile_path.mkdir(parents=True, exist_ok=True)
+ process = await asyncio.create_subprocess_exec(
+ node_path,
+ str(BROWSER_HELPER_PATH),
+ "login" if login else "cookies",
+ host,
+ str(profile_path),
+ str(login_timeout_seconds),
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ stdout, _ = await process.communicate()
+ if process.returncode == 2:
+ raise PermanentCanaryError("auth_required")
+ if process.returncode != 0:
+ raise PermanentCanaryError("browser_auth_failed")
+ try:
+ return parse_browser_credentials(stdout.decode())
+ except UnicodeDecodeError as error:
+ raise PermanentCanaryError("browser_auth_failed") from error
+
+
+class TaskStreamReconnect(CanaryError):
+ def __init__(self, last_event_id: str | None) -> None:
+ super().__init__("task_stream_reconnect")
+ self.last_event_id = last_event_id
+
+
+class TaskStreamEnded(CanaryError):
+ def __init__(self) -> None:
+ super().__init__("task_stream_ended")
+
+
+def _raise_for_api_error(response: httpx.Response) -> None:
+ if response.status_code == 429 or response.status_code >= 500:
+ raise RetryableCanaryError(f"http_{response.status_code}")
+ if response.is_error:
+ raise PermanentCanaryError(f"http_{response.status_code}")
+
+
+async def _consume_task_stream(response: httpx.Response) -> None:
+ event_name = "message"
+ event_id: str | None = None
+ last_event_id: str | None = None
+ data_lines: list[str] = []
+
+ def consume_event() -> bool:
+ nonlocal event_name, event_id, last_event_id, data_lines
+ current_event_name = event_name
+ current_data_lines = data_lines
+ if event_id is not None:
+ last_event_id = event_id
+ event_name = "message"
+ event_id = None
+ data_lines = []
+
+ if current_event_name == "end":
+ raise TaskStreamReconnect(last_event_id)
+ if current_event_name == "stream-end":
+ raise TaskStreamEnded
+ if not current_data_lines:
+ return False
+ try:
+ payload = json.loads("\n".join(current_data_lines))
+ except json.JSONDecodeError as error:
+ raise RetryableCanaryError("invalid_sse_json") from error
+ if not isinstance(payload, dict):
+ return False
+ return _is_completed_turn(payload)
+
+ try:
+ async for line in response.aiter_lines():
+ if not line:
+ if consume_event():
+ return
+ continue
+ if line.startswith(":"):
+ continue
+ field, separator, value = line.partition(":")
+ if not separator:
+ continue
+ value = value.removeprefix(" ")
+ if field == "event":
+ event_name = value
+ elif field == "id":
+ event_id = value
+ elif field == "data":
+ data_lines.append(value)
+ except (httpx.TimeoutException, httpx.TransportError) as error:
+ raise TaskStreamReconnect(last_event_id) from error
+
+ if data_lines and consume_event():
+ return
+ raise TaskStreamReconnect(last_event_id)
+
+
+def _is_completed_turn(payload: dict[str, object]) -> bool:
+ payload_type = payload.get("type")
+ if payload_type == "task_run_state":
+ status = payload.get("status")
+ if status == "completed":
+ return True
+ if status in {"failed", "cancelled"}:
+ raise RetryableCanaryError(f"task_run_{status}")
+ return False
+ if payload_type == "notification":
+ notification = payload.get("notification")
+ return isinstance(notification, dict) and notification.get("method") == "_posthog/turn_complete"
+ if payload_type != "permission_request":
+ return False
+ tool_call = payload.get("toolCall")
+ if not isinstance(tool_call, dict):
+ raise PermanentCanaryError("permission_required")
+ metadata = tool_call.get("_meta")
+ if not isinstance(metadata, dict):
+ raise PermanentCanaryError("permission_required")
+ questions = metadata.get("questions")
+ if metadata.get("codeToolKind") == "question" and isinstance(questions, list) and questions:
+ return True
+ raise PermanentCanaryError("permission_required")
+
+
+async def execute_canary(
+ client: PostHogCanaryClient,
+ config: CanaryRunConfig,
+ *,
+ id_factory: Callable[[], UUID] = uuid4,
+) -> CanaryRunResult:
+ started_at = datetime.now(UTC)
+ snapshot = await client.load_dataset_snapshot(config.dataset_name, config.revision)
+ selected_cases = _select_cases(snapshot.cases, config.case_ids)
+ if not selected_cases:
+ raise PermanentCanaryError("no_enabled_cases")
+ semaphore = asyncio.Semaphore(config.max_concurrency)
+
+ async def execute_with_limit(case: CanaryCase) -> CanaryCaseResult:
+ async with semaphore:
+ return await _execute_case(client, config, case, id_factory)
+
+ case_results = await asyncio.gather(*(execute_with_limit(case) for case in selected_cases))
+ completed_cases = sum(result.status == "completed" for result in case_results)
+ failed_cases = len(case_results) - completed_cases
+ if failed_cases == 0:
+ status: RunStatus = "completed"
+ elif completed_cases == 0:
+ status = "failed"
+ else:
+ status = "partial"
+
+ return CanaryRunResult(
+ run_id=config.run_id,
+ project_id=client.project_id,
+ dataset_id=snapshot.dataset_id,
+ dataset_name=snapshot.dataset_name,
+ dataset_revision=snapshot.revision,
+ started_at=started_at,
+ completed_at=datetime.now(UTC),
+ status=status,
+ total_cases=len(case_results),
+ completed_cases=completed_cases,
+ failed_cases=failed_cases,
+ cases=case_results,
+ )
+
+
+def _select_cases(cases: list[CanaryCase], requested_case_ids: tuple[str, ...]) -> list[CanaryCase]:
+ if not requested_case_ids:
+ return cases
+ requested = set(requested_case_ids)
+ selected = [case for case in cases if case.case_id in requested]
+ missing = requested - {case.case_id for case in selected}
+ if missing:
+ raise PermanentCanaryError("case_not_found")
+ return selected
+
+
+async def _execute_case(
+ client: PostHogCanaryClient,
+ config: CanaryRunConfig,
+ case: CanaryCase,
+ id_factory: Callable[[], UUID],
+) -> CanaryCaseResult:
+ started_at = time.monotonic()
+ attempts: list[CanaryAttemptResult] = []
+ unconfirmed_conversation_id: str | None = None
+
+ for attempt_number in range(1, config.max_attempts + 1):
+ conversation_id = unconfirmed_conversation_id or str(id_factory())
+ trace_id = str(id_factory())
+ attempt_started_at = time.monotonic()
+ opened: _ConversationOpenResponse | None = None
+ try:
+ opened = await client.open_turn(
+ run_id=config.run_id,
+ case=case,
+ conversation_id=conversation_id,
+ trace_id=trace_id,
+ )
+ await client.wait_for_turn(opened)
+ except CanaryError as error:
+ unconfirmed_conversation_id = conversation_id if opened is None else None
+ attempts.append(
+ CanaryAttemptResult(
+ attempt=attempt_number,
+ status="failed",
+ trace_id=trace_id,
+ conversation_id=conversation_id,
+ task_id=opened.task_id if opened is not None else None,
+ task_run_id=opened.run_id if opened is not None else None,
+ task_url=client.task_url(opened.task_id, opened.run_id) if opened is not None else None,
+ duration_ms=_duration_ms(attempt_started_at),
+ error=error.code,
+ )
+ )
+ if isinstance(error, PermanentCanaryError):
+ break
+ continue
+
+ attempts.append(
+ CanaryAttemptResult(
+ attempt=attempt_number,
+ status="completed",
+ trace_id=trace_id,
+ conversation_id=conversation_id,
+ task_id=opened.task_id,
+ task_run_id=opened.run_id,
+ task_url=client.task_url(opened.task_id, opened.run_id),
+ duration_ms=_duration_ms(attempt_started_at),
+ )
+ )
+ return CanaryCaseResult(
+ case_id=case.case_id,
+ category=case.category,
+ expected_metric=case.expected_metric,
+ expected_routing=case.expected_routing,
+ expected_behavior=case.expected_behavior,
+ agent_mode=case.agent_mode,
+ status="completed",
+ duration_ms=_duration_ms(started_at),
+ trace_id=trace_id,
+ conversation_id=conversation_id,
+ task_id=opened.task_id,
+ task_run_id=opened.run_id,
+ task_url=client.task_url(opened.task_id, opened.run_id),
+ attempts=attempts,
+ )
+
+ return CanaryCaseResult(
+ case_id=case.case_id,
+ category=case.category,
+ expected_metric=case.expected_metric,
+ expected_routing=case.expected_routing,
+ expected_behavior=case.expected_behavior,
+ agent_mode=case.agent_mode,
+ status="failed",
+ duration_ms=_duration_ms(started_at),
+ trace_id=None,
+ conversation_id=None,
+ task_id=None,
+ task_run_id=None,
+ task_url=None,
+ attempts=attempts,
+ )
+
+
+def _duration_ms(started_at: float) -> int:
+ return max(0, round((time.monotonic() - started_at) * 1_000))
+
+
+def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--host", default=DEFAULT_HOST)
+ parser.add_argument("--project-id", type=int, default=DEFAULT_PROJECT_ID)
+ parser.add_argument("--dataset-name", default=DEFAULT_DATASET_NAME)
+ parser.add_argument("--revision", type=int)
+ parser.add_argument("--run-id", default=str(uuid4()))
+ parser.add_argument("--case", action="append", default=[], dest="case_ids")
+ parser.add_argument("--max-concurrency", type=int, default=DEFAULT_MAX_CONCURRENCY)
+ parser.add_argument("--max-attempts", type=int, default=DEFAULT_MAX_ATTEMPTS)
+ parser.add_argument("--timeout-seconds", type=float, default=DEFAULT_TIMEOUT_SECONDS)
+ parser.add_argument("--output", type=Path)
+ parser.add_argument("--browser-profile", type=Path, default=DEFAULT_BROWSER_PROFILE)
+ parser.add_argument("--browser-login", action="store_true")
+ parser.add_argument("--browser-login-if-needed", action="store_true")
+ parser.add_argument(
+ "--browser-login-timeout-seconds",
+ type=int,
+ default=DEFAULT_BROWSER_LOGIN_TIMEOUT_SECONDS,
+ )
+ return parser.parse_args(argv)
+
+
+async def _run_from_args(args: argparse.Namespace) -> CanaryRunResult:
+ try:
+ browser_credentials = await load_browser_credentials(
+ host=args.host,
+ profile_path=args.browser_profile,
+ login=False,
+ login_timeout_seconds=args.browser_login_timeout_seconds,
+ )
+ except PermanentCanaryError as error:
+ if error.code != "auth_required" or not args.browser_login_if_needed:
+ raise
+ browser_credentials = await load_browser_credentials(
+ host=args.host,
+ profile_path=args.browser_profile,
+ login=True,
+ login_timeout_seconds=args.browser_login_timeout_seconds,
+ )
+ config = CanaryRunConfig(
+ dataset_name=args.dataset_name,
+ revision=args.revision,
+ run_id=args.run_id,
+ case_ids=tuple(args.case_ids),
+ max_concurrency=args.max_concurrency,
+ max_attempts=args.max_attempts,
+ )
+ async with PostHogCanaryClient(
+ host=args.host,
+ project_id=args.project_id,
+ browser_credentials=browser_credentials,
+ timeout_seconds=args.timeout_seconds,
+ ) as client:
+ return await execute_canary(client, config)
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ args = _parse_args(argv)
+ try:
+ if args.browser_login:
+ asyncio.run(
+ load_browser_credentials(
+ host=args.host,
+ profile_path=args.browser_profile,
+ login=True,
+ login_timeout_seconds=args.browser_login_timeout_seconds,
+ )
+ )
+ print(json.dumps({"status": "authenticated", "browser_profile": str(args.browser_profile)}))
+ return 0
+ result = asyncio.run(_run_from_args(args))
+ except (CanaryError, ValidationError, httpx.HTTPError) as error:
+ code = error.code if isinstance(error, CanaryError) else type(error).__name__
+ print(json.dumps({"status": "error", "error": code}), file=sys.stderr)
+ return 1
+
+ output = result.model_dump_json(indent=2)
+ if args.output is not None:
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ args.output.write_text(f"{output}\n")
+ print(output)
+ return 0 if result.status == "completed" else 1
+
+
+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
new file mode 100644
index 000000000000..20aafa394805
--- /dev/null
+++ b/products/data_catalog/scripts/test/test_semantic_layer_canary.py
@@ -0,0 +1,497 @@
+import json
+import asyncio
+from collections.abc import AsyncIterator, Callable
+from uuid import UUID
+
+import pytest
+
+import httpx
+
+from products.data_catalog.scripts.semantic_layer_canary import (
+ BrowserSessionCredentials,
+ CanaryRunConfig,
+ PermanentCanaryError,
+ PostHogCanaryClient,
+ execute_canary,
+ parse_browser_credentials,
+)
+
+DATASET_ID = "11111111-1111-1111-1111-111111111111"
+
+
+def _browser_credentials() -> BrowserSessionCredentials:
+ return BrowserSessionCredentials(session_id="session-secret", csrf_token="csrf-secret")
+
+
+def _dataset_response(*, revision: int = 7) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ json={
+ "count": 1,
+ "next": None,
+ "previous": None,
+ "results": [
+ {
+ "id": DATASET_ID,
+ "name": "semantic-layer-canaries-v1",
+ "current_revision": revision,
+ }
+ ],
+ },
+ )
+
+
+def _dataset_item(
+ case_id: str,
+ *,
+ enabled: bool = True,
+ question: str = "Show weekly widget activations.",
+) -> dict[str, object]:
+ return {
+ "id": f"item-{case_id}",
+ "input": {"question": question},
+ "expected_output": {
+ "expected_metric": "Weekly widget activations",
+ "expected_routing": "canonical_metric",
+ "expected_behavior": "Run the approved metric and summarize its output.",
+ },
+ "metadata": {
+ "case_id": case_id,
+ "category": "direct_match",
+ "enabled": enabled,
+ },
+ }
+
+
+def _items_response(items: list[dict[str, object]]) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ json={"count": len(items), "next": None, "previous": None, "results": items},
+ )
+
+
+def _open_response(*, task_id: str, task_run_id: str, trace_id: str) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ json={
+ "task_id": task_id,
+ "run_id": task_run_id,
+ "trace_id": trace_id,
+ "run_status": "queued",
+ "just_created_run": True,
+ },
+ )
+
+
+def _turn_complete_response() -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text=('id: 1-0\ndata: {"type":"notification","notification":{"method":"_posthog/turn_complete"}}\n\n'),
+ )
+
+
+def _id_factory(values: list[str]) -> Callable[[], UUID]:
+ identifiers = iter(UUID(value) for value in values)
+ return lambda: next(identifiers)
+
+
+class _DisconnectingStream(httpx.AsyncByteStream):
+ async def __aiter__(self) -> AsyncIterator[bytes]:
+ yield b'id: 123-0\ndata: {"type":"keepalive"}\n\n'
+ raise httpx.RemoteProtocolError("stream disconnected")
+
+
+async def test_load_dataset_snapshot_pins_revision_and_excludes_disabled_cases() -> None:
+ async def handler(request: httpx.Request) -> httpx.Response:
+ assert "Authorization" not in request.headers
+ if request.url.path.endswith("/datasets/"):
+ assert request.url.params["search"] == "semantic-layer-canaries-v1"
+ return _dataset_response()
+
+ assert request.url.path.endswith("/dataset_items/")
+ assert request.url.params["dataset"] == DATASET_ID
+ assert request.url.params["revision"] == "7"
+ assert request.url.params["archived"] == "false"
+ return _items_response([_dataset_item("enabled"), _dataset_item("disabled", enabled=False)])
+
+ async with PostHogCanaryClient(
+ host="https://us.posthog.test",
+ project_id=2,
+ browser_credentials=_browser_credentials(),
+ transport=httpx.MockTransport(handler),
+ ) as client:
+ snapshot = await client.load_dataset_snapshot("semantic-layer-canaries-v1")
+
+ assert snapshot.dataset_id == DATASET_ID
+ assert snapshot.revision == 7
+ assert [case.case_id for case in snapshot.cases] == ["enabled"]
+ assert snapshot.cases[0].expected_behavior == "Run the approved metric and summarize its output."
+
+
+async def test_browser_session_auth_sends_cookies_and_csrf_without_authorization_header() -> None:
+ async def handler(request: httpx.Request) -> httpx.Response:
+ assert "Authorization" not in request.headers
+ assert request.headers["X-CSRFToken"] == "csrf-secret"
+ assert request.headers["Origin"] == "https://us.posthog.test"
+ assert request.headers["Referer"] == "https://us.posthog.test/"
+ assert request.headers["Cookie"] == "sessionid=session-secret; posthog_csrftoken=csrf-secret"
+ if request.url.path.endswith("/datasets/"):
+ return _dataset_response()
+ return _items_response([_dataset_item("enabled")])
+
+ async with PostHogCanaryClient(
+ host="https://us.posthog.test",
+ project_id=2,
+ browser_credentials=BrowserSessionCredentials(
+ session_id="session-secret",
+ csrf_token="csrf-secret",
+ ),
+ transport=httpx.MockTransport(handler),
+ ) as client:
+ snapshot = await client.load_dataset_snapshot("semantic-layer-canaries-v1")
+
+ assert [case.case_id for case in snapshot.cases] == ["enabled"]
+
+
+def test_parse_browser_credentials_redacts_secrets_and_rejects_missing_session() -> None:
+ credentials = parse_browser_credentials('{"session_id":"session-secret","csrf_token":"csrf-secret"}')
+
+ assert credentials.session_id.get_secret_value() == "session-secret"
+ assert credentials.csrf_token.get_secret_value() == "csrf-secret"
+ assert "session-secret" not in repr(credentials)
+ assert "csrf-secret" not in repr(credentials)
+
+ with pytest.raises(PermanentCanaryError, match="auth_required"):
+ parse_browser_credentials('{"session_id":"","csrf_token":"csrf-secret"}')
+
+
+async def test_execute_canary_rejects_dataset_without_enabled_cases() -> None:
+ async def handler(request: httpx.Request) -> httpx.Response:
+ if request.url.path.endswith("/datasets/"):
+ return _dataset_response()
+ return _items_response([_dataset_item("disabled", enabled=False)])
+
+ async with PostHogCanaryClient(
+ host="https://us.posthog.test",
+ project_id=2,
+ browser_credentials=_browser_credentials(),
+ transport=httpx.MockTransport(handler),
+ ) as client:
+ with pytest.raises(RuntimeError, match="no_enabled_cases"):
+ await execute_canary(client, CanaryRunConfig())
+
+
+async def test_execute_canary_retries_with_new_correlation_ids_without_leaking_content() -> None:
+ post_payloads: list[dict[str, object]] = []
+ post_paths: list[str] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ if request.method == "GET" and request.url.path.endswith("/datasets/"):
+ return _dataset_response()
+ if request.method == "GET" and request.url.path.endswith("/dataset_items/"):
+ return _items_response([_dataset_item("revenue")])
+ if request.method == "GET" and "/runs/task-run-failed/stream/" in request.url.path:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text=(
+ 'id: 1-0\ndata: {"type":"task_run_state","status":"failed","error_message":"private failure"}\n\n'
+ ),
+ )
+ if request.method == "GET" and "/runs/task-run-completed/stream/" in request.url.path:
+ return _turn_complete_response()
+
+ post_paths.append(request.url.path)
+ post_payloads.append(json.loads(request.content))
+ assert request.headers["X-POSTHOG-SESSION-ID"] == "semantic-canary:run-1"
+ if len(post_payloads) == 1:
+ return _open_response(task_id="task-failed", task_run_id="task-run-failed", trace_id=identifiers[1])
+ return _open_response(task_id="task-completed", task_run_id="task-run-completed", trace_id=identifiers[3])
+
+ identifiers = [
+ "00000000-0000-0000-0000-000000000001",
+ "00000000-0000-0000-0000-000000000002",
+ "00000000-0000-0000-0000-000000000003",
+ "00000000-0000-0000-0000-000000000004",
+ ]
+ async with PostHogCanaryClient(
+ host="https://us.posthog.test",
+ project_id=2,
+ browser_credentials=_browser_credentials(),
+ transport=httpx.MockTransport(handler),
+ ) as client:
+ result = await execute_canary(
+ client,
+ CanaryRunConfig(dataset_name="semantic-layer-canaries-v1", run_id="run-1", max_attempts=2),
+ id_factory=_id_factory(identifiers),
+ )
+
+ assert post_paths == [
+ f"/api/projects/2/conversations/{identifiers[0]}/open/",
+ f"/api/projects/2/conversations/{identifiers[2]}/open/",
+ ]
+ assert post_payloads == [
+ {"content": "Show weekly widget activations.", "trace_id": identifiers[1], "initial_permission_mode": "auto"},
+ {"content": "Show weekly widget activations.", "trace_id": identifiers[3], "initial_permission_mode": "auto"},
+ ]
+ case_result = result.cases[0]
+ assert case_result.status == "completed"
+ assert case_result.trace_id == identifiers[3]
+ assert case_result.conversation_id == identifiers[2]
+ assert case_result.task_id == "task-completed"
+ assert case_result.task_run_id == "task-run-completed"
+ assert case_result.task_url == "https://us.posthog.test/project/2/tasks/task-completed?runId=task-run-completed"
+ assert [attempt.status for attempt in case_result.attempts] == ["failed", "completed"]
+ assert [attempt.task_run_id for attempt in case_result.attempts] == ["task-run-failed", "task-run-completed"]
+ 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
+ serialized = result.model_dump_json()
+ assert "Show weekly widget activations" not in serialized
+ assert "private failure" not in serialized
+
+
+async def test_execute_canary_reuses_the_conversation_after_an_ambiguous_open_failure() -> None:
+ post_paths: list[str] = []
+ post_payloads: list[dict[str, object]] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ if request.method == "GET" and request.url.path.endswith("/datasets/"):
+ return _dataset_response()
+ if request.method == "GET" and request.url.path.endswith("/dataset_items/"):
+ return _items_response([_dataset_item("revenue")])
+ if request.method == "GET" and "/runs/task-run-completed/stream/" in request.url.path:
+ return _turn_complete_response()
+
+ post_paths.append(request.url.path)
+ post_payloads.append(json.loads(request.content))
+ if len(post_paths) == 1:
+ raise httpx.ConnectError("connection reset", request=request)
+ return _open_response(task_id="task-completed", task_run_id="task-run-completed", trace_id=identifiers[2])
+
+ identifiers = [
+ "00000000-0000-0000-0000-000000000001",
+ "00000000-0000-0000-0000-000000000002",
+ "00000000-0000-0000-0000-000000000003",
+ ]
+ async with PostHogCanaryClient(
+ host="https://us.posthog.test",
+ project_id=2,
+ browser_credentials=_browser_credentials(),
+ transport=httpx.MockTransport(handler),
+ ) as client:
+ result = await execute_canary(
+ client,
+ CanaryRunConfig(dataset_name="semantic-layer-canaries-v1", run_id="run-1", max_attempts=2),
+ id_factory=_id_factory(identifiers),
+ )
+
+ assert post_paths == [
+ f"/api/projects/2/conversations/{identifiers[0]}/open/",
+ f"/api/projects/2/conversations/{identifiers[0]}/open/",
+ ]
+ assert [payload["trace_id"] for payload in post_payloads] == [identifiers[1], identifiers[2]]
+ case_result = result.cases[0]
+ assert case_result.status == "completed"
+ assert case_result.conversation_id == identifiers[0]
+ assert case_result.task_id == "task-completed"
+
+
[email protected]("disconnect_kind", ["rotation", "transport"])
+async def test_execute_canary_resumes_an_open_stream_without_resending_the_question(disconnect_kind: str) -> None:
+ post_payloads: list[dict[str, object]] = []
+ stream_requests: list[httpx.Request] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ if request.method == "GET" and request.url.path.endswith("/datasets/"):
+ return _dataset_response()
+ if request.method == "GET" and request.url.path.endswith("/dataset_items/"):
+ return _items_response([_dataset_item("revenue")])
+ if request.method == "GET":
+ stream_requests.append(request)
+ if len(stream_requests) == 1 and disconnect_kind == "transport":
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=_DisconnectingStream(),
+ )
+ if len(stream_requests) == 1:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text='id: 123-0\nevent: end\ndata: {"type":"rotated"}\n\n',
+ )
+ return _turn_complete_response()
+
+ post_payloads.append(json.loads(request.content))
+ return _open_response(task_id="task-1", task_run_id="task-run-1", trace_id=identifiers[1])
+
+ identifiers = [
+ "00000000-0000-0000-0000-000000000001",
+ "00000000-0000-0000-0000-000000000002",
+ "00000000-0000-0000-0000-000000000003",
+ "00000000-0000-0000-0000-000000000004",
+ ]
+ async with PostHogCanaryClient(
+ host="https://us.posthog.test",
+ project_id=2,
+ browser_credentials=_browser_credentials(),
+ transport=httpx.MockTransport(handler),
+ ) as client:
+ result = await execute_canary(
+ client,
+ CanaryRunConfig(dataset_name="semantic-layer-canaries-v1", run_id="run-1", max_attempts=2),
+ id_factory=_id_factory(identifiers),
+ )
+
+ assert post_payloads == [
+ {"content": "Show weekly widget activations.", "trace_id": identifiers[1], "initial_permission_mode": "auto"}
+ ]
+ assert [request.url.path for request in stream_requests] == [
+ "/api/projects/2/tasks/task-1/runs/task-run-1/stream/",
+ "/api/projects/2/tasks/task-1/runs/task-run-1/stream/",
+ ]
+ assert stream_requests[0].headers.get("Last-Event-ID") is None
+ assert stream_requests[1].headers["Last-Event-ID"] == "123-0"
+ case_result = result.cases[0]
+ assert case_result.status == "completed"
+ assert case_result.trace_id == identifiers[1]
+ assert case_result.conversation_id == identifiers[0]
+ assert case_result.task_id == "task-1"
+ assert case_result.task_run_id == "task-run-1"
+ assert [attempt.status for attempt in case_result.attempts] == ["completed"]
+
+
+async def test_execute_canary_accepts_an_agent_clarification_question_as_a_completed_turn() -> None:
+ 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.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"]))
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text=(
+ 'id: 1-0\ndata: {"type":"permission_request","requestId":"request-1",'
+ '"toolCallId":"tool-1","options":[{"optionId":"answer","kind":"allow_once"}],'
+ '"toolCall":{"toolCallId":"tool-1","_meta":{"codeToolKind":"question",'
+ '"questions":[{"question":"Which engagement window?","header":"Window",'
+ '"options":[{"label":"Weekly","description":"Active in the last seven days"}]}]}}}\n\n'
+ ),
+ )
+
+ async with PostHogCanaryClient(
+ host="https://us.posthog.test",
+ project_id=2,
+ browser_credentials=_browser_credentials(),
+ transport=httpx.MockTransport(handler),
+ ) as client:
+ result = await execute_canary(
+ client,
+ 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"
+
+
+async def test_execute_canary_confirms_terminal_run_status_after_stream_end() -> None:
+ 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("revenue")])
+ 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"]))
+ if request.url.path.endswith("/stream/"):
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text='event: stream-end\ndata: {"status":"complete"}\n\n',
+ )
+ return httpx.Response(200, json={"id": "task-run-1", "status": "completed"})
+
+ async with PostHogCanaryClient(
+ host="https://us.posthog.test",
+ project_id=2,
+ browser_credentials=_browser_credentials(),
+ transport=httpx.MockTransport(handler),
+ ) as client:
+ result = await execute_canary(
+ client,
+ CanaryRunConfig(dataset_name="semantic-layer-canaries-v1", run_id="run-terminal", max_attempts=1),
+ )
+
+ assert result.status == "completed"
+
+
+async def test_execute_canary_never_exceeds_configured_concurrency() -> None:
+ active_requests = 0
+ maximum_active_requests = 0
+ post_count = 0
+ first_three_started = asyncio.Event()
+ release_requests = asyncio.Event()
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ nonlocal active_requests, maximum_active_requests, post_count
+ if request.method == "GET" and request.url.path.endswith("/datasets/"):
+ return _dataset_response()
+ if request.method == "GET" and request.url.path.endswith("/dataset_items/"):
+ return _items_response([_dataset_item(f"case-{index}") for index in range(4)])
+
+ if request.method == "POST":
+ post_count += 1
+ payload = json.loads(request.content)
+ return _open_response(
+ task_id=f"task-{post_count}",
+ task_run_id=f"task-run-{post_count}",
+ trace_id=str(payload["trace_id"]),
+ )
+
+ active_requests += 1
+ maximum_active_requests = max(maximum_active_requests, active_requests)
+ if active_requests == 3:
+ first_three_started.set()
+ await release_requests.wait()
+ active_requests -= 1
+ return _turn_complete_response()
+
+ async with PostHogCanaryClient(
+ host="https://us.posthog.test",
+ project_id=2,
+ browser_credentials=_browser_credentials(),
+ transport=httpx.MockTransport(handler),
+ ) as client:
+ run_task = asyncio.create_task(
+ execute_canary(
+ client,
+ CanaryRunConfig(
+ dataset_name="semantic-layer-canaries-v1",
+ run_id="run-2",
+ max_attempts=1,
+ max_concurrency=3,
+ ),
+ )
+ )
+ await asyncio.wait_for(first_three_started.wait(), timeout=1)
+ assert post_count == 3
+ release_requests.set()
+ result = await run_task
+
+ assert maximum_active_requests == 3
+ assert result.completed_cases == 4