: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): route MCP SQL schema discovery through system.information_schema behind a flag (#66308)
Georgiy Tarasov067e9b9cfc51
diff --git a/ee/hogai/eval/sandboxed/conftest.py b/ee/hogai/eval/sandboxed/conftest.pyindex 403cb3a94679..5695df3d6df0 100644--- a/ee/hogai/eval/sandboxed/conftest.py+++ b/ee/hogai/eval/sandboxed/conftest.py@@ -202,8 +202,15 @@ def _django_live_server(_sandboxed_eval_database_access):"""from pytest_django.live_server_helper import LiveServer- server = LiveServer(f"localhost:{DJANGO_LIVE_PORT}")- logger.info("Django live server started at %s", server.url)+ # Bind on all interfaces so the sandbox Docker container can reach the server+ # via ``host.docker.internal`` (the docker bridge gateway). The socket binds+ # at thread start using this host; we then re-point ``thread.host`` at+ # localhost purely so ``server.url`` advertises a loopback address to+ # host-side clients (MCP server, LLM gateway) — the already-bound 0.0.0.0+ # socket still accepts both loopback and bridge connections.+ server = LiveServer(f"0.0.0.0:{DJANGO_LIVE_PORT}")+ server.thread.host = "127.0.0.1"+ logger.info("Django live server started at %s (bound on 0.0.0.0)", server.url)yield server@@ -298,6 +305,10 @@ def _sandbox_settings(with (override_settings(DEBUG=True, # Required for sandbox URL validation to allow http://localhost+ # The sandbox container reaches the Django live server with a+ # ``Host: host.docker.internal`` header; allow it (test-only) so the+ # agent's event-ingest stream isn't rejected with an invalid-host 400.+ ALLOWED_HOSTS=["*"],SANDBOX_PROVIDER="docker",SANDBOX_API_URL=docker_api_url,SANDBOX_LLM_GATEWAY_URL=docker_llm_gateway_url,@@ -542,7 +553,10 @@ def _mcp_server(_django_live_server, _sandbox_settings):# Force flag-gated behavior on for evals via the dev/test-only override seam# (honored only when NODE_ENV is explicitly development/test — set above).# `mcp-render-ui` gates the render_ui umbrella tool — see eval_render_ui.py.- "FEATURE_FLAG_OVERRIDES": json.dumps({"mcp-render-ui": True}),+ # `mcp-sql-schema-discovery` routes warehouse/system-table schema discovery+ # through `system.information_schema.*` SQL instead of read-data-warehouse-schema+ # — see eval_system_table_search.py.+ "FEATURE_FLAG_OVERRIDES": json.dumps({"mcp-render-ui": True, "mcp-sql-schema-discovery": True}),}logger.info("Starting MCP server (Hono runtime) on port %d (API: %s)", MCP_PORT, api_url)diff --git a/ee/hogai/eval/sandboxed/data_warehouse/__init__.py b/ee/hogai/eval/sandboxed/data_warehouse/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/ee/hogai/eval/sandboxed/data_warehouse/eval_information_schema.py b/ee/hogai/eval/sandboxed/data_warehouse/eval_information_schema.pynew file mode 100644index 000000000000..e524e645a4d7--- /dev/null+++ b/ee/hogai/eval/sandboxed/data_warehouse/eval_information_schema.py@@ -0,0 +1,296 @@+"""Data-warehouse ``information_schema`` navigation evals for the sandboxed agent.++Each eval seeds a per-case team with hundreds of synthetic warehouse tables,+data-modeling views, and join relationships (``seed_warehouse_schema``), then grades+whether the agent uses ``system.information_schema`` to navigate the catalog at scale.+The ``mcp-sql-schema-discovery`` flag is forced on in the harness, so discovery runs+through ``execute-sql`` against ``system.information_schema.*`` and the dedicated+``read-data-warehouse-schema`` tool is gated off.++The cases are split into one eval function per capability so each Braintrust+experiment reports a clean, homogeneous scorecard (a single shared scorer list mixed+unrelated cases, since every scorer self-skips on cases it doesn't apply to):++* ``eval_dw_discovery`` — discover the right table/model among the noise, using+ agentic search (filter by name/description/data_type) rather than dumping the+ catalog.+* ``eval_dw_value_retrieval`` — retrieve a lookup needle with a real SQL query,+ including duck typing (a column declared ``String`` whose content is numeric).+* ``eval_dw_relationships`` — follow joins surfaced in+ ``information_schema.relationships``, single-hop and multi-hop.+* ``eval_dw_table_relevancy`` — pick the live table over a near-identical+ frozen/superseded decoy, distinguishable only by its annotation.++Prompts read like real user questions and never mention ``information_schema``.++To run a single eval::++ pytest ee/hogai/eval/sandboxed/data_warehouse/eval_information_schema.py::eval_dw_discovery+"""++from __future__ import annotations++from ee.hogai.eval.sandboxed.base import SandboxedPublicEval+from ee.hogai.eval.sandboxed.config import SandboxedEvalCase+from ee.hogai.eval.sandboxed.data_warehouse.scorers import (+ AgenticSearchUsed,+ AnswerQueryRanWhenExpected,+ InformationSchemaBeforeAnswer,+ InformationSchemaQueried,+ JoinPathTraversed,+ NeedleTableIdentified,+ NeedleValueRetrieved,+ RelationshipDiscovery,+ StaleTableAvoided,+ WarehouseAnswerCorrectness,+)+from ee.hogai.eval.sandboxed.data_warehouse.seeder import seed_warehouse_schema+from ee.hogai.eval.sandboxed.data_warehouse.synthesizer import (+ CHAIN_NEEDLE_HOP3,+ DESC_NEEDLE_TABLE,+ REL_NEEDLE_SOURCE,+ REL_NEEDLE_TARGET,+ RELEVANCY_NEEDLE_CURRENT,+ RELEVANCY_NEEDLE_STALE,+ RETRIEVAL_NEEDLE_ANSWER,+ RETRIEVAL_NEEDLE_EVENT_ID,+ RETRIEVAL_NEEDLE_TABLE,+ TYPE_NEEDLE_TABLE,+ VIEW_NEEDLE_NAME,+)+from ee.hogai.eval.sandboxed.scorers import ExitCodeZero+++async def eval_dw_discovery(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+ """Find the right table/model among hundreds via agentic search over the catalog."""+ cases: list[SandboxedEvalCase] = [+ # Discover a specific data model (view) among hundreds of tables. Graded on+ # discovery success (the right model is named), mechanism-agnostic: a view is+ # legitimately discoverable via the `view-list` tool, so this doesn't force+ # information_schema. The information_schema path is enforced by the search /+ # relationship cases, where read-data-warehouse-schema is gated off.+ SandboxedEvalCase(+ name="dw_discover_model_view",+ prompt=(+ "Which data model (view) in our warehouse produces the daily MRR numbers the "+ "finance dashboard reads? Just give me its name."+ ),+ expected={"needle_table_identified": {"table": VIEW_NEEDLE_NAME}},+ setup=seed_warehouse_schema,+ ),+ # Search by description text — the needle is found by filtering the catalog's+ # `description` column with a text pattern, not by guessing the opaque name.+ SandboxedEvalCase(+ name="dw_search_by_description",+ prompt=(+ "We have hundreds of warehouse tables. Find the one whose documentation says it's "+ "the canonical source for monthly recurring revenue, and tell me what it tracks."+ ),+ expected={+ "information_schema_queried": {},+ "agentic_search_used": {"require_pattern": True},+ "needle_table_identified": {"table": DESC_NEEDLE_TABLE},+ },+ setup=seed_warehouse_schema,+ ),+ # Search by column data_type (an equality filter, not a text pattern).+ SandboxedEvalCase(+ name="dw_search_by_column_type",+ prompt=(+ "Across all our warehouse tables, which one has a column stored as a high-precision "+ "Decimal type (not a plain Float)? Give the table and column name."+ ),+ expected={+ "information_schema_queried": {},+ "agentic_search_used": {},+ "needle_table_identified": {"table": TYPE_NEEDLE_TABLE},+ },+ setup=seed_warehouse_schema,+ ),+ ]++ await SandboxedPublicEval(+ experiment_name=f"sandboxed-warehouse-discovery-{mcp_mode}",+ cases=cases,+ scorers=[+ ExitCodeZero(),+ InformationSchemaQueried(),+ AgenticSearchUsed(),+ NeedleTableIdentified(),+ ],+ pytestconfig=pytestconfig,+ sandboxed_demo_data=sandboxed_demo_data,+ posthog_client=posthog_client,+ )+++async def eval_dw_value_retrieval(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+ """Retrieve a lookup needle with a real SQL query, including duck-typed columns."""+ cases: list[SandboxedEvalCase] = [+ # Value lookup against the queryable needle: discover via information_schema,+ # then run a real row query to read the value out of a text-stored JSON payload.+ SandboxedEvalCase(+ name="dw_needle_value_lookup",+ prompt=(+ f"In the warehouse table holding raw Stripe events, the row with "+ f"event_id '{RETRIEVAL_NEEDLE_EVENT_ID}' has a JSON payload stored as text. "+ f"What is its secret_code?"+ ),+ expected={+ "information_schema_before_answer": {},+ "answer_query_ran": {},+ "needle_value_retrieved": {},+ "warehouse_answer_correctness": {+ "expected_answer": (+ f"The secret_code in the payload of row {RETRIEVAL_NEEDLE_EVENT_ID} in "+ f"{RETRIEVAL_NEEDLE_TABLE} is {RETRIEVAL_NEEDLE_ANSWER}."+ ),+ "requires_queryable": True,+ },+ },+ setup=seed_warehouse_schema,+ ),+ # Duck typing: declared String, content is numeric. The agent must cast to+ # compare (a plain text max returns the wrong row).+ SandboxedEvalCase(+ name="dw_duck_typing_amount",+ prompt=(+ f"The 'amount' column in our '{RETRIEVAL_NEEDLE_TABLE}' table is stored as text. "+ "What is the largest amount value in that table, and is it actually numeric?"+ ),+ expected={+ "information_schema_queried": {},+ "needle_value_retrieved": {"value": "24990"},+ "warehouse_answer_correctness": {+ "expected_answer": (+ f"The largest amount in {RETRIEVAL_NEEDLE_TABLE} is 24990; the column is "+ "declared as String/text but the values are numeric and must be cast to compare "+ "(a plain text/string max would wrongly return 9990)."+ ),+ "requires_queryable": True,+ },+ },+ setup=seed_warehouse_schema,+ ),+ ]++ await SandboxedPublicEval(+ experiment_name=f"sandboxed-warehouse-retrieval-{mcp_mode}",+ cases=cases,+ scorers=[+ ExitCodeZero(),+ InformationSchemaQueried(),+ InformationSchemaBeforeAnswer(),+ NeedleValueRetrieved(),+ AnswerQueryRanWhenExpected(name="answer_query_ran"),+ WarehouseAnswerCorrectness(),+ ],+ pytestconfig=pytestconfig,+ sandboxed_demo_data=sandboxed_demo_data,+ posthog_client=posthog_client,+ )+++async def eval_dw_relationships(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+ """Follow joins surfaced in information_schema.relationships, single- and multi-hop."""+ cases: list[SandboxedEvalCase] = [+ # Single-hop relationship traversal. Graded deterministically by+ # relationship_discovery (relationships queried + both tables named); no LLM+ # judge, since the answer comes from the discovery query rather than a row query.+ SandboxedEvalCase(+ name="dw_relationship_traversal",+ prompt=(+ f"Our orders table '{REL_NEEDLE_SOURCE}' is linked to another warehouse table "+ f"through a defined relationship. Which table is it, and on what key do they join?"+ ),+ expected={+ "information_schema_queried": {},+ "relationship_discovery": {},+ },+ setup=seed_warehouse_schema,+ ),+ # Multi-hop / multi-table: assemble a two-hop join path by querying relationships+ # iteratively (orders -> account xref -> account owners). Tests combining several+ # discovered tables, not a single needle.+ SandboxedEvalCase(+ name="dw_multi_hop_join_path",+ prompt=(+ f"Starting from our orders table '{REL_NEEDLE_SOURCE}', I need to reach account-owner "+ "information. Which tables do I join through, in order, and on what keys? Trace the full path."+ ),+ expected={+ "information_schema_queried": {},+ "join_path_traversed": {},+ "warehouse_answer_correctness": {+ "expected_answer": (+ f"The path is two hops: {REL_NEEDLE_SOURCE} joins {REL_NEEDLE_TARGET} on account_ref, "+ f"and {REL_NEEDLE_TARGET} joins {CHAIN_NEEDLE_HOP3} on owner_id. So orders -> account "+ "xref -> account owners."+ ),+ },+ },+ setup=seed_warehouse_schema,+ ),+ ]++ await SandboxedPublicEval(+ experiment_name=f"sandboxed-warehouse-relationships-{mcp_mode}",+ cases=cases,+ scorers=[+ ExitCodeZero(),+ InformationSchemaQueried(),+ RelationshipDiscovery(),+ JoinPathTraversed(),+ WarehouseAnswerCorrectness(),+ ],+ pytestconfig=pytestconfig,+ sandboxed_demo_data=sandboxed_demo_data,+ posthog_client=posthog_client,+ )+++async def eval_dw_table_relevancy(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+ """Pick the live table over a near-identical frozen/superseded decoy."""+ cases: list[SandboxedEvalCase] = [+ # Two near-identical accounts dimensions, one live and one frozen/superseded.+ # Only the annotation distinguishes them, so the agent must read metadata (not+ # shortcut on the name) and recommend the current table while flagging the stale+ # one — not pick the decoy.+ SandboxedEvalCase(+ name="dw_table_relevancy_stale",+ prompt=(+ "We have more than one accounts dimension table in the warehouse. Which one should I "+ "use for current customer reporting, and what's wrong with the other one?"+ ),+ expected={+ "information_schema_queried": {},+ "agentic_search_used": {},+ "needle_table_identified": {"table": RELEVANCY_NEEDLE_CURRENT},+ "stale_table_avoided": {},+ "warehouse_answer_correctness": {+ "expected_answer": (+ f"Use {RELEVANCY_NEEDLE_CURRENT} — it is the live, daily-refreshed canonical "+ f"accounts dimension. {RELEVANCY_NEEDLE_STALE} is deprecated/superseded: a frozen "+ "2023 snapshot that is no longer refreshed, so it must not be used for current reporting."+ ),+ },+ },+ setup=seed_warehouse_schema,+ ),+ ]++ await SandboxedPublicEval(+ experiment_name=f"sandboxed-warehouse-relevancy-{mcp_mode}",+ cases=cases,+ scorers=[+ ExitCodeZero(),+ InformationSchemaQueried(),+ AgenticSearchUsed(),+ NeedleTableIdentified(),+ StaleTableAvoided(),+ WarehouseAnswerCorrectness(),+ ],+ pytestconfig=pytestconfig,+ sandboxed_demo_data=sandboxed_demo_data,+ posthog_client=posthog_client,+ )diff --git a/ee/hogai/eval/sandboxed/data_warehouse/scorers.py b/ee/hogai/eval/sandboxed/data_warehouse/scorers.pynew file mode 100644index 000000000000..a832ab7ef6cc--- /dev/null+++ b/ee/hogai/eval/sandboxed/data_warehouse/scorers.py@@ -0,0 +1,616 @@+"""Scorers for the data-warehouse ``information_schema`` navigation eval.++All scorers are mode-agnostic: they read tool calls through ``LogParser``+(tools-mode and CLI exec both normalize to ``execute-sql``) and the agent's+final text. Each self-skips with ``Score(score=None)`` when its ``expected`` key+is absent, so one global scorer list works across every case — Braintrust drops+``None`` from per-metric aggregates.++Targets/answers come from ``output["seed"]`` (set by ``seed_warehouse_schema``);+cases opt a scorer in by listing its ``_name()`` in ``expected``. The scorers+degrade gracefully when the queryable needle's backing data is unavailable:+discovery/search/relationship grading never touches object storage.+"""++from __future__ import annotations++from typing import Any++from braintrust import Score+from braintrust_core.score import Scorer++from ee.hogai.eval.sandboxed.log_parser import LogParser, ToolCall+from ee.hogai.eval.sandboxed.product_analytics.scorers import (+ GRADED_ALIGNMENT_CHOICE_SCORES,+ JUDGE_MODEL,+ JudgedScorer,+ parser_for,+ user_prompt,+)+from ee.hogai.eval.sandboxed.sql.scorers import _truncate_result_for_judge, extract_last_execute_sql_call++__all__ = [+ "InformationSchemaQueried",+ "InformationSchemaBeforeAnswer",+ "AgenticSearchUsed",+ "NeedleTableIdentified",+ "NeedleValueRetrieved",+ "RelationshipDiscovery",+ "StaleTableAvoided",+ "JoinPathTraversed",+ "AnswerQueryRanWhenExpected",+ "WarehouseAnswerCorrectness",+]++SQL_TOOL = "execute-sql"+_INFO_SCHEMA = "information_schema"+++def _query_text(call: ToolCall) -> str:+ query = call.input.get("query") if isinstance(call.input, dict) else None+ return query.lower() if isinstance(query, str) else ""+++def _is_info_schema(call: ToolCall) -> bool:+ return _INFO_SCHEMA in _query_text(call)+++def _successful_sql(parser: LogParser) -> list[ToolCall]:+ return sorted((c for c in parser.get_tool_calls(SQL_TOOL) if not c.is_error), key=lambda c: c.position)+++def _seed(output: dict[str, Any] | None) -> dict[str, Any]:+ seed = output.get("seed") if output else None+ return seed if isinstance(seed, dict) else {}+++def _requested(expected: dict | None, name: str) -> bool:+ return isinstance(expected, dict) and name in expected+++def _final_message(output: dict[str, Any] | None) -> str:+ message = (output or {}).get("last_message") or ""+ return message if isinstance(message, str) else str(message)+++class InformationSchemaQueried(Scorer):+ """Binary: did the agent discover the schema via ``system.information_schema``?++ The primary capability-#1 check — never needs row data, so it grades the same+ whether or not the warehouse is queryable. Opt-in via ``expected`` key.+ """++ def _name(self) -> str:+ return "information_schema_queried"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ if not output:+ return Score(name=self._name(), score=None, metadata={"reason": "No output"})+ if not _requested(expected, self._name()):+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})+ parser = parser_for(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})+ hits = [c for c in _successful_sql(parser) if _is_info_schema(c)]+ return Score(name=self._name(), score=1.0 if hits else 0.0, metadata={"info_schema_queries": len(hits)})+++class InformationSchemaBeforeAnswer(Scorer):+ """Binary: was every non-discovery ``execute-sql`` preceded by an info_schema query?++ DWH adaptation of the ``system.*`` discipline scorer: warehouse tables are+ bare-named, so the "answer" query is simply any successful ``execute-sql`` that+ is not an ``information_schema`` lookup. ``None`` when no answer query ran.+ """++ def _name(self) -> str:+ return "information_schema_before_answer"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ if not output:+ return Score(name=self._name(), score=None, metadata={"reason": "No output"})+ if not _requested(expected, self._name()):+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})+ parser = parser_for(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ seen_discovery = False+ offenders: list[str] = []+ answer_calls = 0+ for call in _successful_sql(parser):+ if _is_info_schema(call):+ seen_discovery = True+ continue+ answer_calls += 1+ if not seen_discovery:+ offenders.append(call.call_id)++ if answer_calls == 0:+ return Score(name=self._name(), score=None, metadata={"reason": "No non-discovery answer query ran"})+ if offenders:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "answer query ran before discovery", "offenders": offenders},+ )+ return Score(name=self._name(), score=1.0, metadata={"answer_calls": answer_calls})+++class AgenticSearchUsed(Scorer):+ """Binary: did discovery filter the catalog instead of dumping it?++ Inspects the SQL text of ``information_schema`` queries. A *filtered* query has+ a ``WHERE`` referencing a real metadata column or using a pattern predicate; a+ *dump* selects from ``tables``/``columns`` with no ``WHERE``. When the case sets+ ``require_pattern``, only a pattern predicate (LIKE/ILIKE/match) counts.+ """++ _FILTERABLE = (+ "table_name",+ "table_type",+ "table_schema",+ "description",+ "data_type",+ "column_name",+ "field_kind",+ "source_table",+ "target_table",+ "relationship_kind",+ )+ _PATTERNS = ("like", "ilike", "match(", "multisearchany", "positioncaseinsensitive")++ def _name(self) -> str:+ return "agentic_search_used"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ if not output:+ return Score(name=self._name(), score=None, metadata={"reason": "No output"})+ if not _requested(expected, self._name()):+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})+ spec = expected.get(self._name()) if isinstance(expected, dict) else None+ spec = spec if isinstance(spec, dict) else {}+ parser = parser_for(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ info_queries = [_query_text(c) for c in _successful_sql(parser) if _is_info_schema(c)]+ if not info_queries:+ return Score(name=self._name(), score=None, metadata={"reason": "No information_schema query ran"})++ filtered = dumps = patterns = 0+ for query in info_queries:+ has_where = " where " in query+ uses_pattern = any(p in query for p in self._PATTERNS)+ refs_column = any(col in query for col in self._FILTERABLE)+ if uses_pattern:+ patterns += 1+ if has_where and (refs_column or uses_pattern):+ filtered += 1+ elif not has_where and ("information_schema.tables" in query or "information_schema.columns" in query):+ dumps += 1++ metadata = {"filtered": filtered, "dumps": dumps, "patterns": patterns, "total": len(info_queries)}+ if spec.get("require_pattern"):+ return Score(name=self._name(), score=1.0 if patterns else 0.0, metadata=metadata)+ return Score(name=self._name(), score=1.0 if filtered else 0.0, metadata=metadata)+++class NeedleTableIdentified(Scorer):+ """Binary: did the agent name the correct needle table (queryability-safe)?++ Resolves the target table from ``expected[name]["table"]`` or, when the case+ points at a seed entry, ``seed[expected[name]["seed_key"]]["table"]``. Passes+ when the table appears in the final message or any ``execute-sql`` text.+ """++ def _name(self) -> str:+ return "needle_table_identified"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _resolve_table(self, output: dict | None, expected: dict | None) -> str | None:+ spec = expected.get(self._name()) if isinstance(expected, dict) else None+ if not isinstance(spec, dict):+ return None+ if isinstance(spec.get("table"), str):+ return spec["table"]+ seed_key = spec.get("seed_key")+ if isinstance(seed_key, str):+ entry = _seed(output).get(seed_key)+ if isinstance(entry, dict) and isinstance(entry.get("table"), str):+ return entry["table"]+ return None++ def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ if not output:+ return Score(name=self._name(), score=None, metadata={"reason": "No output"})+ if not _requested(expected, self._name()):+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})+ table = self._resolve_table(output, expected)+ if not table:+ return Score(name=self._name(), score=None, metadata={"reason": "no table configured"})+ needle = table.lower()+ if needle in _final_message(output).lower():+ return Score(name=self._name(), score=1.0, metadata={"matched_via": "final_message", "table": table})+ parser = parser_for(output)+ if parser is not None:+ for call in _successful_sql(parser):+ if needle in _query_text(call):+ return Score(name=self._name(), score=1.0, metadata={"matched_via": "sql_ref", "table": table})+ return Score(name=self._name(), score=0.0, metadata={"table": table})+++class NeedleValueRetrieved(Scorer):+ """Binary: does the retrieval-needle value appear in the SQL result or final answer?++ The graded value defaults to the retrieval needle's ``answer`` (the JSON+ secret_code), but a case can override it via ``expected[name]["value"]`` — e.g.+ the duck-typing case grades the numeric max, not the secret_code.++ Self-skips (``None``) when the queryable needle could not be created (object+ storage unavailable) — the value is genuinely unreachable then. Otherwise the+ value must appear in the last non-discovery ``execute-sql`` result (preferred)+ or the final message (``degraded`` fallback).+ """++ def _name(self) -> str:+ return "needle_value_retrieved"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ if not output:+ return Score(name=self._name(), score=None, metadata={"reason": "No output"})+ if not _requested(expected, self._name()):+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})+ retrieval = _seed(output).get("retrieval_needle")+ if not isinstance(retrieval, dict):+ return Score(name=self._name(), score=None, metadata={"reason": "no retrieval needle configured"})+ if not retrieval.get("queryable"):+ return Score(name=self._name(), score=None, metadata={"reason": "needle not queryable in this env"})++ spec = expected.get(self._name()) if isinstance(expected, dict) else None+ override = spec.get("value") if isinstance(spec, dict) else None+ value = override if isinstance(override, str) else retrieval.get("answer")+ if not isinstance(value, str):+ return Score(name=self._name(), score=None, metadata={"reason": "no needle value configured"})++ needle = value.lower()+ call = extract_last_execute_sql_call(output)+ if call and needle in (call.get("result") or "").lower():+ return Score(name=self._name(), score=1.0, metadata={"matched_via": "sql_result", "needle": needle})+ if needle in _final_message(output).lower():+ return Score(+ name=self._name(),+ score=1.0,+ metadata={"matched_via": "final_message", "needle": needle, "degraded": call is None},+ )+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"needle": needle, "answer_query_ran": call is not None},+ )+++class RelationshipDiscovery(Scorer):+ """Binary: did the agent discover the join and reference both tables?++ Reads the pair from ``seed["relationship_needle"]``. Passes when the agent+ queried ``information_schema.relationships`` (or co-referenced both tables in+ one query) AND both tables appear in a query or the final message.+ """++ def _name(self) -> str:+ return "relationship_discovery"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ if not output:+ return Score(name=self._name(), score=None, metadata={"reason": "No output"})+ if not _requested(expected, self._name()):+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})+ rel = _seed(output).get("relationship_needle")+ if not isinstance(rel, dict) or not rel.get("source") or not rel.get("target"):+ return Score(name=self._name(), score=None, metadata={"reason": "no relationship needle configured"})+ parser = parser_for(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ source, target = rel["source"].lower(), rel["target"].lower()+ calls = _successful_sql(parser)+ rel_queried = any("information_schema.relationships" in _query_text(c) for c in calls)+ joined_in_sql = any(source in _query_text(c) and target in _query_text(c) for c in calls)+ final = _final_message(output).lower()+ named_in_message = source in final and target in final++ discovered = rel_queried or joined_in_sql+ referenced = joined_in_sql or named_in_message+ ok = discovered and referenced+ return Score(+ name=self._name(),+ score=1.0 if ok else 0.0,+ metadata={+ "relationships_queried": rel_queried,+ "joined_in_sql": joined_in_sql,+ "named_in_message": named_in_message,+ "degraded": ok and not joined_in_sql,+ },+ )+++class StaleTableAvoided(Scorer):+ """Binary: did the agent pick the live table over the superseded decoy?++ Two near-identical tables share a topic; only the annotation says which is+ current. Reads the pair from ``seed["relevancy_needle"]`` (``current`` /+ ``stale``). Passes when the final answer surfaces the current table AND does not+ leave the stale table standing as a usable option — naming the stale table is+ fine only when the answer flags it as deprecated/superseded. Fails when the+ agent recommends the stale table or never finds the current one.+ """++ _DEPRECATION_CUES = (+ "deprecat",+ "supersed",+ "no longer",+ "frozen",+ "stale",+ "outdated",+ "do not use",+ "don't use",+ "legacy",+ "replaced",+ "not refreshed",+ "instead of",+ )++ def _name(self) -> str:+ return "stale_table_avoided"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ if not output:+ return Score(name=self._name(), score=None, metadata={"reason": "No output"})+ if not _requested(expected, self._name()):+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})+ rel = _seed(output).get("relevancy_needle")+ if not isinstance(rel, dict) or not rel.get("current") or not rel.get("stale"):+ return Score(name=self._name(), score=None, metadata={"reason": "no relevancy needle configured"})++ current, stale = rel["current"].lower(), rel["stale"].lower()+ final = _final_message(output).lower()+ current_named = current in final+ stale_named = stale in final+ # Only count the stale name as "deprecation-flagged" when a cue word actually+ # appears in the answer — otherwise a bare mention reads as recommending it.+ stale_flagged = stale_named and any(cue in final for cue in self._DEPRECATION_CUES)++ ok = current_named and (not stale_named or stale_flagged)+ return Score(+ name=self._name(),+ score=1.0 if ok else 0.0,+ metadata={+ "current_named": current_named,+ "stale_named": stale_named,+ "stale_flagged": stale_flagged,+ },+ )+++class JoinPathTraversed(Scorer):+ """Binary: did the agent assemble the full multi-hop join path?++ Reads the ordered path from ``seed["chain_needle"]`` (``tables``: source-first;+ ``keys``: per hop). Passes when the agent queried+ ``information_schema.relationships`` AND every table on the path appears in a+ query or the final answer — i.e. it followed the relationships out across more+ than one hop rather than stopping at the first. Join keys named are tracked in+ metadata but not required (table coverage is the load-bearing signal).+ """++ def _name(self) -> str:+ return "join_path_traversed"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ if not output:+ return Score(name=self._name(), score=None, metadata={"reason": "No output"})+ if not _requested(expected, self._name()):+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})+ chain = _seed(output).get("chain_needle")+ tables = chain.get("tables") if isinstance(chain, dict) else None+ if not isinstance(tables, list) or len(tables) < 3:+ return Score(name=self._name(), score=None, metadata={"reason": "no chain needle configured"})+ parser = parser_for(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ calls = _successful_sql(parser)+ rel_queried = any("information_schema.relationships" in _query_text(c) for c in calls)+ final = _final_message(output).lower()+ sql_blob = " ".join(_query_text(c) for c in calls)+ named = [t for t in tables if t.lower() in final or t.lower() in sql_blob]+ all_named = len(named) == len(tables)++ keys = chain.get("keys") if isinstance(chain, dict) else []+ keys = keys if isinstance(keys, list) else []+ keys_named = [k for k in keys if k.lower() in final]++ ok = rel_queried and all_named+ return Score(+ name=self._name(),+ score=1.0 if ok else 0.0,+ metadata={+ "relationships_queried": rel_queried,+ "tables_named": named,+ "all_tables_named": all_named,+ "keys_named": keys_named,+ },+ )+++class AnswerQueryRanWhenExpected(Scorer):+ """Binary: did a real (non-discovery) ``execute-sql`` answer query run?++ Gates the reused ``AnswerQueryRan`` behind an ``expected`` opt-in. The base+ scorer scores 0.0 even when the agent legitimately answers from+ ``information_schema`` alone, which would wrongly fail discovery/search cases —+ so this returns ``None`` unless the case opts in.+ """++ def __init__(self, *, name: str = "answer_query_ran") -> None:+ self._label = name++ def _name(self) -> str:+ return self._label++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:+ if not output:+ return Score(name=self._name(), score=None, metadata={"reason": "No output"})+ if not _requested(expected, self._name()):+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})+ ran = extract_last_execute_sql_call(output) is not None+ return Score(name=self._name(), score=1.0 if ran else 0.0, metadata={"answer_query_ran": ran})+++WAREHOUSE_ANSWER_PROMPT = """+You are an expert data analyst judging whether an agent correctly answered a user's question about a data warehouse, given the SQL it ran and its final message.++The agent navigates the warehouse via `system.information_schema` and `execute-sql`. Judge the FINAL message against the expected answer. Use the executed query and result as supporting evidence.++Grade on faithfulness and completeness:+- Reward an answer that matches the expected answer's key facts (the right table/column/value/relationship).+- For "duck typing" questions, reward correctly recognizing that a column declared as `String` actually holds numeric or JSON content by INSPECTING the values, and penalize an answer that trusts the declared type without looking at the data.+- Penalize fabricated values not supported by the SQL result, or an answer that contradicts the result.+- If the executed result is genuinely empty or unavailable, only accept an answer that honestly reports that — do not reward invented values.++User prompt:+<user_prompt>+{{output.prompt}}+</user_prompt>++Expected answer:+<expected_answer>+{{expected.expected_answer}}+</expected_answer>++Executed HogQL (may be "(no row query executed)"):+<executed_query>+{{output.sql_query}}+</executed_query>++SQL result (may be "(unavailable)"):+<sql_result>+{{output.sql_result}}+</sql_result>++Final assistant message:+<final_message>+{{output.final_message}}+</final_message>+""".strip()+++WAREHOUSE_ANSWER_RUBRIC = """+How would you rate the assistant's final answer against the expected answer? Choose one:+- perfect: States the expected answer's key facts (table/column/value/relationship) with no errors.+- near_perfect: Conveys the expected answer with only a minor omission or harmless extra detail.+- slightly_off: Mostly correct but misses a minor fact or is slightly imprecise.+- somewhat_misaligned: Partly correct but omits an important fact or is hard to act on.+- strongly_misaligned: Contradicts the expected answer, answers a different question, or trusts a declared type without inspecting the data when the question required it.+- useless: No meaningful answer, fabricated value, or impossible to evaluate.++Be strict about factual faithfulness. Do not reward a fluent answer that invents values not supported by the SQL result.+""".strip()+++class WarehouseAnswerCorrectness(JudgedScorer):+ """Graded LLM judge: did the final message correctly answer the warehouse question?++ Used on the nuanced duck-typing / relationship cases where string-matching is+ too brittle. Self-skips (``None``) when not requested, or when the case sets+ ``requires_queryable`` and the retrieval needle is not queryable in this env.+ """++ def _prepare(self, output, expected) -> dict[str, Any] | Score:+ spec = expected.get(self._name()) if isinstance(expected, dict) else None+ if not isinstance(spec, dict) or not isinstance(spec.get("expected_answer"), str):+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})+ if spec.get("requires_queryable"):+ retrieval = _seed(output).get("retrieval_needle")+ if not (isinstance(retrieval, dict) and retrieval.get("queryable")):+ return Score(name=self._name(), score=None, metadata={"reason": "needle not queryable in this env"})++ parser = parser_for(output)+ final = parser.get_final_agent_message() if parser is not None else None+ if not isinstance(final, str) or not final.strip():+ return Score(name=self._name(), score=0.0, metadata={"reason": "no final message"})++ call = extract_last_execute_sql_call(output)+ return {+ "output": {+ "prompt": user_prompt(output),+ "sql_query": call["query"] if call else "(no row query executed)",+ "sql_result": _truncate_result_for_judge(call["result"]) if call else "(unavailable)",+ "final_message": final,+ },+ "expected": {"expected_answer": spec["expected_answer"]},+ }++ def __init__(self, **kwargs):+ super().__init__(+ name="warehouse_answer_correctness",+ prompt_template=WAREHOUSE_ANSWER_PROMPT + "\n\n" + WAREHOUSE_ANSWER_RUBRIC,+ choice_scores=GRADED_ALIGNMENT_CHOICE_SCORES,+ model=JUDGE_MODEL,+ max_completion_tokens=512,+ **kwargs,+ )diff --git a/ee/hogai/eval/sandboxed/data_warehouse/seeder.py b/ee/hogai/eval/sandboxed/data_warehouse/seeder.pynew file mode 100644index 000000000000..29c3d2b1786b--- /dev/null+++ b/ee/hogai/eval/sandboxed/data_warehouse/seeder.py@@ -0,0 +1,251 @@+"""Seeder hook that installs a synthetic data warehouse into a per-case team.++Translates the pure ``WarehouseSchemaSynthesizer`` output into ORM rows:+hundreds of self-managed ``DataWarehouseTable`` metadata rows (no S3 needed to be+*discoverable*), their table/column annotations, the data-modeling views, and the+join relationships. The one queryable "duck typing" needle is created best-effort+via CSV upload to object storage — if that environment isn't available the seed+still succeeds and records ``queryable=False`` so its scorer self-skips.++Runs synchronously in a worker thread (``asyncio.to_thread``) from+``base.py:task()`` after the per-case team is provisioned; the returned dict is+merged into the task output under ``seed`` for scorers.+"""++from __future__ import annotations++import csv+import logging+from typing import TYPE_CHECKING, Any++from ee.hogai.eval.sandboxed.data_warehouse.synthesizer import (+ CHAIN_NEEDLE_HOP3,+ CHAIN_NEEDLE_KEY,+ DESC_NEEDLE_PHRASE,+ DESC_NEEDLE_TABLE,+ REL_NEEDLE_FIELD,+ REL_NEEDLE_KEY,+ REL_NEEDLE_SOURCE,+ REL_NEEDLE_TARGET,+ RELEVANCY_NEEDLE_CURRENT,+ RELEVANCY_NEEDLE_STALE,+ RETRIEVAL_NEEDLE_ANSWER,+ RETRIEVAL_NEEDLE_EVENT_ID,+ RETRIEVAL_NEEDLE_PREFIX,+ TYPE_NEEDLE_COLUMN,+ TYPE_NEEDLE_DATA_TYPE,+ TYPE_NEEDLE_TABLE,+ VIEW_NEEDLE_NAME,+ SynthTable,+ WarehouseSchemaSynthesizer,+)++if TYPE_CHECKING:+ from posthog.models.team import Team++ from products.tasks.backend.facade.agents import CustomPromptSandboxContext++logger = logging.getLogger(__name__)++__all__ = ["seed_warehouse_schema"]+++def seed_warehouse_schema(context: CustomPromptSandboxContext) -> dict[str, Any]:+ """Seed a synthetic warehouse: ~250 metadata tables, annotations, views, joins,+ and one best-effort queryable CSV needle. Returns the ``seed`` dict scorers read."""+ from posthog.models.scoping import team_scope+ from posthog.models.team import Team++ from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+ from products.data_tools.backend.models.join import DataWarehouseJoin+ from products.warehouse_sources.backend.models.column_annotation import WarehouseColumnAnnotation+ from products.warehouse_sources.backend.models.table import DataWarehouseTable++ team = Team.objects.get(pk=context.team_id)+ user_id = context.user_id+ warehouse = WarehouseSchemaSynthesizer().generate()++ # 1. Metadata tables. Self-managed (no external_data_source / credential) so they+ # register under their literal name and surface in information_schema without S3.+ metadata_tables = [t for t in warehouse.tables if not t.queryable]+ table_models = {+ t.name: DataWarehouseTable(+ team=team,+ name=t.name,+ format=DataWarehouseTable.TableFormat.CSVWithNames,+ url_pattern="",+ columns=t.columns_json(),+ row_count=t.row_count,+ credential=None,+ )+ for t in metadata_tables+ }+ DataWarehouseTable.objects.bulk_create(list(table_models.values()), batch_size=200)++ # 2. Annotations — table-level (column_name="") and column-level — under team_scope.+ # UUIDTModel ids are generated client-side, so the in-memory models carry valid pks.+ annotations: list[WarehouseColumnAnnotation] = []+ source = WarehouseColumnAnnotation.DescriptionSource.CANONICAL+ for t in metadata_tables:+ model = table_models[t.name]+ if t.description:+ annotations.append(+ WarehouseColumnAnnotation(+ team=team, table=model, column_name="", description=t.description, description_source=source+ )+ )+ for column in t.columns:+ if column.description:+ annotations.append(+ WarehouseColumnAnnotation(+ team=team,+ table=model,+ column_name=column.name,+ description=column.description,+ description_source=source,+ )+ )+ with team_scope(team.id, canonical=True):+ WarehouseColumnAnnotation.objects.bulk_create(annotations, batch_size=200)++ # 3. Views ("models").+ for view in warehouse.views:+ DataWarehouseSavedQuery.objects.create(+ team=team,+ created_by_id=user_id,+ name=view.name,+ columns=view.columns_json(),+ query={"query": view.sql},+ status=DataWarehouseSavedQuery.Status.COMPLETED,+ )++ # 4. Joins — both endpoint tables already exist, keys are bare column names.+ for join in warehouse.joins:+ DataWarehouseJoin.objects.create(+ team=team,+ source_table_name=join.source_table,+ source_table_key=join.source_key,+ joining_table_name=join.joining_table,+ joining_table_key=join.joining_key,+ field_name=join.field_name,+ )++ # 5. Queryable retrieval needle — best-effort; never fail the seed.+ retrieval_table = next((t for t in warehouse.tables if t.queryable), None)+ retrieval_meta: dict[str, Any] = {"queryable": False, "answer": RETRIEVAL_NEEDLE_ANSWER}+ if retrieval_table is not None:+ retrieval_meta = _create_queryable_needle(team, retrieval_table)++ payload: dict[str, Any] = {+ "table_count": len(metadata_tables) + (1 if retrieval_meta.get("queryable") else 0),+ "view_count": len(warehouse.views),+ "join_count": len(warehouse.joins),+ "description_needle": {"table": DESC_NEEDLE_TABLE, "phrase": DESC_NEEDLE_PHRASE},+ "column_type_needle": {+ "table": TYPE_NEEDLE_TABLE,+ "column": TYPE_NEEDLE_COLUMN,+ "data_type": TYPE_NEEDLE_DATA_TYPE,+ },+ "relationship_needle": {+ "source": REL_NEEDLE_SOURCE,+ "target": REL_NEEDLE_TARGET,+ "key": REL_NEEDLE_KEY,+ "field_name": REL_NEEDLE_FIELD,+ },+ "relevancy_needle": {"current": RELEVANCY_NEEDLE_CURRENT, "stale": RELEVANCY_NEEDLE_STALE},+ "chain_needle": {+ "tables": [REL_NEEDLE_SOURCE, REL_NEEDLE_TARGET, CHAIN_NEEDLE_HOP3],+ "keys": [REL_NEEDLE_KEY, CHAIN_NEEDLE_KEY],+ },+ "view_needle": {"name": VIEW_NEEDLE_NAME},+ "retrieval_needle": retrieval_meta,+ }+ logger.info(+ "Seeded synthetic warehouse for team_id=%s: %d tables, %d views, %d joins (retrieval queryable=%s)",+ team.id,+ payload["table_count"],+ payload["view_count"],+ payload["join_count"],+ retrieval_meta.get("queryable"),+ )+ return payload+++def _create_queryable_needle(team: Team, table: SynthTable) -> dict[str, Any]:+ """Upload the needle's CSV to object storage and register a queryable table.++ Inlines the minimal create-from-CSV path (it only needs ``warehouse_sources``+ models) so the eval doesn't reach into another product's test helpers. Returns+ ``queryable=False`` (and logs) on any failure — object storage may be+ unavailable in the harness, in which case the retrieval scorer self-skips and+ the other four needles (metadata-only) are unaffected.+ """+ import s3fs++ from posthog.settings import (+ OBJECT_STORAGE_ACCESS_KEY_ID,+ OBJECT_STORAGE_BUCKET,+ OBJECT_STORAGE_ENDPOINT,+ OBJECT_STORAGE_SECRET_ACCESS_KEY,+ XDIST_SUFFIX,+ )++ from products.warehouse_sources.backend.models.credential import DataWarehouseCredential+ from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+ from products.warehouse_sources.backend.models.table import DataWarehouseTable+ from products.warehouse_sources.backend.types import ExternalDataSourceType++ degraded = {"queryable": False, "answer": RETRIEVAL_NEEDLE_ANSWER, "event_id": RETRIEVAL_NEEDLE_EVENT_ID}+ if not OBJECT_STORAGE_ACCESS_KEY_ID or not OBJECT_STORAGE_SECRET_ACCESS_KEY:+ return degraded++ try:+ name = f"{RETRIEVAL_NEEDLE_PREFIX}{table.name}"+ bucket = f"eval_warehouse{XDIST_SUFFIX}"+ folder = f"{OBJECT_STORAGE_BUCKET}/{bucket}/{name}"+ fs = s3fs.S3FileSystem(+ client_kwargs={+ "region_name": "us-east-1",+ "endpoint_url": OBJECT_STORAGE_ENDPOINT,+ "aws_access_key_id": OBJECT_STORAGE_ACCESS_KEY_ID,+ "aws_secret_access_key": OBJECT_STORAGE_SECRET_ACCESS_KEY,+ },+ )+ with fs.open(f"{folder}/data.csv", "w", newline="") as handle:+ writer = csv.writer(handle)+ writer.writerow([column.name for column in table.columns])+ for row in table.rows:+ writer.writerow(row)++ source = ExternalDataSource.objects.create(+ team=team,+ source_id="eval_source",+ connection_id="eval_connection",+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.STRIPE,+ prefix=RETRIEVAL_NEEDLE_PREFIX,+ )+ credential = DataWarehouseCredential.objects.create(+ team=team,+ access_key=OBJECT_STORAGE_ACCESS_KEY_ID,+ access_secret=OBJECT_STORAGE_SECRET_ACCESS_KEY,+ )+ created = DataWarehouseTable.objects.create(+ name=name,+ format=DataWarehouseTable.TableFormat.CSVWithNames,+ team=team,+ external_data_source=source,+ credential=credential,+ url_pattern=f"http://host.docker.internal:19000/{folder}/*.csv",+ columns=table.columns_json(),+ options={"csv_allow_double_quotes": True},+ )+ return {+ "queryable": True,+ "table": created.name,+ "answer": RETRIEVAL_NEEDLE_ANSWER,+ "event_id": RETRIEVAL_NEEDLE_EVENT_ID,+ }+ except Exception:+ logger.exception("Queryable needle creation failed; degrading retrieval needle to metadata-only")+ return degradeddiff --git a/ee/hogai/eval/sandboxed/data_warehouse/synthesizer.py b/ee/hogai/eval/sandboxed/data_warehouse/synthesizer.pynew file mode 100644index 000000000000..ce9856377924--- /dev/null+++ b/ee/hogai/eval/sandboxed/data_warehouse/synthesizer.py@@ -0,0 +1,770 @@+"""Deterministic synthetic data-warehouse generator for the information_schema eval.++Produces a large, realistic catalog — hundreds of warehouse tables across several+source connectors, a handful of data-modeling views, join relationships, and five+planted "needles" — so an agent has to *navigate* the catalog via+``system.information_schema`` rather than guess or list everything.++The module is intentionally pure: no Django, no I/O. It emits frozen dataclasses+that the seeder (``seeder.py``) translates into ORM rows + an optional CSV upload.+That split keeps generation unit-testable and byte-for-byte reproducible — all+randomness flows from the seeded mimesis bundle in ``seeders/common.py``.++The needles each target a distinct discovery skill:++* **description** — a table found only by its annotation text (opaque name).+* **column_type** — the one table with a column typed ``UUID`` (rare on purpose).+* **relationship** — two tables linked by a join, surfaced in+ ``information_schema.relationships``.+* **view** — a data-modeling view ("model") among noise views.+* **retrieval** — a queryable, S3-backed table whose columns are all declared+ ``String`` but whose row content is numeric/JSON (duck typing): the answer can+ only be had by selecting and parsing a value, not by trusting the declared type.+* **relevancy** — two near-identical tables on the same topic where only the+ annotation distinguishes the live canonical table from a frozen, superseded one:+ the agent must read metadata to pick the current table, not the stale decoy.+* **chain** — a two-hop join path (orders → account xref → account owners) the+ agent can only assemble by querying ``relationships`` iteratively, one hop at a+ time, then combining the discovered tables.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Literal++from ee.hogai.eval.sandboxed.seeders.common import DEFAULT_NAME_SEED, NameProviders, make_name_providers++__all__ = [+ "HogqlType",+ "SynthColumn",+ "SynthTable",+ "SynthView",+ "SynthJoin",+ "NeedleSpec",+ "SynthWarehouse",+ "WarehouseSchemaSynthesizer",+ "DESC_NEEDLE_TABLE",+ "DESC_NEEDLE_PHRASE",+ "TYPE_NEEDLE_TABLE",+ "TYPE_NEEDLE_COLUMN",+ "TYPE_NEEDLE_DATA_TYPE",+ "REL_NEEDLE_SOURCE",+ "REL_NEEDLE_TARGET",+ "REL_NEEDLE_KEY",+ "REL_NEEDLE_FIELD",+ "VIEW_NEEDLE_NAME",+ "RETRIEVAL_NEEDLE_TABLE",+ "RETRIEVAL_NEEDLE_ANSWER",+ "RETRIEVAL_NEEDLE_PREFIX",+ "RETRIEVAL_NEEDLE_EVENT_ID",+ "RELEVANCY_NEEDLE_CURRENT",+ "RELEVANCY_NEEDLE_STALE",+ "RELEVANCY_NEEDLE_TOPIC",+ "CHAIN_NEEDLE_HOP3",+ "CHAIN_NEEDLE_KEY",+ "CHAIN_NEEDLE_FIELD",+]+++HogqlType = Literal[+ "StringDatabaseField",+ "IntegerDatabaseField",+ "FloatDatabaseField",+ "BooleanDatabaseField",+ "DateTimeDatabaseField",+ "DateDatabaseField",+ "DecimalDatabaseField",+ "StringJSONDatabaseField",+]++# The HogQL field class is what drives ``information_schema.columns.data_type``.+# Only field classes in the warehouse ``STR_TO_HOGQL_MAPPING`` resolve to a real+# type — others fall back to ``Unknown``. (Notably ``UUIDDatabaseField`` is NOT+# supported for warehouse columns, so the rare-type needle uses ``Decimal``.) The+# ClickHouse type is only the storage hint stored on the table's columns JSON.+_CLICKHOUSE_FOR_HOGQL: dict[str, str] = {+ "StringDatabaseField": "String",+ "IntegerDatabaseField": "Int64",+ "FloatDatabaseField": "Float64",+ "BooleanDatabaseField": "Bool",+ "DateTimeDatabaseField": "DateTime64(6, 'UTC')",+ "DateDatabaseField": "Date",+ "DecimalDatabaseField": "Decimal(38, 18)",+ "StringJSONDatabaseField": "JSON",+}++# Decimal is deliberately excluded from the noise pool so the column-type needle+# (the one Decimal column in the catalog) stays unique. ``_validate`` enforces it.+_NOISE_HOGQL_TYPES: tuple[HogqlType, ...] = (+ "StringDatabaseField",+ "IntegerDatabaseField",+ "FloatDatabaseField",+ "BooleanDatabaseField",+ "DateTimeDatabaseField",+ "DateDatabaseField",+ "StringJSONDatabaseField",+)+++# Needle constants — referenced verbatim by eval prompts and scorers.+DESC_NEEDLE_TABLE = "pg_ext_4471"+DESC_NEEDLE_PHRASE = "canonical MRR source of truth"+TYPE_NEEDLE_TABLE = "hubspot_sync_meta"+TYPE_NEEDLE_COLUMN = "fx_rate"+TYPE_NEEDLE_DATA_TYPE = "Decimal"+REL_NEEDLE_SOURCE = "pg_orders_2023"+REL_NEEDLE_TARGET = "salesforce_acct_xref"+REL_NEEDLE_KEY = "account_ref"+REL_NEEDLE_FIELD = "account"+VIEW_NEEDLE_NAME = "mart_active_revenue_v2"+RETRIEVAL_NEEDLE_TABLE = "stripe_raw_events"+RETRIEVAL_NEEDLE_ANSWER = "HEDGE-7731"+RETRIEVAL_NEEDLE_PREFIX = "evalwh_"+RETRIEVAL_NEEDLE_EVENT_ID = "evt_target"+# Relevancy needle — two near-identical accounts-dimension tables, identical schema;+# only the annotation says which is live (canonical) vs frozen (superseded). The+# stale table's name carries no "old"/"deprecated" tell, so the agent has to read+# the description to pick the current one rather than shortcut on the name.+RELEVANCY_NEEDLE_CURRENT = "dim_accounts_snapshot"+RELEVANCY_NEEDLE_STALE = "dim_accounts_snapshot_2023"+RELEVANCY_NEEDLE_TOPIC = "accounts dimension"+# Chain needle — the second join hop past the relationship needle, so the path is+# pg_orders_2023 -> salesforce_acct_xref -> salesforce_acct_owners.+CHAIN_NEEDLE_HOP3 = "salesforce_acct_owners"+CHAIN_NEEDLE_KEY = "owner_id"+CHAIN_NEEDLE_FIELD = "owner"+++@dataclass(frozen=True)+class SynthColumn:+ name: str+ hogql: HogqlType+ nullable: bool = True+ description: str | None = None # -> WarehouseColumnAnnotation(column_name=name)++ @property+ def clickhouse_base(self) -> str:+ """The bare ClickHouse type (no ``Nullable`` wrapper) — used for CSV-backed tables."""+ return _CLICKHOUSE_FOR_HOGQL[self.hogql]++ @property+ def clickhouse(self) -> str:+ base = self.clickhouse_base+ return f"Nullable({base})" if self.nullable else base++ def to_columns_entry(self) -> tuple[str, dict[str, Any]]:+ return self.name, {"hogql": self.hogql, "clickhouse": self.clickhouse, "valid": True}+++@dataclass(frozen=True)+class SynthTable:+ name: str+ domain: str+ columns: tuple[SynthColumn, ...]+ description: str | None = None # table-level annotation (column_name="")+ queryable: bool = False # True only for the retrieval needle (S3-backed)+ rows: tuple[tuple[Any, ...], ...] = () # CSV rows, only when queryable+ row_count: int | None = None # surfaced in information_schema.tables.row_count++ def columns_json(self) -> dict[str, Any]:+ return dict(c.to_columns_entry() for c in self.columns)+++@dataclass(frozen=True)+class SynthView:+ name: str # identifier only (validate_saved_query_name)+ columns: tuple[SynthColumn, ...]+ sql: str # goes into query={"query": sql}+ description: str | None = None++ def columns_json(self) -> dict[str, Any]:+ return dict(c.to_columns_entry() for c in self.columns)+++@dataclass(frozen=True)+class SynthJoin:+ source_table: str+ source_key: str # bare column name (a valid HogQL field chain)+ joining_table: str+ joining_key: str+ field_name: str # the LazyJoin field name on the source table+++@dataclass(frozen=True)+class NeedleSpec:+ kind: Literal["description", "column_type", "relationship", "view", "retrieval", "relevancy", "chain"]+ answer: Any # what the scorer checks for in the final answer / result+ target_table: str | None = None+ target_view: str | None = None+ relationship: tuple[str, str] | None = None # (source_table, joining_table)+ distinguishing_phrase: str | None = None+ queryable: bool = False+ secondary_table: str | None = None # the stale decoy (relevancy needle)+ chain: tuple[str, ...] = () # ordered join path, source-first (chain needle)+++@dataclass(frozen=True)+class SynthWarehouse:+ tables: tuple[SynthTable, ...]+ views: tuple[SynthView, ...]+ joins: tuple[SynthJoin, ...]+ needles: dict[str, NeedleSpec]+++# Per-domain vocabulary. Each domain contributes a name prefix, a pool of entity+# nouns (real connector tables), a column pool, and a description template.+@dataclass(frozen=True)+class _Domain:+ key: str+ prefix: str+ entities: tuple[str, ...]+ column_pool: tuple[SynthColumn, ...]+ description_template: str+++def _col(name: str, hogql: HogqlType, *, nullable: bool = True) -> SynthColumn:+ return SynthColumn(name=name, hogql=hogql, nullable=nullable)+++_DOMAINS: tuple[_Domain, ...] = (+ _Domain(+ key="stripe",+ prefix="stripe_",+ entities=(+ "charges",+ "invoices",+ "subscriptions",+ "refunds",+ "payouts",+ "disputes",+ "balance_transactions",+ "customers",+ "products",+ "prices",+ "coupons",+ "checkout_sessions",+ "payment_intents",+ "invoice_items",+ ),+ column_pool=(+ _col("id", "StringDatabaseField"),+ _col("amount", "IntegerDatabaseField"),+ _col("currency", "StringDatabaseField"),+ _col("customer_id", "StringDatabaseField"),+ _col("created", "DateTimeDatabaseField"),+ _col("status", "StringDatabaseField"),+ _col("metadata", "StringJSONDatabaseField"),+ _col("description", "StringDatabaseField"),+ _col("livemode", "BooleanDatabaseField"),+ _col("amount_refunded", "IntegerDatabaseField"),+ ),+ description_template="Stripe {entity} synced from the Stripe billing connector.",+ ),+ _Domain(+ key="salesforce",+ prefix="salesforce_",+ entities=(+ "accounts",+ "opportunities",+ "leads",+ "contacts",+ "campaigns",+ "opportunity_history",+ "opportunity_line_items",+ "users",+ "tasks",+ "events",+ "cases",+ "products2",+ ),+ column_pool=(+ _col("Id", "StringDatabaseField"),+ _col("Name", "StringDatabaseField"),+ _col("Amount", "FloatDatabaseField"),+ _col("StageName", "StringDatabaseField"),+ _col("CloseDate", "DateDatabaseField"),+ _col("OwnerId", "StringDatabaseField"),+ _col("IsWon", "BooleanDatabaseField"),+ _col("CreatedDate", "DateTimeDatabaseField"),+ _col("Email", "StringDatabaseField"),+ _col("Industry", "StringDatabaseField"),+ ),+ description_template="Salesforce {entity} replicated from the Salesforce CRM connector.",+ ),+ _Domain(+ key="hubspot",+ prefix="hubspot_",+ entities=(+ "deals",+ "companies",+ "contacts",+ "emails",+ "tickets",+ "deal_pipelines",+ "deal_stage_history",+ "engagements",+ "owners",+ "line_items",+ "forms",+ "calls",+ ),+ column_pool=(+ _col("hs_object_id", "StringDatabaseField"),+ _col("dealstage", "StringDatabaseField"),+ _col("amount", "FloatDatabaseField"),+ _col("closedate", "DateTimeDatabaseField"),+ _col("hs_lastmodifieddate", "DateTimeDatabaseField"),+ _col("pipeline", "StringDatabaseField"),+ _col("dealname", "StringDatabaseField"),+ _col("is_closed", "BooleanDatabaseField"),+ _col("num_contacted_notes", "IntegerDatabaseField"),+ _col("properties", "StringJSONDatabaseField"),+ ),+ description_template="HubSpot {entity} synced from the HubSpot marketing connector.",+ ),+ _Domain(+ key="postgres_replica",+ prefix="pg_",+ entities=(+ "users",+ "orders",+ "order_items",+ "products",+ "payments",+ "sessions",+ "audit_log",+ "addresses",+ "carts",+ "shipments",+ "reviews",+ "inventory",+ "refund_requests",+ ),+ column_pool=(+ _col("id", "IntegerDatabaseField", nullable=False),+ _col("email", "StringDatabaseField"),+ _col("created_at", "DateTimeDatabaseField"),+ _col("updated_at", "DateTimeDatabaseField"),+ _col("total_cents", "IntegerDatabaseField"),+ _col("is_active", "BooleanDatabaseField"),+ _col("payload", "StringJSONDatabaseField"),+ _col("status", "StringDatabaseField"),+ _col("quantity", "IntegerDatabaseField"),+ _col("price", "FloatDatabaseField"),+ ),+ description_template="Postgres {entity} streamed from the production read replica.",+ ),+ _Domain(+ key="analytics",+ prefix="model_",+ entities=(+ "stg_stripe_charges",+ "stg_hubspot_deals",+ "fct_subscriptions",+ "fct_orders",+ "dim_customers",+ "dim_products",+ "mart_revenue_daily",+ "mart_funnel_weekly",+ "int_active_accounts",+ "int_billing_events",+ ),+ column_pool=(+ _col("date_day", "DateDatabaseField"),+ _col("revenue", "FloatDatabaseField"),+ _col("active_subscriptions", "IntegerDatabaseField"),+ _col("active_customers", "IntegerDatabaseField"),+ _col("mrr", "FloatDatabaseField"),+ _col("churn_rate", "FloatDatabaseField"),+ _col("cohort_month", "DateDatabaseField"),+ _col("segment", "StringDatabaseField"),+ ),+ description_template="Analytics model: {entity}, materialized by the data-modeling layer.",+ ),+)++# Plausible column descriptions, applied to ~30% of columns so descriptions are+# noisy — the description needle can't be found just by "the table that has one".+_COLUMN_DESCRIPTION_TEMPLATES: tuple[str, ...] = (+ "The {col} value as ingested from the source system.",+ "Primary {col} field used for joins and lookups.",+ "Denormalized {col} copied from the upstream record.",+ "Audit field tracking {col} for this row.",+)+++class WarehouseSchemaSynthesizer:+ """Deterministic generator. All randomness flows from ``seed``."""++ def __init__(self, *, seed: int = DEFAULT_NAME_SEED, noise_table_count: int = 250) -> None:+ self._providers: NameProviders = make_name_providers(seed)+ self._rnd = self._providers.rnd+ self._noise_table_count = noise_table_count++ def generate(self) -> SynthWarehouse:+ # Reserve needle names up front so noise generation can never collide.+ reserved = {+ DESC_NEEDLE_TABLE,+ TYPE_NEEDLE_TABLE,+ REL_NEEDLE_SOURCE,+ REL_NEEDLE_TARGET,+ RETRIEVAL_NEEDLE_TABLE,+ RELEVANCY_NEEDLE_CURRENT,+ RELEVANCY_NEEDLE_STALE,+ CHAIN_NEEDLE_HOP3,+ }+ noise_tables = self._generate_noise_tables(reserved)+ needles, needle_tables, needle_views, needle_joins = self._generate_needles()+ views = (*self._generate_noise_views(), *needle_views)+ warehouse = SynthWarehouse(+ tables=(*noise_tables, *needle_tables),+ views=views,+ joins=tuple(needle_joins),+ needles=needles,+ )+ self._validate(warehouse)+ return warehouse++ # -- noise ---------------------------------------------------------------++ def _generate_noise_tables(self, reserved: set[str]) -> list[SynthTable]:+ names: set[str] = set(reserved)+ tables: list[SynthTable] = []+ domains = list(_DOMAINS)+ per_domain = self._noise_table_count // len(domains)+ for domain in domains:+ tables.extend(self._generate_domain_tables(domain, per_domain, names))+ return tables++ def _generate_domain_tables(self, domain: _Domain, count: int, names: set[str]) -> list[SynthTable]:+ tables: list[SynthTable] = []+ suffixes = ("", "_v2", "_archive", "_staging", "_2022", "_2023", "_2024", "_raw", "_history")+ attempts = 0+ while len(tables) < count and attempts < count * 20:+ attempts += 1+ entity = self._rnd.choice(domain.entities)+ suffix = self._rnd.choice(suffixes)+ name = f"{domain.prefix}{entity}{suffix}"+ if name in names:+ continue+ names.add(name)+ tables.append(+ SynthTable(+ name=name,+ domain=domain.key,+ columns=self._generate_columns(domain, entity),+ description=domain.description_template.format(entity=entity.replace("_", " ")),+ row_count=self._rnd.randint(100, 5_000_000),+ )+ )+ return tables++ def _generate_columns(self, domain: _Domain, entity: str) -> tuple[SynthColumn, ...]:+ pool = list(domain.column_pool)+ n = min(self._rnd.randint(3, 20), len(pool))+ chosen = self._rnd.sample(pool, n)+ out: list[SynthColumn] = []+ for col in chosen:+ description = None+ if self._rnd.random() < 0.3:+ template = self._rnd.choice(_COLUMN_DESCRIPTION_TEMPLATES)+ description = template.format(col=col.name)+ out.append(SynthColumn(name=col.name, hogql=col.hogql, nullable=col.nullable, description=description))+ return tuple(out)++ def _generate_noise_views(self) -> tuple[SynthView, ...]:+ return (+ SynthView(+ name="stg_stripe_charges",+ columns=(_col("id", "StringDatabaseField"), _col("amount", "IntegerDatabaseField")),+ sql="SELECT id, amount FROM stripe_charges",+ description="Staging model cleaning raw Stripe charges.",+ ),+ SynthView(+ name="dim_customers",+ columns=(_col("customer_id", "StringDatabaseField"), _col("email", "StringDatabaseField")),+ sql="SELECT customer_id, email FROM stripe_customers",+ description="Customer dimension keyed by Stripe customer id.",+ ),+ SynthView(+ name="fct_subscriptions",+ columns=(_col("subscription_id", "StringDatabaseField"), _col("mrr", "FloatDatabaseField")),+ sql="SELECT id AS subscription_id, amount AS mrr FROM stripe_subscriptions",+ description="Subscription fact table with one row per active subscription.",+ ),+ )++ # -- needles -------------------------------------------------------------++ def _generate_needles(+ self,+ ) -> tuple[dict[str, NeedleSpec], list[SynthTable], list[SynthView], list[SynthJoin]]:+ tables: list[SynthTable] = []+ views: list[SynthView] = []+ joins: list[SynthJoin] = []++ # A — found only by description (opaque name, generic columns).+ tables.append(+ SynthTable(+ name=DESC_NEEDLE_TABLE,+ domain="postgres_replica",+ columns=(+ _col("id", "IntegerDatabaseField", nullable=False),+ _col("account_id", "StringDatabaseField"),+ _col("snapshot_date", "DateDatabaseField"),+ _col("value", "FloatDatabaseField"),+ _col("kind", "StringDatabaseField"),+ _col("meta", "StringJSONDatabaseField"),+ ),+ description=(+ f"Stores the per-account monthly recurring revenue snapshot used for the board "+ f"revenue report. This is the {DESC_NEEDLE_PHRASE} for MRR — do not use "+ f"stripe_invoices for MRR."+ ),+ row_count=self._rnd.randint(1_000, 50_000),+ )+ )++ # B — found by column data_type (the only Decimal column anywhere; warehouse+ # columns can't be UUID, so Decimal is the rare, distinctive type here).+ tables.append(+ SynthTable(+ name=TYPE_NEEDLE_TABLE,+ domain="hubspot",+ columns=(+ _col("hs_object_id", "StringDatabaseField"),+ _col(TYPE_NEEDLE_COLUMN, "DecimalDatabaseField"),+ _col("region_geojson", "StringJSONDatabaseField"),+ _col("synced_at", "DateTimeDatabaseField"),+ ),+ description="HubSpot sync metadata, including the high-precision FX rate used for currency conversion.",+ row_count=self._rnd.randint(100, 10_000),+ )+ )++ # C — reachable only via a relationship (join surfaced in relationships).+ rel_columns = (+ _col("id", "IntegerDatabaseField", nullable=False),+ _col(REL_NEEDLE_KEY, "StringDatabaseField"),+ _col("order_total", "FloatDatabaseField"),+ _col("ordered_at", "DateTimeDatabaseField"),+ )+ tables.append(+ SynthTable(+ name=REL_NEEDLE_SOURCE,+ domain="postgres_replica",+ columns=rel_columns,+ description="Orders placed in 2023, keyed to Salesforce accounts via account_ref.",+ row_count=self._rnd.randint(10_000, 500_000),+ )+ )+ tables.append(+ SynthTable(+ name=REL_NEEDLE_TARGET,+ domain="salesforce",+ columns=(+ _col(REL_NEEDLE_KEY, "StringDatabaseField"),+ _col("company_name", "StringDatabaseField"),+ _col("industry", "StringDatabaseField"),+ _col(CHAIN_NEEDLE_KEY, "StringDatabaseField"), # FK to the owners table (second hop)+ ),+ description="Cross-reference mapping order account_ref to Salesforce company records.",+ row_count=self._rnd.randint(1_000, 50_000),+ )+ )+ joins.append(+ SynthJoin(+ source_table=REL_NEEDLE_SOURCE,+ source_key=REL_NEEDLE_KEY,+ joining_table=REL_NEEDLE_TARGET,+ joining_key=REL_NEEDLE_KEY,+ field_name=REL_NEEDLE_FIELD,+ )+ )++ # C2 — second join hop, so the agent must traverse relationships twice:+ # pg_orders_2023 -> salesforce_acct_xref -> salesforce_acct_owners.+ tables.append(+ SynthTable(+ name=CHAIN_NEEDLE_HOP3,+ domain="salesforce",+ columns=(+ _col(CHAIN_NEEDLE_KEY, "StringDatabaseField"),+ _col("owner_name", "StringDatabaseField"),+ _col("region", "StringDatabaseField"),+ ),+ description="Salesforce account owners, keyed by owner_id; the account xref links here on owner_id.",+ row_count=self._rnd.randint(100, 5_000),+ )+ )+ joins.append(+ SynthJoin(+ source_table=REL_NEEDLE_TARGET,+ source_key=CHAIN_NEEDLE_KEY,+ joining_table=CHAIN_NEEDLE_HOP3,+ joining_key=CHAIN_NEEDLE_KEY,+ field_name=CHAIN_NEEDLE_FIELD,+ )+ )++ # F — relevancy: two identical-schema accounts dimensions; only the annotation+ # says which is live vs frozen. A naive name/schema scan can't disambiguate.+ relevancy_columns = (+ _col("account_id", "StringDatabaseField"),+ _col("company_name", "StringDatabaseField"),+ _col("industry", "StringDatabaseField"),+ _col("plan", "StringDatabaseField"),+ _col("seats", "IntegerDatabaseField"),+ _col("signed_up_at", "DateTimeDatabaseField"),+ _col("is_active", "BooleanDatabaseField"),+ )+ tables.append(+ SynthTable(+ name=RELEVANCY_NEEDLE_CURRENT,+ domain="postgres_replica",+ columns=relevancy_columns,+ description=(+ "Live accounts dimension, refreshed daily — the canonical accounts source for "+ f"current reporting. Replaced the frozen {RELEVANCY_NEEDLE_STALE}."+ ),+ row_count=self._rnd.randint(10_000, 80_000),+ )+ )+ tables.append(+ SynthTable(+ name=RELEVANCY_NEEDLE_STALE,+ domain="postgres_replica",+ columns=relevancy_columns,+ description=(+ "DEPRECATED point-in-time accounts snapshot frozen at the end of 2023; no longer "+ f"refreshed. Superseded by {RELEVANCY_NEEDLE_CURRENT} — do not use for current reporting."+ ),+ row_count=self._rnd.randint(10_000, 80_000),+ )+ )++ # D — the discovery-target view ("model").+ views.append(+ SynthView(+ name=VIEW_NEEDLE_NAME,+ columns=(+ _col("date_day", "DateDatabaseField"),+ _col("mrr", "FloatDatabaseField"),+ _col("active_customers", "IntegerDatabaseField"),+ ),+ sql=(+ "SELECT toDate(created) AS date_day, sum(amount) / 100.0 AS mrr, "+ "count(DISTINCT customer_id) AS active_customers "+ "FROM stripe_charges GROUP BY date_day"+ ),+ description="Daily MRR and active-customer counts; the model the finance dashboard reads.",+ )+ )++ # E — queryable duck-typing needle: all columns declared String, content lies.+ # Amounts are chosen so the *string* max ("9990") differs from the *numeric*+ # max (24990) — getting the right max requires casting text to a number, not+ # trusting the declared String type.+ retrieval_rows = (+ ("evt_001", "1990", '{"plan":"pro","seats":3}', "false"),+ ("evt_002", "24990", '{"plan":"standard","seats":12}', "false"),+ (+ RETRIEVAL_NEEDLE_EVENT_ID,+ "4990",+ f'{{"plan":"enterprise","seats":42,"secret_code":"{RETRIEVAL_NEEDLE_ANSWER}"}}',+ "false",+ ),+ ("evt_004", "0", '{"plan":"free","seats":1}', "true"),+ ("evt_005", "9990", '{"plan":"pro","seats":2}', "false"),+ )+ tables.append(+ SynthTable(+ name=RETRIEVAL_NEEDLE_TABLE,+ domain="stripe",+ columns=(+ _col("event_id", "StringDatabaseField"),+ _col("amount", "StringDatabaseField"),+ _col("payload", "StringDatabaseField"),+ _col("is_test", "StringDatabaseField"),+ ),+ description="Raw Stripe webhook events; values are stored verbatim as text.",+ queryable=True,+ rows=retrieval_rows,+ row_count=len(retrieval_rows),+ )+ )++ needles: dict[str, NeedleSpec] = {+ "description": NeedleSpec(+ kind="description",+ answer=DESC_NEEDLE_TABLE,+ target_table=DESC_NEEDLE_TABLE,+ distinguishing_phrase=DESC_NEEDLE_PHRASE,+ ),+ "column_type": NeedleSpec(+ kind="column_type",+ answer={"table": TYPE_NEEDLE_TABLE, "column": TYPE_NEEDLE_COLUMN},+ target_table=TYPE_NEEDLE_TABLE,+ ),+ "relationship": NeedleSpec(+ kind="relationship",+ answer=REL_NEEDLE_TARGET,+ relationship=(REL_NEEDLE_SOURCE, REL_NEEDLE_TARGET),+ ),+ "view": NeedleSpec(kind="view", answer=VIEW_NEEDLE_NAME, target_view=VIEW_NEEDLE_NAME),+ "retrieval": NeedleSpec(+ kind="retrieval",+ answer=RETRIEVAL_NEEDLE_ANSWER,+ target_table=RETRIEVAL_NEEDLE_TABLE,+ queryable=True,+ ),+ "relevancy": NeedleSpec(+ kind="relevancy",+ answer=RELEVANCY_NEEDLE_CURRENT,+ target_table=RELEVANCY_NEEDLE_CURRENT,+ secondary_table=RELEVANCY_NEEDLE_STALE,+ ),+ "chain": NeedleSpec(+ kind="chain",+ answer=CHAIN_NEEDLE_HOP3,+ chain=(REL_NEEDLE_SOURCE, REL_NEEDLE_TARGET, CHAIN_NEEDLE_HOP3),+ ),+ }+ return needles, tables, views, joins++ # -- validation ----------------------------------------------------------++ def _validate(self, warehouse: SynthWarehouse) -> None:+ """Guard the invariants the needles and scorers depend on."""+ names = [t.name for t in warehouse.tables]+ assert len(names) == len(set(names)), "duplicate table names generated"++ # Exactly one Decimal column in the whole catalog (the column-type needle).+ decimal_tables = [t.name for t in warehouse.tables for c in t.columns if c.hogql == "DecimalDatabaseField"]+ assert decimal_tables == [TYPE_NEEDLE_TABLE], f"Decimal column must be unique to needle, got {decimal_tables}"++ # The relationship join's endpoints must both exist as tables.+ table_names = set(names)+ for join in warehouse.joins:+ assert join.source_table in table_names, f"join source {join.source_table} missing"+ assert join.joining_table in table_names, f"join target {join.joining_table} missing"++ # Relevancy decoys: both accounts dimensions exist with identical schema, so+ # only the annotation distinguishes them.+ relevancy = {+ t.name: t for t in warehouse.tables if t.name in (RELEVANCY_NEEDLE_CURRENT, RELEVANCY_NEEDLE_STALE)+ }+ assert set(relevancy) == {RELEVANCY_NEEDLE_CURRENT, RELEVANCY_NEEDLE_STALE}, "relevancy pair missing"+ assert relevancy[RELEVANCY_NEEDLE_CURRENT].columns == relevancy[RELEVANCY_NEEDLE_STALE].columns, (+ "relevancy decoys must share an identical schema"+ )++ # Chain: the two-hop join path must be fully wired (orders -> xref -> owners).+ chain_edges = {(j.source_table, j.joining_table) for j in warehouse.joins}+ assert (REL_NEEDLE_SOURCE, REL_NEEDLE_TARGET) in chain_edges, "chain hop 1 missing"+ assert (REL_NEEDLE_TARGET, CHAIN_NEEDLE_HOP3) in chain_edges, "chain hop 2 missing"++ # Exactly one queryable table (the retrieval needle).+ queryable = [t.name for t in warehouse.tables if t.queryable]+ assert queryable == [RETRIEVAL_NEEDLE_TABLE], f"expected one queryable table, got {queryable}"diff --git a/ee/hogai/eval/sandboxed/retrieval/eval_system_table_search.py b/ee/hogai/eval/sandboxed/retrieval/eval_system_table_search.pyindex 635280b1c2c5..8e42b1f615df 100644--- a/ee/hogai/eval/sandboxed/retrieval/eval_system_table_search.py+++ b/ee/hogai/eval/sandboxed/retrieval/eval_system_table_search.py@@ -5,22 +5,23 @@ When users ask the agent to find or modify a PostHog entity by nameagainst ``system.*``. The failure modes this eval grades:1. The agent guesses column names (``last_modified_at``, ``description``,- ``short_id``) without calling ``read-data-warehouse-schema`` first.- Different ``system.*`` tables expose different columns, so guessing- produces queries that fail or silently return wrong rows.+ ``short_id``) without discovering the schema via+ ``system.information_schema`` first. Different ``system.*`` tables+ expose different columns, so guessing produces queries that fail or+ silently return wrong rows.2. In single-exec CLI mode, the agent invokes a tool without firstloading its schema via ``info <tool>`` — skipping the discovery stepthat surfaces parameter shapes and discovery workflows.Metrics:-* ``warehouse_schema_before_sql`` — was every successful ``execute-sql``- preceded by a successful ``read-data-warehouse-schema`` in the same- run? Mode-agnostic (works for both v2 tools mode and CLI exec mode).-* ``info_before_execute_sql`` / ``info_before_read_data_warehouse_schema``- — CLI-mode only: was each tool's ``info`` payload loaded before its- first successful ``call``? Skipped (``None``) in v2 tools mode where- schemas come bundled.+* ``information_schema_before_sql`` — was every ``execute-sql`` against a+ ``system.*`` entity table preceded by a ``system.information_schema``+ discovery query in the same run? Mode-agnostic (works for both v2 tools+ mode and CLI exec mode).+* ``info_before_execute_sql`` — CLI-mode only: was ``execute-sql``'s+ ``info`` payload loaded before its first successful ``call``? Skipped+ (``None``) in v2 tools mode where schemas come bundled.To run::@@ -31,7 +32,7 @@ from __future__ import annotationsfrom ee.hogai.eval.sandboxed.base import SandboxedPublicEvalfrom ee.hogai.eval.sandboxed.config import SandboxedEvalCase-from ee.hogai.eval.sandboxed.retrieval.scorers import InfoCalledBeforeTool, WarehouseSchemaBeforeSql+from ee.hogai.eval.sandboxed.retrieval.scorers import InfoCalledBeforeTool, InformationSchemaBeforeSqlfrom ee.hogai.eval.sandboxed.scorers import ExitCodeZerofrom ee.hogai.eval.sandboxed.seeders.insight import seed_insight_noise@@ -46,7 +47,7 @@ async def eval_system_table_search(sandboxed_demo_data, pytestconfig, posthog_clSandboxedEvalCase(name="system_table_search_insights_rename",prompt=("rename the insight 'Monthly Active Users (Hedgebox)' to have a 'MAU - ' prefix"),- expected={"warehouse_schema_before_sql": {}},+ expected={"information_schema_before_sql": {}},setup=seed_insight_noise,),SandboxedEvalCase(@@ -56,7 +57,7 @@ async def eval_system_table_search(sandboxed_demo_data, pytestconfig, posthog_cl"it's probably an existing insight, and created/last used by ""me around this time last year."),- expected={"warehouse_schema_before_sql": {}},+ expected={"information_schema_before_sql": {}},setup=seed_insight_noise,),SandboxedEvalCase(@@ -65,7 +66,7 @@ async def eval_system_table_search(sandboxed_demo_data, pytestconfig, posthog_cl"do we have any insights tracking revenue or payments? ""list every match with its ID, name, and last-modified time."),- expected={"warehouse_schema_before_sql": {}},+ expected={"information_schema_before_sql": {}},setup=seed_insight_noise,),]@@ -75,9 +76,8 @@ async def eval_system_table_search(sandboxed_demo_data, pytestconfig, posthog_clcases=cases,scorers=[ExitCodeZero(),- WarehouseSchemaBeforeSql(),+ InformationSchemaBeforeSql(),InfoCalledBeforeTool("execute-sql"),- InfoCalledBeforeTool("read-data-warehouse-schema"),],pytestconfig=pytestconfig,sandboxed_demo_data=sandboxed_demo_data,diff --git a/ee/hogai/eval/sandboxed/retrieval/scorers.py b/ee/hogai/eval/sandboxed/retrieval/scorers.pyindex 5d5c8a8a60f0..2616cdb62859 100644--- a/ee/hogai/eval/sandboxed/retrieval/scorers.py+++ b/ee/hogai/eval/sandboxed/retrieval/scorers.py@@ -7,23 +7,25 @@ Four binary scorers grade the retrieval flow:* ``LookupIdInOutput`` — does the agent's final assistant message containthe seeded lookup insight's ID, proving it actually queried PostHograther than hallucinating?-* ``WarehouseSchemaBeforeSql`` — did the agent call- ``read-data-warehouse-schema`` before every successful ``execute-sql``- call? Catches the failure mode where the agent guesses column names on- ``system.*`` tables and gets a query that fails or silently returns- wrong rows. Mode-agnostic: works for both v2 tools mode and CLI exec- mode because ``LogParser`` normalizes both to the same tool name.+* ``InformationSchemaBeforeSql`` — did the agent discover the schema via+ ``system.information_schema.*`` before every ``execute-sql`` that hits a+ ``system.*`` entity table? Catches the failure mode where the agent+ guesses column names on ``system.*`` tables and gets a query that fails+ or silently returns wrong rows. Both the discovery step and the real+ query are ``execute-sql`` calls, so they're told apart by SQL text.+ Mode-agnostic: works for both v2 tools mode and CLI exec mode because+ ``LogParser`` normalizes both to the same tool name and input.* ``InfoCalledBeforeTool`` — in single-exec CLI mode, did the agent run``info <tool>`` before the first successful ``call <tool>``? Enforcesthe "load schema before invoking" discipline for tools whose- guidance lives behind ``info`` (e.g. ``execute-sql``,- ``read-data-warehouse-schema``). Returns ``None`` (skipped) outside CLI- mode, where tool schemas come bundled with the tool registration.+ guidance lives behind ``info`` (e.g. ``execute-sql``). Returns ``None``+ (skipped) outside CLI mode, where tool schemas come bundled with the+ tool registration.The first two scorers walk ``output["messages"]`` (Anthropic-format) and``output["seed"]`` (set by the seeder hook in ``base.py:task()``), sonothing has to be threaded through ``expected``. The third opts in via-``expected = {"warehouse_schema_before_sql": {}}``.+``expected = {"information_schema_before_sql": {}}``."""from __future__ import annotations@@ -36,7 +38,7 @@ from braintrust_core.score import Scorerfrom ee.hogai.eval.sandboxed.log_parser import INFO_SYNTHETIC_PREFIX, LogParser-__all__ = ["InfoCalledBeforeTool", "LookupIdInOutput", "SkillLoaded", "WarehouseSchemaBeforeSql"]+__all__ = ["InfoCalledBeforeTool", "InformationSchemaBeforeSql", "LookupIdInOutput", "SkillLoaded"]class SkillLoaded(Scorer):@@ -262,29 +264,35 @@ class LookupIdInOutput(Scorer):return ""-class WarehouseSchemaBeforeSql(Scorer):- """Binary: did the agent run ``read-data-warehouse-schema`` before any successful ``execute-sql``?+class InformationSchemaBeforeSql(Scorer):+ """Binary: did the agent discover the schema via ``system.information_schema`` before querying ``system.*``?- Opt-in via presence of ``expected = {"warehouse_schema_before_sql": {}}``.+ Opt-in via presence of ``expected = {"information_schema_before_sql": {}}``.- For each successful ``execute-sql`` call, requires that a successful- ``read-data-warehouse-schema`` call appeared earlier in the same run.- Mode-agnostic — walks all tool calls regardless of whether they came- via tools-mode dispatch or via ``posthog:exec`` unwrapping; the- ``LogParser`` normalizes both into the same tool name.+ Both the discovery step and the real query are ``execute-sql`` calls, so+ they're distinguished by the SQL text (``input["query"]``):- Score 1.0 if every successful ``execute-sql`` was preceded by a- successful ``read-data-warehouse-schema``. 0.0 otherwise (with the- offending call IDs in metadata). ``None`` when ``execute-sql`` was- never called successfully — the case didn't exercise the path this- scorer grades.+ * a **discovery** call selects from ``system.information_schema`` (any of+ ``.tables`` / ``.columns`` / ``.relationships`` / ``.data_types``);+ * a **graded** call hits a ``system.*`` entity table (``system.insights``,+ ``system.dashboards``, …) but *not* ``information_schema`` — i.e. an+ actual entity search whose columns must be confirmed first.++ Requires that every graded call was preceded by a successful discovery+ call in the same run. Mode-agnostic — walks all tool calls whether they+ came via tools-mode dispatch or via ``posthog:exec`` unwrapping; the+ ``LogParser`` normalizes both into the same tool name and input.++ Score 1.0 if every graded call was preceded by a successful discovery+ call. 0.0 otherwise (with the offending call IDs in metadata). ``None``+ when no graded call ran — the case didn't exercise the path this scorer+ grades."""- SCHEMA_TOOL = "read-data-warehouse-schema"SQL_TOOL = "execute-sql"def _name(self) -> str:- return "warehouse_schema_before_sql"+ return "information_schema_before_sql"async def _run_eval_async(self, output, expected=None, **kwargs):return self._evaluate(output, expected)@@ -292,6 +300,20 @@ class WarehouseSchemaBeforeSql(Scorer):def _run_eval_sync(self, output, expected=None, **kwargs):return self._evaluate(output, expected)+ @staticmethod+ def _query_text(call) -> str:+ query = call.input.get("query") if isinstance(call.input, dict) else None+ return query.lower() if isinstance(query, str) else ""++ @classmethod+ def _is_discovery(cls, call) -> bool:+ return "information_schema" in cls._query_text(call)++ @classmethod+ def _is_graded(cls, call) -> bool:+ query = cls._query_text(call)+ return "system." in query and "information_schema" not in query+def _evaluate(self, output: dict | None, expected: dict | None = None) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})@@ -305,40 +327,40 @@ class WarehouseSchemaBeforeSql(Scorer):parser = LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")calls = sorted(parser.get_tool_calls(), key=lambda c: c.position)- seen_schema = False+ seen_discovery = Falseoffenders: list[str] = []- successful_calls = 0+ graded_calls = 0for call in calls:- if call.is_error:+ if call.is_error or call.name != self.SQL_TOOL:continue- if call.name == self.SCHEMA_TOOL:- seen_schema = True+ if self._is_discovery(call):+ seen_discovery = Truecontinue- if call.name == self.SQL_TOOL:- successful_calls += 1- if not seen_schema:+ if self._is_graded(call):+ graded_calls += 1+ if not seen_discovery:offenders.append(call.call_id)- if successful_calls == 0:+ if graded_calls == 0:return Score(name=self._name(),score=None,- metadata={"reason": f"'{self.SQL_TOOL}' was never called successfully"},+ metadata={"reason": "No 'system.*' entity-table query ran"},)if offenders:return Score(name=self._name(),score=0.0,metadata={- "reason": f"'{self.SQL_TOOL}' was called without a prior successful '{self.SCHEMA_TOOL}'",+ "reason": "'system.*' entity query ran without a prior 'system.information_schema' discovery query","offenders": offenders,- "total_calls": successful_calls,+ "total_calls": graded_calls,},)return Score(name=self._name(),score=1.0,- metadata={"total_calls": successful_calls},+ metadata={"total_calls": graded_calls},)diff --git a/ee/hogai/eval/sandboxed/sql/eval_sql.py b/ee/hogai/eval/sandboxed/sql/eval_sql.pyindex 38c7d892b1b9..3e76c692406f 100644--- a/ee/hogai/eval/sandboxed/sql/eval_sql.py+++ b/ee/hogai/eval/sandboxed/sql/eval_sql.py@@ -24,8 +24,8 @@ from ee.hogai.eval.sandboxed.base import SandboxedPublicEvalfrom ee.hogai.eval.sandboxed.config import SandboxedEvalCasefrom ee.hogai.eval.sandboxed.product_analytics.scorers import INSIGHT_WRITE_TOOLSfrom ee.hogai.eval.sandboxed.retrieval.scorers import SkillLoaded-from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, LastToolCallNot, NoToolCall, RequiredToolCall-from ee.hogai.eval.sandboxed.sql.scorers import SQLResultMessageAlignment, SQLSchemaAlignment+from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, LastToolCallNot, NoToolCall+from ee.hogai.eval.sandboxed.sql.scorers import AnswerQueryRan, SQLResultMessageAlignment, SQLSchemaAlignmentdef _sql_case(*, name: str, prompt: str, expected_sql: str) -> SandboxedEvalCase:@@ -385,7 +385,7 @@ WHERE properties.interests IS NOT NULLscorers=[ExitCodeZero(),NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),- RequiredToolCall(required={"execute-sql"}, name="execute_sql_called"),+ AnswerQueryRan(name="execute_sql_called"),LastToolCallNot(forbidden={"query-trends", "query-funnel", "query-retention"},name="last_call_not_typed_query",diff --git a/ee/hogai/eval/sandboxed/sql/scorers.py b/ee/hogai/eval/sandboxed/sql/scorers.pyindex 7adb32ed495e..469e4761b7c8 100644--- a/ee/hogai/eval/sandboxed/sql/scorers.py+++ b/ee/hogai/eval/sandboxed/sql/scorers.py@@ -28,6 +28,7 @@ from __future__ import annotationsfrom typing import Anyfrom braintrust import Score+from braintrust_core.score import Scorerfrom ee.hogai.eval.sandboxed.product_analytics.scorers import (GRADED_ALIGNMENT_CHOICE_SCORES,@@ -43,17 +44,28 @@ _MAX_RESULT_CHARS_FOR_JUDGE = 12_000def extract_last_execute_sql_call(output: dict[str, Any] | None) -> dict[str, str] | None:- """Return the query and result from the most recent successful ``execute-sql`` call.-- Returns ``None`` when the agent never ran the tool successfully — scorers- should short-circuit in that case rather than count it as an incorrect- answer.+ """Return the query and result from the most recent successful *answer* ``execute-sql`` call.++ Schema discovery runs through ``execute-sql`` against+ ``system.information_schema.*`` (the ``mcp-sql-schema-discovery`` regime,+ forced on in the sandbox), so those discovery queries land in the same+ ``execute-sql`` call list as the real answer query. They are skipped here so+ the judge grades the question's answer, not a column lookup the agent ran+ afterward.++ Returns ``None`` when the agent never ran an answer query successfully —+ scorers should short-circuit in that case rather than count it as an+ incorrect answer."""parser = parser_for(output)if parser is None:return None- successful = [call for call in parser.get_tool_calls(QUERY_SQL_TOOL_NAME) if not call.is_error]+ 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 successful:return None@@ -64,6 +76,48 @@ def extract_last_execute_sql_call(output: dict[str, Any] | None) -> dict[str, streturn {"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?++ Under the ``mcp-sql-schema-discovery`` regime (forced on in the sandbox),+ schema discovery also runs through ``execute-sql`` against+ ``system.information_schema.*``. So a plain "``execute-sql`` was called"+ check passes even when the agent only inspected the schema and never+ answered with SQL. This requires a successful ``execute-sql`` whose query+ is *not* an ``information_schema`` lookup — i.e. an actual answer query.++ Score 1.0 when an answer query ran, 0.0 otherwise.+ """++ def __init__(self, *, name: str = "answer_query_ran"):+ self._label = name++ def _name(self) -> str:+ return self._label++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output)++ def _evaluate(self, output: dict | None) -> Score:+ if not output:+ return Score(name=self._name(), score=None, metadata={"reason": "No output"})+ if extract_last_execute_sql_query(output) is None:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "No non-discovery execute-sql answer query ran"},+ )+ return Score(name=self._name(), score=1.0, metadata={})++def extract_last_execute_sql_query(output: dict[str, Any] | None) -> str | None:"""Return the query string from the most recent successful ``execute-sql`` call."""call = extract_last_execute_sql_call(output)diff --git a/ee/hogai/test/eval/test_warehouse_scorers.py b/ee/hogai/test/eval/test_warehouse_scorers.pynew file mode 100644index 000000000000..f04b3472b7aa--- /dev/null+++ b/ee/hogai/test/eval/test_warehouse_scorers.py@@ -0,0 +1,420 @@+"""Unit tests for the data-warehouse information_schema scorers.++Builds minimal ACP session logs (the same shape ``LogParser`` consumes in+production) plus synthetic ``seed`` dicts, then asserts each scorer's verdict —+no sandboxed stack. Lives above ``sandboxed/`` so it stays a fast unit test+instead of booting the eval harness via that package's conftest.+"""++from __future__ import annotations++import json++from braintrust import Score++from ee.hogai.eval.sandboxed.data_warehouse.scorers import (+ AgenticSearchUsed,+ AnswerQueryRanWhenExpected,+ InformationSchemaBeforeAnswer,+ InformationSchemaQueried,+ JoinPathTraversed,+ NeedleTableIdentified,+ NeedleValueRetrieved,+ RelationshipDiscovery,+ StaleTableAvoided,+ WarehouseAnswerCorrectness,+)++_TS = "2026-04-15T10:00:0"+++def _session_update(seq: int, update: dict) -> str:+ return json.dumps(+ {+ "type": "notification",+ "timestamp": f"{_TS}{seq}.000Z",+ "notification": {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {"sessionId": "s", "update": update},+ },+ }+ )+++def _prompt(seq: int, text: str) -> str:+ return json.dumps(+ {+ "type": "notification",+ "timestamp": f"{_TS}{seq}.000Z",+ "notification": {+ "jsonrpc": "2.0",+ "method": "session/prompt",+ "params": {"sessionId": "s", "prompt": [{"type": "text", "text": text}]},+ },+ }+ )+++def _end_turn(seq: int) -> str:+ return json.dumps(+ {+ "type": "notification",+ "timestamp": f"{_TS}{seq}.000Z",+ "notification": {+ "jsonrpc": "2.0",+ "result": {+ "stopReason": "end_turn",+ "usage": {+ "inputTokens": 1,+ "outputTokens": 1,+ "cachedReadTokens": 0,+ "cachedWriteTokens": 0,+ "totalTokens": 2,+ },+ },+ },+ }+ )+++def _sql_call(seq: int, call_id: str, query: str, output: str = "ok", status: str = "completed") -> list[str]:+ return [+ _session_update(+ seq,+ {+ "sessionUpdate": "tool_call",+ "toolCallId": call_id,+ "status": "pending",+ "rawInput": {},+ "title": "execute-sql",+ "_meta": {"claudeCode": {"toolName": "execute-sql"}},+ },+ ),+ _session_update(+ seq,+ {"sessionUpdate": "tool_call_update", "toolCallId": call_id, "status": None, "rawInput": {"query": query}},+ ),+ _session_update(+ seq,+ {"sessionUpdate": "tool_call_update", "toolCallId": call_id, "status": status, "rawOutput": output},+ ),+ ]+++def _agent_text(seq: int, text: str) -> str:+ return _session_update(seq, {"sessionUpdate": "agent_message", "content": {"type": "text", "text": text}})+++def _make_output(+ *,+ sql_calls: list[tuple[str, str]] | None = None, # (query, result)+ final_text: str = "done",+ seed: dict | None = None,+) -> dict:+ lines = [_prompt(0, "question")]+ seq = 1+ for idx, (query, result) in enumerate(sql_calls or []):+ lines.extend(_sql_call(seq, f"c{idx}", query, output=result))+ seq += 1+ lines.append(_agent_text(seq, final_text))+ lines.append(_end_turn(seq + 1))+ return {+ "raw_log": "\n".join(lines),+ "last_message": final_text,+ "prompt": "question",+ "seed": seed or {},+ }+++# -- InformationSchemaQueried -------------------------------------------------+++def test_information_schema_queried_passes_when_info_schema_hit():+ out = _make_output(sql_calls=[("SELECT table_name FROM system.information_schema.tables", "rows")])+ score = InformationSchemaQueried()._evaluate(out, {"information_schema_queried": {}})+ assert score.score == 1.0+++def test_information_schema_queried_fails_without_info_schema():+ out = _make_output(sql_calls=[("SELECT 1 FROM stripe_charges", "rows")])+ score = InformationSchemaQueried()._evaluate(out, {"information_schema_queried": {}})+ assert score.score == 0.0+++def test_information_schema_queried_skips_when_not_requested():+ out = _make_output(sql_calls=[("SELECT 1 FROM system.information_schema.tables", "rows")])+ score = InformationSchemaQueried()._evaluate(out, {})+ assert score.score is None+++# -- InformationSchemaBeforeAnswer --------------------------------------------+++def test_before_answer_passes_when_discovery_precedes_answer():+ out = _make_output(+ sql_calls=[+ ("SELECT column_name FROM system.information_schema.columns WHERE table_name = 'pg_orders'", "rows"),+ ("SELECT * FROM pg_orders LIMIT 5", "rows"),+ ]+ )+ score = InformationSchemaBeforeAnswer()._evaluate(out, {"information_schema_before_answer": {}})+ assert score.score == 1.0+++def test_before_answer_fails_when_answer_precedes_discovery():+ out = _make_output(+ sql_calls=[+ ("SELECT * FROM pg_orders LIMIT 5", "rows"),+ ("SELECT column_name FROM system.information_schema.columns", "rows"),+ ]+ )+ score = InformationSchemaBeforeAnswer()._evaluate(out, {"information_schema_before_answer": {}})+ assert score.score == 0.0+++def test_before_answer_skips_when_no_answer_query():+ out = _make_output(sql_calls=[("SELECT table_name FROM system.information_schema.tables", "rows")])+ score = InformationSchemaBeforeAnswer()._evaluate(out, {"information_schema_before_answer": {}})+ assert score.score is None+++# -- AgenticSearchUsed --------------------------------------------------------+++def test_agentic_search_passes_for_filtered_query():+ out = _make_output(+ sql_calls=[("SELECT table_name FROM system.information_schema.tables WHERE table_name = 'pg_orders'", "rows")]+ )+ score = AgenticSearchUsed()._evaluate(out, {"agentic_search_used": {}})+ assert score.score == 1.0+++def test_agentic_search_fails_for_unfiltered_dump():+ out = _make_output(sql_calls=[("SELECT table_name FROM system.information_schema.tables", "rows")])+ score = AgenticSearchUsed()._evaluate(out, {"agentic_search_used": {}})+ assert score.score == 0.0+++def test_agentic_search_require_pattern_needs_like():+ where_eq = _make_output(+ sql_calls=[("SELECT table_name FROM system.information_schema.tables WHERE table_name = 'x'", "rows")]+ )+ where_like = _make_output(+ sql_calls=[("SELECT table_name FROM system.information_schema.tables WHERE description ILIKE '%mrr%'", "rows")]+ )+ spec = {"agentic_search_used": {"require_pattern": True}}+ assert AgenticSearchUsed()._evaluate(where_eq, spec).score == 0.0+ assert AgenticSearchUsed()._evaluate(where_like, spec).score == 1.0+++# -- NeedleTableIdentified ----------------------------------------------------+++def test_needle_table_identified_via_final_message():+ out = _make_output(final_text="The canonical MRR table is pg_ext_4471.")+ score = NeedleTableIdentified()._evaluate(out, {"needle_table_identified": {"table": "pg_ext_4471"}})+ assert score.score == 1.0+++def test_needle_table_identified_resolves_seed_key():+ out = _make_output(+ final_text="It's hubspot_sync_meta.", seed={"column_type_needle": {"table": "hubspot_sync_meta"}}+ )+ score = NeedleTableIdentified()._evaluate(out, {"needle_table_identified": {"seed_key": "column_type_needle"}})+ assert score.score == 1.0+++def test_needle_table_identified_fails_when_absent():+ out = _make_output(final_text="I could not find it.")+ score = NeedleTableIdentified()._evaluate(out, {"needle_table_identified": {"table": "pg_ext_4471"}})+ assert score.score == 0.0+++# -- NeedleValueRetrieved -----------------------------------------------------+++def test_needle_value_retrieved_from_sql_result():+ out = _make_output(+ sql_calls=[("SELECT payload FROM evalwh_stripe_raw_events WHERE event_id = 'evt_target'", "HEDGE-7731")],+ final_text="The secret_code is HEDGE-7731.",+ seed={"retrieval_needle": {"queryable": True, "answer": "HEDGE-7731"}},+ )+ score = NeedleValueRetrieved()._evaluate(out, {"needle_value_retrieved": {}})+ assert score.score == 1.0+++def test_needle_value_retrieved_skips_when_not_queryable():+ out = _make_output(seed={"retrieval_needle": {"queryable": False, "answer": "HEDGE-7731"}})+ score = NeedleValueRetrieved()._evaluate(out, {"needle_value_retrieved": {}})+ assert score.score is None+++def test_needle_value_retrieved_honors_value_override():+ out = _make_output(+ sql_calls=[("SELECT max(toInt64(amount)) FROM evalwh_stripe_raw_events", "24990")],+ final_text="Largest is 24990.",+ seed={"retrieval_needle": {"queryable": True, "answer": "HEDGE-7731"}},+ )+ score = NeedleValueRetrieved()._evaluate(out, {"needle_value_retrieved": {"value": "24990"}})+ assert score.score == 1.0+++# -- RelationshipDiscovery ----------------------------------------------------+++def test_relationship_discovery_passes_with_relationships_query_and_named_pair():+ out = _make_output(+ sql_calls=[+ ("SELECT * FROM system.information_schema.relationships WHERE source_table = 'pg_orders_2023'", "r")+ ],+ final_text="pg_orders_2023 joins salesforce_acct_xref on account_ref.",+ seed={"relationship_needle": {"source": "pg_orders_2023", "target": "salesforce_acct_xref"}},+ )+ score = RelationshipDiscovery()._evaluate(out, {"relationship_discovery": {}})+ assert score.score == 1.0+++def test_relationship_discovery_fails_without_discovery():+ out = _make_output(+ final_text="They are probably related somehow.",+ seed={"relationship_needle": {"source": "pg_orders_2023", "target": "salesforce_acct_xref"}},+ )+ score = RelationshipDiscovery()._evaluate(out, {"relationship_discovery": {}})+ assert score.score == 0.0+++# -- StaleTableAvoided --------------------------------------------------------++_RELEVANCY_SEED = {"relevancy_needle": {"current": "dim_accounts_snapshot", "stale": "dim_accounts_snapshot_2023"}}+++def test_stale_table_avoided_passes_when_current_recommended_and_stale_flagged():+ out = _make_output(+ final_text=(+ "Use dim_accounts_snapshot — it's the live canonical table. "+ "dim_accounts_snapshot_2023 is deprecated and no longer refreshed."+ ),+ seed=_RELEVANCY_SEED,+ )+ score = StaleTableAvoided()._evaluate(out, {"stale_table_avoided": {}})+ assert score.score == 1.0+++def test_stale_table_avoided_passes_when_only_current_named():+ out = _make_output(final_text="You should use dim_accounts_snapshot for current reporting.", seed=_RELEVANCY_SEED)+ score = StaleTableAvoided()._evaluate(out, {"stale_table_avoided": {}})+ assert score.score == 1.0+++def test_stale_table_avoided_fails_when_stale_recommended():+ out = _make_output(final_text="Use dim_accounts_snapshot_2023 for your accounts reporting.", seed=_RELEVANCY_SEED)+ score = StaleTableAvoided()._evaluate(out, {"stale_table_avoided": {}})+ assert score.score == 0.0+++def test_stale_table_avoided_fails_when_stale_named_without_deprecation_cue():+ # Both named but no cue flags the stale one — reads as offering it as usable.+ out = _make_output(+ final_text="There's dim_accounts_snapshot and dim_accounts_snapshot_2023; either has accounts.",+ seed=_RELEVANCY_SEED,+ )+ score = StaleTableAvoided()._evaluate(out, {"stale_table_avoided": {}})+ assert score.score == 0.0+++def test_stale_table_avoided_skips_when_not_requested():+ out = _make_output(final_text="anything", seed=_RELEVANCY_SEED)+ score = StaleTableAvoided()._evaluate(out, {})+ assert score.score is None+++# -- JoinPathTraversed --------------------------------------------------------++_CHAIN_SEED = {+ "chain_needle": {+ "tables": ["pg_orders_2023", "salesforce_acct_xref", "salesforce_acct_owners"],+ "keys": ["account_ref", "owner_id"],+ }+}+++def test_join_path_traversed_passes_with_relationships_query_and_all_tables_named():+ out = _make_output(+ sql_calls=[+ ("SELECT * FROM system.information_schema.relationships WHERE source_table = 'pg_orders_2023'", "r"),+ ("SELECT * FROM system.information_schema.relationships WHERE source_table = 'salesforce_acct_xref'", "r"),+ ],+ final_text=(+ "Join pg_orders_2023 to salesforce_acct_xref on account_ref, then "+ "salesforce_acct_xref to salesforce_acct_owners on owner_id."+ ),+ seed=_CHAIN_SEED,+ )+ score = JoinPathTraversed()._evaluate(out, {"join_path_traversed": {}})+ assert score.score == 1.0+ assert score.metadata["keys_named"] == ["account_ref", "owner_id"]+++def test_join_path_traversed_fails_when_only_first_hop_found():+ out = _make_output(+ sql_calls=[+ ("SELECT * FROM system.information_schema.relationships WHERE source_table = 'pg_orders_2023'", "r"),+ ],+ final_text="pg_orders_2023 joins salesforce_acct_xref on account_ref.",+ seed=_CHAIN_SEED,+ )+ score = JoinPathTraversed()._evaluate(out, {"join_path_traversed": {}})+ assert score.score == 0.0+++def test_join_path_traversed_fails_without_relationships_query():+ out = _make_output(+ final_text="pg_orders_2023, salesforce_acct_xref and salesforce_acct_owners are probably related.",+ seed=_CHAIN_SEED,+ )+ score = JoinPathTraversed()._evaluate(out, {"join_path_traversed": {}})+ assert score.score == 0.0+++def test_join_path_traversed_skips_when_not_requested():+ out = _make_output(final_text="anything", seed=_CHAIN_SEED)+ score = JoinPathTraversed()._evaluate(out, {})+ assert score.score is None+++# -- AnswerQueryRanWhenExpected -----------------------------------------------+++def test_answer_query_ran_true_for_real_answer():+ out = _make_output(sql_calls=[("SELECT * FROM pg_orders LIMIT 5", "rows")])+ score = AnswerQueryRanWhenExpected()._evaluate(out, {"answer_query_ran": {}})+ assert score.score == 1.0+++def test_answer_query_ran_false_for_discovery_only():+ out = _make_output(sql_calls=[("SELECT table_name FROM system.information_schema.tables", "rows")])+ score = AnswerQueryRanWhenExpected()._evaluate(out, {"answer_query_ran": {}})+ assert score.score == 0.0+++def test_answer_query_ran_skips_when_not_requested():+ out = _make_output(sql_calls=[("SELECT * FROM pg_orders", "rows")])+ score = AnswerQueryRanWhenExpected()._evaluate(out, {})+ assert score.score is None+++# -- WarehouseAnswerCorrectness (synchronous short-circuits only) -------------+++def test_warehouse_answer_correctness_skips_when_not_requested():+ out = _make_output(final_text="anything")+ prepared = WarehouseAnswerCorrectness()._prepare(out, {})+ assert isinstance(prepared, Score) and prepared.score is None+++def test_warehouse_answer_correctness_skips_when_requires_queryable_unavailable():+ out = _make_output(final_text="anything", seed={"retrieval_needle": {"queryable": False}})+ spec = {"warehouse_answer_correctness": {"expected_answer": "x", "requires_queryable": True}}+ prepared = WarehouseAnswerCorrectness()._prepare(out, spec)+ assert isinstance(prepared, Score) and prepared.score is Nonediff --git a/ee/hogai/test/eval/test_warehouse_seeder.py b/ee/hogai/test/eval/test_warehouse_seeder.pynew file mode 100644index 000000000000..5f1277df3ddc--- /dev/null+++ b/ee/hogai/test/eval/test_warehouse_seeder.py@@ -0,0 +1,93 @@+"""DB-backed integration test for the warehouse seeder.++Runs the seeder against a real test team and asserts the synthetic catalog is+discoverable through ``system.information_schema`` — the contract the eval's+scorers depend on. The queryable needle requires object storage and degrades to+``queryable=False`` here; that path is covered too.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import TYPE_CHECKING, cast++from posthog.test.base import APIBaseTest, ClickhouseTestMixin++from posthog.hogql.query import execute_hogql_query++from ee.hogai.eval.sandboxed.data_warehouse.seeder import seed_warehouse_schema++if TYPE_CHECKING:+ from products.tasks.backend.facade.agents import CustomPromptSandboxContext+from ee.hogai.eval.sandboxed.data_warehouse.synthesizer import (+ DESC_NEEDLE_PHRASE,+ DESC_NEEDLE_TABLE,+ REL_NEEDLE_SOURCE,+ REL_NEEDLE_TARGET,+ TYPE_NEEDLE_COLUMN,+ TYPE_NEEDLE_TABLE,+ VIEW_NEEDLE_NAME,+)+++class TestWarehouseSeeder(ClickhouseTestMixin, APIBaseTest):+ def setUp(self):+ super().setUp()+ # The seeder only reads team_id/user_id; a namespace stands in for the real+ # sandbox context here.+ context = cast("CustomPromptSandboxContext", SimpleNamespace(team_id=self.team.id, user_id=self.user.id))+ self.seed = seed_warehouse_schema(context)++ def _query(self, sql: str) -> list:+ return execute_hogql_query(sql, team=self.team).results or []++ def test_seed_payload_has_all_needles(self):+ assert self.seed["table_count"] >= 200+ assert self.seed["view_count"] >= 1+ assert self.seed["join_count"] >= 1+ assert set(self.seed) >= {+ "description_needle",+ "column_type_needle",+ "relationship_needle",+ "view_needle",+ "retrieval_needle",+ }++ def test_hundreds_of_tables_are_discoverable(self):+ rows = self._query("SELECT count() FROM system.information_schema.tables WHERE table_type = 'data_warehouse'")+ assert rows[0][0] >= 200++ def test_description_needle_surfaces_with_phrase(self):+ rows = self._query(+ f"SELECT description FROM system.information_schema.tables WHERE table_name = '{DESC_NEEDLE_TABLE}'"+ )+ assert rows and DESC_NEEDLE_PHRASE in (rows[0][0] or "")++ def test_description_search_finds_only_the_needle(self):+ rows = self._query(+ "SELECT table_name FROM system.information_schema.tables WHERE description ILIKE '%canonical MRR%'"+ )+ assert [r[0] for r in rows] == [DESC_NEEDLE_TABLE]++ def test_decimal_column_is_unique_among_warehouse_tables(self):+ # `information_schema.columns` spans every table, so the Decimal needle is+ # unique only within the warehouse schema — which is what the eval prompt+ # scopes to ("across all our warehouse tables").+ rows = self._query(+ "SELECT table_name, column_name FROM system.information_schema.columns "+ "WHERE data_type = 'Decimal' AND table_schema = 'warehouse'"+ )+ assert [tuple(r) for r in rows] == [(TYPE_NEEDLE_TABLE, TYPE_NEEDLE_COLUMN)]++ def test_relationship_needle_surfaces(self):+ rows = self._query(+ "SELECT source_table, target_table FROM system.information_schema.relationships "+ f"WHERE source_table = '{REL_NEEDLE_SOURCE}'"+ )+ assert [REL_NEEDLE_SOURCE, REL_NEEDLE_TARGET] in [[r[0], r[1]] for r in rows]++ def test_view_needle_is_classified_as_view(self):+ rows = self._query(+ f"SELECT table_type FROM system.information_schema.tables WHERE table_name = '{VIEW_NEEDLE_NAME}'"+ )+ assert rows and rows[0][0] == "view"diff --git a/ee/hogai/test/eval/test_warehouse_synthesizer.py b/ee/hogai/test/eval/test_warehouse_synthesizer.pynew file mode 100644index 000000000000..399c42a0fa17--- /dev/null+++ b/ee/hogai/test/eval/test_warehouse_synthesizer.py@@ -0,0 +1,112 @@+"""Unit tests for the pure warehouse synthesizer — no Django, no infra."""++from __future__ import annotations++from dataclasses import astuple++from ee.hogai.eval.sandboxed.data_warehouse.synthesizer import (+ CHAIN_NEEDLE_HOP3,+ DESC_NEEDLE_PHRASE,+ DESC_NEEDLE_TABLE,+ REL_NEEDLE_SOURCE,+ REL_NEEDLE_TARGET,+ RELEVANCY_NEEDLE_CURRENT,+ RELEVANCY_NEEDLE_STALE,+ RETRIEVAL_NEEDLE_ANSWER,+ RETRIEVAL_NEEDLE_TABLE,+ TYPE_NEEDLE_COLUMN,+ TYPE_NEEDLE_TABLE,+ VIEW_NEEDLE_NAME,+ WarehouseSchemaSynthesizer,+)+++def test_generation_is_deterministic():+ first = WarehouseSchemaSynthesizer(seed=7).generate()+ second = WarehouseSchemaSynthesizer(seed=7).generate()+ assert [astuple(t) for t in first.tables] == [astuple(t) for t in second.tables]+ assert [astuple(v) for v in first.views] == [astuple(v) for v in second.views]+ assert [astuple(j) for j in first.joins] == [astuple(j) for j in second.joins]+++def test_catalog_is_large_and_unique():+ warehouse = WarehouseSchemaSynthesizer(noise_table_count=250).generate()+ names = [t.name for t in warehouse.tables]+ assert len(names) == len(set(names))+ # ~250 noise + 5 needle tables; allow slack for dedup collisions in noise.+ assert len(names) >= 200+++def test_decimal_column_is_unique_to_the_type_needle():+ warehouse = WarehouseSchemaSynthesizer().generate()+ decimal_owners = [t.name for t in warehouse.tables for c in t.columns if c.hogql == "DecimalDatabaseField"]+ assert decimal_owners == [TYPE_NEEDLE_TABLE]+ type_needle = next(t for t in warehouse.tables if t.name == TYPE_NEEDLE_TABLE)+ assert any(c.name == TYPE_NEEDLE_COLUMN for c in type_needle.columns)+++def test_description_needle_carries_distinguishing_phrase():+ warehouse = WarehouseSchemaSynthesizer().generate()+ table = next(t for t in warehouse.tables if t.name == DESC_NEEDLE_TABLE)+ assert table.description is not None and DESC_NEEDLE_PHRASE in table.description+++def test_relationship_endpoints_exist_and_are_joined():+ warehouse = WarehouseSchemaSynthesizer().generate()+ names = {t.name for t in warehouse.tables}+ assert {REL_NEEDLE_SOURCE, REL_NEEDLE_TARGET}.issubset(names)+ assert any(j.source_table == REL_NEEDLE_SOURCE and j.joining_table == REL_NEEDLE_TARGET for j in warehouse.joins)+++def test_view_needle_present_among_views():+ warehouse = WarehouseSchemaSynthesizer().generate()+ assert any(v.name == VIEW_NEEDLE_NAME for v in warehouse.views)+++def test_retrieval_needle_is_queryable_with_duck_typed_content():+ warehouse = WarehouseSchemaSynthesizer().generate()+ queryable = [t for t in warehouse.tables if t.queryable]+ assert [t.name for t in queryable] == [RETRIEVAL_NEEDLE_TABLE]+ needle = queryable[0]+ # All columns are declared String even though content is numeric/JSON.+ assert all(c.hogql == "StringDatabaseField" for c in needle.columns)+ # The secret answer lives in exactly one row's payload, and string-max != numeric-max.+ flat = [cell for row in needle.rows for cell in row]+ assert any(RETRIEVAL_NEEDLE_ANSWER in cell for cell in flat)+ amounts = [int(row[1]) for row in needle.rows]+ assert max(amounts) == 24990+ assert max(row[1] for row in needle.rows) == "9990" # lexical max differs from numeric max+++def test_relevancy_decoys_share_schema_and_differ_only_by_annotation():+ warehouse = WarehouseSchemaSynthesizer().generate()+ by_name = {t.name: t for t in warehouse.tables}+ current = by_name[RELEVANCY_NEEDLE_CURRENT]+ stale = by_name[RELEVANCY_NEEDLE_STALE]+ # Identical schema → only the annotation can disambiguate which is live.+ assert current.columns == stale.columns+ assert "canonical" in (current.description or "").lower()+ assert "deprecated" in (stale.description or "").lower()+ assert RELEVANCY_NEEDLE_CURRENT in (stale.description or "") # stale points at its successor+++def test_chain_needle_wires_a_two_hop_join_path():+ warehouse = WarehouseSchemaSynthesizer().generate()+ names = {t.name for t in warehouse.tables}+ assert {REL_NEEDLE_SOURCE, REL_NEEDLE_TARGET, CHAIN_NEEDLE_HOP3}.issubset(names)+ edges = {(j.source_table, j.joining_table) for j in warehouse.joins}+ assert (REL_NEEDLE_SOURCE, REL_NEEDLE_TARGET) in edges+ assert (REL_NEEDLE_TARGET, CHAIN_NEEDLE_HOP3) in edges+++def test_needles_map_covers_all_kinds():+ warehouse = WarehouseSchemaSynthesizer().generate()+ assert set(warehouse.needles) == {+ "description",+ "column_type",+ "relationship",+ "view",+ "retrieval",+ "relevancy",+ "chain",+ }diff --git a/products/posthog_ai/skills/querying-posthog-data/references/guidelines.md b/products/posthog_ai/skills/querying-posthog-data/references/guidelines.mdindex b53529c25c0b..d711f5a1f35e 100644--- a/products/posthog_ai/skills/querying-posthog-data/references/guidelines.md+++ b/products/posthog_ai/skills/querying-posthog-data/references/guidelines.md@@ -1,6 +1,6 @@### Querying data in PostHog-Use the `posthog:execute-sql` MCP tool to execute HogQL queries. HogQL is PostHog's variant of SQL that supports most of ClickHouse SQL. We use terms "HogQL" and "SQL" interchangeably. References mentioned in this file are relevant to PostHog's skill `querying-posthog-data`.+Use the `posthog:execute-sql` MCP tool to execute HogQL queries. HogQL is PostHog's variant of SQL that supports most of ClickHouse SQL. We use terms "HogQL" and "SQL" interchangeably. More info is available in the `querying-posthog-data` skill.Do not assume that data exists. Use the SQL tool proactively to find the right data.@@ -20,27 +20,7 @@ PostHog has two distinct groups of data you can query:Data created directly in PostHog by users - metadata about PostHog setup.-All system tables are prefixed with `system.`:--Table | Description-`system.actions` | Named event combinations for filtering-`system.cohorts` | Groups of persons for segmentation-`system.dashboards` | Collections of insights-`system.data_warehouse_sources` | Connected external data sources-`system.data_warehouse_tables` | Connected tables with their columns and formats-`system.error_tracking_issues` | Error tracking issues (grouped exceptions)-`system.experiments` | A/B tests and experiments-`system.exports` | Export jobs-`system.feature_flags` | Feature flags for controlling rollouts-`system.groups` | Group entities-`system.ingestion_warnings` | Data ingestion issues-`system.insight_variables` | SQL, dashboard, and insight variables for dynamic query filtering-`system.insights` | Visual and textual representations of aggregated data-`system.logs_alerts` | Log alert configurations and their states-`system.logs_views` | Saved log filter views-`system.notebooks` | Collaborative documents with embedded insights-`system.surveys` | Questionnaires and feedback forms-`system.teams` | Team/project settings+All these tables are prefixed with `system.`. The most-used entities are `system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.actions`, and `system.notebooks` — list the full, current set (it drifts as products are added) via `information_schema`, covered in **Schema discovery** below.**Example - List insights:**@@ -54,31 +34,6 @@ SELECT id, name, short_id FROM system.insights WHERE NOT deleted LIMIT 10SELECT count() AS total FROM system.insight_variables```-**System Models Reference**--Schema reference for PostHog's core system models, organized by domain:--- [Actions](references/models-actions.md)-- [Cohorts & Persons](references/models-cohorts.md)-- [Dashboards, Tiles & Insights](references/models-dashboards-insights.md)-- [Data Warehouse](references/models-data-warehouse.md)-- [Error Tracking](references/models-error-tracking.md)-- [Logs](references/models-logs.md)-- [Flags & Experiments](references/models-flags-experiments.md)-- [Notebooks](references/models-notebooks.md)-- [Surveys](references/models-surveys.md)-- [SQL Variables](references/models-variables.md)--**Entity Relationships**--From | Relation | To | Join-Experiment | 1:1 | FeatureFlag | `feature_flag_id`-Experiment | N:1 | Cohort | `exposure_cohort_id`-Survey | N:1 | FeatureFlag | `linked_flag_id`, `targeting_flag_id`-Survey | N:1 | Insight | `linked_insight_id`-Cohort | M:N | Person | via `cohortpeople`-Person | 1:N | PersonDistinctId | `person_id`-All entities are scoped by a team by default. You cannot access data of another team unless you switch a team.##### 2. Captured Data (Analytics Data)@@ -92,7 +47,7 @@ Table | Description`sessions` | Session data captured by the SDKData warehouse tables | Connected external data sources and custom views-Use `posthog:read-data-warehouse-schema` to retrieve the full schema of the tables above.+Discover the columns and relationships of these tables with `information_schema`, covered in **Schema discovery** below.**Key concepts:**@@ -130,6 +85,64 @@ Run separately for each model. Available models: `'text-embedding-3-small-1536'`Use `embedText(text, model_name)` and `cosineDistance()` for semantic search. See the `signals` skill for detailed query patterns around the signals product specifically, including required deduplication and metadata extraction.+#### Schema discovery (information_schema)++Don't guess table or column names — they differ per entity and drift over time. Discover the live schema for **every** data group above (system, captured, and data-warehouse tables) by querying `system.information_schema` via `execute-sql`. It exposes four self-describing virtual tables — every column below is selectable:++- `tables` — table_catalog, table_schema, table_name, table_type, description, row_count. table_type is one of system, data_warehouse, view, posthog (built-in analytics tables like events / persons), or information_schema.+- `columns` — table_schema, table_name, column_name, ordinal_position, data_type, is_nullable, is_array, field_kind, description.+- `relationships` — source_table, source_column, target_table, target_column, relationship_kind, via.+- `data_types` — type_name, description.++It describes itself, so the full column set is always discoverable: `SELECT column_name, data_type FROM system.information_schema.columns WHERE table_name = 'system.information_schema.columns'`.++**List tables** — filter `table_type` to target a group (`system`, `data_warehouse`, `view`, `posthog`):++```sql+SELECT table_name, description+FROM system.information_schema.tables+WHERE table_type = 'system'+ORDER BY table_name+```++**Find a table by what its docs say** — names are often opaque (especially data-warehouse tables), so search the `description` text instead of guessing names. The documentation lives in `system.information_schema.tables.description` (the catalog) — not on the `system.data_warehouse_tables` entity, which only holds connection metadata:++```sql+SELECT table_name, description+FROM system.information_schema.tables+WHERE table_type = 'data_warehouse' AND description ILIKE '%canonical mrr%'+```++Column docs are searchable the same way via `information_schema.columns.description`. Prefer an `ILIKE` filter over dumping the whole catalog and scanning it yourself.++**Inspect a table's columns:**++```sql+SELECT column_name, data_type, is_nullable, description+FROM system.information_schema.columns+WHERE table_name = 'events'+```++This works for `system.*` entity tables too — query them by full name, e.g. `WHERE table_name = 'system.insights'`. Their column sets differ per entity, so confirm columns before projecting them.++**Discover how a table joins to others:**++```sql+SELECT source_table, source_column, target_table, target_column, relationship_kind+FROM system.information_schema.relationships+WHERE source_table = 'events'+```++`relationship_kind` is either `lazy_join` (a foreign-key-style join to a related table, e.g. `events.person_id` to persons) or `field_traverser` (an alias that hops to another field on the same row); `via` names the resolver when one applies.++**Interpret a data type** — `data_types` describes the possible values of `columns.data_type` (String, Integer, Float, Decimal, Boolean, Date, DateTime, UUID, JSON, Array, Struct, Expression, VirtualTable, Unknown):++```sql+SELECT type_name, description FROM system.information_schema.data_types+```++`information_schema` covers table and column **structure**. To verify which events, properties, and property values actually exist in captured data, use `read-data-schema` (see **Schema verification** below).+#### Querying guidelines##### Schema verificationdiff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex b4f7912abd8d..0636bacb689c 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -2799,7 +2799,7 @@}},"execute-sql": {- "description": "Use this tool to execute an SQL query (or HogQL, which is PostHog's variant of SQL that supports most of ClickHouse SQL). We're going to use terms \"HogQL\" and \"SQL\" interchangeably. For more information, see the querying-posthog-data skill.\nBEFORE writing any query, you should follow these steps:\n1. Call posthog:read-data-warehouse-schema to discover available tables, views, columns, and their types. Do NOT guess table or column names.\n2. Call posthog:read-data-schema to discover available events, properties, and property values. Do NOT rely on training data or PostHog defaults.\n3. Only after completing steps 1 and 2, write and execute your SQL query using verified table and column names.\nUse system tables with the system. prefix for PostHog-created data. For example, count SQL insight variables with:\n```sql\nSELECT count() AS total FROM system.insight_variables\n```\nAn example query to retrieve columns of a custom data warehouse table:\n```sql\nSELECT columns FROM system.data_warehouse_tables WHERE name = 'my_table'\n```\nIMPORTANT: By default, large JSON values in results (like full `properties` objects) are truncated. If you anticipate that results might be large or you are selecting the full `properties` object (e.g., `SELECT properties FROM events`), you should dump the results to a file instead of outputting them directly. Use bash commands to process the file. Alternatively, cherry-pick only the specific properties you need (e.g., `properties.$browser`) instead of selecting the entire object.\nPROPERTY ACCESS: dot notation (`properties.$browser`) only works for keys that are valid identifiers — they must start with a letter, underscore, or `$` and contain only letters, digits, underscores, and `$` (`^[A-Za-z_$][A-Za-z0-9_$]*$`). Keys that break this rule (hyphens, dots, spaces, or a leading digit) cannot use dot notation; for example `properties.$survey_response_0196e96d-7705-7d32` is parsed as a subtraction and fails. Use bracket notation with a quoted string for those keys: `properties['$survey_response_0196e96d-7705-7d32']`. This applies to all JSON columns (e.g. `person.properties[...]`).",+ "description": "Use this tool to execute an SQL query (or HogQL, which is PostHog's variant of SQL that supports most of ClickHouse SQL). We're going to use terms \"HogQL\" and \"SQL\" interchangeably. For more information, see the querying-posthog-data skill.\nBEFORE writing any query, you should follow these steps:\n1. Discover the available tables, views, columns, and their types before querying. Do NOT guess table or column names.\n2. Call posthog:read-data-schema to discover available events, properties, and property values. Do NOT rely on training data or PostHog defaults.\n3. Only after completing steps 1 and 2, write and execute your SQL query using verified table and column names.\nUse system tables with the system. prefix for PostHog-created data. For example, count SQL insight variables with:\n```sql\nSELECT count() AS total FROM system.insight_variables\n```\nAn example query to retrieve columns of a custom data warehouse table:\n```sql\nSELECT columns FROM system.data_warehouse_tables WHERE name = 'my_table'\n```\nIMPORTANT: By default, large JSON values in results (like full `properties` objects) are truncated. If you anticipate that results might be large or you are selecting the full `properties` object (e.g., `SELECT properties FROM events`), you should dump the results to a file instead of outputting them directly. Use bash commands to process the file. Alternatively, cherry-pick only the specific properties you need (e.g., `properties.$browser`) instead of selecting the entire object.\nPROPERTY ACCESS: dot notation (`properties.$browser`) only works for keys that are valid identifiers — they must start with a letter, underscore, or `$` and contain only letters, digits, underscores, and `$` (`^[A-Za-z_$][A-Za-z0-9_$]*$`). Keys that break this rule (hyphens, dots, spaces, or a leading digit) cannot use dot notation; for example `properties.$survey_response_0196e96d-7705-7d32` is parsed as a subtraction and fails. Use bracket notation with a quoted string for those keys: `properties['$survey_response_0196e96d-7705-7d32']`. This applies to all JSON columns (e.g. `person.properties[...]`).","category": "SQL","feature": "sql","summary": "Execute an SQL query.",@@ -6593,6 +6593,8 @@"summary": "Read core data warehouse schemas and table lists.","title": "Read data warehouse schema","required_scopes": ["warehouse_table:read", "warehouse_view:read"],+ "feature_flag": "mcp-sql-schema-discovery",+ "feature_flag_behavior": "disable","annotations": {"destructiveHint": false,"idempotentHint": true,diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex 785810d5c8d2..b0d0863b3cda 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -593,7 +593,7 @@}},"execute-sql": {- "description": "Use this tool to execute an SQL query (or HogQL, which is PostHog's variant of SQL that supports most of ClickHouse SQL). We're going to use terms \"HogQL\" and \"SQL\" interchangeably. For more information, see the querying-posthog-data skill.\nBEFORE writing any query, you should follow these steps:\n1. Call posthog:read-data-warehouse-schema to discover available tables, views, columns, and their types. Do NOT guess table or column names.\n2. Call posthog:read-data-schema to discover available events, properties, and property values. Do NOT rely on training data or PostHog defaults.\n3. Only after completing steps 1 and 2, write and execute your SQL query using verified table and column names.\nUse system tables with the system. prefix for PostHog-created data. For example, count SQL insight variables with:\n```sql\nSELECT count() AS total FROM system.insight_variables\n```\nAn example query to retrieve columns of a custom data warehouse table:\n```sql\nSELECT columns FROM system.data_warehouse_tables WHERE name = 'my_table'\n```\nIMPORTANT: By default, large JSON values in results (like full `properties` objects) are truncated. If you anticipate that results might be large or you are selecting the full `properties` object (e.g., `SELECT properties FROM events`), you should dump the results to a file instead of outputting them directly. Use bash commands to process the file. Alternatively, cherry-pick only the specific properties you need (e.g., `properties.$browser`) instead of selecting the entire object.\nPROPERTY ACCESS: dot notation (`properties.$browser`) only works for keys that are valid identifiers — they must start with a letter, underscore, or `$` and contain only letters, digits, underscores, and `$` (`^[A-Za-z_$][A-Za-z0-9_$]*$`). Keys that break this rule (hyphens, dots, spaces, or a leading digit) cannot use dot notation; for example `properties.$survey_response_0196e96d-7705-7d32` is parsed as a subtraction and fails. Use bracket notation with a quoted string for those keys: `properties['$survey_response_0196e96d-7705-7d32']`. This applies to all JSON columns (e.g. `person.properties[...]`).",+ "description": "Use this tool to execute an SQL query (or HogQL, which is PostHog's variant of SQL that supports most of ClickHouse SQL). We're going to use terms \"HogQL\" and \"SQL\" interchangeably. For more information, see the querying-posthog-data skill.\nBEFORE writing any query, you should follow these steps:\n1. Discover the available tables, views, columns, and their types before querying. Do NOT guess table or column names.\n2. Call posthog:read-data-schema to discover available events, properties, and property values. Do NOT rely on training data or PostHog defaults.\n3. Only after completing steps 1 and 2, write and execute your SQL query using verified table and column names.\nUse system tables with the system. prefix for PostHog-created data. For example, count SQL insight variables with:\n```sql\nSELECT count() AS total FROM system.insight_variables\n```\nAn example query to retrieve columns of a custom data warehouse table:\n```sql\nSELECT columns FROM system.data_warehouse_tables WHERE name = 'my_table'\n```\nIMPORTANT: By default, large JSON values in results (like full `properties` objects) are truncated. If you anticipate that results might be large or you are selecting the full `properties` object (e.g., `SELECT properties FROM events`), you should dump the results to a file instead of outputting them directly. Use bash commands to process the file. Alternatively, cherry-pick only the specific properties you need (e.g., `properties.$browser`) instead of selecting the entire object.\nPROPERTY ACCESS: dot notation (`properties.$browser`) only works for keys that are valid identifiers — they must start with a letter, underscore, or `$` and contain only letters, digits, underscores, and `$` (`^[A-Za-z_$][A-Za-z0-9_$]*$`). Keys that break this rule (hyphens, dots, spaces, or a leading digit) cannot use dot notation; for example `properties.$survey_response_0196e96d-7705-7d32` is parsed as a subtraction and fails. Use bracket notation with a quoted string for those keys: `properties['$survey_response_0196e96d-7705-7d32']`. This applies to all JSON columns (e.g. `person.properties[...]`).","category": "SQL","feature": "sql","summary": "Execute an SQL query.",@@ -627,6 +627,8 @@"summary": "Read core data warehouse schemas and table lists.","title": "Read data warehouse schema","required_scopes": ["warehouse_table:read", "warehouse_view:read"],+ "feature_flag": "mcp-sql-schema-discovery",+ "feature_flag_behavior": "disable","annotations": {"destructiveHint": false,"idempotentHint": true,diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.tsindex eeccbd4b2f69..5cb83d2d3e8f 100644--- a/services/mcp/src/hono/instructions.ts+++ b/services/mcp/src/hono/instructions.ts@@ -3,11 +3,18 @@ import type { Tool as McpTool } from '@modelcontextprotocol/sdk/types.js'import { hasScope } from '@/lib/api'import type { QueryToolInfo } from '@/lib/instructions'-import { type InstructionsContext, InstructionsFormatter } from '@/lib/instructions-formatter'+import {+ type InstructionsContext,+ InstructionsFormatter,+ schemaDiscoveryViaSqlEnabled,+} from '@/lib/instructions-formatter'+import type { EvaluatedFlags } from '@/lib/posthog/flags'import type { RequestProperties } from '@/lib/request-properties'import { formatPrompt } from '@/lib/utils'import { RENDER_UI_RESOURCE_URI } from '@/resources/ui-apps.generated'import EXECUTE_SQL_PROMPT from '@/templates/execute-sql-prompt.md'+import SCHEMA_DISCOVERY_INFOSCHEMA from '@/templates/sections/schema-discovery-infoschema.md'+import SCHEMA_DISCOVERY_LEGACY from '@/templates/sections/schema-discovery-legacy.md'import {getRenderableToolNames,makeRenderUiSchema,@@ -132,7 +139,13 @@ export class InstructionsBuilder {return this.guidelines}- formatExecuteSqlDescription(): string {- return formatPrompt(EXECUTE_SQL_PROMPT, { guidelines: this.guidelines.trim() })+ formatExecuteSqlDescription(featureFlags?: EvaluatedFlags): string {+ const schemaDiscovery = schemaDiscoveryViaSqlEnabled(featureFlags)+ ? SCHEMA_DISCOVERY_INFOSCHEMA+ : SCHEMA_DISCOVERY_LEGACY+ return formatPrompt(EXECUTE_SQL_PROMPT, {+ guidelines: this.guidelines.trim(),+ schema_discovery: schemaDiscovery.trim(),+ })}}diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex dbb61d276bd6..ca9b61dcb1fc 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -9,6 +9,7 @@ import {} from '@/lib/posthog/flags'import type { RequestProperties } from '@/lib/request-properties'import type { McpMode } from '@/lib/utils'+import { SQL_SCHEMA_DISCOVERY_FEATURE_FLAG } from '@/tools/posthogAiTools/readDataWarehouseSchema'import { RENDER_UI_FEATURE_FLAG } from '@/tools/render-ui'import { getRequiredFeatureFlags, getScopeGatedTools, type ScopeGatedTool } from '@/tools/toolDefinitions'import type { Context, Tool, Env, State, ZodObjectAny } from '@/tools/types'@@ -113,7 +114,11 @@ export class RequestStateResolver {// `mcp-render-ui` isn't a catalog tool flag, but it rides the same batched// evaluation and lives in the same map so the instructions layer can gate// the rendering prompt section on it (like `mcp-feedback-tool`).- const allFlagKeys = [...toolFlagKeys, RENDER_UI_FEATURE_FLAG]+ // `mcp-sql-schema-discovery` now gates the read-data-warehouse-schema tool, so+ // it already arrives via `getRequiredFeatureFlags()`; keep it listed (and dedupe)+ // since the instructions layer also reads it for SQL discovery steering — neither+ // concern should depend on the other's wiring.+ const allFlagKeys = [...new Set([...toolFlagKeys, RENDER_UI_FEATURE_FLAG, SQL_SCHEMA_DISCOVERY_FEATURE_FLAG])]const flagAnalyticsContext = await reqCtx.safelyGetAnalyticsContext(context)const flagGroups = flagAnalyticsContext ? buildMCPAnalyticsGroups(flagAnalyticsContext) : undefineddiff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 1014f2953e64..43b25805fe30 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -84,7 +84,10 @@ export class ToolExecutor {return filteredTools.map((entry) => {if (entry.name === 'execute-sql') {- return { ...entry, description: this.instructionsBuilder.formatExecuteSqlDescription() }+ return {+ ...entry,+ description: this.instructionsBuilder.formatExecuteSqlDescription(state.toolFeatureFlags),+ }}return entry})@@ -332,8 +335,20 @@ export class ToolExecutor {}const clientContext = getEffectiveMCPClientContext(state.requestContext, state.sessionContext)+ // CLI `info execute-sql` returns the tool's static description from the catalog.+ // Override it with the same flag-aware prompt tools-mode advertises, so the+ // information_schema steering (or its absence) matches across both modes.+ const execTools = state.allTools.map((tool) =>+ tool.name === 'execute-sql'+ ? {+ ...tool,+ description: this.instructionsBuilder.formatExecuteSqlDescription(state.toolFeatureFlags),+ }+ : tool+ )+const execTool = createExecTool(- state.allTools,+ execTools,state.context,this.instructionsBuilder.buildExecToolDescription(),commandReference,diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.tsindex 1c6aeda8bd41..5a0e4e721864 100644--- a/services/mcp/src/lib/instructions-formatter.ts+++ b/services/mcp/src/lib/instructions-formatter.ts@@ -18,6 +18,8 @@ import CLI_RENDERING from '@/templates/sections/cli-rendering.md'import CLI_SCHEMA_DRILLDOWN from '@/templates/sections/cli-schema-drilldown.md'import CLI_SYNTAX from '@/templates/sections/cli-syntax.md'import COMPACT_INSTRUCTIONS from '@/templates/sections/compact-instructions.md'+import ENTITY_SCHEMA_DISCOVERY_INFOSCHEMA from '@/templates/sections/entity-schema-discovery-infoschema.md'+import ENTITY_SCHEMA_DISCOVERY_LEGACY from '@/templates/sections/entity-schema-discovery-legacy.md'import ENV_CONTEXT from '@/templates/sections/env-context.md'import EXAMPLES from '@/templates/sections/examples.md'import EXEC_TOOL_BLURB from '@/templates/sections/exec-tool-blurb.md'@@ -25,6 +27,7 @@ import RETRIEVING_DATA from '@/templates/sections/retrieving-data.md'import SCHEMA_WORKFLOW from '@/templates/sections/schema-workflow.md'import TOOL_SEARCH from '@/templates/sections/tool-search.md'import URL_PATTERNS from '@/templates/sections/url-patterns.md'+import { SQL_SCHEMA_DISCOVERY_FEATURE_FLAG } from '@/tools/posthogAiTools/readDataWarehouseSchema'export interface InstructionsContext {guidelines: string@@ -41,6 +44,14 @@ export interface InstructionsContext {renderUiEnabled?: boolean | undefined}+/** Whether schema discovery should be routed through `system.information_schema.*`+ * SQL (the `mcp-sql-schema-discovery` flag) instead of the `read-data-warehouse-schema`+ * tool. Prompt-only: when on, no instruction names the tool, so the agent discovers+ * tables/columns/relationships with SQL. The tool itself stays advertised either way. */+export function schemaDiscoveryViaSqlEnabled(featureFlags: EvaluatedFlags | undefined): boolean {+ return featureFlags?.[SQL_SCHEMA_DISCOVERY_FEATURE_FLAG] === true+}+/*** Composes MCP instruction prompts for the two client modes (tools-mode and* single-exec). Each mode declares an ordered list of subprompts under@@ -102,7 +113,7 @@ export class InstructionsFormatter {EXAMPLES,]const renderCtx: InstructionsContext = opts.stripEnvContext- ? { guidelines: ctx.guidelines, queryTools: ctx.queryTools }+ ? { guidelines: ctx.guidelines, queryTools: ctx.queryTools, featureFlags: ctx.featureFlags }: ctxreturn this.compose(sections, renderCtx, { compact: false })}@@ -119,12 +130,16 @@ export class InstructionsFormatter {// `{query_tools}` only appears in non-compact sections (the exec command// reference and tools-mode instructions); compact mode surfaces queries// via the single `query` tool domain instead.+ const entitySchemaDiscovery = schemaDiscoveryViaSqlEnabled(ctx.featureFlags)+ ? ENTITY_SCHEMA_DISCOVERY_INFOSCHEMA+ : ENTITY_SCHEMA_DISCOVERY_LEGACYconst vars = {guidelines: ctx.guidelines.trim(),defined_groups: buildDefinedGroupsBlock(ctx.groupTypes),metadata: ctx.metadata?.trim() ?? '',tool_domains: ctx.tools ? renderToolDomains(ctx.tools) : '',query_tools: ctx.queryTools ? buildQueryToolsBlock(ctx.queryTools) : '',+ entity_schema_discovery: entitySchemaDiscovery.trim(),}const body = sections.map((s) => s.trim())diff --git a/services/mcp/src/templates/execute-sql-prompt.md b/services/mcp/src/templates/execute-sql-prompt.mdindex 5c2be9e7f2e9..e7ad7f96bf84 100644--- a/services/mcp/src/templates/execute-sql-prompt.md+++ b/services/mcp/src/templates/execute-sql-prompt.md@@ -18,18 +18,7 @@ If a `query-*` tool fits, use it. Default to `query-*`; SQL is the escape hatch,Before writing any SQL, read the PostHog `querying-posthog-data` skill. It is the source of truth for up-to-date HogQL patterns, system table schemas (`system.insights`, `system.dashboards`, `system.cohorts`, etc.), and function references. Do not rely on training data — table and column names drift.-### Discovery workflow (mandatory)--1. **Warehouse schema** — call `read-data-warehouse-schema` to verify tables, views, and columns. Do not guess names. **This applies to `system.*` tables too** (`system.insights`, `system.dashboards`, `system.cohorts`, …); their column sets differ per entity and drift over time. For a specific custom warehouse table, inspect its columns with:-- ```sql- SELECT columns FROM system.data_warehouse_tables WHERE name = 'my_table'- ```--2. **Event taxonomy** — call `read-data-schema` to verify events, properties, and property values. Do not rely on training data or PostHog defaults.-3. **Write the SQL** only after steps 1 and 2 confirm the data exists, using the verified table and column names.--If the required events, properties, or tables do not exist, say so — do not run queries that will return empty results.+{schema_discovery}### Format SQL for readability@@ -134,13 +123,13 @@ ORDER BY timestamp<example>User: Do we have any insights tracking revenue or payments?Assistant: I'll search existing insights and dashboards via SQL.-1. Discover columns: `read-data-warehouse-schema` to confirm `system.insights` and `system.dashboards` expose `name`, `description`, `deleted`, `last_modified_at`, and the ID columns I plan to project. Without this step I'd be guessing — column sets differ per system table.+1. Discover columns: run the schema-discovery step from the workflow above to confirm `system.insights` and `system.dashboards` expose `name`, `description`, `deleted`, `last_modified_at`, and the ID columns I plan to project. Without this step I'd be guessing — column sets differ per system table.2. Search insights by name (using only confirmed columns): `execute-sql` with `SELECT id, name, short_id, description FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR name ILIKE '%payment%') ORDER BY last_modified_at DESC LIMIT 20`.3. If results are sparse, broaden to dashboards (re-using the same schema lookup — `system.dashboards` has its own column set, e.g. no `short_id`): `execute-sql` with `SELECT id, name, description FROM system.dashboards WHERE NOT deleted AND (name ILIKE '%revenue%' OR name ILIKE '%payment%') ORDER BY last_modified_at DESC LIMIT 20`.4. Validate promising insights with `insight-retrieve`.5. Summarize with links.<reasoning>-1. `read-data-warehouse-schema` is mandatory step 1 of the discovery workflow above; `system.*` tables are warehouse tables and their column sets differ per entity (e.g. not every system table has `last_modified_at` or `short_id`).+1. Schema discovery is mandatory step 1 of the discovery workflow above; `system.*` tables' column sets differ per entity (e.g. not every system table has `last_modified_at` or `short_id`).2. SQL against `system.*` tables is the fastest way to discover existing entities — no `query-*` tool covers entity search.3. ILIKE with multiple terms catches naming variants ("Monthly Revenue", "MRR", "Payment Events").4. `insight-retrieve` confirms the insight's query configuration still matches intent.diff --git a/services/mcp/src/templates/sections/entity-schema-discovery-infoschema.md b/services/mcp/src/templates/sections/entity-schema-discovery-infoschema.mdnew file mode 100644index 000000000000..4e2f8bac65b3--- /dev/null+++ b/services/mcp/src/templates/sections/entity-schema-discovery-infoschema.md@@ -0,0 +1,15 @@+#### Searching for existing entities++"find / which / do we have / what's our X chart" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.++Required order on every run, no shortcuts — schema first, every run:++1. Confirm the table's columns with an `execute-sql` against `system.information_schema.columns`, e.g. `SELECT column_name, data_type, description FROM system.information_schema.columns WHERE table_name = 'system.insights'`. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — query the schema.+2. `execute-sql` against `system.*` — uses only columns confirmed in step 1.+3. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.++<bad-example>+User: rename / find / list … (any `system.*` question)+Assistant: [Calls `execute-sql` against `system.insights` without first confirming its columns via `system.information_schema.columns` — OR checks the schema partway through, only after several `execute-sql` calls thrashed]+WRONG — the rule is "schema first, every run, no shortcuts." Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against a `system.*` entity table MUST be preceded by an `execute-sql` against `system.information_schema.columns` for that table in the same run. Skipping or postponing the schema check is a hard violation.+</bad-example>diff --git a/services/mcp/src/templates/sections/entity-schema-discovery-legacy.md b/services/mcp/src/templates/sections/entity-schema-discovery-legacy.mdnew file mode 100644index 000000000000..25023e63347c--- /dev/null+++ b/services/mcp/src/templates/sections/entity-schema-discovery-legacy.md@@ -0,0 +1,16 @@+#### Searching for existing entities++"find / which / do we have / what's our X chart" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.++Required order on every run, no shortcuts:++1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.+2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.+3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.+4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.++<bad-example>+User: rename / find / list … (any `system.*` question)+Assistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]+WRONG — the rule is "schema first, every run, no shortcuts." Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.+</bad-example>diff --git a/services/mcp/src/templates/sections/retrieving-data.md b/services/mcp/src/templates/sections/retrieving-data.mdindex 5cb3d570cc32..55d0ba6f47db 100644--- a/services/mcp/src/templates/sections/retrieving-data.md+++ b/services/mcp/src/templates/sections/retrieving-data.md@@ -10,22 +10,7 @@ Reach for `execute-sql` only when no `query-*` tool can express the question:When you do use `execute-sql`, run `info execute-sql` first for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.-#### Searching for existing entities--"find / which / do we have / what's our X chart" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.--Required order on every run, no shortcuts:--1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.-2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.-3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.-4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.--<bad-example>-User: rename / find / list … (any `system.*` question)-Assistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]-WRONG — the rule is "schema first, every run, no shortcuts." Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.-</bad-example>+{entity_schema_discovery}#### Available insight query toolsdiff --git a/services/mcp/src/templates/sections/schema-discovery-infoschema.md b/services/mcp/src/templates/sections/schema-discovery-infoschema.mdnew file mode 100644index 000000000000..241cc015bdc4--- /dev/null+++ b/services/mcp/src/templates/sections/schema-discovery-infoschema.md@@ -0,0 +1,12 @@+### Discovery workflow (mandatory)++1. **Table & column schema** — discover the data model with HogQL against `system.information_schema.*`. Do not guess table or column names; they differ per entity and drift over time.+ - List available tables: `SELECT table_name, table_type, description FROM system.information_schema.tables`.+ - Inspect a table's columns: `SELECT column_name, data_type, is_nullable, description FROM system.information_schema.columns WHERE table_name = 'events'`.+ - Discover joins / foreign keys: `SELECT source_table, source_column, target_table, target_column FROM system.information_schema.relationships WHERE source_table = 'events'`.++ **This covers `system.*` entity tables too** (`system.insights`, `system.dashboards`, `system.cohorts`, …) — query them by their full name, e.g. `WHERE table_name = 'system.insights'`. Their column sets differ per entity, so confirm columns before projecting them.+2. **Event taxonomy** — call `read-data-schema` to verify events, properties, and property values. Do not rely on training data or PostHog defaults.+3. **Write the SQL** only after steps 1 and 2 confirm the data exists, using the verified table and column names.++If the required events, properties, or tables do not exist, say so — do not run queries that will return empty results.diff --git a/services/mcp/src/templates/sections/schema-discovery-legacy.md b/services/mcp/src/templates/sections/schema-discovery-legacy.mdnew file mode 100644index 000000000000..a05192150680--- /dev/null+++ b/services/mcp/src/templates/sections/schema-discovery-legacy.md@@ -0,0 +1,12 @@+### Discovery workflow (mandatory)++1. **Warehouse schema** — call `read-data-warehouse-schema` to verify tables, views, and columns. Do not guess names. **This applies to `system.*` tables too** (`system.insights`, `system.dashboards`, `system.cohorts`, …); their column sets differ per entity and drift over time. For a specific custom warehouse table, inspect its columns with:++ ```sql+ SELECT columns FROM system.data_warehouse_tables WHERE name = 'my_table'+ ```++2. **Event taxonomy** — call `read-data-schema` to verify events, properties, and property values. Do not rely on training data or PostHog defaults.+3. **Write the SQL** only after steps 1 and 2 confirm the data exists, using the verified table and column names.++If the required events, properties, or tables do not exist, say so — do not run queries that will return empty results.diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 51da1a052533..9e8f9908587b 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -120,11 +120,17 @@ export function createExecInnerToolCallResolver(}}-// Tools that were removed from the MCP server. When the model attempts to call-// one, surface a targeted redirect to the replacement instead of dumping the-// full tool catalog. Keep the redirect text editorial — schemas don't carry-// "use X instead" guidance.+// Tools that were removed from the MCP server — or flag-gated out of the active+// catalog. When the model attempts to call one that isn't present, surface a+// targeted redirect to the replacement instead of dumping the full tool catalog.+// Keep the redirect text editorial — schemas don't carry "use X instead"+// guidance. A redirect only fires when the tool is absent, so an entry for a+// conditionally-gated tool is inert whenever that tool is registered.const DEPRECATED_TOOL_REDIRECTS: Record<string, (allTools: Tool<ZodObjectAny>[]) => string> = {+ // Disabled while `mcp-sql-schema-discovery` is on; the SQL information_schema+ // path replaces it. See readDataWarehouseSchema.ts for the flag/TODO.+ 'read-data-warehouse-schema': () =>+ 'Tool "read-data-warehouse-schema" was removed in favor of SQL-based schema discovery. Use "execute-sql" against `system.information_schema.*` (`tables`, `columns`, `relationships`, `data_types`) — it scales to large catalogs and supports filtering/search (e.g. `WHERE description ILIKE \'%...%\'`). Consult the `querying-posthog-data` skill for patterns.','entity-search': () =>'Tool "entity-search" was removed. Use "execute-sql" to search PostHog data via HogQL. Consult the `querying-posthog-data` skill for system-table patterns (system.insights, system.dashboards, system.cohorts, ...).','event-definitions-list': () =>diff --git a/services/mcp/src/tools/posthogAiTools/readDataWarehouseSchema.ts b/services/mcp/src/tools/posthogAiTools/readDataWarehouseSchema.tsindex dfde0d9790f7..b608ea1cebe8 100644--- a/services/mcp/src/tools/posthogAiTools/readDataWarehouseSchema.ts+++ b/services/mcp/src/tools/posthogAiTools/readDataWarehouseSchema.ts@@ -3,6 +3,21 @@ import type { Context, ToolBase } from '@/tools/types'import { invokeMcpTool } from './invokeTool'+// Flag that routes schema discovery through `system.information_schema.*` SQL. When it+// is on, two things happen: the discovery instructions steer the agent toward+// `execute-sql` against `system.information_schema.*`, and this tool is gated OUT of the+// catalog (via `feature_flag_behavior: "disable"` in tool-definitions.json) so the SQL+// path is the only one. An agent that still calls it by name gets the redirect in+// `DEPRECATED_TOOL_REDIRECTS`. Off-flag, the tool stays registered and callable.+//+// TODO: once `mcp-sql-schema-discovery` is rolled out to 100%, delete this tool+// entirely — the `system.information_schema.*` SQL path fully replaces it — and retire+// this flag along with the legacy (non-infoschema) discovery prompt sections.+export const SQL_SCHEMA_DISCOVERY_FEATURE_FLAG = 'mcp-sql-schema-discovery'++// The advertised name of this tool.+export const READ_DATA_WAREHOUSE_SCHEMA_TOOL_NAME = 'read-data-warehouse-schema'+const schema = ReadDataWarehouseSchemaSchemaexport const readDataWarehouseSchemaHandler: ToolBase<typeof schema, string>['handler'] = async (context: Context) => {@@ -18,7 +33,7 @@ export const readDataWarehouseSchemaHandler: ToolBase<typeof schema, string>['ha}const tool = (): ToolBase<typeof schema, string> => ({- name: 'read-data-warehouse-schema',+ name: READ_DATA_WAREHOUSE_SCHEMA_TOOL_NAME,schema,handler: readDataWarehouseSchemaHandler,})diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsindex d8a9da981d20..bee93f3a68aa 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -93,6 +93,13 @@ function makeResolver(): RequestStateResolver {return new RequestStateResolver(catalog as any, {} as RedisLike, {} as Env)}+function makeResolverWithTools(toolNames: string[]): RequestStateResolver {+ const catalog = {+ getFilteredTools: vi.fn(() => toolNames.map((name) => ({ name }))),+ }+ return new RequestStateResolver(catalog as any, {} as RedisLike, {} as Env)+}+describe('RequestStateResolver MCP client contexts', () => {beforeEach(() => {mockSessionStore.clear()@@ -319,3 +326,25 @@ describe('RequestStateResolver MCP client contexts', () => {expect(mockSessionStore.get('mcpConsumer')).toBe('posthog-code')})})++describe('RequestStateResolver SQL schema-discovery flag', () => {+ beforeEach(() => {+ mockSessionStore.clear()+ mockTokenStore.clear()+ vi.mocked(evaluateFeatureFlags).mockResolvedValue({})+ })++ // The flag steers discovery instructions toward SQL but is prompt-only — it must NOT+ // remove read-data-warehouse-schema from the tool set. Guards against re-introducing+ // tool gating here; the tool stays advertised/callable whether the flag is on or off.+ it.each([true, false])('keeps read-data-warehouse-schema available when the flag is %s', async (flagOn) => {+ vi.mocked(evaluateFeatureFlags).mockResolvedValueOnce({ 'mcp-sql-schema-discovery': flagOn })+ const resolver = makeResolverWithTools(['read-data-warehouse-schema', 'execute-sql'])++ const result = await resolver.resolve(makeProps())++ const names = result.allTools.map((t) => t.name)+ expect(names).toContain('read-data-warehouse-schema')+ expect(names).toContain('execute-sql')+ })+})diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 4ace3b95a312..460a74c4884d 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -784,6 +784,7 @@ describe('exec tool', () => {describe('deprecated tool redirects', () => {it.each([+ ['read-data-warehouse-schema', 'execute-sql'],['entity-search', 'execute-sql'],['event-definitions-list', 'read-data-schema'],['properties-list', 'read-data-schema'],diff --git a/services/mcp/tests/unit/schema-discovery-flag.test.ts b/services/mcp/tests/unit/schema-discovery-flag.test.tsnew file mode 100644index 000000000000..bb2697ae8b37--- /dev/null+++ b/services/mcp/tests/unit/schema-discovery-flag.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest'++import { InstructionsBuilder } from '@/hono/instructions'+import { InstructionsFormatter, type InstructionsContext } from '@/lib/instructions-formatter'+import { SQL_SCHEMA_DISCOVERY_FEATURE_FLAG } from '@/tools/posthogAiTools/readDataWarehouseSchema'++// The `mcp-sql-schema-discovery` flag is prompt-only: when on, no instruction names+// `read-data-warehouse-schema` and discovery is steered through+// `system.information_schema.*`. When off, the legacy tool-based discovery stays.+describe('mcp-sql-schema-discovery flag gating', () => {+ const ctx: InstructionsContext = {+ guidelines: 'some guidelines',+ tools: [+ { name: 'execute-sql', category: 'SQL' },+ { name: 'read-data-warehouse-schema', category: 'Data schema' },+ ],+ }++ describe('execute-sql description (InstructionsBuilder.formatExecuteSqlDescription)', () => {+ const builder = new InstructionsBuilder('some guidelines')++ it.each([undefined, {}, { [SQL_SCHEMA_DISCOVERY_FEATURE_FLAG]: false }])(+ 'names read-data-warehouse-schema when the flag is off (%o)',+ (featureFlags) => {+ const result = builder.formatExecuteSqlDescription(featureFlags)+ expect(result).toContain('read-data-warehouse-schema')+ expect(result).not.toContain('system.information_schema')+ }+ )++ it('routes through system.information_schema and never names the tool when the flag is on', () => {+ const result = builder.formatExecuteSqlDescription({ [SQL_SCHEMA_DISCOVERY_FEATURE_FLAG]: true })+ expect(result).toContain('system.information_schema')+ expect(result).not.toContain('read-data-warehouse-schema')+ })+ })++ describe('entity discovery section (InstructionsFormatter)', () => {+ const formatter = new InstructionsFormatter()+ const renderBothModes = (c: InstructionsContext): string[] => [+ formatter.buildToolsInstructions(c),+ formatter.buildExecCommandReference(c, { stripEnvContext: false }),+ ]++ it('names read-data-warehouse-schema in both modes when the flag is off', () => {+ const [toolsMode, cliMode] = renderBothModes(ctx)+ expect(toolsMode).toContain('read-data-warehouse-schema')+ expect(toolsMode).not.toContain('system.information_schema')+ expect(cliMode).toContain('read-data-warehouse-schema')+ expect(cliMode).not.toContain('system.information_schema')+ })++ it('routes through system.information_schema in both modes when the flag is on', () => {+ const [toolsMode, cliMode] = renderBothModes({+ ...ctx,+ featureFlags: { [SQL_SCHEMA_DISCOVERY_FEATURE_FLAG]: true },+ })+ expect(toolsMode).toContain('system.information_schema')+ expect(toolsMode).not.toContain('read-data-warehouse-schema')+ expect(cliMode).toContain('system.information_schema')+ expect(cliMode).not.toContain('read-data-warehouse-schema')+ })+ })+})diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 65b820b2914e..ca7c05e9ec13 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -189,6 +189,26 @@ describe('Tool Filtering - Tools Allowlist', () => {expect(toolsWithoutFlags).not.toContain('agent-feedback')})+ it('should hide read-data-warehouse-schema when mcp-sql-schema-discovery is on (disable gate)', () => {+ // SQL information_schema discovery replaces the tool while the flag is on.+ const withFlagOn = getToolsForFeatures({+ tools: ['read-data-warehouse-schema'],+ featureFlags: { 'mcp-sql-schema-discovery': true },+ })+ expect(withFlagOn).not.toContain('read-data-warehouse-schema')++ // Off / unevaluated → the tool stays available (disable default is "show").+ expect(getToolsForFeatures({ tools: ['read-data-warehouse-schema'] })).toContain(+ 'read-data-warehouse-schema'+ )+ expect(+ getToolsForFeatures({+ tools: ['read-data-warehouse-schema'],+ featureFlags: { 'mcp-sql-schema-discovery': false },+ })+ ).toContain('read-data-warehouse-schema')+ })+it('should union with features (OR) when both are provided', () => {const tools = getToolsForFeatures({ features: ['flags'], tools: ['dashboard-get'] })@@ -754,9 +774,10 @@ describe('Tool Filtering - Feature Flags', () => {'field-notes','mcp-analytics','metrics',+ 'mcp-sql-schema-discovery',]))- expect(flags).toHaveLength(18)+ expect(flags).toHaveLength(19)})// Exercise the real predicate (toolPassesFlagGate) over hand-rolled entriesdiff --git a/tach.toml b/tach.tomlindex 19f825ccb777..33b09c9ec0f4 100644--- a/tach.toml+++ b/tach.toml@@ -42,6 +42,7 @@ depends_on = ["products.customer_analytics","products.dashboards","products.data_modeling",+ "products.data_tools","products.error_tracking","products.event_definitions","products.experiments",