Skip to content

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

feat(phai): require warehouse schema discovery before SQL on system.* (#57694)

Georgiy Tarasov9faeee9addba
diff --git a/ee/hogai/eval/conftest.py b/ee/hogai/eval/conftest.py
index 1235b2a5f631..00391a6bcea6 100644
--- a/ee/hogai/eval/conftest.py
+++ b/ee/hogai/eval/conftest.py
@@ -32,10 +32,10 @@ def pytest_addoption(parser):
parser.addoption(
"--agent-model",
action="store",
- default="claude-opus-4-7",
+ default="anthropic/claude-opus-4-7",
help=(
"Model the sandboxed agent runs against. Pinned for stable cross-run "
- "comparisons. Defaults to claude-opus-4-7."
+ "comparisons. Defaults to anthropic/claude-opus-4-7."
),
)
diff --git a/ee/hogai/eval/sandboxed/ci/eval_basic.py b/ee/hogai/eval/sandboxed/ci/eval_basic.py
index bc97ea532ffc..be6aede7c2e2 100644
--- a/ee/hogai/eval/sandboxed/ci/eval_basic.py
+++ b/ee/hogai/eval/sandboxed/ci/eval_basic.py
@@ -11,14 +11,11 @@ Example eval case pattern:
from __future__ import annotations
-import pytest
-
from ee.hogai.eval.sandboxed.base import SandboxedPublicEval
from ee.hogai.eval.sandboxed.config import SandboxedEvalCase
from ee.hogai.eval.sandboxed.scorers import ExitCodeZero
async def eval_bugfix(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
cases = [
SandboxedEvalCase(
diff --git a/ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.py b/ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.py
index 59e194462822..33e8c0f48928 100644
--- a/ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.py
+++ b/ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.py
@@ -43,7 +43,6 @@ from ee.hogai.eval.sandboxed.config import SandboxedEvalCase
from ee.hogai.eval.sandboxed.scorers import ExitCodeZero
async def eval_typo_recovery(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
"""Prompted with a deprecated or typo'd tool name, the agent must recover."""
if mcp_mode == "tools":
@@ -82,7 +81,6 @@ async def eval_typo_recovery(sandboxed_demo_data, pytestconfig, posthog_client,
)
async def eval_schema_drilldown(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
"""Trends question with breakdown — the agent must drill into nested schema fields."""
if mcp_mode == "tools":
@@ -115,7 +113,6 @@ async def eval_schema_drilldown(sandboxed_demo_data, pytestconfig, posthog_clien
)
async def eval_search_first(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
"""Open-ended discovery — the agent must prefer ``search`` over bare ``tools``."""
if mcp_mode == "tools":
@@ -142,7 +139,6 @@ async def eval_search_first(sandboxed_demo_data, pytestconfig, posthog_client, m
)
async def eval_info_before_call(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
"""Every successful ``call <tool>`` must be preceded by ``info <tool>``."""
if mcp_mode == "tools":
@@ -177,7 +173,6 @@ async def eval_info_before_call(sandboxed_demo_data, pytestconfig, posthog_clien
)
async def eval_json_for_post_processing(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
"""Post-processing scenario — agent must request raw JSON and run Python on it.
@@ -223,7 +218,6 @@ async def eval_json_for_post_processing(sandboxed_demo_data, pytestconfig, posth
)
async def eval_verify_event_before_query(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
"""``query-*`` calls must be preceded by a successful ``read-data-schema`` call."""
if mcp_mode == "tools":
diff --git a/ee/hogai/eval/sandboxed/conftest.py b/ee/hogai/eval/sandboxed/conftest.py
index 54dd80171fdb..acf60c3e0aef 100644
--- a/ee/hogai/eval/sandboxed/conftest.py
+++ b/ee/hogai/eval/sandboxed/conftest.py
@@ -1,15 +1,12 @@
from __future__ import annotations
import os
-import time
import atexit
-import signal
-import socket
import asyncio
import logging
import threading
import subprocess
-from collections.abc import Callable, Generator
+from collections.abc import Generator
from pathlib import Path
import pytest
@@ -30,6 +27,7 @@ from products.tasks.backend.temporal import (
# We want the PostHog set_up_evals fixture here
from ee.hogai.eval.conftest import set_up_evals # noqa: F401
from ee.hogai.eval.data_setup import copy_demo_data_to_new_team, create_core_memory, ensure_master_demo_team
+from ee.hogai.eval.sandboxed.long_lived_subprocess import LongLivedSubprocessManager
logger = logging.getLogger(__name__)
@@ -37,36 +35,28 @@ MCP_PORT = 18787 # Non-default port to avoid conflicts with dev MCP
DJANGO_LIVE_PORT = 18000 # Non-default port for in-process Django server
LLM_GATEWAY_PORT = 13308 # Non-default port to avoid conflicts with dev LLM gateway
-# Sandboxed evals issue HogQL validation that touches the `persons_db_*`
-# replicas (the validator opens connections even when the query itself
-# doesn't read persons). pytest-django defaults a test's allowed
-# databases to ``{"default"}`` only, so without this whitelist
-# `execute-sql` raises an internal error. Applied via
-# ``pytest_collection_modifyitems`` below so individual evals don't have
-# to repeat it on every ``@pytest.mark.django_db`` marker.
-SANDBOXED_EVAL_DATABASES = ("default", "persons_db_writer", "persons_db_reader")
+# pytest-django normally derives this from ``@pytest.mark.django_db`` markers.
+# Sandboxed evals intentionally strip those markers to avoid per-test DB
+# transactions/flushes, so the local ``django_db_setup`` override below forces
+# setup of the base Django DB explicitly. Person DB setup is handled by
+# PostHog's eval setup after the default test DB name is known.
+SANDBOXED_EVAL_SETUP_DATABASES: dict[str, None] = {"default": None}
def pytest_collection_modifyitems(config, items): # noqa: ARG001
- """Auto-extend ``@pytest.mark.django_db`` for every sandboxed eval.
-
- Tests under this directory transparently get access to the persons
- replicas. If a test ever needs a narrower whitelist it can set
- ``databases=...`` on its own marker — explicit kwargs win.
-
- ``transaction=True`` is applied by default so ORM writes are committed and
- visible to Temporal activities, which run on worker threads with their own
- DB connections. Without this, ``get_task_processing_context`` raises
- ``TaskRun matching query does not exist`` while the test transaction is
- still open.
-
- Prepended via ``append=False`` so it beats the function-level
- ``@pytest.mark.django_db`` in pytest's ``iter_markers``/``get_closest_marker``
- resolution; otherwise the original (no-kwargs) marker is read first
- and pytest-django defaults ``databases`` back to ``{"default"}``.
-
- This piggybacks on the same ``pytest_collection_modifyitems`` hook
- that ``mcp_mode`` parametrization uses.
+ """Keep sandboxed evals out of pytest-django's per-test DB wrappers.
+
+ The sandbox harness starts a live Django server and Temporal worker that
+ use separate DB connections. They must see committed rows immediately, so
+ normal pytest-django test transactions do not work. ``transaction=True``
+ makes the rows visible, but also puts every eval on the transactional test
+ path, which flushes/re-initializes state between tests and defeats the
+ long-lived eval database.
+
+ Instead, ``_sandboxed_eval_database_access`` below creates the DB once and
+ leaves access unblocked for the whole eval session. Strip accidental
+ ``django_db`` markers so pytest-django does not add transactional fixtures
+ back in.
"""
base_dir = Path(__file__).parent
for item in items:
@@ -75,122 +65,76 @@ def pytest_collection_modifyitems(config, items): # noqa: ARG001
test_path.relative_to(base_dir)
except (TypeError, ValueError):
continue
- existing = item.get_closest_marker("django_db")
- if existing is not None and "databases" in existing.kwargs:
- continue # respect explicit per-test override
- args = existing.args if existing is not None else ()
- kwargs = {**(existing.kwargs if existing is not None else {}), "databases": list(SANDBOXED_EVAL_DATABASES)}
- if "transaction" not in kwargs:
- kwargs["transaction"] = True
- item.add_marker(pytest.mark.django_db(*args, **kwargs), append=False)
+ node = item
+ while node is not None:
+ own_markers = getattr(node, "own_markers", None)
+ if own_markers is not None:
+ node.own_markers = [marker for marker in own_markers if marker.name != "django_db"]
+ node = node.parent
+ item.keywords.pop("django_db", None)
-# Sandbox container name prefix used by the eval harness (set in SandboxConfig.name)
-_EVAL_CONTAINER_PREFIX = "task-sandbox-"
-
[email protected](scope="session")
+def django_db_setup(
+ request: pytest.FixtureRequest,
+ django_test_environment: None,
+ django_db_blocker,
+ django_db_use_migrations: bool,
+ django_db_keepdb: bool,
+ django_db_createdb: bool,
+ django_db_modify_db_settings: None,
+) -> Generator[None, None, None]:
+ """Create the eval test DB even though eval items have no django_db marker."""
+ from django.test.utils import setup_databases, teardown_databases
-def _temporal_client_target(env: WorkflowEnvironment) -> tuple[str, str]:
- config = env.client.config()
- service_client = config["service_client"]
- target_host = service_client.config.target_host
- host, port = target_host.rsplit(":", maxsplit=1)
- return host, port
+ from pytest_django.fixtures import _disable_migrations
+ if not django_db_use_migrations:
+ _disable_migrations()
-def _start_long_lived_subprocess(
- *,
- name: str,
- port: int,
- cmd: list[str],
- cwd: Path,
- env: dict[str, str],
- log_prefix: str,
- readiness_timeout: float = 30.0,
-) -> tuple[subprocess.Popen, Callable[[], None]]:
- """Spawn a long-lived support service (LLM gateway, MCP server) for the eval session.
-
- Three guarantees beyond a bare ``subprocess.Popen``:
-
- * **Pre-flight port check** — refuses to start if ``port`` is already bound.
- A previous session's stale process would otherwise pass our TCP-level
- readiness check (we'd connect to the *old* process), and tests would
- silently run against a gateway tied to a deleted test database.
-
- * **Subprocess-aware readiness wait** — polls ``proc.poll()`` on every
- iteration. If the subprocess died during startup (e.g. EADDRINUSE that
- slipped past the pre-flight check, missing dependency, config error),
- fails loudly with the captured returncode rather than waiting for the
- TCP timeout.
-
- * **Process-group cleanup on session exit** — ``start_new_session=True``
- puts the child in its own process group, and an ``atexit`` hook sends
- ``SIGTERM`` (then ``SIGKILL``) to the whole group. Mirrors the docker
- container cleanup pattern in ``_cleanup_eval_containers``. Doesn't fire
- on ``SIGKILL`` of pytest itself — but the next session's pre-flight
- check will catch any leak with a specific ``lsof`` hint.
- """
- try:
- pre_sock = socket.create_connection(("localhost", port), timeout=0.5)
- pre_sock.close()
- pytest.fail(
- f"Port {port} is already in use — likely a stale {name} from a prior eval session. "
- f"Find and kill it:\n lsof -iTCP:{port} -sTCP:LISTEN"
+ with django_db_blocker.unblock():
+ db_cfg = setup_databases(
+ verbosity=request.config.option.verbose,
+ interactive=False,
+ keepdb=django_db_keepdb and not django_db_createdb,
+ aliases=SANDBOXED_EVAL_SETUP_DATABASES,
+ serialized_aliases=set(),
)
- except OSError:
- pass # port is free, proceed
- proc = subprocess.Popen(
- cmd,
- cwd=cwd,
- env=env,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- start_new_session=True,
- )
+ yield
- def _stop() -> None:
- if proc.poll() is not None:
- return
- try:
- os.killpg(proc.pid, signal.SIGTERM)
- except (ProcessLookupError, PermissionError):
- return
- try:
- proc.wait(timeout=5)
- except subprocess.TimeoutExpired:
- try:
- os.killpg(proc.pid, signal.SIGKILL)
- except (ProcessLookupError, PermissionError):
- pass
+ if not django_db_keepdb:
+ with django_db_blocker.unblock():
+ teardown_databases(db_cfg, verbosity=request.config.option.verbose)
- atexit.register(_stop)
- def _pipe_to_logger(pipe, level):
- for line in iter(pipe.readline, b""):
- text = line.decode("utf-8", errors="replace").rstrip()
- if text:
- logger.log(level, "[%s] %s", log_prefix, text)
- pipe.close()
[email protected](scope="session", autouse=True)
+def _sandboxed_eval_database_access(set_up_evals, django_db_blocker) -> Generator[None, None, None]: # noqa: F811
+ """Use one committed eval database instead of per-test transactions."""
+ django_db_blocker.unblock()
+ yield
+ django_db_blocker.restore()
- threading.Thread(target=_pipe_to_logger, args=(proc.stdout, logging.INFO), daemon=True).start()
- threading.Thread(target=_pipe_to_logger, args=(proc.stderr, logging.WARNING), daemon=True).start()
- deadline = time.monotonic() + readiness_timeout
- while time.monotonic() < deadline:
- if proc.poll() is not None:
- pytest.fail(
- f"{name} subprocess exited with code {proc.returncode} during startup. "
- f"Check the [{log_prefix}] WARNING lines above."
- )
- try:
- sock = socket.create_connection(("localhost", port), timeout=1)
- sock.close()
- return proc, _stop
- except OSError:
- time.sleep(0.5)
+# Sandbox container name prefix used by the eval harness (set in SandboxConfig.name)
+_EVAL_CONTAINER_PREFIX = "task-sandbox-"
+_LONG_LIVED_SUBPROCESSES = LongLivedSubprocessManager()
+
+
+def pytest_keyboard_interrupt(excinfo: object) -> None: # noqa: ARG001
+ _LONG_LIVED_SUBPROCESSES.stop_all()
+
+
+def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None: # noqa: ARG001
+ _LONG_LIVED_SUBPROCESSES.stop_all()
- _stop()
- pytest.fail(f"{name} failed to start on port {port} within {readiness_timeout:.0f}s.")
+
+def _temporal_client_target(env: WorkflowEnvironment) -> tuple[str, str]:
+ config = env.client.config()
+ service_client = config["service_client"]
+ target_host = service_client.config.target_host
+ host, port = target_host.rsplit(":", maxsplit=1)
+ return host, port
def _cleanup_eval_containers():
@@ -234,7 +178,7 @@ def _cleanup_sandbox_containers(pytestconfig):
@pytest.fixture(scope="session", autouse=True)
-def _django_live_server(django_db_setup, django_db_blocker):
+def _django_live_server(_sandboxed_eval_database_access):
"""Start an in-process Django HTTP server on the test database.
Uses Django's ``LiveServerThread`` (same mechanism as pytest-django's
@@ -242,20 +186,17 @@ def _django_live_server(django_db_setup, django_db_blocker):
calls this server via ``host.docker.internal`` for API requests,
log persistence, and the LLM gateway.
- Depends on ``django_db_setup`` so the test database is created before
- any subprocess (LLM gateway, MCP) tries to connect to it.
+ Depends on ``_sandboxed_eval_database_access`` so the PostHog eval database
+ setup has completed before any subprocess (LLM gateway, MCP) connects.
"""
from pytest_django.live_server_helper import LiveServer
- django_db_blocker.unblock()
-
server = LiveServer(f"localhost:{DJANGO_LIVE_PORT}")
logger.info("Django live server started at %s", server.url)
yield server
server.stop()
- django_db_blocker.restore()
logger.info("Django live server stopped")
@@ -438,7 +379,7 @@ def _terminate_stale_workflows(_sandbox_settings):
@pytest.fixture(scope="session", autouse=True)
-def _temporal_worker(_sandbox_settings, _terminate_stale_workflows, django_db_blocker):
+def _temporal_worker(_sandbox_settings, _terminate_stale_workflows, _sandboxed_eval_database_access):
"""Start an in-process temporal worker for the tasks queue.
Mirrors the dev worker (``manage.py start_temporal_worker``) using
@@ -476,14 +417,10 @@ def _temporal_worker(_sandbox_settings, _terminate_stale_workflows, django_db_bl
await managed.shutdown()
worker_task.cancel()
- # Unblock DB access for the worker thread and its activity thread pool
- django_db_blocker.unblock()
-
thread = threading.Thread(target=loop.run_until_complete, args=(_run(),), daemon=True)
thread.start()
if not ready_event.wait(timeout=30):
- django_db_blocker.restore()
pytest.fail(
f"Temporal worker failed to start within 30s. "
f"Is temporal running at {settings.TEMPORAL_HOST}:{settings.TEMPORAL_PORT}?"
@@ -494,7 +431,6 @@ def _temporal_worker(_sandbox_settings, _terminate_stale_workflows, django_db_bl
loop.call_soon_threadsafe(stop_event.set)
thread.join(timeout=10)
- django_db_blocker.restore()
@pytest.fixture(scope="session", autouse=True)
@@ -538,7 +474,7 @@ def _llm_gateway(_django_live_server, sandboxed_demo_data):
}
logger.info("Starting LLM gateway on port %d", LLM_GATEWAY_PORT)
- _, stop = _start_long_lived_subprocess(
+ _, stop = _LONG_LIVED_SUBPROCESSES.start(
name="LLM gateway",
port=LLM_GATEWAY_PORT,
cmd=[
@@ -595,7 +531,7 @@ def _mcp_server(_django_live_server, _sandbox_settings):
var_args.extend(["--var", v])
logger.info("Starting MCP server on port %d (API: %s)", MCP_PORT, api_url)
- _, stop = _start_long_lived_subprocess(
+ _, stop = _LONG_LIVED_SUBPROCESSES.start(
name="MCP server",
port=MCP_PORT,
cmd=["pnpm", "wrangler", "dev", "--port", str(MCP_PORT), *var_args],
diff --git a/ee/hogai/eval/sandboxed/experiments/eval_create_control_variant.py b/ee/hogai/eval/sandboxed/experiments/eval_create_control_variant.py
index 231a52114fe7..8428f19c662e 100644
--- a/ee/hogai/eval/sandboxed/experiments/eval_create_control_variant.py
+++ b/ee/hogai/eval/sandboxed/experiments/eval_create_control_variant.py
@@ -33,14 +33,11 @@ To run:
from __future__ import annotations
-import pytest
-
from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval
from ee.hogai.eval.sandboxed.config import SandboxedEvalCase
from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, RequiredToolCall
async def eval_create_control_variant(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
cases: list[SandboxedEvalCase] = [
# Single high-coverage case. The "A (existing) vs B (new)" framing
diff --git a/ee/hogai/eval/sandboxed/experiments/eval_lifecycle_skills.py b/ee/hogai/eval/sandboxed/experiments/eval_lifecycle_skills.py
index c36ee66fc5cf..03903cdd47c0 100644
--- a/ee/hogai/eval/sandboxed/experiments/eval_lifecycle_skills.py
+++ b/ee/hogai/eval/sandboxed/experiments/eval_lifecycle_skills.py
@@ -33,8 +33,6 @@ To run:
from __future__ import annotations
-import pytest
-
from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval
from ee.hogai.eval.sandboxed.config import SandboxedEvalCase
from ee.hogai.eval.sandboxed.experiments.scorers import (
@@ -54,7 +52,6 @@ from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, NoToolCall, RequiredTo
# parallelism, and break cross-case comparison. Every existing sandboxed eval
# (eval_funnel, eval_retention, eval_insight_retrieval, eval_rollout_skill)
# follows this same single-function-multiple-cases shape.
async def eval_lifecycle_skills(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
cases: list[SandboxedEvalCase] = [
# Case 1: Ship variant must require confirmation.
diff --git a/ee/hogai/eval/sandboxed/experiments/eval_rollout_skill.py b/ee/hogai/eval/sandboxed/experiments/eval_rollout_skill.py
index 58ab412156dc..a05c9a079159 100644
--- a/ee/hogai/eval/sandboxed/experiments/eval_rollout_skill.py
+++ b/ee/hogai/eval/sandboxed/experiments/eval_rollout_skill.py
@@ -20,8 +20,6 @@ To run:
from __future__ import annotations
-import pytest
-
from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval
from ee.hogai.eval.sandboxed.config import SandboxedEvalCase
from ee.hogai.eval.sandboxed.experiments.seeders import ROLLOUT_EXPERIMENT_NAME, seed_running_experiment
@@ -31,7 +29,6 @@ from ee.hogai.eval.sandboxed.scorers import ExitCodeZero
SKILL_NAME = "configuring-experiment-rollout"
async def eval_rollout_skill(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
cases: list[SandboxedEvalCase] = [
SandboxedEvalCase(
diff --git a/ee/hogai/eval/sandboxed/experiments/eval_shared_metric_validation.py b/ee/hogai/eval/sandboxed/experiments/eval_shared_metric_validation.py
index bc0f004b3b30..326e8bb89101 100644
--- a/ee/hogai/eval/sandboxed/experiments/eval_shared_metric_validation.py
+++ b/ee/hogai/eval/sandboxed/experiments/eval_shared_metric_validation.py
@@ -7,8 +7,6 @@ and (2) reach the correct verdict citing grounded discrepancies.
from __future__ import annotations
-import pytest
-
from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval
from ee.hogai.eval.sandboxed.config import SandboxedEvalCase
from ee.hogai.eval.sandboxed.experiments.scorers import SharedMetricValidationVerdict
@@ -16,7 +14,6 @@ from ee.hogai.eval.sandboxed.experiments.seeders import SHARED_METRIC_NAME, seed
from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, RequiredToolCall
async def eval_shared_metric_validation(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
cases: list[SandboxedEvalCase] = [
# Case 1: criteria match the seeded metric exactly. Agent should
diff --git a/ee/hogai/eval/sandboxed/experiments/eval_unknown_events_confirmation.py b/ee/hogai/eval/sandboxed/experiments/eval_unknown_events_confirmation.py
index 655c3669a7ac..d10d954ffc1b 100644
--- a/ee/hogai/eval/sandboxed/experiments/eval_unknown_events_confirmation.py
+++ b/ee/hogai/eval/sandboxed/experiments/eval_unknown_events_confirmation.py
@@ -37,8 +37,6 @@ To run:
from __future__ import annotations
-import pytest
-
from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval
from ee.hogai.eval.sandboxed.config import SandboxedEvalCase
from ee.hogai.eval.sandboxed.experiments.scorers import AskedForConfirmation
@@ -50,7 +48,6 @@ from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, NoToolCall, RequiredTo
UNKNOWN_EVENT_NAME = "totally_made_up_event_qzx"
async def eval_unknown_events_confirmation(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
cases: list[SandboxedEvalCase] = [
# The agent is asked to wire up a metric on an event the project
diff --git a/ee/hogai/eval/sandboxed/long_lived_subprocess.py b/ee/hogai/eval/sandboxed/long_lived_subprocess.py
new file mode 100644
index 000000000000..47196a4d2f70
--- /dev/null
+++ b/ee/hogai/eval/sandboxed/long_lived_subprocess.py
@@ -0,0 +1,361 @@
+from __future__ import annotations
+
+import os
+import json
+import time
+import atexit
+import signal
+import socket
+import logging
+import tempfile
+import threading
+import subprocess
+from collections.abc import Callable
+from pathlib import Path
+from types import FrameType
+from typing import TypedDict, cast
+
+import pytest
+
+logger = logging.getLogger(__name__)
+
+StopCallback = Callable[[], None]
+
+
+class ProcessMetadata(TypedDict):
+ name: str
+ port: int
+ pid: int
+ pgid: int
+ cmd: list[str]
+ cwd: str
+
+
+class LongLivedSubprocessManager:
+ """Own support subprocess lifecycle for sandboxed eval sessions."""
+
+ def __init__(self) -> None:
+ self._stops: list[StopCallback] = []
+ self._stops_lock = threading.Lock()
+ self._previous_signal_handlers: dict[int, object] = {}
+ self._signal_handlers_installed = False
+ self._handling_termination_signal = False
+
+ def start(
+ self,
+ *,
+ name: str,
+ port: int,
+ cmd: list[str],
+ cwd: Path,
+ env: dict[str, str],
+ log_prefix: str,
+ readiness_timeout: float = 30.0,
+ ) -> tuple[subprocess.Popen, StopCallback]:
+ """Spawn a long-lived support service for the eval session.
+
+ Three guarantees beyond a bare ``subprocess.Popen``:
+
+ * **Pre-flight port check** — refuses to start if ``port`` is already
+ bound. A stale process would otherwise pass readiness checks and run
+ against the wrong test database.
+ * **Subprocess-aware readiness wait** — polls ``proc.poll()`` while
+ waiting for the port, so early startup failures fail loudly.
+ * **Process-group cleanup on exit / interrupt** — fixture teardown,
+ an ``atexit`` hook, and SIGINT/SIGTERM handlers send ``SIGTERM``
+ then ``SIGKILL`` to the process group.
+ """
+ self._stop_stale_managed_process(name=name, port=port, cmd=cmd, cwd=cwd)
+ self._fail_if_port_bound(name, port)
+
+ proc = subprocess.Popen(
+ cmd,
+ cwd=cwd,
+ env=env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ start_new_session=True,
+ )
+ self._write_pid_file(name=name, port=port, proc=proc, cmd=cmd, cwd=cwd)
+
+ def stop() -> None:
+ try:
+ self._stop_process_group(proc)
+ finally:
+ self._remove_pid_file(port)
+ self._unregister(stop)
+
+ self._register(stop)
+ atexit.register(stop)
+ self._pipe_output(proc, log_prefix)
+
+ deadline = time.monotonic() + readiness_timeout
+ while time.monotonic() < deadline:
+ if proc.poll() is not None:
+ stop()
+ pytest.fail(
+ f"{name} subprocess exited with code {proc.returncode} during startup. "
+ f"Check the [{log_prefix}] WARNING lines above."
+ )
+ try:
+ sock = socket.create_connection(("localhost", port), timeout=1)
+ sock.close()
+ return proc, stop
+ except OSError:
+ time.sleep(0.5)
+
+ stop()
+ pytest.fail(f"{name} failed to start on port {port} within {readiness_timeout:.0f}s.")
+
+ def stop_all(self) -> None:
+ with self._stops_lock:
+ stops = list(reversed(self._stops))
+
+ for stop in stops:
+ try:
+ stop()
+ except Exception:
+ logger.warning("Failed to stop sandboxed eval support subprocess", exc_info=True)
+
+ def _fail_if_port_bound(self, name: str, port: int) -> None:
+ try:
+ pre_sock = socket.create_connection(("localhost", port), timeout=0.5)
+ pre_sock.close()
+ pytest.fail(
+ f"Port {port} is already in use — likely a stale {name} from a prior eval session. "
+ f"Find and kill it:\n lsof -iTCP:{port} -sTCP:LISTEN"
+ )
+ except OSError:
+ pass
+
+ def _stop_stale_managed_process(self, *, name: str, port: int, cmd: list[str], cwd: Path) -> None:
+ metadata = self._read_pid_file(port)
+ if metadata is None:
+ return
+
+ if not self._metadata_matches(metadata, name=name, port=port, cmd=cmd, cwd=cwd):
+ return
+
+ pid = metadata["pid"]
+ pgid = metadata["pgid"]
+ if not self._process_exists(pid):
+ self._remove_pid_file(port)
+ return
+
+ try:
+ process_pgid = os.getpgid(pid)
+ except (ProcessLookupError, PermissionError):
+ self._remove_pid_file(port)
+ return
+
+ if process_pgid != pgid:
+ self._remove_pid_file(port)
+ return
+
+ if not self._is_port_bound(port):
+ self._remove_pid_file(port)
+ return
+
+ logger.warning("Stopping stale sandboxed eval %s process group %s on port %s", name, pgid, port)
+ self._terminate_process_group(pgid, port)
+ self._remove_pid_file(port)
+
+ def _stop_process_group(self, proc: subprocess.Popen) -> None:
+ if proc.poll() is not None:
+ return
+ try:
+ os.killpg(proc.pid, signal.SIGTERM)
+ except (ProcessLookupError, PermissionError):
+ return
+ try:
+ proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ try:
+ os.killpg(proc.pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+
+ def _terminate_process_group(self, pgid: int, port: int) -> None:
+ try:
+ os.killpg(pgid, signal.SIGTERM)
+ except (ProcessLookupError, PermissionError):
+ return
+
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline:
+ if not self._is_port_bound(port):
+ return
+ time.sleep(0.1)
+
+ try:
+ os.killpg(pgid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ return
+
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline:
+ if not self._is_port_bound(port):
+ return
+ time.sleep(0.1)
+
+ def _is_port_bound(self, port: int) -> bool:
+ try:
+ sock = socket.create_connection(("localhost", port), timeout=0.5)
+ sock.close()
+ return True
+ except OSError:
+ return False
+
+ def _process_exists(self, pid: int) -> bool:
+ try:
+ os.kill(pid, 0)
+ return True
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+
+ def _pid_file_path(self, port: int) -> Path:
+ return Path(tempfile.gettempdir()) / f"posthog-sandboxed-eval-{port}.json"
+
+ def _read_pid_file(self, port: int) -> ProcessMetadata | None:
+ pid_file = self._pid_file_path(port)
+ try:
+ raw: object = json.loads(pid_file.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+
+ if not isinstance(raw, dict):
+ return None
+
+ data = cast(dict[str, object], raw)
+ name = data.get("name")
+ stored_port = data.get("port")
+ pid = data.get("pid")
+ pgid = data.get("pgid")
+ cmd = data.get("cmd")
+ cwd = data.get("cwd")
+
+ if (
+ not isinstance(name, str)
+ or not isinstance(stored_port, int)
+ or not isinstance(pid, int)
+ or not isinstance(pgid, int)
+ or not isinstance(cmd, list)
+ or not all(isinstance(part, str) for part in cmd)
+ or not isinstance(cwd, str)
+ ):
+ return None
+
+ return {
+ "name": name,
+ "port": stored_port,
+ "pid": pid,
+ "pgid": pgid,
+ "cmd": cast(list[str], cmd),
+ "cwd": cwd,
+ }
+
+ def _write_pid_file(
+ self,
+ *,
+ name: str,
+ port: int,
+ proc: subprocess.Popen,
+ cmd: list[str],
+ cwd: Path,
+ ) -> None:
+ metadata: ProcessMetadata = {
+ "name": name,
+ "port": port,
+ "pid": proc.pid,
+ "pgid": os.getpgid(proc.pid),
+ "cmd": cmd,
+ "cwd": str(cwd),
+ }
+ self._pid_file_path(port).write_text(json.dumps(metadata), encoding="utf-8")
+
+ def _remove_pid_file(self, port: int) -> None:
+ try:
+ self._pid_file_path(port).unlink()
+ except FileNotFoundError:
+ pass
+
+ def _metadata_matches(
+ self,
+ metadata: ProcessMetadata,
+ *,
+ name: str,
+ port: int,
+ cmd: list[str],
+ cwd: Path,
+ ) -> bool:
+ return (
+ metadata["name"] == name
+ and metadata["port"] == port
+ and metadata["cmd"] == cmd
+ and Path(metadata["cwd"]) == cwd
+ )
+
+ def _pipe_output(self, proc: subprocess.Popen, log_prefix: str) -> None:
+ def pipe_to_logger(pipe, level: int) -> None:
+ for line in iter(pipe.readline, b""):
+ text = line.decode("utf-8", errors="replace").rstrip()
+ if text:
+ logger.log(level, "[%s] %s", log_prefix, text)
+ pipe.close()
+
+ if proc.stdout is not None:
+ threading.Thread(target=pipe_to_logger, args=(proc.stdout, logging.INFO), daemon=True).start()
+ if proc.stderr is not None:
+ threading.Thread(target=pipe_to_logger, args=(proc.stderr, logging.WARNING), daemon=True).start()
+
+ def _register(self, stop: StopCallback) -> None:
+ self._install_signal_handlers()
+ with self._stops_lock:
+ self._stops.append(stop)
+
+ def _unregister(self, stop: StopCallback) -> None:
+ with self._stops_lock:
+ try:
+ self._stops.remove(stop)
+ except ValueError:
+ pass
+
+ def _install_signal_handlers(self) -> None:
+ if self._signal_handlers_installed:
+ return
+
+ if threading.current_thread() is not threading.main_thread():
+ return
+
+ for signum in (signal.SIGINT, signal.SIGTERM):
+ self._previous_signal_handlers[signum] = signal.getsignal(signum)
+ signal.signal(signum, self._handle_termination_signal)
+
+ self._signal_handlers_installed = True
+
+ def _handle_termination_signal(self, signum: int, frame: FrameType | None) -> None:
+ if self._handling_termination_signal:
+ return
+
+ self._handling_termination_signal = True
+ try:
+ self.stop_all()
+ finally:
+ self._handling_termination_signal = False
+
+ self._delegate_to_previous_signal_handler(signum, frame)
+
+ def _delegate_to_previous_signal_handler(self, signum: int, frame: FrameType | None) -> None:
+ previous_handler = self._previous_signal_handlers.get(signum, signal.SIG_DFL)
+
+ if callable(previous_handler):
+ previous_handler(signum, frame)
+ return
+
+ if previous_handler == signal.SIG_IGN:
+ return
+
+ signal.signal(signum, signal.SIG_DFL)
+ os.kill(os.getpid(), signum)
diff --git a/ee/hogai/eval/sandboxed/product_analytics/eval_funnel.py b/ee/hogai/eval/sandboxed/product_analytics/eval_funnel.py
index a6a588acdbb0..687995bf56ce 100644
--- a/ee/hogai/eval/sandboxed/product_analytics/eval_funnel.py
+++ b/ee/hogai/eval/sandboxed/product_analytics/eval_funnel.py
@@ -13,8 +13,6 @@ from __future__ import annotations
from datetime import datetime
-import pytest
-
from posthog.schema import (
AssistantFunnelsEventsNode,
AssistantFunnelsExclusionEventsNode,
@@ -47,7 +45,6 @@ def _funnel_case(
)
[email protected]_db(transaction=True, databases="__all__")
async def eval_funnel(sandboxed_demo_data, pytestconfig, posthog_client):
now = datetime.now()
this_year = now.year
diff --git a/ee/hogai/eval/sandboxed/product_analytics/eval_retention.py b/ee/hogai/eval/sandboxed/product_analytics/eval_retention.py
index 3c52f93f6678..232214c60278 100644
--- a/ee/hogai/eval/sandboxed/product_analytics/eval_retention.py
+++ b/ee/hogai/eval/sandboxed/product_analytics/eval_retention.py
@@ -12,8 +12,6 @@ To run:
from __future__ import annotations
-import pytest
-
from posthog.schema import AssistantRetentionEventsNode, AssistantRetentionFilter, AssistantRetentionQuery
from ee.hogai.eval.sandboxed.base import SandboxedPublicEval
@@ -41,7 +39,6 @@ def _retention_case(
)
async def eval_retention(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
cases = [
_retention_case(
diff --git a/ee/hogai/eval/sandboxed/product_analytics/eval_schema_discovery.py b/ee/hogai/eval/sandboxed/product_analytics/eval_schema_discovery.py
index a2dd0776b11e..996fff7026d6 100644
--- a/ee/hogai/eval/sandboxed/product_analytics/eval_schema_discovery.py
+++ b/ee/hogai/eval/sandboxed/product_analytics/eval_schema_discovery.py
@@ -19,8 +19,6 @@ from __future__ import annotations
from typing import Any
-import pytest
-
from ee.hogai.eval.sandboxed.base import SandboxedPublicEval
from ee.hogai.eval.sandboxed.config import SandboxedEvalCase
from ee.hogai.eval.sandboxed.product_analytics.scorers import INSIGHT_WRITE_TOOLS, SchemaDiscoveryOrder
@@ -45,7 +43,6 @@ def _discovery_case(
return SandboxedEvalCase(name=name, prompt=prompt, expected=expected)
async def eval_schema_discovery(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
cases = [
_discovery_case(
diff --git a/ee/hogai/eval/sandboxed/product_analytics/eval_trends.py b/ee/hogai/eval/sandboxed/product_analytics/eval_trends.py
index f013dbffe725..4903d4b11576 100644
--- a/ee/hogai/eval/sandboxed/product_analytics/eval_trends.py
+++ b/ee/hogai/eval/sandboxed/product_analytics/eval_trends.py
@@ -13,8 +13,6 @@ from __future__ import annotations
from datetime import datetime
-import pytest
-
from posthog.schema import (
AssistantEventMultipleBreakdownFilterType,
AssistantGenericMultipleBreakdownFilter,
@@ -51,7 +49,6 @@ def _trends_case(
)
async def eval_trends(sandboxed_demo_data, pytestconfig, posthog_client):
cases = [
_trends_case(
diff --git a/ee/hogai/eval/sandboxed/retrieval/eval_insight_retrieval.py b/ee/hogai/eval/sandboxed/retrieval/eval_insight_retrieval.py
index 84dce4a2c790..0d18a1c95b0e 100644
--- a/ee/hogai/eval/sandboxed/retrieval/eval_insight_retrieval.py
+++ b/ee/hogai/eval/sandboxed/retrieval/eval_insight_retrieval.py
@@ -19,8 +19,6 @@ To run:
from __future__ import annotations
-import pytest
-
from ee.hogai.eval.sandboxed.base import SandboxedPublicEval
from ee.hogai.eval.sandboxed.config import SandboxedEvalCase
from ee.hogai.eval.sandboxed.retrieval.scorers import LookupIdInOutput, SkillLoaded
@@ -30,7 +28,6 @@ from ee.hogai.eval.sandboxed.seeders.insight import seed_insight_noise
SKILL_NAME = "querying-posthog-data"
async def eval_insight_retrieval(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
cases: list[SandboxedEvalCase] = [
SandboxedEvalCase(
diff --git a/ee/hogai/eval/sandboxed/retrieval/eval_system_table_search.py b/ee/hogai/eval/sandboxed/retrieval/eval_system_table_search.py
new file mode 100644
index 000000000000..635280b1c2c5
--- /dev/null
+++ b/ee/hogai/eval/sandboxed/retrieval/eval_system_table_search.py
@@ -0,0 +1,85 @@
+"""System-table search eval for the sandboxed product-analytics agent.
+
+When users ask the agent to find or modify a PostHog entity by name
+(e.g. "rename the MAU insight"), the agent reaches for ``execute-sql``
+against ``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.
+2. In single-exec CLI mode, the agent invokes a tool without first
+ loading its schema via ``info <tool>`` — skipping the discovery step
+ that 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.
+
+To run::
+
+ pytest ee/hogai/eval/sandboxed/retrieval/eval_system_table_search.py
+"""
+
+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.retrieval.scorers import InfoCalledBeforeTool, WarehouseSchemaBeforeSql
+from ee.hogai.eval.sandboxed.scorers import ExitCodeZero
+from ee.hogai.eval.sandboxed.seeders.insight import seed_insight_noise
+
+
+async def eval_system_table_search(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
+ # ``seed_insight_noise`` adds ~1000 plausible-looking noise insights plus a
+ # handful of deterministic lookup insights (incl. "Monthly Active Users
+ # (Hedgebox)") to the per-case team. The noise volume makes `insights-list`
+ # pagination painful and pushes the agent toward `execute-sql` against
+ # `system.insights` — which is what the schema-discipline scorers grade.
+ cases: list[SandboxedEvalCase] = [
+ SandboxedEvalCase(
+ name="system_table_search_insights_rename",
+ prompt=("rename the insight 'Monthly Active Users (Hedgebox)' to have a 'MAU - ' prefix"),
+ expected={"warehouse_schema_before_sql": {}},
+ setup=seed_insight_noise,
+ ),
+ SandboxedEvalCase(
+ name="system_table_search_insights_find",
+ prompt=(
+ "find me a graph of MAUs using the app. "
+ "it's probably an existing insight, and created/last used by "
+ "me around this time last year."
+ ),
+ expected={"warehouse_schema_before_sql": {}},
+ setup=seed_insight_noise,
+ ),
+ SandboxedEvalCase(
+ name="system_table_search_insights_list_revenue",
+ prompt=(
+ "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": {}},
+ setup=seed_insight_noise,
+ ),
+ ]
+
+ await SandboxedPublicEval(
+ experiment_name=f"sandboxed-system-table-search-{mcp_mode}",
+ cases=cases,
+ scorers=[
+ ExitCodeZero(),
+ WarehouseSchemaBeforeSql(),
+ InfoCalledBeforeTool("execute-sql"),
+ InfoCalledBeforeTool("read-data-warehouse-schema"),
+ ],
+ pytestconfig=pytestconfig,
+ sandboxed_demo_data=sandboxed_demo_data,
+ posthog_client=posthog_client,
+ )
diff --git a/ee/hogai/eval/sandboxed/retrieval/scorers.py b/ee/hogai/eval/sandboxed/retrieval/scorers.py
index df9a0475308e..5d5c8a8a60f0 100644
--- a/ee/hogai/eval/sandboxed/retrieval/scorers.py
+++ b/ee/hogai/eval/sandboxed/retrieval/scorers.py
@@ -1,16 +1,29 @@
-"""Deterministic scorers for the insight-retrieval eval.
+"""Deterministic scorers for the retrieval evals.
-Two binary scorers grade the retrieval flow:
+Four binary scorers grade the retrieval flow:
* ``SkillLoaded`` — did the agent load the named skill (e.g.
``querying-posthog-data``) before producing its answer?
* ``LookupIdInOutput`` — does the agent's final assistant message contain
the seeded lookup insight's ID, proving it actually queried PostHog
rather than hallucinating?
-
-Both scorers walk ``output["messages"]`` (Anthropic-format) and
+* ``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.
+* ``InfoCalledBeforeTool`` — in single-exec CLI mode, did the agent run
+ ``info <tool>`` before the first successful ``call <tool>``? Enforces
+ the "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.
+
+The first two scorers walk ``output["messages"]`` (Anthropic-format) and
``output["seed"]`` (set by the seeder hook in ``base.py:task()``), so
-nothing has to be threaded through ``expected``.
+nothing has to be threaded through ``expected``. The third opts in via
+``expected = {"warehouse_schema_before_sql": {}}``.
"""
from __future__ import annotations
@@ -21,9 +34,9 @@ from typing import Any
from braintrust import Score
from braintrust_core.score import Scorer
-from ee.hogai.eval.sandboxed.log_parser import LogParser
+from ee.hogai.eval.sandboxed.log_parser import INFO_SYNTHETIC_PREFIX, LogParser
-__all__ = ["SkillLoaded", "LookupIdInOutput"]
+__all__ = ["InfoCalledBeforeTool", "LookupIdInOutput", "SkillLoaded", "WarehouseSchemaBeforeSql"]
class SkillLoaded(Scorer):
@@ -247,3 +260,169 @@ class LookupIdInOutput(Scorer):
if isinstance(text, str) and text:
return text
return ""
+
+
+class WarehouseSchemaBeforeSql(Scorer):
+ """Binary: did the agent run ``read-data-warehouse-schema`` before any successful ``execute-sql``?
+
+ Opt-in via presence of ``expected = {"warehouse_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.
+
+ 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.
+ """
+
+ SCHEMA_TOOL = "read-data-warehouse-schema"
+ SQL_TOOL = "execute-sql"
+
+ def _name(self) -> str:
+ return "warehouse_schema_before_sql"
+
+ 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 isinstance(expected, dict) or self._name() not in expected:
+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} key on case"})
+
+ raw_log = output.get("raw_log")
+ if not raw_log:
+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})
+
+ parser = LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")
+ calls = sorted(parser.get_tool_calls(), key=lambda c: c.position)
+
+ seen_schema = False
+ offenders: list[str] = []
+ successful_calls = 0
+ for call in calls:
+ if call.is_error:
+ continue
+ if call.name == self.SCHEMA_TOOL:
+ seen_schema = True
+ continue
+ if call.name == self.SQL_TOOL:
+ successful_calls += 1
+ if not seen_schema:
+ offenders.append(call.call_id)
+
+ if successful_calls == 0:
+ return Score(
+ name=self._name(),
+ score=None,
+ metadata={"reason": f"'{self.SQL_TOOL}' was never called successfully"},
+ )
+ 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}'",
+ "offenders": offenders,
+ "total_calls": successful_calls,
+ },
+ )
+ return Score(
+ name=self._name(),
+ score=1.0,
+ metadata={"total_calls": successful_calls},
+ )
+
+
+class InfoCalledBeforeTool(Scorer):
+ """Binary: did the agent call ``info <tool>`` before the first successful ``call <tool>``?
+
+ CLI-mode-specific. In single-exec mode the agent must learn each tool's
+ schema by running ``exec {command: "info <tool>"}`` before invoking it
+ via ``exec {command: "call <tool> <json>"}``. The ``LogParser`` unwraps
+ both shapes; ``info`` becomes the synthetic name
+ ``__info__:<tool>``. This scorer ensures every successful call to
+ ``<tool>`` was preceded by a successful ``info <tool>`` in the same run.
+
+ Returns ``None`` (skipped) when:
+ * the run is not CLI mode (no ``exec``-unwrapped tool calls), or
+ * the target tool was never called.
+
+ Returns ``1.0`` if every successful call was preceded by ``info``,
+ ``0.0`` otherwise (with offending call IDs in metadata).
+ """
+
+ def __init__(self, tool_name: str, *, name: str | None = None):
+ self.tool_name = tool_name
+ self._label = name or f"info_before_{tool_name.replace('-', '_')}"
+
+ 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"})
+ raw_log = output.get("raw_log")
+ if not raw_log:
+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})
+
+ parser = LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")
+ calls = sorted(parser.get_tool_calls(), key=lambda c: c.position)
+
+ if not any(call.is_exec_unwrapped for call in calls):
+ return Score(
+ name=self._name(),
+ score=None,
+ metadata={"reason": "Not single-exec CLI mode (no exec-unwrapped calls)"},
+ )
+
+ info_synthetic = f"{INFO_SYNTHETIC_PREFIX}{self.tool_name}"
+ seen_info = False
+ offenders: list[str] = []
+ successful_calls = 0
+ for call in calls:
+ if call.is_error:
+ continue
+ if call.name == info_synthetic:
+ seen_info = True
+ continue
+ if call.name == self.tool_name:
+ successful_calls += 1
+ if not seen_info:
+ offenders.append(call.call_id)
+
+ if successful_calls == 0:
+ return Score(
+ name=self._name(),
+ score=None,
+ metadata={"reason": f"'{self.tool_name}' was never called successfully"},
+ )
+ if offenders:
+ return Score(
+ name=self._name(),
+ score=0.0,
+ metadata={
+ "reason": f"'{self.tool_name}' called without a prior successful 'info {self.tool_name}'",
+ "offenders": offenders,
+ "total_calls": successful_calls,
+ },
+ )
+ return Score(
+ name=self._name(),
+ score=1.0,
+ metadata={"total_calls": successful_calls},
+ )
diff --git a/ee/hogai/eval/sandboxed/sql/eval_sql.py b/ee/hogai/eval/sandboxed/sql/eval_sql.py
index 6fa9eb9a5de8..38c7d892b1b9 100644
--- a/ee/hogai/eval/sandboxed/sql/eval_sql.py
+++ b/ee/hogai/eval/sandboxed/sql/eval_sql.py
@@ -20,8 +20,6 @@ To run:
from __future__ import annotations
-import pytest
-
from ee.hogai.eval.sandboxed.base import SandboxedPublicEval
from ee.hogai.eval.sandboxed.config import SandboxedEvalCase
from ee.hogai.eval.sandboxed.product_analytics.scorers import INSIGHT_WRITE_TOOLS
@@ -38,7 +36,6 @@ def _sql_case(*, name: str, prompt: str, expected_sql: str) -> SandboxedEvalCase
)
async def eval_sql(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
cases = [
# Straightforward breakdowns
diff --git a/ee/hogai/eval/sandboxed/surveys/eval_surveys.py b/ee/hogai/eval/sandboxed/surveys/eval_surveys.py
index 0a2c3b39dfcd..c41159c89236 100644
--- a/ee/hogai/eval/sandboxed/surveys/eval_surveys.py
+++ b/ee/hogai/eval/sandboxed/surveys/eval_surveys.py
@@ -51,7 +51,6 @@ def _survey_case(
)
async def eval_surveys(
sandboxed_demo_data: Any,
pytestconfig: pytest.Config,
diff --git a/ee/hogai/test/eval/test_acp_log_model.py b/ee/hogai/test/eval/test_acp_log_model.py
index 49c8567be7cb..cf2a70b4dd44 100644
--- a/ee/hogai/test/eval/test_acp_log_model.py
+++ b/ee/hogai/test/eval/test_acp_log_model.py
@@ -16,9 +16,16 @@ def _line(payload: dict) -> str:
[
pytest.param(
[
- _line({"jsonrpc": "2.0", "id": 1, "method": "session/new", "params": {"model": "claude-opus-4-7"}}),
+ _line(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "session/new",
+ "params": {"model": "anthropic/claude-opus-4-7"},
+ }
+ ),
],
- "claude-opus-4-7",
+ "anthropic/claude-opus-4-7",
id="captures_from_session_new_params",
),
pytest.param(
@@ -37,7 +44,14 @@ def _line(payload: dict) -> str:
),
pytest.param(
[
- _line({"jsonrpc": "2.0", "id": 1, "method": "session/new", "params": {"model": "claude-opus-4-7"}}),
+ _line(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "session/new",
+ "params": {"model": "anthropic/claude-opus-4-7"},
+ }
+ ),
_line(
{
"jsonrpc": "2.0",
@@ -46,7 +60,7 @@ def _line(payload: dict) -> str:
}
),
],
- "claude-opus-4-7",
+ "anthropic/claude-opus-4-7",
id="prefers_params_over_result_when_both_present",
),
pytest.param(
diff --git a/products/posthog_ai/skills/querying-posthog-data/references/guidelines.md b/products/posthog_ai/skills/querying-posthog-data/references/guidelines.md
index 9e1e21e1ee43..b53529c25c0b 100644
--- a/products/posthog_ai/skills/querying-posthog-data/references/guidelines.md
+++ b/products/posthog_ai/skills/querying-posthog-data/references/guidelines.md
@@ -182,6 +182,16 @@ The task list helps the assistant to stay on track.
This prevents wasted API calls and gives users immediate feedback when the data they're looking for doesn't exist.
+##### Progressive exploration
+
+For unfamiliar or potentially large datasets, probe cheaply before running the expensive aggregation. Widen only if the cheap step looks reasonable:
+
+1. **Count first** — `SELECT count() FROM events WHERE timestamp >= now() - INTERVAL 1 DAY AND event = 'foo'`. Confirms the data exists and gives a sense of volume.
+2. **Small sample** — inspect a handful of rows (`LIMIT 10`) to verify property shapes and values match expectations.
+3. **Full query** — run the real aggregation with a time range and `LIMIT`, having confirmed it won't scan needlessly or return empty.
+
+This is faster than discovering an empty result or a mis-shaped property after the full aggregation, and it costs less.
+
##### Skipping index
You should use the skipping index signature to write optimized analytical queries.
@@ -220,6 +230,8 @@ Keep in mind that the right expression is loaded in memory when joining data in
- Subqueries as a source or filter.
- Arrays (arrayMap, arrayJoin) and ARRAY JOIN.
+A subquery used as a join/correlation source must **pre-filter and, where possible, pre-aggregate** — push the time range, `WHERE`, and any `GROUP BY` inside it so the right side stays small in memory. Wrapping a full table in a subquery without narrowing it gains nothing. When you only need a single match per row (enrichment lookups, e.g. attaching one attribute from system data), use `LEFT ANY JOIN` — it stops at the first match, using less memory and running faster than a regular join.
+
**System data**
You are allowed joining system data. Insights are the most used entity, so keep it on the left.
diff --git a/services/mcp/src/templates/execute-sql-prompt.md b/services/mcp/src/templates/execute-sql-prompt.md
index dffdaff36ecd..eb25c42f6b12 100644
--- a/services/mcp/src/templates/execute-sql-prompt.md
+++ b/services/mcp/src/templates/execute-sql-prompt.md
@@ -20,7 +20,7 @@ Before writing any SQL, read the PostHog `querying-posthog-data` skill. It is th
### Discovery workflow (mandatory)
-1. **Warehouse schema** — call `read-data-warehouse-schema` to verify tables, views, and columns. Do not guess names. For a specific custom warehouse table, inspect its columns with:
+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'
@@ -53,13 +53,15 @@ Prefer `query-llm-trace` / `query-llm-traces-list` whenever you need any of thos
<example>
User: Do we have any insights tracking revenue or payments?
Assistant: I'll search existing insights and dashboards via SQL.
-1. Search insights by name: `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`
-2. If results are sparse, broaden to dashboards: `execute-sql` with `SELECT id, name, description FROM system.dashboards WHERE NOT deleted AND (name ILIKE '%revenue%' OR name ILIKE '%payment%')`
-3. Validate promising insights with `insight-retrieve`.
-4. Summarize with links.
+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.
+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. SQL against `system.*` tables is the fastest way to discover existing entities — no `query-*` tool covers entity search.
-2. ILIKE with multiple terms catches naming variants ("Monthly Revenue", "MRR", "Payment Events").
-3. `insight-retrieve` confirms the insight's query configuration still matches intent.
+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`).
+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.
</reasoning>
</example>
diff --git a/services/mcp/src/templates/sections/retrieving-data.md b/services/mcp/src/templates/sections/retrieving-data.md
index a3e8f5cf250c..5cb3d570cc32 100644
--- a/services/mcp/src/templates/sections/retrieving-data.md
+++ b/services/mcp/src/templates/sections/retrieving-data.md
@@ -8,41 +8,23 @@ Reach for `execute-sql` only when no `query-*` tool can express the question:
- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.
- Pre-filtering or shaping data before running a `query-*` call.
-When you do use `execute-sql`, run `info execute-sql` first to load its full guidance.
+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
-Any "find / which / do we have / what's our X chart" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.
+"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.
-Map intent to table:
+Required order on every run, no shortcuts:
-- "find an insight" / "what's our X chart" / "is this insight saved" → `system.insights`
-- "find a dashboard" → `system.dashboards`
-- "find a cohort" → `system.cohorts`
-- "find a feature flag" → `system.feature_flags`
-- "find an experiment" → `system.experiments`
-- "find a survey" → `system.surveys`
-- "find a notebook" → `system.notebooks`
-
-Search rules:
-
-1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.
-2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.
-3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.
-4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.
-5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.
-
-<example>
-User: Do we have any insights tracking revenue?
-Assistant: [Calls `execute-sql` with `SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20`]
-[Picks the most plausible match by name, then calls `insight-get` with the candidate's `id` (or `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]
-<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>
-</example>
+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: Find me a graph of MAUs.
-Assistant: [Calls `execute-sql` with `SELECT * FROM system.insights WHERE id = 33800 LIMIT 1` after a search SELECT already surfaced id 33800]
-WRONG — verify with `insight-get` (passing `id: 33800`) instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.
+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>
#### Available insight query tools
diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.json
index 25f97137ad22..6ecd985c46ae 100644
--- a/services/mcp/tests/unit/__snapshots__/exec-tool.json
+++ b/services/mcp/tests/unit/__snapshots__/exec-tool.json
@@ -15,7 +15,7 @@
"properties": {
"command": {
"type": "string",
- "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary\nwith drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), you MUST call\n`schema <tool_name> <field_name>` for each field you need to populate BEFORE\nconstructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large),\ndrill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> properties` — to see property filter structure\n- `schema <tool> breakdownFilter` — when using breakdowns\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"Run `schema query-trends series` for full structure\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- batch\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-prompt-duplicate\n- llma-score-definition-new-version\n- llma-skill-archive\n- llma-skill-duplicate\n- llma-skill-file-rename\n- llma-tagger-test-hog\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first to load its full guidance.\n\n#### Searching for existing entities\n\nAny \"find / which / do we have / what's our X chart\" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.\n\nMap intent to table:\n\n- \"find an insight\" / \"what's our X chart\" / \"is this insight saved\" → `system.insights`\n- \"find a dashboard\" → `system.dashboards`\n- \"find a cohort\" → `system.cohorts`\n- \"find a feature flag\" → `system.feature_flags`\n- \"find an experiment\" → `system.experiments`\n- \"find a survey\" → `system.surveys`\n- \"find a notebook\" → `system.notebooks`\n\nSearch rules:\n\n1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.\n2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.\n3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.\n4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.\n5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.\n\n<example>\nUser: Do we have any insights tracking revenue?\nAssistant: [Calls `execute-sql` with `SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20`]\n[Picks the most plausible match by name, then calls `insight-get` with the candidate's `id` (or `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]\n<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>\n</example>\n\n<bad-example>\nUser: Find me a graph of MAUs.\nAssistant: [Calls `execute-sql` with `SELECT * FROM system.insights WHERE id = 33800 LIMIT 1` after a search SELECT already surfaced id 33800]\nWRONG — verify with `insight-get` (passing `id: 33800`) instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nAll PostHog app URLs must use relative paths without a domain (no us.posthog.com, eu.posthog.com, app.posthog.com), and omit the `/project/:id/` prefix. Never include `/-/` in URLs.\nUse Markdown with descriptive anchor text, for example \"[Cohorts view](/cohorts)\".\n\nKey URL patterns:\n\n- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`\n- Data management: `/data-management/events`, `/data-management/properties`\n- Billing: `/organization/billing`\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"
+ "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary\nwith drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), you MUST call\n`schema <tool_name> <field_name>` for each field you need to populate BEFORE\nconstructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large),\ndrill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> properties` — to see property filter structure\n- `schema <tool> breakdownFilter` — when using breakdowns\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"Run `schema query-trends series` for full structure\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- batch\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-prompt-duplicate\n- llma-score-definition-new-version\n- llma-skill-archive\n- llma-skill-duplicate\n- llma-skill-file-rename\n- llma-tagger-test-hog\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen 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.\n\n#### Searching for existing entities\n\n\"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.\n\nRequired order on every run, no shortcuts:\n\n1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.\n2. `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.\n3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.\n4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.\n\n<bad-example>\nUser: rename / find / list … (any `system.*` question)\nAssistant: [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]\nWRONG — 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.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nAll PostHog app URLs must use relative paths without a domain (no us.posthog.com, eu.posthog.com, app.posthog.com), and omit the `/project/:id/` prefix. Never include `/-/` in URLs.\nUse Markdown with descriptive anchor text, for example \"[Cohorts view](/cohorts)\".\n\nKey URL patterns:\n\n- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`\n- Data management: `/data-management/events`, `/data-management/properties`\n- Billing: `/organization/billing`\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"
}
},
"required": ["command"]
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
index 349fce30f06e..504f6f549604 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
@@ -190,41 +190,23 @@ Reach for `execute-sql` only when no `query-*` tool can express the question:
- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.
- Pre-filtering or shaping data before running a `query-*` call.
-When you do use `execute-sql`, run `info execute-sql` first to load its full guidance.
+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
-Any "find / which / do we have / what's our X chart" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.
+"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.
-Map intent to table:
+Required order on every run, no shortcuts:
-- "find an insight" / "what's our X chart" / "is this insight saved" → `system.insights`
-- "find a dashboard" → `system.dashboards`
-- "find a cohort" → `system.cohorts`
-- "find a feature flag" → `system.feature_flags`
-- "find an experiment" → `system.experiments`
-- "find a survey" → `system.surveys`
-- "find a notebook" → `system.notebooks`
-
-Search rules:
-
-1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.
-2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.
-3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.
-4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.
-5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.
-
-<example>
-User: Do we have any insights tracking revenue?
-Assistant: [Calls `execute-sql` with `SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20`]
-[Picks the most plausible match by name, then calls `insight-get` with the candidate's `id` (or `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]
-<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>
-</example>
+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: Find me a graph of MAUs.
-Assistant: [Calls `execute-sql` with `SELECT * FROM system.insights WHERE id = 33800 LIMIT 1` after a search SELECT already surfaced id 33800]
-WRONG — verify with `insight-get` (passing `id: 33800`) instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.
+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>
#### Available insight query tools
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
index 7033c9fe14e4..9e3cf8b67c22 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
@@ -74,41 +74,23 @@ Reach for `execute-sql` only when no `query-*` tool can express the question:
- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.
- Pre-filtering or shaping data before running a `query-*` call.
-When you do use `execute-sql`, run `info execute-sql` first to load its full guidance.
+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
-Any "find / which / do we have / what's our X chart" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.
+"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.
-Map intent to table:
+Required order on every run, no shortcuts:
-- "find an insight" / "what's our X chart" / "is this insight saved" → `system.insights`
-- "find a dashboard" → `system.dashboards`
-- "find a cohort" → `system.cohorts`
-- "find a feature flag" → `system.feature_flags`
-- "find an experiment" → `system.experiments`
-- "find a survey" → `system.surveys`
-- "find a notebook" → `system.notebooks`
-
-Search rules:
-
-1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.
-2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.
-3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.
-4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.
-5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.
-
-<example>
-User: Do we have any insights tracking revenue?
-Assistant: [Calls `execute-sql` with `SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20`]
-[Picks the most plausible match by name, then calls `insight-get` with the candidate's `id` (or `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]
-<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>
-</example>
+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: Find me a graph of MAUs.
-Assistant: [Calls `execute-sql` with `SELECT * FROM system.insights WHERE id = 33800 LIMIT 1` after a search SELECT already surfaced id 33800]
-WRONG — verify with `insight-get` (passing `id: 33800`) instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.
+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>
#### Available insight query tools