Skip to content

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

feat(ai): add SQL-routing and execute-sql lock-in evals (#89122)

Daniel Parkera685cdcd76c3
diff --git a/products/posthog_ai/eval_harness/base.py b/products/posthog_ai/eval_harness/base.py
index cbccf4813e19..ebbcdd582a4b 100644
--- a/products/posthog_ai/eval_harness/base.py
+++ b/products/posthog_ai/eval_harness/base.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import os
import time
import uuid
import asyncio
@@ -7,8 +8,11 @@ import logging
from collections.abc import Sequence
from dataclasses import replace
from functools import partial
+from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
+import orjson
+
from .acp_log import ParsedLog, parse_log
from .config import AgentArtifacts, BaseEvalCase, SandboxedEvalCase
from .engines.base import EvalEngine
@@ -74,6 +78,12 @@ def _log_conversation_spans(hooks: CaseHooks, parsed: ParsedLog) -> None:
else:
display_content = str(content)
+ if role == "assistant" and tool_calls:
+ for tool_call in tool_calls:
+ with hooks.start_span(f"tool_call: {tool_call['tool']}", "function") as span:
+ span.log(input=[tool_call], output=display_content)
+ continue
+
span_type: SpanKind
if role == "assistant":
span_type = "function" if tool_calls else "llm"
@@ -183,7 +193,7 @@ class _BaseEvalRun:
def _case_input(self, case: BaseEvalCase) -> dict[str, Any]:
"""The JSON-safe ``input`` dict a case round-trips through Braintrust as."""
- return {"name": case.name, "prompt": case.prompt}
+ return {"name": case.name, "prompt": case.prompt, "followups": case.followups}
def _build_eval_cases(self) -> list[CaseSpec]:
eval_cases: list[CaseSpec] = []
@@ -299,6 +309,46 @@ class _BaseEvalRun:
error_count = sum(1 for r in result.results if r.error is not None)
await self.ctx.reporter.record_summary(self.experiment_name, result.summary, error_count=error_count)
+ if os.getenv("EXPORT_EVAL_RESULTS"):
+ self._export_case_results(result)
+
+ def _export_case_results(self, result: ExperimentResult) -> None:
+ """Write one JSONL row per case x trial to the run's local log dir.
+
+ The reporter's ``eval_results.jsonl`` carries only per-experiment
+ aggregates, and ``eval_harness/logs/`` case logs overwrite each other
+ across trials — neither supports a paired case-level analysis. The data
+ already lives in ``ExperimentResult.results``; persist it here.
+ ``trial_index`` groups the trials of one case: scores from the same
+ trial index are comparable across runs of the same case set, but a
+ trial index is a repetition counter, not a fixed condition.
+ """
+ rows_by_trial: dict[str, int] = {}
+ rows: list[dict[str, Any]] = []
+ for case_result in result.results:
+ case_name = case_result.input.get("name", "") if isinstance(case_result.input, dict) else ""
+ if not case_name:
+ continue
+ trial_index = rows_by_trial.get(case_name, 0)
+ rows_by_trial[case_name] = trial_index + 1
+ rows.append(
+ {
+ "run_id": self.experiment_id,
+ "experiment": self.experiment_name,
+ "case_name": case_name,
+ "trial_index": trial_index,
+ "scores": case_result.scores,
+ "error": case_result.error,
+ }
+ )
+ path = Path(self.run_log_dir) / "case_results.jsonl"
+ try:
+ with open(path, "wb") as f:
+ for row in rows:
+ f.write(orjson.dumps(row) + b"\n")
+ except OSError:
+ logger.exception("Failed to export per-case results for '%s'", self.experiment_name)
+
async def run(self) -> ExperimentResult:
eval_cases = self._build_eval_cases()
@@ -485,6 +535,8 @@ class _SandboxedEvalRun(_BaseEvalRun):
"last_message": last_message,
"messages": messages,
"raw_log": result.raw_log,
+ "turn_logs": result.turn_logs,
+ "turn_prompts": [eval_case.prompt, *eval_case.followups],
"seed": seed_result,
"prompt": eval_case.prompt,
}
@@ -493,6 +545,7 @@ class _SandboxedEvalRun(_BaseEvalRun):
eval_case = SandboxedEvalCase(
name=input["name"],
prompt=input["prompt"],
+ followups=list(input.get("followups") or []),
repo_fixture=input.get("repo_fixture", ""),
)
original_case = self.cases_by_name.get(input["name"])
diff --git a/products/posthog_ai/eval_harness/config.py b/products/posthog_ai/eval_harness/config.py
index 781382266ab0..6c4176a1d854 100644
--- a/products/posthog_ai/eval_harness/config.py
+++ b/products/posthog_ai/eval_harness/config.py
@@ -21,7 +21,19 @@ class BaseEvalCase(BaseModel):
"""Human-readable name for this eval case."""
prompt: str
- """Natural language task description for the agent or model."""
+ """Natural language task description for the agent or model.
+
+ The first turn of the conversation. Append follow-up user messages via
+ ``followups``."""
+
+ followups: list[str] = Field(default_factory=list)
+ """Follow-up user messages, sent one turn at a time after ``prompt``.
+
+ Empty (the default) runs a single-turn case exactly as before. Non-empty
+ keeps the same agent session alive across ``1 + len(followups)`` turns —
+ for suites that grade how routing or behavior changes over a conversation.
+ Sandboxed cases only; the one-shot runner executes a single model call per
+ case and never reads this field."""
expected: dict[str, Any] = Field(default_factory=dict)
"""Expected values for scoring, keyed by scorer ``_name()``.
diff --git a/products/posthog_ai/eval_harness/harness/cli.py b/products/posthog_ai/eval_harness/harness/cli.py
index 87f453c71a12..ea16227040aa 100644
--- a/products/posthog_ai/eval_harness/harness/cli.py
+++ b/products/posthog_ai/eval_harness/harness/cli.py
@@ -65,6 +65,13 @@ def _default_case_timeout() -> int:
return DEFAULT_CASE_TIMEOUT_SECONDS
+# Multi-turn cases poll once per turn, each poll with its own budget, so a
+# single turn's budget cannot cover a whole conversation. Lifecycle scales the
+# per-case timeout by this factor when a selected module declares multi-turn
+# cases (see discovery.MULTI_TURN_MODULE_MARKER).
+MULTI_TURN_CASE_TIMEOUT_MULTIPLIER = 3
+
+
def _default_team_setup_concurrency() -> int:
if os.getenv("CODER") is not None or os.getenv("CI") is not None:
return MANAGED_TEAM_SETUP_CONCURRENCY
diff --git a/products/posthog_ai/eval_harness/harness/discovery.py b/products/posthog_ai/eval_harness/harness/discovery.py
index 458fde1952c0..91252a007a8f 100644
--- a/products/posthog_ai/eval_harness/harness/discovery.py
+++ b/products/posthog_ai/eval_harness/harness/discovery.py
@@ -28,6 +28,15 @@ class SuiteDiscoveryError(RuntimeError):
pass
+MULTI_TURN_MODULE_MARKER = "MULTI_TURN_CASES"
+"""Module-level marker a suite module sets to declare multi-turn cases.
+
+The marker makes the harness scale the per-case timeout: a multi-turn case
+polls once per turn, each poll with its own budget, so one turn's budget cannot
+cover a whole conversation. ``_collect_suites`` copies the marker onto every
+suite function of the module so lifecycle can read it off the suite."""
+
+
@dataclass(frozen=True)
class EvalSuite:
domain: str
@@ -102,6 +111,7 @@ def _collect_suites(module: ModuleType, domain: str, module_name: str, dotted: s
kind = getattr(module, "SUITE_KIND", SuiteKind.SANDBOXED)
if not isinstance(kind, SuiteKind):
raise SuiteDiscoveryError(f"{dotted}.SUITE_KIND must be a SuiteKind member, got {kind!r}")
+ multi_turn = bool(getattr(module, MULTI_TURN_MODULE_MARKER, False))
collected: list[EvalSuite] = []
for fn_name, fn in vars(module).items():
if not fn_name.startswith("eval_") or not inspect.iscoroutinefunction(fn):
@@ -110,6 +120,9 @@ def _collect_suites(module: ModuleType, domain: str, module_name: str, dotted: s
# module would otherwise be collected twice.
if fn.__module__ != dotted:
continue
+ if multi_turn:
+ # The dataclass is frozen, so carry the marker on the function.
+ setattr(fn, MULTI_TURN_MODULE_MARKER, True)
collected.append(EvalSuite(domain=domain, module_name=module_name, fn_name=fn_name, fn=fn, kind=kind))
return collected
diff --git a/products/posthog_ai/eval_harness/harness/lifecycle.py b/products/posthog_ai/eval_harness/harness/lifecycle.py
index 253e0393e6dc..6fc33adbe22a 100644
--- a/products/posthog_ai/eval_harness/harness/lifecycle.py
+++ b/products/posthog_ai/eval_harness/harness/lifecycle.py
@@ -6,6 +6,7 @@ import asyncio
import logging
from collections.abc import Sequence
from contextlib import AsyncExitStack, ExitStack
+from dataclasses import replace
from unittest.mock import patch
@@ -25,10 +26,10 @@ from products.tasks.backend.temporal.process_task.utils import get_reasoning_eff
from ..engines.base import EvalEngine
from ..engines.registry import resolve_engine
-from .cli import DEFAULT_ONE_SHOT_CONCURRENCY, HarnessOptions
+from .cli import DEFAULT_ONE_SHOT_CONCURRENCY, MULTI_TURN_CASE_TIMEOUT_MULTIPLIER, HarnessOptions
from .context import EvalContext
from .demo_data import SandboxedDemoData, ensure_demo_ready
-from .discovery import EvalSuite, discover_suites
+from .discovery import MULTI_TURN_MODULE_MARKER, EvalSuite, discover_suites
from .django_env import EvalDatabase
from .env_preflight import validate_eval_env
from .kernel_sandboxes import reclaim_kernels
@@ -103,6 +104,22 @@ class SandboxedEvalHarness:
print(f"{suite.id} [{suite.kind.value}]") # noqa: T201
return 0
+ # Multi-turn cases poll once per turn, each poll with its own budget, so
+ # their per-case budget must scale with the turn count. Multi-turn modules
+ # declare the marker at module level (see discovery._collect_suites).
+ multi_turn_modules = {
+ suite.module_name for suite in suites if getattr(suite.fn, MULTI_TURN_MODULE_MARKER, False)
+ }
+ if multi_turn_modules:
+ scaled = self.options.per_case_timeout_seconds * MULTI_TURN_CASE_TIMEOUT_MULTIPLIER
+ logger.warning(
+ "Multi-turn eval module(s) %s selected: scaling --case-timeout from %ds to %ds",
+ sorted(multi_turn_modules),
+ self.options.per_case_timeout_seconds,
+ scaled,
+ )
+ self.options = replace(self.options, per_case_timeout_seconds=scaled)
+
# Boot only what the selected suites' kinds require: a one-shot-only run
# never pays for (or fails on) sandbox infrastructure.
kinds = {suite.kind for suite in suites}
@@ -119,6 +136,7 @@ class SandboxedEvalHarness:
agent_model=self.options.agent_model,
max_sandboxes=self.options.max_sandboxes,
trials=self.options.trials,
+ case_timeout_seconds=self.options.per_case_timeout_seconds,
)
started = time.monotonic()
diff --git a/products/posthog_ai/eval_harness/harness/reporting.py b/products/posthog_ai/eval_harness/harness/reporting.py
index 5751414d5c18..f094d7d59923 100644
--- a/products/posthog_ai/eval_harness/harness/reporting.py
+++ b/products/posthog_ai/eval_harness/harness/reporting.py
@@ -59,6 +59,7 @@ class ProgressReporter:
agent_model: str,
max_sandboxes: int,
trials: int,
+ case_timeout_seconds: int,
) -> None:
lines = [
"Sandboxed eval run",
@@ -67,6 +68,7 @@ class ProgressReporter:
f"Agent: {agent_runtime} / {agent_model}",
f"Sandbox concurrency: {max_sandboxes}",
f"Trials per case: {trials}",
+ f"Case timeout: {case_timeout_seconds}s",
"",
]
_emit("\n".join(lines))
diff --git a/products/posthog_ai/eval_harness/log_parser.py b/products/posthog_ai/eval_harness/log_parser.py
index 57dc0a812ffd..de7063675d0b 100644
--- a/products/posthog_ai/eval_harness/log_parser.py
+++ b/products/posthog_ai/eval_harness/log_parser.py
@@ -22,6 +22,7 @@ from .acp_log import parse_log
SKILL_TOOL_NAME = "Skill"
EXEC_TOOL_NAME = "exec"
+EXECUTE_SQL_TOOL_NAME = "execute-sql"
INFO_SYNTHETIC_PREFIX = "__info__:"
"""Synthetic name assigned when ``exec {command: "info <tool>"}`` is unwrapped.
@@ -103,6 +104,27 @@ class ToolCall(BaseModel):
discovery commands. See ``services/mcp/src/tools/exec.ts`` for the schema."""
+def is_schema_discovery_call(call: ToolCall) -> bool:
+ """True when an ``execute-sql`` call is a catalog lookup rather than an answer query.
+
+ The MCP instructions make catalog lookups mandatory and route them through
+ ``execute-sql`` against ``system.information_schema.*``: table and column
+ discovery (``sections/schema-discovery.md``), the metric catalog
+ (``sections/metric-discovery.md``), and join validation
+ (``sections/catalog-trust-discovery.md``). Those calls land in the same
+ ``execute-sql`` call list as the query that answers the user, so a scorer
+ that grades SQL usage must drop them first, otherwise it grades the
+ instructions the agent was told to follow instead of the route it chose.
+
+ Non-``execute-sql`` calls are never discovery, so callers can apply this to
+ a mixed call list.
+ """
+ if call.name != EXECUTE_SQL_TOOL_NAME:
+ return False
+ query = call.input.get("query")
+ return isinstance(query, str) and "information_schema" in query.lower()
+
+
class SkillCall(BaseModel):
model_config = ConfigDict(frozen=True)
diff --git a/products/posthog_ai/eval_harness/runner.py b/products/posthog_ai/eval_harness/runner.py
index 0b646d693b92..be24c46d640c 100644
--- a/products/posthog_ai/eval_harness/runner.py
+++ b/products/posthog_ai/eval_harness/runner.py
@@ -6,14 +6,19 @@ import time
import uuid
import asyncio
import logging
-from dataclasses import dataclass
from typing import TYPE_CHECKING
from temporalio.client import WorkflowFailureError
+from posthog.dataclasses import frozen
from posthog.temporal.common.client import async_connect
-from products.tasks.backend.facade.agents import CustomPromptSandboxContext, create_task_and_trigger, poll_for_turn
+from products.tasks.backend.facade.agents import (
+ CustomPromptSandboxContext,
+ MultiTurnSession,
+ create_task_and_trigger,
+ poll_for_turn,
+)
from products.tasks.backend.facade.temporal import ProcessTaskWorkflow
from .config import AgentArtifacts, SandboxedEvalCase
@@ -22,6 +27,8 @@ from .harness.providers import SandboxProviderStrategy
if TYPE_CHECKING:
from temporalio.client import WorkflowHandle
+ from products.tasks.backend.models import Task
+
logger = logging.getLogger(__name__)
__all__ = ["run_eval_case"]
@@ -99,11 +106,17 @@ async def _finish_workflow(handle: WorkflowHandle, *, status: str, reason: str |
return await _wait_for_workflow_terminal(handle, WORKFLOW_CANCELLATION_GRACE_SECONDS)
-@dataclass
+@frozen
class EvalCaseResult:
artifacts: AgentArtifacts
trace_id: str = ""
raw_log: str = ""
+ turn_logs: list[str] | None = None
+ """One cumulative-log slice per completed turn, when the case ran multi-turn.
+
+ Slice ``i`` covers turn ``i + 1`` — that turn's prompt, tool calls, and
+ ``end_turn``. ``None`` for single-turn cases and for any case whose log
+ lines could not be split (malformed lines); scorers self-skip on it."""
async def run_eval_case(
@@ -122,38 +135,34 @@ async def run_eval_case(
trace_id = str(uuid.uuid4())
logger.info("Starting eval case '%s' (trace=%s) with prompt: %.100s...", case.name, trace_id, case.prompt)
start = time.monotonic()
- task = None
- handle: WorkflowHandle | None = None
+ # The helpers mutate this in place as they provision, so the except/finally
+ # blocks can finish the workflow and clean up the task even when a turn
+ # raises before the helpers return.
+ state = _CaseRunState()
completion_task: asyncio.Task[bool] | None = None
try:
# Eval is a test harness — direct use of internals (instead of MTS) is intentional:
# the agent isn't asked for structured JSON, and we need full_log for artifact parsing.
- task, task_run = await create_task_and_trigger(case.prompt, context, step_name=case.name)
+ if case.followups:
+ full_log, turn_logs = await _run_multi_turn_case(case, context, state)
+ else:
+ full_log, turn_logs = await _run_single_turn_case(case, context, state)
+ # Both helpers set task and handle before their first poll, so a clean
+ # return guarantees they are populated.
+ assert state.task is not None and state.handle is not None
# Register the task so the end-of-run sweep stays scoped to this run's sandboxes.
- provider.register_task(str(task.id))
- # Handle to the case's workflow so a timeout/error can shut the agent down.
- workflow_id = task_run.get_workflow_id(task.id, task_run.id)
- client = await async_connect()
- handle = client.get_workflow_handle(workflow_id)
- turn = await poll_for_turn(task_run, verbose=True, output_fn=lambda msg: logger.info("agent: %s", msg))
- full_log = turn.full_log or ""
+ provider.register_task(str(state.task.id))
duration = time.monotonic() - start
- logger.info(
- "Eval case '%s' completed in %.1fs, log size=%d, last_message=%.200s",
- case.name,
- duration,
- len(full_log),
- turn.last_message or "(none)",
- )
+ logger.info("Eval case '%s' completed in %.1fs, log size=%d", case.name, duration, len(full_log))
artifacts = _parse_artifacts_from_log(full_log, duration, agent_finished=True)
- completion_task = asyncio.create_task(_finish_workflow(handle, status="completed", reason=None))
+ completion_task = asyncio.create_task(_finish_workflow(state.handle, status="completed", reason=None))
cleanup_confirmed = await asyncio.shield(completion_task)
if not cleanup_confirmed:
raise WorkflowCleanupError(
f"Eval case '{case.name}' finished, but its workflow cleanup could not be confirmed"
)
- return EvalCaseResult(artifacts=artifacts, trace_id=trace_id, raw_log=full_log)
+ return EvalCaseResult(artifacts=artifacts, trace_id=trace_id, raw_log=full_log, turn_logs=turn_logs)
except (Exception, asyncio.CancelledError) as e:
# CancelledError is how the caller's asyncio.wait_for timeout reaches this
# coroutine; catch it explicitly so we can stop the workflow, then re-raise.
@@ -165,19 +174,106 @@ async def run_eval_case(
# already running. Let that bounded task settle instead of sending a
# conflicting failed completion signal.
cleanup_confirmed = await asyncio.shield(completion_task)
- elif handle is not None and not isinstance(e, WorkflowCleanupError):
+ elif state.handle is not None and not isinstance(e, WorkflowCleanupError):
cleanup_confirmed = await asyncio.shield(
- _finish_workflow(handle, status="failed", reason=f"eval case '{case.name}' failed: {e}")
+ _finish_workflow(state.handle, status="failed", reason=f"eval case '{case.name}' failed: {e}")
)
- if handle is not None and not cleanup_confirmed:
+ if state.handle is not None and not cleanup_confirmed:
logger.warning("Eval workflow cleanup could not be confirmed for case '%s'", case.name)
raise
finally:
- if task is not None:
+ if state.task is not None:
try:
- await asyncio.to_thread(provider.cleanup_case, str(task.id))
+ await asyncio.to_thread(provider.cleanup_case, str(state.task.id))
except Exception:
- logger.warning("Provider cleanup failed for eval task %s", task.id, exc_info=True)
+ logger.warning("Provider cleanup failed for eval task %s", state.task.id, exc_info=True)
+
+
+@frozen(frozen=False)
+class _CaseRunState:
+ """Provisioning state a turn helper fills in before it can raise.
+
+ ``run_eval_case`` owns this and reads it in its cleanup paths, so a turn
+ that raises mid-poll still has its task and workflow handle reachable for
+ the failure signal and provider sweep.
+ """
+
+ task: Task | None = None
+ handle: WorkflowHandle | None = None
+
+
+async def _run_single_turn_case(
+ case: SandboxedEvalCase, context: CustomPromptSandboxContext, state: _CaseRunState
+) -> tuple[str, list[str] | None]:
+ """The historical one-prompt path: create, poll once, return the full log."""
+ task, task_run = await create_task_and_trigger(case.prompt, context, step_name=case.name)
+ state.task = task
+ # Handle to the case's workflow so a timeout/error can shut the agent down.
+ workflow_id = task_run.get_workflow_id(task.id, task_run.id)
+ client = await async_connect()
+ state.handle = client.get_workflow_handle(workflow_id)
+ turn = await poll_for_turn(task_run, verbose=True, output_fn=lambda msg: logger.info("agent: %s", msg))
+ logger.info("Eval case '%s' turn 1/1: last_message=%.200s", case.name, turn.last_message or "(none)")
+ return turn.full_log or "", None
+
+
+async def _run_multi_turn_case(
+ case: SandboxedEvalCase, context: CustomPromptSandboxContext, state: _CaseRunState
+) -> tuple[str, list[str] | None]:
+ """Run ``case.prompt`` plus every follow-up in one agent session.
+
+ ``session.end()`` only signals completion, so the caller still finishes the
+ workflow through ``_finish_workflow`` like any other case.
+ """
+ session, _ = await MultiTurnSession.start_raw(
+ prompt=case.prompt,
+ context=context,
+ step_name=case.name,
+ verbose=True,
+ output_fn=lambda msg: logger.info("agent: %s", msg),
+ )
+ state.task = session.task
+ state.handle = session.workflow_handle
+ # One entry per completed turn: the line count of the cumulative log at that
+ # turn's end. Turn 1 starts at line 0; turn i's lines sit between marks[i-1]
+ # and marks[i].
+ line_marks = [session.log_lines_seen]
+ for followup in case.followups:
+ await session.send_followup_raw(followup, label=f"{case.name} followup")
+ line_marks.append(session.log_lines_seen)
+ return session.last_full_log, _slice_turn_logs(session.last_full_log, line_marks)
+
+
+def _slice_turn_logs(full_log: str, line_marks: list[int]) -> list[str] | None:
+ """Split a cumulative JSONL session log into one slice per turn.
+
+ ``line_marks[i]`` is the total line count when turn ``i + 1`` ended, so turn
+ ``i + 1``'s slice is the lines between ``marks[i - 1]`` and ``marks[i]``
+ (turn 1 starts at line 0). The session log cursor counts only non-blank,
+ JSON-parseable lines, so a file that splits differently would produce wrong
+ slices; return ``None`` and let turn scorers skip rather than grade a
+ misaligned slice.
+ """
+ lines: list[str] = []
+ for raw_line in full_log.strip().split("\n"):
+ line = raw_line.strip()
+ if not line:
+ continue
+ try:
+ json.loads(line)
+ except json.JSONDecodeError:
+ logger.warning("Multi-turn eval log holds a malformed line; turn slicing unavailable")
+ return None
+ lines.append(line)
+ if not line_marks or line_marks[-1] > len(lines):
+ logger.warning(
+ "Multi-turn eval log line marks (%s) exceed the parsed line count (%d); turn slicing unavailable",
+ line_marks,
+ len(lines),
+ )
+ return None
+ bounds = [0, *line_marks]
+ return ["\n".join(lines[bounds[i] : bounds[i + 1]]) for i in range(len(line_marks))]
def _parse_artifacts_from_log(log_content: str, duration_seconds: float, agent_finished: bool) -> AgentArtifacts:
diff --git a/products/posthog_ai/eval_harness/scorers/__init__.py b/products/posthog_ai/eval_harness/scorers/__init__.py
index 6e3f4efa7b3c..c90cd7a653e6 100644
--- a/products/posthog_ai/eval_harness/scorers/__init__.py
+++ b/products/posthog_ai/eval_harness/scorers/__init__.py
@@ -1,6 +1,6 @@
from products.posthog_ai.eval_harness.log_parser import LogParser, normalize_tool_name
-from .deterministic import ExitCodeZero, LastToolCallNot, NoToolCall, RequiredToolCall
+from .deterministic import AnswerToolCallNot, ExitCodeZero, NoToolCall, RequiredToolCall
from .judged import (
BINARY_CHOICE_SCORES,
GRADED_ALIGNMENT_CHOICE_SCORES,
@@ -14,10 +14,10 @@ __all__ = [
"BINARY_CHOICE_SCORES",
"GRADED_ALIGNMENT_CHOICE_SCORES",
"JUDGE_MODEL",
+ "AnswerToolCallNot",
"AsyncOnlyScorerMixin",
"ExitCodeZero",
"JudgedScorer",
- "LastToolCallNot",
"LogParser",
"NoToolCall",
"RequiredToolCall",
diff --git a/products/posthog_ai/eval_harness/scorers/deterministic.py b/products/posthog_ai/eval_harness/scorers/deterministic.py
index 841fbf5f5eb4..7e404a51417d 100644
--- a/products/posthog_ai/eval_harness/scorers/deterministic.py
+++ b/products/posthog_ai/eval_harness/scorers/deterministic.py
@@ -2,10 +2,30 @@ from __future__ import annotations
from collections.abc import Iterable
-from products.posthog_ai.eval_harness.log_parser import LogParser
+from products.posthog_ai.eval_harness.log_parser import LogParser, is_schema_discovery_call
from .contract import Score, Scorer
+QUERY_TOOL_PREFIX = "query-"
+"""Prefix marking a typed query runner. The MCP server treats every ``query-*``
+tool as a typed runner (see the ``query-run`` fallback in ``tools/exec.ts``),
+so new runners are covered without an enumerated list going stale."""
+
+EXECUTE_SQL_TOOL = "execute-sql"
+
+
+def is_answer_query_tool(name: str) -> bool:
+ """True when a tool produces a query result that can answer the user's question.
+
+ The typed ``query-*`` runners (trends, funnel, retention, stickiness,
+ lifecycle, paths, web analytics, llm-trace, and their ``-actors``
+ variants) and arbitrary ``execute-sql`` are the answer-producing tools.
+ Discovery, schema, and skill calls (``ToolSearch``, ``read-data-schema``,
+ bare ``exec``) are intermediary: they run constantly in a healthy run and
+ never count as the answer.
+ """
+ return name == EXECUTE_SQL_TOOL or name.startswith(QUERY_TOOL_PREFIX)
+
class ExitCodeZero(Scorer):
"""Binary scorer: did the agent process exit cleanly (code 0)?"""
@@ -67,29 +87,44 @@ class NoToolCall(Scorer):
return Score(name=self._name(), score=1.0, metadata={})
-class LastToolCallNot(Scorer):
- """Binary scorer: was the agent's *final* tool call not a forbidden one?
+class AnswerToolCallNot(Scorer):
+ """Binary scorer: did the agent's *answer* come from a tool not in the forbidden set?
+
+ Reading only the final successful call fails a run whose answer came from
+ a typed tool but that closed on an ``execute-sql`` validation call. This
+ scorer reads the *answer-producing* call instead.
- Walks the parsed tool-call list from ``LogParser`` and inspects only the
- last successful call — scores ``0.0`` if its normalized name is in the
- forbidden set. Earlier calls (including failed ones) are ignored: the
- agent is free to explore and even hit the forbidden tool mid-run, as long
- as the final answer comes from a different tool.
+ A call counts as answer-producing when it succeeded, is a query-producing
+ tool (``is_answer_query_tool``: a typed ``query-*`` runner or
+ ``execute-sql``), and is not a schema discovery lookup
+ (``is_schema_discovery_call`` drops ``execute-sql`` queries against
+ ``information_schema``). Intermediary calls like ``ToolSearch``,
+ ``read-data-schema``, and bare ``exec`` never count. Among the answer
+ calls, a call whose name is in ``preferred`` wins over every other: when
+ the agent used a typed ``query-*`` tool, that tool is the answer and a
+ trailing ``execute-sql`` is treated as validation. Only when no preferred
+ tool ran does the last remaining answer call count.
- Typical use: forbid ``execute-sql`` as the closing call in product-analytics
- evals where the agent is expected to land on ``query-trends`` /
- ``query-funnel`` / ``query-retention``. Lets the agent peek at SQL during
- discovery without penalising the run, but fails it for answering via SQL.
+ Scores ``0.0`` when the answer call's name is in the forbidden set, else
+ ``1.0``. ``score=None`` when nothing answer-producing ran.
"""
forbidden: frozenset[str]
+ preferred: frozenset[str]
_label: str
- def __init__(self, forbidden: str | Iterable[str], *, name: str = "last_tool_call_not_forbidden"):
+ def __init__(
+ self,
+ forbidden: str | Iterable[str],
+ preferred: Iterable[str],
+ *,
+ name: str = "answer_tool_call_not_forbidden",
+ ):
if isinstance(forbidden, str):
self.forbidden = frozenset({forbidden})
else:
self.forbidden = frozenset(forbidden)
+ self.preferred = frozenset(preferred)
self._label = name
def _name(self) -> str:
@@ -103,18 +138,24 @@ class LastToolCallNot(Scorer):
return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})
parser = LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")
- successful = [call for call in parser.get_tool_calls() if not call.is_error]
- if not successful:
- return Score(name=self._name(), score=None, metadata={"reason": "No successful tool calls"})
+ answer_calls = [
+ call
+ for call in parser.get_tool_calls()
+ if not call.is_error and is_answer_query_tool(call.name) and not is_schema_discovery_call(call)
+ ]
+ if not answer_calls:
+ return Score(name=self._name(), score=None, metadata={"reason": "No answer-producing tool call"})
+
+ typed = [call for call in answer_calls if call.name in self.preferred]
+ answer = typed[-1] if typed else answer_calls[-1]
- last = successful[-1]
- if last.name in self.forbidden:
+ if answer.name in self.forbidden:
return Score(
name=self._name(),
score=0.0,
- metadata={"last_tool_call": last.name},
+ metadata={"answer_tool_call": answer.name},
)
- return Score(name=self._name(), score=1.0, metadata={"last_tool_call": last.name})
+ return Score(name=self._name(), score=1.0, metadata={"answer_tool_call": answer.name})
class RequiredToolCall(Scorer):
diff --git a/products/posthog_ai/eval_harness/test/test_cli_mcp_scorers.py b/products/posthog_ai/eval_harness/test/test_cli_mcp_scorers.py
new file mode 100644
index 000000000000..d32f20aaafcd
--- /dev/null
+++ b/products/posthog_ai/eval_harness/test/test_cli_mcp_scorers.py
@@ -0,0 +1,243 @@
+from __future__ import annotations
+
+import json
+
+from parameterized import parameterized
+
+from products.posthog_ai.evals.cli_mcp.scorers import DidNotCiteRawSqlAfterTypedQuery, FirstRelevantTool
+
+
+def _tool_call_start(call_id: str, command: str) -> str:
+ return json.dumps(
+ {
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": call_id,
+ "rawInput": {"command": command},
+ "_meta": {"claudeCode": {"toolName": "mcp__posthog__exec"}},
+ }
+ },
+ }
+ }
+ )
+
+
+def _tool_call_result(call_id: str) -> str:
+ return json.dumps(
+ {
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": call_id,
+ "status": "completed",
+ "rawOutput": "ok",
+ }
+ },
+ }
+ }
+ )
+
+
+def _tool_call(call_id: str, command: str) -> list[str]:
+ return [_tool_call_start(call_id, command), _tool_call_result(call_id)]
+
+
+def _raw_log(turns: list[list[str]]) -> str:
+ """Render one assistant turn per inner list of commands.
+
+ The parser opens a new assistant message when a tool call follows a
+ captured result, so emitting every call of a turn before any of its
+ results is what gives those calls one shared position.
+ """
+ lines: list[str] = []
+ for turn_index, commands in enumerate(turns):
+ call_ids = [f"call-{turn_index}-{index}" for index in range(len(commands))]
+ lines += [_tool_call_start(call_id, command) for call_id, command in zip(call_ids, commands)]
+ lines += [_tool_call_result(call_id) for call_id in call_ids]
+ return "\n".join(lines)
+
+
+ANALYSIS_QUERY_TOOLS = frozenset({"query-trends", "query-funnel", "query-retention", "execute-sql"})
+
+_DISCOVERY_SQL = "SELECT column_name FROM system.information_schema.columns WHERE table_name = 'events'"
+_ANSWER_SQL = "SELECT count() FROM events WHERE event = 'logged_in'"
+
+
+def _sql_command(query: str) -> str:
+ payload = json.dumps({"query": query})
+ return f"call execute-sql {payload}"
+
+
+ [
+ (
+ "typed_query_first_then_sql",
+ [["call query-retention {}"], [_sql_command(_ANSWER_SQL)]],
+ "query-retention",
+ 1.0,
+ ["query-retention"],
+ ),
+ (
+ "sql_answer_before_the_typed_query",
+ [[_sql_command(_ANSWER_SQL)], ["call query-retention {}"]],
+ "query-retention",
+ 0.0,
+ ["execute-sql"],
+ ),
+ (
+ "mandated_catalog_lookup_before_the_typed_query",
+ [[_sql_command(_DISCOVERY_SQL)], ["call query-retention {}"]],
+ "query-retention",
+ 1.0,
+ ["query-retention"],
+ ),
+ (
+ "sql_control_that_only_looked_up_the_catalog",
+ [[_sql_command(_DISCOVERY_SQL)]],
+ "execute-sql",
+ 0.0,
+ None,
+ ),
+ (
+ "typed_query_and_sql_in_one_turn_fails_the_typed_case",
+ [["call query-retention {}", _sql_command(_ANSWER_SQL)]],
+ "query-retention",
+ 0.0,
+ ["execute-sql", "query-retention"],
+ ),
+ (
+ "typed_query_and_sql_in_one_turn_fails_the_sql_control",
+ [[_sql_command(_ANSWER_SQL), "call query-retention {}"]],
+ "execute-sql",
+ 0.0,
+ ["execute-sql", "query-retention"],
+ ),
+ ]
+)
+def test_first_relevant_tool_grades_the_answer_route(
+ _name: str,
+ turns: list[list[str]],
+ target: str,
+ expected_score: float,
+ expected_turn_tools: list[str] | None,
+) -> None:
+ result = FirstRelevantTool(relevant_tools=ANALYSIS_QUERY_TOOLS)._run_eval_sync(
+ {"raw_log": _raw_log(turns)},
+ expected={"first_relevant_tool": {"tool": target}},
+ )
+
+ assert result.score == expected_score
+ assert result.metadata.get("first_relevant_tools") == expected_turn_tools
+ assert result.name == "first_relevant_tool"
+
+
+ [
+ ("hogql_tag", 'Here is the trend: <hogql label="pageviews">SELECT count() FROM events</hogql>'),
+ ("sql_fence", "Here is the trend:\n```sql\nSELECT count() FROM events\n```"),
+ ]
+)
+def test_did_not_cite_raw_sql_fails_when_answer_hand_writes_sql_after_typed_query(
+ _name: str, last_message: str
+) -> None:
+ raw_log = "\n".join(_tool_call("trends", "call query-trends {}"))
+
+ result = DidNotCiteRawSqlAfterTypedQuery()._run_eval_sync(
+ {"raw_log": raw_log, "last_message": last_message},
+ expected={"did_not_cite_raw_sql_after_typed_query": {"tool": "query-trends"}},
+ )
+
+ assert result.score == 0.0
+
+
+def test_did_not_cite_raw_sql_passes_when_answer_trusts_the_tool_result() -> None:
+ raw_log = "\n".join(_tool_call("trends", "call query-trends {}"))
+
+ result = DidNotCiteRawSqlAfterTypedQuery()._run_eval_sync(
+ {"raw_log": raw_log, "last_message": "Pageviews were up 12% over the last 7 days."},
+ expected={"did_not_cite_raw_sql_after_typed_query": {"tool": "query-trends"}},
+ )
+
+ assert result.score == 1.0
+
+
+def test_did_not_cite_raw_sql_is_none_when_the_typed_tool_was_never_called() -> None:
+ raw_log = "\n".join(_tool_call("sql", "call execute-sql {}"))
+
+ result = DidNotCiteRawSqlAfterTypedQuery()._run_eval_sync(
+ {"raw_log": raw_log, "last_message": "<hogql>SELECT count() FROM events</hogql>"},
+ expected={"did_not_cite_raw_sql_after_typed_query": {"tool": "query-trends"}},
+ )
+
+ assert result.score is None
+
+
+def _multi_turn_output(turn_commands: list[str], *, turn_index: int, total_turns: int = 4) -> dict:
+ """Build the runner's multi-turn output shape, with a real log only in one slice.
+
+ Each slice carries distinct SQL so the process-wide ``LogParser.cached`` key
+ never collides across parameterizations. ``turn_index`` is 0-based.
+ """
+ turn_logs = [f'{{"filler-turn": {i}}}' for i in range(total_turns)]
+ turn_logs[turn_index] = _raw_log([[turn_commands[turn_index]]])
+ return {
+ "raw_log": turn_logs[turn_index],
+ "prompt": "turn 1 prompt",
+ "turn_logs": turn_logs,
+ "turn_prompts": [f"turn {i + 1} prompt" for i in range(total_turns)],
+ }
+
+
+ [
+ ("turn3_recovers_to_typed", 2, "call query-trends {}", "query-trends", 1.0),
+ ("turn3_stays_on_sql", 2, _sql_command(_ANSWER_SQL), "query-trends", 0.0),
+ ("turn2_sql_matches_its_override", 1, _sql_command(_ANSWER_SQL), "execute-sql", 1.0),
+ ]
+)
+def test_first_relevant_tool_grades_a_single_turn(
+ _name: str, turn_index: int, command: str, target: str, expected_score: float
+) -> None:
+ commands = [command] * 4
+ output = _multi_turn_output(commands, turn_index=turn_index)
+
+ result = FirstRelevantTool(relevant_tools=ANALYSIS_QUERY_TOOLS, turn=turn_index + 1, tool=target)._run_eval_sync(
+ output,
+ expected={"first_relevant_tool": {"tool": "query-trends"}},
+ )
+
+ assert result.score == expected_score
+ # A distinct name per turn keeps the four per-turn scores from colliding on
+ # one key in the per-case export and the rollup.
+ assert result.name == f"first_relevant_tool_t{turn_index + 1}"
+
+
+def test_first_relevant_tool_turn_reads_expected_tool_without_override() -> None:
+ output = _multi_turn_output(["call query-trends {}"] * 4, turn_index=2)
+
+ result = FirstRelevantTool(relevant_tools=ANALYSIS_QUERY_TOOLS, turn=3)._run_eval_sync(
+ output,
+ expected={"first_relevant_tool": {"tool": "query-trends"}},
+ )
+
+ assert result.score == 1.0
+ # Name diverges by turn, but the expected lookup still resolves under the
+ # shared base key.
+ assert result.name == "first_relevant_tool_t3"
+
+
+def test_first_relevant_tool_turn_skips_a_missing_slice() -> None:
+ output = _multi_turn_output(["call query-trends {}"] * 4, turn_index=2)
+
+ result = FirstRelevantTool(relevant_tools=ANALYSIS_QUERY_TOOLS, turn=9)._run_eval_sync(
+ output,
+ expected={"first_relevant_tool": {"tool": "query-trends"}},
+ )
+
+ assert result.score is None
+ assert "No turn 9 log slice" in result.metadata["reason"]
diff --git a/products/posthog_ai/eval_harness/test/test_eval_scorers.py b/products/posthog_ai/eval_harness/test/test_eval_scorers.py
index 57434fe0d4aa..08a6dc045099 100644
--- a/products/posthog_ai/eval_harness/test/test_eval_scorers.py
+++ b/products/posthog_ai/eval_harness/test/test_eval_scorers.py
@@ -7,6 +7,7 @@ from typing import Any
import pytest
from products.posthog_ai.eval_harness.log_parser import SKILL_TOOL_NAME
+from products.posthog_ai.eval_harness.scorers import AnswerToolCallNot
from products.posthog_ai.evals.error_tracking.scorers import (
ERROR_TRACKING_WRITE_TOOLS,
QUERY_ISSUE_EVENTS_TOOL,
@@ -212,3 +213,93 @@ def test_skill_triggered_skips_when_the_case_declares_no_direction(expected: dic
)
assert score.score is None
+
+
+ "calls,expected_score,expected_answer_tool",
+ [
+ # Typed answer followed by an execute-sql validation call: the typed
+ # tool wins, the trailing SQL is validation. Reading only the last
+ # call instead of the answer scored this 0.
+ (
+ [
+ ("query-trends", {"query": {}}, {"results": []}),
+ ("execute-sql", {"query": "SELECT count() FROM events"}, "1"),
+ ],
+ 1.0,
+ "query-trends",
+ ),
+ # execute-sql as the only answer-producing call: it is the answer.
+ ([("execute-sql", {"query": "SELECT count() FROM events"}, "1")], 0.0, "execute-sql"),
+ # Typed answer, no trailing SQL.
+ ([("query-trends", {"query": {}}, {"results": []})], 1.0, "query-trends"),
+ # information_schema discovery is not answer-producing and is dropped.
+ (
+ [
+ ("execute-sql", {"query": "SELECT * FROM system.information_schema.tables"}, "t"),
+ ("query-trends", {"query": {}}, {"results": []}),
+ ],
+ 1.0,
+ "query-trends",
+ ),
+ # Two typed answers: the last typed call is the answer.
+ (
+ [
+ ("query-funnel", {"query": {}}, {"results": []}),
+ ("query-trends", {"query": {}}, {"results": []}),
+ ],
+ 1.0,
+ "query-trends",
+ ),
+ # Intermediary calls after the typed answer never become the answer.
+ (
+ [
+ ("query-trends", {"query": {}}, {"results": []}),
+ ("read-data-schema", {"kind": "events"}, "ok"),
+ ("exec", {"command": "search"}, "ok"),
+ ],
+ 1.0,
+ "query-trends",
+ ),
+ # execute-sql answer followed by an intermediary call: the SQL is
+ # still the answer, the intermediary is ignored.
+ (
+ [
+ ("execute-sql", {"query": "SELECT count() FROM events"}, "1"),
+ ("read-data-schema", {"kind": "events"}, "ok"),
+ ],
+ 0.0,
+ "execute-sql",
+ ),
+ # Any typed query-* runner counts, not only trends/funnel: a runner
+ # outside the original four (web analytics here) is still
+ # answer-producing, so it scores as the answer rather than being skipped.
+ ([("query-web-stats", {"query": {}}, {"results": []})], 1.0, "query-web-stats"),
+ ],
+)
+def test_answer_tool_call_not_reads_answer_not_last_call(
+ calls: list[tuple], expected_score: float, expected_answer_tool: str
+) -> None:
+ score = AnswerToolCallNot(forbidden="execute-sql", preferred={"query-trends", "query-funnel"})._run_eval_sync(
+ {"raw_log": _raw_tool_log(calls)}
+ )
+
+ assert score.score == expected_score
+ assert score.metadata["answer_tool_call"] == expected_answer_tool
+
+
+ "calls",
+ [
+ # Only schema-discovery SQL ran: no answer-producing call.
+ [("execute-sql", {"query": "SELECT * FROM system.information_schema.tables"}, "t")],
+ # Only intermediary (non-query) calls ran: no answer-producing call.
+ [("read-data-schema", {"kind": "events"}, "ok"), ("exec", {"command": "search"}, "ok")],
+ ],
+)
+def test_answer_tool_call_not_skips_when_nothing_answer_producing_ran(calls: list[tuple]) -> None:
+ score = AnswerToolCallNot(forbidden="execute-sql", preferred={"query-trends"})._run_eval_sync(
+ {"raw_log": _raw_tool_log(calls)}
+ )
+
+ assert score.score is None
diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py
index 6638a1a3679d..7d80a4a95793 100644
--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py
+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py
@@ -319,3 +319,23 @@ class TestAgentRunFailureDetection:
) -> None:
artifacts = AgentArtifacts(exit_code=1 if stderr else 0, stderr=stderr, tool_call_count=tool_call_count)
assert runner.agent_never_ran(artifacts) is expected
+
+
+class TestSliceTurnLogs:
+ def test_slices_by_turn_line_marks(self) -> None:
+ log = "\n".join(f'{{"line": {i}}}' for i in range(5))
+ assert runner._slice_turn_logs(log, [2, 5]) == [
+ '{"line": 0}\n{"line": 1}',
+ '{"line": 2}\n{"line": 3}\n{"line": 4}',
+ ]
+
+ def test_single_turn_spans_the_whole_log(self) -> None:
+ log = "\n".join(f'{{"line": {i}}}' for i in range(3))
+ assert runner._slice_turn_logs(log, [3]) == [log]
+
+ def test_marks_past_the_line_count_disable_slicing(self) -> None:
+ log = "\n".join(f'{{"line": {i}}}' for i in range(3))
+ assert runner._slice_turn_logs(log, [2, 9]) is None
+
+ def test_a_malformed_line_disables_slicing(self) -> None:
+ assert runner._slice_turn_logs('{"line": 0}\nnot json\n{"line": 1}', [1, 3]) is None
diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py
index 0dbd46aa8446..6036af93d231 100644
--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py
+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py
@@ -57,6 +57,7 @@ async def test_reporter_output_is_labeled_and_reserves_pass_for_the_run(
agent_model="gpt-5",
max_sandboxes=4,
trials=1,
+ case_timeout_seconds=900,
)
await reporter.suite_started("cli_mcp/eval_workflow::eval_verify_event_before_query")
await reporter.experiment_started("sandboxed-cli-mcp-verify-event-cli", 1, tmp_path)
@@ -161,6 +162,26 @@ def test_exec_commands_wrapping_no_inner_tool_stay_under_the_raw_name() -> None:
assert spans == [("tool_call: exec", [{"tool": "exec", "input": {"command": "schema query-trends series"}}])]
+def test_tool_call_spans_are_split_when_one_agent_message_has_multiple_calls() -> None:
+ parsed = ParsedLog(
+ generations=[
+ GenerationDescriptor(
+ output_content=[
+ {"type": "tool_use", "id": "1", "name": "query-retention", "input": {}},
+ {"type": "tool_use", "id": "2", "name": "execute-sql", "input": {}},
+ ],
+ )
+ ]
+ )
+
+ spans = _collect_spans(parsed)
+
+ assert spans == [
+ ("tool_call: query-retention", [{"tool": "query-retention", "input": {}}]),
+ ("tool_call: execute-sql", [{"tool": "execute-sql", "input": {}}]),
+ ]
+
+
def _collect_spans(parsed: ParsedLog) -> list[tuple[str, Any]]:
collected: list[tuple[str, Any]] = []
diff --git a/products/posthog_ai/evals/cli_mcp/eval_render_ui.py b/products/posthog_ai/evals/cli_mcp/eval_render_ui.py
index 62b083ced9cf..492d8f3e323d 100644
--- a/products/posthog_ai/evals/cli_mcp/eval_render_ui.py
+++ b/products/posthog_ai/evals/cli_mcp/eval_render_ui.py
@@ -48,6 +48,7 @@ from products.posthog_ai.eval_harness.config import SandboxedEvalCase
from products.posthog_ai.eval_harness.harness.context import EvalContext
from products.posthog_ai.evals.cli_mcp.scorers import (
CalledTargetTool,
+ DidNotCiteRawSqlAfterTypedQuery,
DidNotRenderUi,
ExecBeforeRender,
RenderedEntityUi,
@@ -107,7 +108,9 @@ async def eval_no_render_for_query_results(ctx: EvalContext) -> None:
``query-trends`` (and the other insight ``query-*`` tools) carry the custom
``query-results`` app, which renders automatically — they are not in
``render-ui``'s enum. The agent should answer with the query tool and never
- call ``render-ui``.
+ call ``render-ui``. It also should not hand-write the equivalent SQL in its
+ final answer once ``query-trends`` already returned a structured result —
+ doing so is the same SQL-first reasoning wearing a different disguise.
"""
cases: list[SandboxedEvalCase] = [
@@ -117,6 +120,7 @@ async def eval_no_render_for_query_results(ctx: EvalContext) -> None:
expected={
"called_target_tool": {"tool": "query-trends"},
"did_not_render_ui": {},
+ "did_not_cite_raw_sql_after_typed_query": {"tool": "query-trends"},
},
),
]
@@ -124,6 +128,6 @@ async def eval_no_render_for_query_results(ctx: EvalContext) -> None:
await SandboxedPublicEval(
experiment_name="sandboxed-cli-mcp-no-render-for-query-cli",
cases=cases,
- scorers=[CalledTargetTool(), DidNotRenderUi()],
+ scorers=[CalledTargetTool(), DidNotRenderUi(), DidNotCiteRawSqlAfterTypedQuery()],
ctx=ctx,
)
diff --git a/products/posthog_ai/evals/cli_mcp/scorers.py b/products/posthog_ai/evals/cli_mcp/scorers.py
index cc1899cc8873..64d7811d8be5 100644
--- a/products/posthog_ai/evals/cli_mcp/scorers.py
+++ b/products/posthog_ai/evals/cli_mcp/scorers.py
@@ -13,6 +13,9 @@ unrelated cases don't drag the rollup down.
* ``CalledTargetTool`` — did the agent successfully invoke
``expected[<scorer_name>]["tool"]`` at least once? Returns 1.0/0.0.
+* ``FirstRelevantTool`` — in the earliest turn where the agent used one of a
+ supplied set of comparable tools, did it use only the expected one?
+ Returns 1.0/0.0.
* ``RecoveredToCorrectTool`` — when prompted to use a wrong tool name
(deprecated or typo'd), did the agent end up calling a correct
replacement?
@@ -26,21 +29,31 @@ unrelated cases don't drag the rollup down.
preceded by ``info <tool>`` in the same run?
* ``VerifiedEventBeforeQuery`` — did the agent run ``read-data-schema``
before any successful ``query-*`` call?
+* ``DidNotCiteRawSqlAfterTypedQuery`` — after a typed query tool succeeded,
+ did the final answer avoid hand-writing the equivalent raw SQL?
"""
from __future__ import annotations
import re
-from products.posthog_ai.eval_harness.log_parser import EXEC_TOOL_NAME, INFO_SYNTHETIC_PREFIX, LogParser, ToolCall
+from products.posthog_ai.eval_harness.log_parser import (
+ EXEC_TOOL_NAME,
+ INFO_SYNTHETIC_PREFIX,
+ LogParser,
+ ToolCall,
+ is_schema_discovery_call,
+)
from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer
__all__ = [
"CalledTargetTool",
+ "DidNotCiteRawSqlAfterTypedQuery",
"DidNotRenderUi",
"DrilledIntoSchema",
"ExecBeforeRender",
"InfoBeforeCall",
+ "FirstRelevantTool",
"PreferredSearchOverTools",
"RanPythonPostProcessing",
"RecoveredToCorrectTool",
@@ -57,6 +70,11 @@ __all__ = [
# the capture keeps a trailing `\` and never substring-matches the (unescaped) final message.
_URL_RE = re.compile(r"https?://[^\s\"'`)\]<>\\]+")
+# Matches a `<hogql>` citation tag or a fenced ```sql block — the two shapes an
+# agent uses to hand-write a raw query in its final answer instead of trusting
+# a typed query tool's own structured result.
+_RAW_SQL_CITATION_RE = re.compile(r"<hogql\b|```sql\b", re.IGNORECASE)
+
RENDER_UI_TOOL_NAME = "render-ui"
"""Normalized name of the umbrella render tool (``mcp__<server>__render-ui`` → ``render-ui``).
@@ -140,6 +158,191 @@ class CalledTargetTool(Scorer):
)
+class DidNotCiteRawSqlAfterTypedQuery(Scorer):
+ """Binary: after a typed query tool succeeded, did the answer avoid raw SQL?
+
+ ``expected = {"did_not_cite_raw_sql_after_typed_query": {"tool": "query-trends"}}``
+
+ A typed query tool (``query-trends`` and friends) already returns a
+ structured, renderable result — there is no reason for the final answer
+ to also hand-write the equivalent SQL. Doing so anyway reads as a routing
+ win under ``CalledTargetTool`` while the underlying reasoning is still
+ SQL-first; this scorer catches that gap.
+
+ Looks for a ``<hogql`` citation tag or a fenced ```sql block in the final
+ assistant message. Score 1.0 if the tool succeeded and neither appears,
+ 0.0 if either appears. ``None`` if ``tool`` was never called successfully
+ (that gap is caught by ``CalledTargetTool``).
+ """
+
+ def _name(self) -> str:
+ return "did_not_cite_raw_sql_after_typed_query"
+
+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:
+ target = _read_tool(expected, self._name())
+ if not target:
+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()}.tool on case"})
+
+ parser = _build_parser(output)
+ if parser is None:
+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})
+
+ called = any(not call.is_error for call in parser.get_tool_calls(target))
+ if not called:
+ return Score(
+ name=self._name(),
+ score=None,
+ metadata={"reason": f"Tool '{target}' was never successfully called", "tool": target},
+ )
+
+ last_message = (output or {}).get("last_message") or ""
+ if not isinstance(last_message, str):
+ last_message = str(last_message)
+
+ match = _RAW_SQL_CITATION_RE.search(last_message)
+ if match:
+ return Score(
+ name=self._name(),
+ score=0.0,
+ metadata={
+ "reason": "Final answer cited raw SQL after a typed query tool already succeeded",
+ "tool": target,
+ "matched": match.group(0),
+ },
+ )
+ return Score(name=self._name(), score=1.0, metadata={"tool": target})
+
+
+class FirstRelevantTool(Scorer):
+ """Binary: did the earliest turn that used ``relevant_tools`` use only the target?
+
+ ``execute-sql`` calls against ``system.information_schema.*`` are skipped:
+ the MCP instructions require that catalog lookup before an answer query, so
+ counting it as the route would score the mandated discovery step rather
+ than the tool the agent picked to answer with.
+
+ ``position`` is the index of the enclosing assistant message, so every call
+ the agent emitted in one response shares it. Such calls are simultaneous —
+ none of them saw another's result — so there is no first among them, and
+ picking one by block order would grade the order the model happened to
+ write them in. This scorer grades the whole batch instead: it passes only
+ when every relevant call in the earliest turn used the target. A turn that
+ fires a typed runner and ``execute-sql`` together is a hedge, not a route,
+ and fails whichever of the two the case expects.
+
+ ``turn=N`` (1-indexed) grades one turn of a multi-turn case instead of the
+ whole conversation: it reads slice ``N - 1`` of the runner's ``turn_logs``
+ (one cumulative-log slice per completed turn) and seeds the parser with
+ that turn's prompt from ``turn_prompts``. A missing slice scores ``None``,
+ not ``0.0`` — a turn that never ran is infrastructure noise, not an agent
+ routing failure.
+
+ ``tool`` overrides the per-case ``expected[...]["tool"]`` target. A
+ multi-turn case carries one ``expected`` dict for every turn, so a scorer
+ whose turn has a different target from the rest (e.g. a turn that must
+ route to ``execute-sql`` while the others expect ``query-trends``) passes
+ its own.
+
+ Each turn's scorer needs a distinct output name, or the four per-turn
+ ``Score`` objects collide on one key: the per-case ``scores`` dict keeps
+ only the last turn's value, and the rollup blends the manipulation-check
+ turn into the recovery metric. So a ``turn`` scorer defaults its name to
+ ``first_relevant_tool_t{turn}`` (override with ``name``). The per-case
+ ``expected`` lookup still uses the shared ``first_relevant_tool`` key, so a
+ renamed scorer keeps finding its target.
+ """
+
+ _EXPECTED_KEY = "first_relevant_tool"
+
+ def __init__(
+ self,
+ *,
+ relevant_tools: frozenset[str],
+ turn: int | None = None,
+ tool: str | None = None,
+ name: str | None = None,
+ ) -> None:
+ self.relevant_tools = relevant_tools
+ self.turn = turn
+ self.tool = tool
+ if name is not None:
+ self._label = name
+ elif turn is not None:
+ self._label = f"{self._EXPECTED_KEY}_t{turn}"
+ else:
+ self._label = self._EXPECTED_KEY
+
+ def _name(self) -> str:
+ return self._label
+
+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:
+ target = self.tool or _read_tool(expected, self._EXPECTED_KEY)
+ if not target:
+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._EXPECTED_KEY}.tool on case"})
+
+ raw_log = (output or {}).get("raw_log")
+ initial_prompt = ((output or {}).get("prompt") or "") if isinstance(output, dict) else ""
+ if self.turn is not None:
+ # Grade one turn of a multi-turn case. Turn logs are cumulative-log
+ # slices: they carry no user_message line, so seed the parser with the
+ # turn's own prompt. A missing slice means the turn never ran — infra
+ # noise, not an agent failure, so skip rather than score 0.
+ turn_logs = (output or {}).get("turn_logs")
+ turn_prompts = (output or {}).get("turn_prompts")
+ if not isinstance(turn_logs, list) or self.turn < 1 or self.turn > len(turn_logs):
+ return Score(
+ name=self._name(),
+ score=None,
+ metadata={"reason": f"No turn {self.turn} log slice", "tool": target},
+ )
+ raw_log = turn_logs[self.turn - 1]
+ if isinstance(turn_prompts, list) and len(turn_prompts) >= self.turn:
+ prompt = turn_prompts[self.turn - 1]
+ initial_prompt = prompt if isinstance(prompt, str) else ""
+ if not raw_log:
+ return Score(
+ name=self._name(),
+ score=None,
+ metadata={"reason": f"Turn {self.turn} log slice is empty", "tool": target},
+ )
+
+ if not raw_log:
+ return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log", "tool": target})
+ parser = LogParser.cached(raw_log, initial_prompt=initial_prompt)
+
+ candidates = [
+ call for call in parser.get_tool_calls() if not call.is_error and call.name in self.relevant_tools
+ ]
+ relevant = [call for call in candidates if not is_schema_discovery_call(call)]
+ skipped_discovery = len(candidates) - len(relevant)
+ if not relevant:
+ return Score(
+ name=self._name(),
+ score=0.0,
+ metadata={
+ "reason": "No successful relevant tool calls",
+ "tool": target,
+ "skipped_discovery_calls": skipped_discovery,
+ },
+ )
+
+ first_position = min(call.position for call in relevant)
+ first_turn = [call for call in relevant if call.position == first_position]
+ turn_tools = sorted({call.name for call in first_turn})
+ metadata: dict[str, object] = {
+ "expected_tool": target,
+ "first_relevant_tool": turn_tools[0] if len(turn_tools) == 1 else None,
+ "first_relevant_tools": turn_tools,
+ "call_ids": [call.call_id for call in first_turn],
+ "skipped_discovery_calls": skipped_discovery,
+ }
+ if turn_tools == [target]:
+ return Score(name=self._name(), score=1.0, metadata=metadata)
+ if len(turn_tools) > 1:
+ metadata["reason"] = "The earliest relevant turn selected several tools at once"
+ return Score(name=self._name(), score=0.0, metadata=metadata)
+
+
def _attempted_tool(call: ToolCall, wrong: str) -> bool:
"""True if a tool call represents an attempt against the ``wrong`` name.
diff --git a/products/posthog_ai/evals/product_analytics/eval_funnel.py b/products/posthog_ai/evals/product_analytics/eval_funnel.py
index 185c952812c4..b53a24b4bc4f 100644
--- a/products/posthog_ai/evals/product_analytics/eval_funnel.py
+++ b/products/posthog_ai/evals/product_analytics/eval_funnel.py
@@ -23,7 +23,7 @@ from posthog.schema import (
from products.posthog_ai.eval_harness.base import SandboxedPublicEval
from products.posthog_ai.eval_harness.config import SandboxedEvalCase
from products.posthog_ai.eval_harness.harness.context import EvalContext
-from products.posthog_ai.eval_harness.scorers import LastToolCallNot, NoToolCall, RequiredToolCall
+from products.posthog_ai.eval_harness.scorers import AnswerToolCallNot, NoToolCall, RequiredToolCall
from products.posthog_ai.evals.product_analytics.scorers import (
INSIGHT_WRITE_TOOLS,
FunnelSchemaAlignment,
@@ -599,7 +599,7 @@ async def eval_funnel(ctx: EvalContext) -> None:
cases=cases,
scorers=[
NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),
- LastToolCallNot(forbidden="execute-sql", name="last_call_not_execute_sql"),
+ AnswerToolCallNot(forbidden="execute-sql", preferred={"query-funnel"}, name="answer_tool_not_execute_sql"),
RequiredToolCall(required={"read-data-schema"}, name="verified_event_exists"),
FunnelSchemaAlignment(),
FunnelTimeRangeRelevancy(),
diff --git a/products/posthog_ai/evals/product_analytics/eval_retention.py b/products/posthog_ai/evals/product_analytics/eval_retention.py
index 7da9879e2147..3020d2717e60 100644
--- a/products/posthog_ai/evals/product_analytics/eval_retention.py
+++ b/products/posthog_ai/evals/product_analytics/eval_retention.py
@@ -17,7 +17,7 @@ from posthog.schema import AssistantRetentionEventsNode, AssistantRetentionFilte
from products.posthog_ai.eval_harness.base import SandboxedPublicEval
from products.posthog_ai.eval_harness.config import SandboxedEvalCase
from products.posthog_ai.eval_harness.harness.context import EvalContext
-from products.posthog_ai.eval_harness.scorers import LastToolCallNot, NoToolCall
+from products.posthog_ai.eval_harness.scorers import AnswerToolCallNot, NoToolCall
from products.posthog_ai.evals.product_analytics.scorers import (
INSIGHT_WRITE_TOOLS,
RetentionSchemaAlignment,
@@ -129,7 +129,9 @@ async def eval_retention(ctx: EvalContext) -> None:
cases=cases,
scorers=[
NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),
- LastToolCallNot(forbidden="execute-sql", name="last_call_not_execute_sql"),
+ AnswerToolCallNot(
+ forbidden="execute-sql", preferred={"query-retention"}, name="answer_tool_not_execute_sql"
+ ),
RetentionSchemaAlignment(),
RetentionTimeRangeRelevancy(),
],
diff --git a/products/posthog_ai/evals/product_analytics/eval_schema_discovery.py b/products/posthog_ai/evals/product_analytics/eval_schema_discovery.py
index 8a0049aef075..6eb3e75c23e2 100644
--- a/products/posthog_ai/evals/product_analytics/eval_schema_discovery.py
+++ b/products/posthog_ai/evals/product_analytics/eval_schema_discovery.py
@@ -22,7 +22,7 @@ from typing import Any
from products.posthog_ai.eval_harness.base import SandboxedPublicEval
from products.posthog_ai.eval_harness.config import SandboxedEvalCase
from products.posthog_ai.eval_harness.harness.context import EvalContext
-from products.posthog_ai.eval_harness.scorers import LastToolCallNot, NoToolCall
+from products.posthog_ai.eval_harness.scorers import AnswerToolCallNot, NoToolCall
from products.posthog_ai.evals.product_analytics.scorers import INSIGHT_WRITE_TOOLS, SchemaDiscoveryOrder
@@ -88,7 +88,11 @@ async def eval_schema_discovery(ctx: EvalContext) -> None:
cases=cases,
scorers=[
NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),
- LastToolCallNot(forbidden="execute-sql", name="last_call_not_execute_sql"),
+ AnswerToolCallNot(
+ forbidden="execute-sql",
+ preferred={"query-trends", "query-funnel", "query-retention"},
+ name="answer_tool_not_execute_sql",
+ ),
SchemaDiscoveryOrder(),
],
ctx=ctx,
diff --git a/products/posthog_ai/evals/product_analytics/eval_sql_shaped_routing.py b/products/posthog_ai/evals/product_analytics/eval_sql_shaped_routing.py
new file mode 100644
index 000000000000..ecf2747c183f
--- /dev/null
+++ b/products/posthog_ai/evals/product_analytics/eval_sql_shaped_routing.py
@@ -0,0 +1,159 @@
+"""MCP routing evals for prompts that sound like raw SQL requests.
+
+The typed cases ask for trends, funnels, retention, stickiness, or lifecycle
+without naming the PostHog analysis. They must call the matching typed runner
+rather than ``execute-sql``. The controls require row-level or windowed work,
+so they must call ``execute-sql`` without using a typed query runner.
+
+Entity search against the ``system.*`` catalog (e.g. "do we already have an
+insight for X?") is a separate failure mode with its own dedicated suite —
+see ``retrieval/eval_system_table_search.py`` — and isn't duplicated here.
+"""
+
+from __future__ import annotations
+
+from products.posthog_ai.eval_harness.base import SandboxedPublicEval
+from products.posthog_ai.eval_harness.config import SandboxedEvalCase
+from products.posthog_ai.eval_harness.harness.context import EvalContext
+from products.posthog_ai.eval_harness.scorers import NoToolCall
+from products.posthog_ai.evals.cli_mcp.scorers import FirstRelevantTool
+from products.posthog_ai.evals.product_analytics.scorers import INSIGHT_WRITE_TOOLS
+
+ANALYSIS_QUERY_TOOLS = frozenset(
+ {"query-trends", "query-funnel", "query-retention", "query-stickiness", "query-lifecycle", "execute-sql"}
+)
+
+
+def _routing_case(*, name: str, prompt: str, target_tool: str) -> SandboxedEvalCase:
+ return SandboxedEvalCase(
+ name=name,
+ prompt=prompt,
+ expected={"first_relevant_tool": {"tool": target_tool}},
+ )
+
+
+async def eval_sql_shaped_typed_query_routing(ctx: EvalContext) -> None:
+ """Typed query runners must handle SQL-shaped product-analytics requests."""
+ cases = [
+ _routing_case(
+ name="trends_count_uploaded_files_per_day",
+ prompt="Count uploaded_file events per day over the last 30 days",
+ target_tool="query-trends",
+ ),
+ _routing_case(
+ name="trends_weekly_signups",
+ prompt="Write me a query showing the number of signed_up events per week over the last 8 weeks",
+ target_tool="query-trends",
+ ),
+ _routing_case(
+ name="trends_downloads_grouped_by_type",
+ prompt="Show downloaded_file events grouped by file_type over the last 30 days",
+ target_tool="query-trends",
+ ),
+ _routing_case(
+ name="trends_average_file_size",
+ prompt="What is the average file_size_b on uploaded_file events over the last 30 days?",
+ target_tool="query-trends",
+ ),
+ _routing_case(
+ name="trends_distinct_logged_in_users",
+ prompt="Count distinct users who fired logged_in in the last 7 days",
+ target_tool="query-trends",
+ ),
+ _routing_case(
+ name="funnel_signup_to_upload",
+ prompt="Of users who fired signed_up, how many went on to fire uploaded_file within a week?",
+ target_tool="query-funnel",
+ ),
+ _routing_case(
+ name="funnel_signup_to_upgrade",
+ prompt="How many people fired signed_up and then upgraded_plan over the last 30 days?",
+ target_tool="query-funnel",
+ ),
+ _routing_case(
+ name="funnel_pricing_to_signup",
+ prompt="What share of users who viewed /pricing/ went on to fire signed_up over the last 8 weeks?",
+ target_tool="query-funnel",
+ ),
+ _routing_case(
+ name="retention_signup_to_login",
+ prompt="Of users who fired signed_up in the last 8 weeks, how many came back to fire logged_in in each of the following weeks?",
+ target_tool="query-retention",
+ ),
+ _routing_case(
+ name="retention_repeat_uploads",
+ prompt="For users whose first uploaded_file was in the last 8 weeks, how many were still uploading each week after?",
+ target_tool="query-retention",
+ ),
+ _routing_case(
+ name="retention_signup_to_login_by_plan",
+ prompt="What's the day-1 and day-7 return rate for people who signed up in the last 4 weeks, split by personal vs. business plan?",
+ target_tool="query-retention",
+ ),
+ _routing_case(
+ name="trends_multi_series_uploads_and_downloads",
+ prompt="Show weekly counts of uploaded_file and downloaded_file side by side over the last 8 weeks",
+ target_tool="query-trends",
+ ),
+ _routing_case(
+ name="trends_compare_invited_vs_new_signups",
+ prompt="Compare weekly signups from invited team members versus new account signups over the last 8 weeks",
+ target_tool="query-trends",
+ ),
+ _routing_case(
+ name="funnel_time_to_first_upload",
+ prompt="How long does it typically take someone to upload their first file after signing up?",
+ target_tool="query-funnel",
+ ),
+ _routing_case(
+ name="stickiness_weekly_repeat_downloads",
+ prompt="Of people who downloaded a file in the last 4 weeks, how many days a week do they typically come back and download again?",
+ target_tool="query-stickiness",
+ ),
+ _routing_case(
+ name="lifecycle_pageview_composition",
+ prompt="Break last month's active website visitors into new, returning, and lapsed",
+ target_tool="query-lifecycle",
+ ),
+ ]
+
+ await SandboxedPublicEval(
+ experiment_name="sandboxed-sql-shaped-typed-query-routing-cli",
+ cases=cases,
+ scorers=[
+ NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),
+ FirstRelevantTool(relevant_tools=ANALYSIS_QUERY_TOOLS),
+ ],
+ ctx=ctx,
+ )
+
+
+async def eval_sql_shaped_sql_controls(ctx: EvalContext) -> None:
+ """SQL-only requests must not be routed through a typed query runner."""
+ cases = [
+ _routing_case(
+ name="sql_list_largest_files",
+ prompt="List the 10 largest files by file_size_b from uploaded_file, with their file_name",
+ target_tool="execute-sql",
+ ),
+ _routing_case(
+ name="sql_first_and_last_login_per_account",
+ prompt="For each account, show the first and last logged_in timestamp",
+ target_tool="execute-sql",
+ ),
+ _routing_case(
+ name="sql_median_file_size_by_account",
+ prompt="What is the median file_size_b on uploaded_file, and which accounts upload above it?",
+ target_tool="execute-sql",
+ ),
+ ]
+
+ await SandboxedPublicEval(
+ experiment_name="sandboxed-sql-shaped-sql-controls-cli",
+ cases=cases,
+ scorers=[
+ NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),
+ FirstRelevantTool(relevant_tools=ANALYSIS_QUERY_TOOLS),
+ ],
+ ctx=ctx,
+ )
diff --git a/products/posthog_ai/evals/product_analytics/eval_trends.py b/products/posthog_ai/evals/product_analytics/eval_trends.py
index 575e406bcfc6..bb8a65b78275 100644
--- a/products/posthog_ai/evals/product_analytics/eval_trends.py
+++ b/products/posthog_ai/evals/product_analytics/eval_trends.py
@@ -26,7 +26,7 @@ from posthog.schema import (
from products.posthog_ai.eval_harness.base import SandboxedPublicEval
from products.posthog_ai.eval_harness.config import SandboxedEvalCase
from products.posthog_ai.eval_harness.harness.context import EvalContext
-from products.posthog_ai.eval_harness.scorers import LastToolCallNot, NoToolCall
+from products.posthog_ai.eval_harness.scorers import AnswerToolCallNot, NoToolCall
from products.posthog_ai.evals.product_analytics.scorers import (
INSIGHT_WRITE_TOOLS,
TrendsSchemaAlignment,
@@ -313,7 +313,7 @@ async def eval_trends(ctx: EvalContext) -> None:
cases=cases,
scorers=[
NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),
- LastToolCallNot(forbidden="execute-sql", name="last_call_not_execute_sql"),
+ AnswerToolCallNot(forbidden="execute-sql", preferred={"query-trends"}, name="answer_tool_not_execute_sql"),
SkillLoaded("providing-insights", name="providing_insights_skill_loaded"),
TrendsSchemaAlignment(),
TrendsTimeRangeRelevancy(),
diff --git a/products/posthog_ai/evals/product_analytics/eval_typed_runner_lock_in.py b/products/posthog_ai/evals/product_analytics/eval_typed_runner_lock_in.py
new file mode 100644
index 000000000000..d02003e698e6
--- /dev/null
+++ b/products/posthog_ai/evals/product_analytics/eval_typed_runner_lock_in.py
@@ -0,0 +1,146 @@
+"""Multi-turn routing evals for the ``execute-sql`` lock-in.
+
+Once the agent falls back to ``execute-sql``, it stays there: it uses SQL even
+for questions a typed runner answered earlier in the same chat. These suites
+measure that drift. Each case runs one agent session across four turns and
+grades tool routing per turn with ``FirstRelevantTool(turn=N)``:
+
+1. Turn 1 is typed-runner shaped and sets the habit (expect ``query-trends``).
+2. Turn 2 forces the fallback: a row-level or windowed request only
+ ``execute-sql`` can answer. It is a manipulation check, not a metric — drop
+ any case whose turn 2 missed ``execute-sql`` before comparing arms.
+3. Turn 3 asks a new typed-runner-shaped question. This is the headline number:
+ does the agent recover to ``query-trends`` after the SQL turn?
+4. Turn 4 asks another. It catches one-call recovery — and it is not optional:
+ a fix that appends a routing hint to the SQL *result* (the re-anchor
+ approach) fires only after the turn-3 route is chosen, so it cannot move
+ turn 3 at all. Without turn 4 the harness is blind to that fix.
+
+``eval_typed_runner_no_lock_in_control`` runs the same turns 3 and 4, but its
+turn 2 is also typed-runner shaped. If turn 3 scores low in both arms, the
+cause is conversation depth, not SQL lock-in, and every lock-in fix is aimed
+wrong — run the control every time; the between-arm delta is the only number
+that isolates the bug.
+
+Turn 3 and 4 prompts must be new questions, not rephrasings of turn 1, or the
+score confounds routing with "I answered this already".
+"""
+
+from __future__ import annotations
+
+from products.posthog_ai.eval_harness.base import SandboxedPublicEval
+from products.posthog_ai.eval_harness.config import SandboxedEvalCase
+from products.posthog_ai.eval_harness.harness.context import EvalContext
+from products.posthog_ai.eval_harness.scorers import NoToolCall
+from products.posthog_ai.evals.cli_mcp.scorers import FirstRelevantTool
+from products.posthog_ai.evals.product_analytics.scorers import INSIGHT_WRITE_TOOLS
+
+from .eval_sql_shaped_routing import ANALYSIS_QUERY_TOOLS
+
+# See harness/discovery.py — scales the per-case timeout for every suite here.
+MULTI_TURN_CASES = True
+
+
+def _lock_in_case(
+ *,
+ name: str,
+ turn1_prompt: str,
+ turn2_prompt: str,
+ turn3_prompt: str,
+ turn4_prompt: str,
+) -> SandboxedEvalCase:
+ return SandboxedEvalCase(
+ name=name,
+ prompt=turn1_prompt,
+ followups=[turn2_prompt, turn3_prompt, turn4_prompt],
+ expected={"first_relevant_tool": {"tool": "query-trends"}},
+ )
+
+
+def _lock_in_scorers(*, turn2_expected: str) -> list:
+ """One ``FirstRelevantTool`` per turn; turn 2 is a manipulation check.
+
+ ``expected`` is per-case, so every turn scorer shares the one
+ ``first_relevant_tool.tool`` (``query-trends``). Turn 2's target is the
+ arm's defining difference, so its scorer takes an explicit ``tool``
+ override instead of reading ``expected``.
+ """
+ return [
+ NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),
+ FirstRelevantTool(relevant_tools=ANALYSIS_QUERY_TOOLS, turn=1),
+ FirstRelevantTool(relevant_tools=ANALYSIS_QUERY_TOOLS, turn=2, tool=turn2_expected),
+ FirstRelevantTool(relevant_tools=ANALYSIS_QUERY_TOOLS, turn=3),
+ FirstRelevantTool(relevant_tools=ANALYSIS_QUERY_TOOLS, turn=4),
+ ]
+
+
+async def eval_typed_runner_no_lock_in_control(ctx: EvalContext) -> None:
+ """Control arm: every turn is typed-runner shaped, so no SQL lock-in can set in.
+
+ Built before the treatment arm on purpose: if turn 3 is low here too, the
+ failure is conversation depth and the lock-in fixes are aimed wrong.
+ """
+ cases = [
+ _lock_in_case(
+ name="control_upload_trends_throughout",
+ turn1_prompt="Count uploaded_file events per day over the last 30 days",
+ turn2_prompt="Show downloaded_file events grouped by file_type over the last 30 days",
+ turn3_prompt="How did weekly deleted_file events trend over the last 8 weeks?",
+ turn4_prompt="Break weekly shared_file_link counts down by file_type over the last 8 weeks",
+ ),
+ _lock_in_case(
+ name="control_signup_trends_throughout",
+ turn1_prompt="How many signed_up events per week over the last 8 weeks?",
+ turn2_prompt="How many logged_in events per week over the last 8 weeks?",
+ turn3_prompt="Break weekly uploaded_file counts down by file_type over the last 8 weeks",
+ turn4_prompt="Compare weekly signups from new accounts versus invited team members over the last 8 weeks",
+ ),
+ _lock_in_case(
+ name="control_download_trends_throughout",
+ turn1_prompt="Show downloaded_file events grouped by file_type over the last 30 days",
+ turn2_prompt="How did weekly uploaded_file counts trend over the last 8 weeks?",
+ turn3_prompt="Count distinct users who uploaded a file each week over the last 8 weeks",
+ turn4_prompt="How did weekly downloaded_file events trend over the last 8 weeks?",
+ ),
+ ]
+
+ await SandboxedPublicEval(
+ experiment_name="sandboxed-typed-runner-no-lock-in-control-cli",
+ cases=cases,
+ scorers=_lock_in_scorers(turn2_expected="query-trends"),
+ ctx=ctx,
+ )
+
+
+async def eval_typed_runner_lock_in(ctx: EvalContext) -> None:
+ """Treatment arm: turn 2 forces ``execute-sql``; turns 3 and 4 measure recovery."""
+ cases = [
+ _lock_in_case(
+ name="lock_in_upload_trends",
+ turn1_prompt="Count uploaded_file events per day over the last 30 days",
+ turn2_prompt="List the 10 largest files by file_size_b from uploaded_file, with their file_name",
+ turn3_prompt="How did weekly deleted_file events trend over the last 8 weeks?",
+ turn4_prompt="Break weekly shared_file_link counts down by file_type over the last 8 weeks",
+ ),
+ _lock_in_case(
+ name="lock_in_signup_trends",
+ turn1_prompt="How many signed_up events per week over the last 8 weeks?",
+ turn2_prompt="For each account, show the first and last logged_in timestamp",
+ turn3_prompt="Break weekly uploaded_file counts down by file_type over the last 8 weeks",
+ turn4_prompt="Compare weekly signups from new accounts versus invited team members over the last 8 weeks",
+ ),
+ _lock_in_case(
+ name="lock_in_download_trends",
+ turn1_prompt="Show downloaded_file events grouped by file_type over the last 30 days",
+ turn2_prompt="What is the median file_size_b on uploaded_file, and which accounts upload above it?",
+ turn3_prompt="Count distinct users who uploaded a file each week over the last 8 weeks",
+ turn4_prompt="How did weekly downloaded_file events trend over the last 8 weeks?",
+ ),
+ ]
+
+ await SandboxedPublicEval(
+ experiment_name="sandboxed-typed-runner-lock-in-cli",
+ cases=cases,
+ scorers=_lock_in_scorers(turn2_expected="execute-sql"),
+ ctx=ctx,
+ )
diff --git a/products/posthog_ai/evals/sql/eval_sql.py b/products/posthog_ai/evals/sql/eval_sql.py
index b23bcd13495a..0cef1140aa2d 100644
--- a/products/posthog_ai/evals/sql/eval_sql.py
+++ b/products/posthog_ai/evals/sql/eval_sql.py
@@ -23,7 +23,7 @@ from __future__ import annotations
from products.posthog_ai.eval_harness.base import SandboxedPublicEval
from products.posthog_ai.eval_harness.config import SandboxedEvalCase
from products.posthog_ai.eval_harness.harness.context import EvalContext
-from products.posthog_ai.eval_harness.scorers import LastToolCallNot, NoToolCall
+from products.posthog_ai.eval_harness.scorers import AnswerToolCallNot, NoToolCall
from products.posthog_ai.evals.product_analytics.scorers import INSIGHT_WRITE_TOOLS
from products.posthog_ai.evals.retrieval.scorers import SkillLoaded
from products.posthog_ai.evals.sql.scorers import AnswerQueryRan, SQLResultMessageAlignment, SQLSchemaAlignment
@@ -386,9 +386,10 @@ WHERE properties.interests IS NOT NULL
scorers=[
NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),
AnswerQueryRan(name="execute_sql_called"),
- LastToolCallNot(
+ AnswerToolCallNot(
forbidden={"query-trends", "query-funnel", "query-retention"},
- name="last_call_not_typed_query",
+ preferred={"execute-sql"},
+ name="answer_tool_not_typed_query",
),
SkillLoaded("querying-posthog-data", name="querying_posthog_data_skill_loaded"),
SQLSchemaAlignment(),
diff --git a/products/posthog_ai/evals/sql/scorers.py b/products/posthog_ai/evals/sql/scorers.py
index aca83e08587b..7e916fd1c999 100644
--- a/products/posthog_ai/evals/sql/scorers.py
+++ b/products/posthog_ai/evals/sql/scorers.py
@@ -24,11 +24,12 @@ from __future__ import annotations
from typing import Any
+from products.posthog_ai.eval_harness.log_parser import EXECUTE_SQL_TOOL_NAME, is_schema_discovery_call
from products.posthog_ai.eval_harness.scorers import GRADED_ALIGNMENT_CHOICE_SCORES, JUDGE_MODEL, JudgedScorer
from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer
from products.posthog_ai.evals.product_analytics.scorers import GRADED_ALIGNMENT_RUBRIC, parser_for, user_prompt
-QUERY_SQL_TOOL_NAME = "execute-sql"
+QUERY_SQL_TOOL_NAME = EXECUTE_SQL_TOOL_NAME
_MAX_RESULT_CHARS_FOR_JUDGE = 12_000
@@ -52,7 +53,7 @@ def extract_last_execute_sql_call(output: dict[str, Any] | None) -> dict[str, st
successful = [
call
for call in parser.get_tool_calls(QUERY_SQL_TOOL_NAME)
- if not call.is_error and not _is_schema_discovery_query(call.input.get("query"))
+ if not call.is_error and not is_schema_discovery_call(call)
]
if not successful:
return None
@@ -64,11 +65,6 @@ def extract_last_execute_sql_call(output: dict[str, Any] | None) -> dict[str, st
return {"query": query, "result": call.output}
-def _is_schema_discovery_query(query: Any) -> bool:
- """True when the query is an ``information_schema`` schema-discovery lookup, not an answer."""
- return isinstance(query, str) and "information_schema" in query.lower()
-
-
class AnswerQueryRan(Scorer):
"""Binary: did the agent run a real (non-discovery) ``execute-sql`` answer query?
diff --git a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
index 3b31114bd34f..090a5e2814aa 100644
--- a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
+++ b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
@@ -43,6 +43,11 @@ class MultiTurnSession:
printed_lines: int = 0
verbose: bool = False
output_fn: OutputFn = field(default=None)
+ last_full_log: str = ""
+ """Cumulative session log (S3 JSONL) as of the latest completed turn. Empty until
+ the first turn returns. Callers slice per-turn ranges off it via ``log_lines_seen`` —
+ ``poll_for_turn`` already reads the full log each turn and discarded it, so retaining
+ it costs nothing extra."""
# Per-turn poll budget. None falls back to `poll_for_turn`'s default (`MAX_POLL_SECONDS`).
# Set this below the caller's Temporal activity `start_to_close_timeout` so the
# dropped-finalization salvage can fire before the activity is cancelled.
@@ -232,6 +237,7 @@ class MultiTurnSession:
)
session.log_lines_seen = turn.total_lines
session.printed_lines = turn.printed_lines
+ session.last_full_log = turn.full_log or ""
logger.info(
"multi_turn: initial turn completed run=%s duration=%.2fs",
task_run.id,
@@ -311,6 +317,7 @@ class MultiTurnSession:
)
self.log_lines_seen = turn.total_lines
self.printed_lines = turn.printed_lines
+ self.last_full_log = turn.full_log or ""
return turn.last_message
# Catch empty turns, raise everything else
except EmptyAgentTurnError as e:
@@ -329,6 +336,13 @@ class MultiTurnSession:
self.output_fn(f"Agent returned empty response for {label or 'followup'}, {action}")
return None
+ @property
+ def workflow_handle(self) -> WorkflowHandle:
+ """The parent workflow's handle. Raises when the session was built without one."""
+ if self._workflow_handle is None:
+ raise RuntimeError("Workflow handle is not available in this session.")
+ return self._workflow_handle
+
@staticmethod
def _parse_and_validate(text: str, model: type[_ModelT], label: str) -> _ModelT:
"""Extract JSON from agent text and validate against a Pydantic model."""