:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(query-performance-ai): local-only autoresearch coordinator (#57304)
Robbie177a93dace20
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 583024e5d6ff..edde040f84f3 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -69,7 +69,7 @@ PRODUCTS_APPS = ["products.platform_features.backend.apps.PlatformFeaturesConfig","products.streamlit_apps.backend.apps.StreamlitAppsConfig","products.legal_documents.backend.apps.LegalDocumentsConfig",- "products.query_performance_ai.backend.apps.QueryPerformanceAiConfig",+ "products.query_performance_ai.orchestrator.apps.QueryPerformanceAiConfig","products.access_control.backend.apps.AccessControlConfig","products.warehouse_sources_queue.backend.apps.WarehouseSourcesQueueConfig",]diff --git a/products/query_performance_ai/README.md b/products/query_performance_ai/README.mdnew file mode 100644index 000000000000..82755e76212d--- /dev/null+++ b/products/query_performance_ai/README.md@@ -0,0 +1,47 @@+# query_performance_ai++Local-only coordinator that hands prod ClickHouse slow queries to a sandboxed agent and asks it to optimise them.++The agent is [pi-coding-agent](https://pi.dev) running the [pi-autoresearch](https://github.com/davebcn87/pi-autoresearch) extension under our bundled `clickhouse-autoresearch-campaign` skill (`sandboxed_autoresearch_agent/pi_plugin/`).++## Prereqs++- macOS — the coordinator hard-fails on other platforms.+- A docker daemon (Orbstack etc).+- `ANTHROPIC_API_KEY` in your `.env`.++## What happens when you run it++1. Fetch slow queries from Metabase's prod `system.query_log` (filtered hard to `ai_data_processing_approved = true` — we only ever feed the agent queries that the customer explicitly approved for AI analysis).+2. Open a token-gated HTTP server on localhost.+3. Spawn one Docker sandbox per query. Each sandbox clones this repo's branch from origin, locks down its network with iptables, and runs pi-coding-agent.+4. The agent submits candidate SQL through the coordinator's `/v1/run`; the coordinator forwards each query to the configured backend.+5. Artifacts (best.sql, metrics, lane / hypothesis notes) are harvested to `data/runs/<query_id>_<run_id>/` and the sandbox is destroyed.++## Backends++```bash+# Replay candidates against a Metabase-fronted test cluster:+python -m products.query_performance_ai.orchestrator.coordinator \+ --target test_cluster --metabase-region us \+ --query-log-database-id 142 --test-cluster-database-id 146 \+ --team-id 2 --max-queries 5+# Requires `hogli metabase:login --region us` first.++# Replay candidates against your local dev ClickHouse:+python -m products.query_performance_ai.orchestrator.coordinator --target local+```++`--target` decides where candidate SQL runs. Slow queries are always sourced from Metabase regardless; only the execution destination differs.++## Smoke test++```bash+python -m products.query_performance_ai.orchestrator.coordinator --target local --test-query+```++`--test-query` skips Metabase and feeds `SELECT 1, sleep(1)` as the campaign SQL. End-to-end smoke — the agent should drop the `sleep` within a couple of iterations.++## Privacy++The Metabase fetch in `orchestrator/slow_queries.py` filters to `ai_data_processing_approved = true` in `log_comment`. This is a hard SQL predicate, not a runtime check; no flag bypasses it. `--test-query` runs a synthetic constant, not a real customer query.diff --git a/products/query_performance_ai/data/.gitignore b/products/query_performance_ai/data/.gitignorenew file mode 100644index 000000000000..a1e03960fbab--- /dev/null+++ b/products/query_performance_ai/data/.gitignore@@ -0,0 +1 @@+runs/diff --git a/products/query_performance_ai/backend/__init__.py b/products/query_performance_ai/orchestrator/__init__.pysimilarity index 100%rename from products/query_performance_ai/backend/__init__.pyrename to products/query_performance_ai/orchestrator/__init__.pydiff --git a/products/query_performance_ai/backend/apps.py b/products/query_performance_ai/orchestrator/apps.pysimilarity index 75%rename from products/query_performance_ai/backend/apps.pyrename to products/query_performance_ai/orchestrator/apps.pyindex bf0f5fc137e9..7e333dc8225f 100644--- a/products/query_performance_ai/backend/apps.py+++ b/products/query_performance_ai/orchestrator/apps.py@@ -3,5 +3,5 @@ from django.apps import AppConfigclass QueryPerformanceAiConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"- name = "products.query_performance_ai.backend"+ name = "products.query_performance_ai.orchestrator"label = "query_performance_ai"diff --git a/products/query_performance_ai/orchestrator/backends/_query_log.py b/products/query_performance_ai/orchestrator/backends/_query_log.pynew file mode 100644index 000000000000..b5976dc599a5--- /dev/null+++ b/products/query_performance_ai/orchestrator/backends/_query_log.py@@ -0,0 +1,57 @@+"""Helpers for pulling CH-side metrics out of `system.query_log`.++Both backends tag candidate SQL with an ``autoresearch_run_id`` in the+``log_comment`` JSON, then look the row up in ``system.query_log`` to get the+authoritative ``query_duration_ms`` / ``read_rows`` / ``read_bytes`` / ``query_id``.+The lookup SQL and parsing live here so the metabase- and local-CH-specific+``run()`` paths share their shape.+"""++from __future__ import annotations++import re+from typing import Any++# Run-id format check: 16 hex chars (``uuid.uuid4().hex[:16]``). The match is+# load-bearing — the run id is interpolated into the lookup SQL as a+# string-literal value, and limiting it to ``[0-9a-f]`` means it can't escape+# the quotes regardless of how it was generated.+_RUN_ID_RE = re.compile(r"[0-9a-f]{16}")+++def is_valid_run_id(run_id: str) -> bool:+ return bool(_RUN_ID_RE.fullmatch(run_id))+++def build_lookup_sql(run_id: str, *, table_expr: str) -> str | None:+ """Return the SELECT to find ``run_id``'s QueryFinish row, or ``None`` if invalid.++ ``table_expr`` is the ClickHouse table reference for ``query_log`` — the+ test cluster wants ``clusterAllReplicas(posthog, system, query_log)`` to+ cover all shards; a single-node dev CH wants ``system.query_log``. The+ column shape is the same on both.+ """+ if not is_valid_run_id(run_id):+ return None+ return (+ "SELECT query_duration_ms, read_rows, read_bytes, query_id "+ f"FROM {table_expr} "+ "WHERE event_date >= today() - 1 "+ "AND type = 'QueryFinish' "+ f"AND JSONExtractString(log_comment, 'autoresearch_run_id') = '{run_id}' "+ "ORDER BY event_time DESC LIMIT 1"+ )+++def parse_lookup_row(row: list[Any]) -> tuple[float, int, int, str] | None:+ """Coerce one query_log result row into (duration_ms, rows_read, bytes_read, query_id).++ Returns ``None`` if the row is malformed (wrong arity, non-numeric timing).+ """+ if len(row) != 4:+ return None+ duration_ms, rows_read, bytes_read, query_id = row+ try:+ return float(duration_ms), int(rows_read), int(bytes_read), str(query_id)+ except (TypeError, ValueError):+ return Nonediff --git a/products/query_performance_ai/orchestrator/backends/base.py b/products/query_performance_ai/orchestrator/backends/base.pynew file mode 100644index 000000000000..949aea190106--- /dev/null+++ b/products/query_performance_ai/orchestrator/backends/base.py@@ -0,0 +1,55 @@+"""Execution backend contract.++The coordinator's HTTP server hides which backend runs candidate SQL. The+sandbox sees the same response shape regardless of whether the bytes ran+on the test cluster (via Metabase) or on a local ClickHouse (via+`sync_execute`). This is what lets the coordinator swap targets without+the agent noticing.+"""++from __future__ import annotations++import abc+from dataclasses import dataclass+from typing import Any+++@dataclass(frozen=True)+class ExecutionResult:+ rows: list[list[Any]]+ elapsed_ms: float+ rows_read: int | None+ bytes_read: int | None+ query_id: str | None+++class BackendError(RuntimeError):+ """Raised by backends when ClickHouse / Metabase rejected the SQL.++ The coordinator turns this into a 502 with the backend's message —+ we don't want to leak server-side stack traces to the sandbox, but+ a focused error string is useful for the agent to react to (e.g.+ syntax error, unknown column).+ """+++class ExecutionBackend(abc.ABC):+ @property+ @abc.abstractmethod+ def name(self) -> str: ...++ @property+ @abc.abstractmethod+ def target(self) -> str:+ """Short identifier surfaced in `/v1/info` (e.g. `test_cluster`, `local`)."""++ @abc.abstractmethod+ def run(self, sql: str, *, timeout_s: int) -> ExecutionResult: ...++ def prompt_addendum(self) -> str:+ """Extra guidance the agent must read before issuing any query.++ Default is the empty string. Override to inject backend-specific+ instructions (e.g. team_id rewrite for the test cluster).+ """+ return ""diff --git a/products/query_performance_ai/orchestrator/backends/local.py b/products/query_performance_ai/orchestrator/backends/local.pynew file mode 100644index 000000000000..ca863a922c22--- /dev/null+++ b/products/query_performance_ai/orchestrator/backends/local.py@@ -0,0 +1,179 @@+"""Local-ClickHouse-backed execution.++Talks to the dev ClickHouse via the bare `clickhouse_driver.Client`. We+deliberately do NOT go through `posthog.clickhouse.client.execute.sync_execute`:+that wrapper pulls in Django + Postgres-backed team routing, query-tag thread+locals, and a bunch of plumbing that doesn't apply to a developer-local+autoresearch tool. Connection params come from `django.conf.settings` (lazy,+no app init) so we pick up the same `CLICKHOUSE_HOST`/`PASSWORD`/etc. that+the rest of the repo reads — including non-trivial defaults like+`CLICKHOUSE_SECURE = not TEST and not DEBUG` that env-var-only would miss.+"""++from __future__ import annotations++import json+import time+import uuid+from typing import TYPE_CHECKING, Any++from . import _query_log+from .base import BackendError, ExecutionBackend, ExecutionResult++if TYPE_CHECKING:+ from clickhouse_driver import Client++_LOCAL_DEV_DB_PROMPT = (+ "## Coordinator routing — LOCAL CLICKHOUSE MODE\n"+ "\n"+ "The coordinator is forwarding your SQL to a developer-local ClickHouse instance "+ "that contains data for **team {team_id} only**. The slow query you're optimizing was "+ "originally tagged with a different team_id; before you can capture a meaningful baseline, "+ "you MUST rewrite every team_id predicate to filter by team {team_id}.\n"+ "\n"+ "Concretely, before running the first baseline:\n"+ "1. Read `query/original.sql`.\n"+ "2. Replace every `team_id = <n>`, `team_id IN (<n>, ...)`, or any equivalent "+ "team-scoping predicate with `team_id = {team_id}`. Do this for every CTE/subquery — a "+ "missed predicate will return zero rows and silently invalidate the baseline.\n"+ "3. Save the rewritten SQL back to `query/original.sql`, `query/current.sql`, "+ "and `query/best.sql`. Then run `ch_capture_baseline.py` yourself.\n"+ "\n"+ "Do this *before* anything else. If the original SQL has no team_id predicate "+ "at all, note that in `autoresearch.md` and proceed without rewriting.\n"+)+++class LocalClickhouseBackend(ExecutionBackend):+ def __init__(self, *, team_id: int = 1) -> None:+ self._team_id = team_id++ @property+ def name(self) -> str:+ return f"local-clickhouse[team={self._team_id}]"++ @property+ def target(self) -> str:+ return "local"++ def prompt_addendum(self) -> str:+ return _LOCAL_DEV_DB_PROMPT.format(team_id=self._team_id)++ def run(self, sql: str, *, timeout_s: int) -> ExecutionResult:+ # Lazy import — both clickhouse_driver and django.conf are in the+ # heavy path; keeps coordinator startup snappy when --target isn't+ # local. `django.conf.settings` is lazy and works without+ # `django.setup()`; the coordinator entry point sets+ # DJANGO_SETTINGS_MODULE so the lookup resolves to posthog.settings.+ from django.conf import settings as dj # noqa: PLC0415++ from clickhouse_driver import Client # noqa: PLC0415+ from clickhouse_driver.errors import Error as ClickHouseError # noqa: PLC0415++ client = Client(+ host=dj.CLICKHOUSE_HOST,+ user=dj.CLICKHOUSE_USER,+ password=dj.CLICKHOUSE_PASSWORD,+ database=dj.CLICKHOUSE_DATABASE,+ secure=dj.CLICKHOUSE_SECURE,+ ca_certs=getattr(dj, "CLICKHOUSE_CA", None),+ verify=getattr(dj, "CLICKHOUSE_VERIFY", True),+ connect_timeout=10,+ send_receive_timeout=timeout_s + 30,+ )++ # Tag the candidate with an `autoresearch_run_id` so we can find the+ # row in `system.query_log` afterwards and pull authoritative CH-side+ # metrics (query_duration_ms / read_rows / read_bytes / query_id).+ # `client.execute` doesn't return any of those directly — and the+ # round-trip wall-clock here would bake in TLS handshake + driver+ # serialisation, so it's worth the extra lookup.+ run_id = uuid.uuid4().hex[:16]+ log_comment = json.dumps(+ {+ "product": "internal",+ "feature": "autoresearch",+ "team_id": self._team_id,+ "kind": "autoresearch_local_replay",+ "query_type": "autoresearch_candidate",+ "autoresearch_run_id": run_id,+ }+ )++ ch_settings: dict[str, Any] = {+ "max_execution_time": timeout_s,+ "max_result_rows": 10_000,+ "result_overflow_mode": "throw",+ # The slow-queries selector deliberately targets queries that+ # already OOM'd or hit memory caps; replay those without caps+ # and a faster-but-wrong candidate kills the dev CH.+ "max_memory_usage": 4 * 1024 * 1024 * 1024, # 4 GiB+ "max_bytes_to_read": 50 * 1024 * 1024 * 1024, # 50 GiB+ # `readonly=2` blocks DDL / DML / mutations (DROP, TRUNCATE,+ # INSERT, ALTER, OPTIMIZE) but still allows per-query SET, so+ # the other settings above keep working. The agent is an LLM+ # writing SQL; this guard means a bad rewrite can't wipe the+ # dev DB.+ "readonly": 2,+ "log_comment": log_comment,+ }++ start = time.monotonic()+ try:+ rows = client.execute(sql, settings=ch_settings, with_column_types=False)+ except ClickHouseError as e:+ client.disconnect()+ raise BackendError(f"clickhouse exec failed: {type(e).__name__}: {str(e)[:1000]}") from e+ round_trip_ms = (time.monotonic() - start) * 1000.0++ # Reuse the same connection for SYSTEM FLUSH LOGS + the query_log+ # lookup so we don't pay another TLS handshake. Failures here are+ # non-fatal — we fall back to round_trip_ms.+ try:+ log_metrics = self._fetch_query_log_metrics(client, run_id)+ finally:+ client.disconnect()++ if log_metrics is not None:+ elapsed_ms, rows_read, bytes_read, query_id = log_metrics+ else:+ elapsed_ms, rows_read, bytes_read, query_id = round_trip_ms, None, None, None++ # `Client.execute` returns `list[tuple[Any, ...]]`; normalize so the+ # JSON shape matches what MetabaseBackend produces.+ normalized = [list(row) if isinstance(row, tuple | list) else [row] for row in rows]+ return ExecutionResult(+ rows=normalized,+ elapsed_ms=elapsed_ms,+ rows_read=rows_read,+ bytes_read=bytes_read,+ query_id=query_id,+ )++ def _fetch_query_log_metrics(self, client: Client, run_id: str) -> tuple[float, int, int, str] | None:+ """Look up the candidate's row in `system.query_log` after a synchronous flush.++ ``SYSTEM FLUSH LOGS`` makes the row visible immediately on a single-node+ dev CH (the alternative — waiting for CH's ~7.5s automatic flush — is+ the metabase path because the test cluster's metabase user can't+ issue SYSTEM commands). If FLUSH LOGS fails (permissions / readonly /+ anything else) we still try the SELECT — if the row happens to be+ flushed already we'll find it; if not we return None and let the+ caller fall back to round-trip wall-clock.+ """+ from clickhouse_driver.errors import Error as ClickHouseError # noqa: PLC0415++ sql = _query_log.build_lookup_sql(run_id, table_expr="system.query_log")+ if sql is None:+ return None+ try:+ client.execute("SYSTEM FLUSH LOGS")+ except ClickHouseError:+ pass+ try:+ rows = client.execute(sql, with_column_types=False)+ except ClickHouseError:+ return None+ if not rows:+ return None+ return _query_log.parse_lookup_row(list(rows[0]))diff --git a/products/query_performance_ai/orchestrator/backends/metabase.py b/products/query_performance_ai/orchestrator/backends/metabase.pynew file mode 100644index 000000000000..a201a8eae6fb--- /dev/null+++ b/products/query_performance_ai/orchestrator/backends/metabase.py@@ -0,0 +1,220 @@+"""Metabase-backed execution: shell out to `hogli metabase:query`.++We reuse `hogli` for the same reason `slow_queries.py` does: cookie+handling and ALB-redirect detection live in one place, and the session+cookie never appears in this process's env or argv.+"""++from __future__ import annotations++import re+import json+import time+import uuid+import shlex+import subprocess++from . import _query_log+from .base import BackendError, ExecutionBackend, ExecutionResult++# How long to wait for a candidate's row to appear in `system.query_log`.+# ClickHouse buffers query_log writes; the cluster's `flush_interval_milliseconds`+# is typically 7.5s (default). We poll the log up to ~9s in 1.5s steps before+# giving up and falling back to Metabase's `running_time`.+_QUERY_LOG_POLL_ATTEMPTS = 6+_QUERY_LOG_POLL_INTERVAL_S = 1.5++# Match the LAST `SETTINGS` keyword in the query so we can splice+# `log_comment = '...'` into an existing settings clause. Word-bounded and+# case-insensitive. Naive but adequate: prod query_log SQL doesn't contain+# the literal string "SETTINGS" inside string literals or comments in+# practice, and the worst case is one query getting an extra trailing+# settings clause that ClickHouse rejects with a clear parse error.+_SETTINGS_KEYWORD_RE = re.compile(r"\bSETTINGS\b", re.IGNORECASE)+++def _tag_with_log_comment(sql: str, log_comment: str) -> str:+ """Inject ``SETTINGS log_comment = '...'`` into ``sql``.++ If the query already has a ``SETTINGS`` clause, merges by inserting+ ``log_comment = '<json>',`` right after the last SETTINGS keyword.+ Otherwise appends ``\\nSETTINGS log_comment = '<json>'`` after stripping+ any trailing semicolon / whitespace. The JSON is single-quote-escaped+ per ClickHouse string-literal rules (``''`` for embedded ``'``).+ """+ escaped = log_comment.replace("'", "''")+ settings_fragment = f"log_comment = '{escaped}'"++ matches = list(_SETTINGS_KEYWORD_RE.finditer(sql))+ if matches:+ # Splice into the existing SETTINGS clause. Putting log_comment first+ # is fine — ClickHouse doesn't care about settings ordering.+ last = matches[-1]+ return sql[: last.end()] + " " + settings_fragment + "," + sql[last.end() :]++ stripped = sql.rstrip().rstrip(";").rstrip()+ return f"{stripped}\nSETTINGS {settings_fragment}"+++_TEST_CLUSTER_PROMPT = (+ "## Coordinator routing — TEST CLUSTER MODE\n"+ "\n"+ "The coordinator is forwarding your SQL to a Metabase database that contains "+ "data for **team {team_id} only**. The slow query you're optimizing was originally "+ "tagged with a different team_id; before you can capture a meaningful baseline, "+ "you MUST rewrite every team_id predicate to filter by team {team_id}.\n"+ "\n"+ "Concretely, before running the first baseline:\n"+ "1. Read `query/original.sql`.\n"+ "2. Replace every `team_id = <n>`, `team_id IN (<n>, ...)`, or any equivalent "+ "team-scoping predicate with `team_id = {team_id}`. Do this for every CTE/subquery — a "+ "missed predicate will return zero rows and silently invalidate the baseline.\n"+ "3. Save the rewritten SQL back to `query/original.sql`, `query/current.sql`, "+ "and `query/best.sql`. Then run `ch_capture_baseline.py` yourself.\n"+ "\n"+ "Do this *before* anything else. If the original SQL has no team_id predicate "+ "at all, note that in `autoresearch.md` and proceed without rewriting.\n"+)+++class MetabaseBackend(ExecutionBackend):+ def __init__(self, *, region: str, database_id: int, team_id: int, target_label: str = "test_cluster") -> None:+ self._region = region+ self._database_id = int(database_id)+ self._team_id = int(team_id)+ self._target_label = target_label++ @property+ def name(self) -> str:+ return f"metabase[{self._region}:{self._database_id}:team={self._team_id}]"++ @property+ def target(self) -> str:+ return self._target_label++ def prompt_addendum(self) -> str:+ return _TEST_CLUSTER_PROMPT.format(team_id=self._team_id)++ def run(self, sql: str, *, timeout_s: int) -> ExecutionResult:+ # Tag the candidate SQL with `log_comment` so `system.query_log` can+ # attribute these replays to autoresearch (and not the metabase+ # `default` user). The `autoresearch_run_id` field is what we use+ # below to find this exact run in query_log — it lets us pull the+ # authoritative ClickHouse-side metrics (query_duration_ms,+ # read_rows, read_bytes, query_id) instead of trusting Metabase's+ # `running_time` (which bakes in JDBC + JSON-serialisation overhead+ # and only reports wall-clock).+ run_id = uuid.uuid4().hex[:16]+ log_comment = json.dumps(+ {+ "product": "internal",+ "feature": "autoresearch",+ "team_id": self._team_id,+ "kind": "autoresearch_test_cluster_replay",+ "query_type": "autoresearch_candidate",+ "autoresearch_run_id": run_id,+ }+ )+ tagged_sql = _tag_with_log_comment(sql, log_comment)++ body, round_trip_ms = self._exec_via_hogli(tagged_sql, timeout_s=timeout_s)+ if body.get("status") == "failed" or body.get("error"):+ raise BackendError(f"metabase exec failed: {body.get('error') or body.get('status')}")+ rows = body.get("data", {}).get("rows") or []++ # CH-side authoritative metrics from system.query_log. None if the+ # log row hasn't flushed inside our poll budget — fall back to+ # Metabase's running_time / round-trip below.+ log_metrics = self._fetch_query_log_metrics(run_id)+ if log_metrics is not None:+ elapsed_ms, rows_read, bytes_read, query_id = log_metrics+ else:+ running_time = body.get("running_time")+ elapsed_ms = float(running_time) if isinstance(running_time, int | float) else round_trip_ms+ rows_read = None+ bytes_read = None+ query_id = None++ return ExecutionResult(+ rows=[list(r) for r in rows],+ elapsed_ms=elapsed_ms,+ rows_read=rows_read,+ bytes_read=bytes_read,+ query_id=query_id,+ )++ def _exec_via_hogli(self, sql: str, *, timeout_s: int) -> tuple[dict, float]:+ """Invoke ``hogli metabase:query`` with ``sql`` on stdin.++ Returns ``(parsed_body, round_trip_ms)``. Raises ``BackendError`` on+ any failure to communicate (timeout, non-zero exit, non-JSON body).+ Does NOT inspect ``body['status']`` / ``body['error']`` — the caller+ decides whether a CH-side failure should propagate or be tolerated+ (the query_log lookup tolerates "no results yet" as a poll miss).+ """+ cmd = [+ "hogli",+ "metabase:query",+ "--region",+ self._region,+ "--database-id",+ str(self._database_id),+ "--format",+ "json",+ "--timeout",+ str(timeout_s),+ ]+ start = time.monotonic()+ try:+ result = subprocess.run( # noqa: S603 — fixed argv, sql via stdin+ cmd,+ input=sql,+ text=True,+ capture_output=True,+ check=False,+ timeout=timeout_s + 30,+ )+ except subprocess.TimeoutExpired as e:+ raise BackendError(f"metabase request timed out after {e.timeout}s") from e+ round_trip_ms = (time.monotonic() - start) * 1000.0++ if result.returncode != 0:+ stderr = (result.stderr or "").strip()+ # `hogli metabase:query` exits non-zero with a `Query failed: …`+ # ClickException for backend-side failures (auth, CH error). The+ # message is safe to surface — it's already what a human would see+ # at the CLI.+ raise BackendError(f"metabase exec failed: {stderr[:1000] or shlex.join(cmd)}")++ try:+ body = json.loads(result.stdout)+ except json.JSONDecodeError as e:+ raise BackendError(f"metabase returned non-JSON response: {result.stdout[:500]!r}") from e+ return body, round_trip_ms++ def _fetch_query_log_metrics(self, run_id: str) -> tuple[float, int, int, str] | None:+ """Poll `system.query_log` for the row matching ``autoresearch_run_id``.++ Returns ``(query_duration_ms, read_rows, read_bytes, query_id)`` once+ the row has flushed, or ``None`` if the poll budget elapses without a+ match. The test cluster's metabase user can't `SYSTEM FLUSH LOGS`,+ so we just wait for CH's automatic flush (default ~7.5s).+ """+ sql = _query_log.build_lookup_sql(run_id, table_expr="clusterAllReplicas(posthog, system, query_log)")+ if sql is None:+ return None+ for attempt in range(_QUERY_LOG_POLL_ATTEMPTS):+ if attempt > 0:+ time.sleep(_QUERY_LOG_POLL_INTERVAL_S)+ try:+ body, _ = self._exec_via_hogli(sql, timeout_s=15)+ except BackendError:+ return None+ if body.get("status") == "failed" or body.get("error"):+ return None+ rows = body.get("data", {}).get("rows") or []+ if rows:+ parsed = _query_log.parse_lookup_row(rows[0])+ if parsed is not None:+ return parsed+ return Nonediff --git a/products/query_performance_ai/orchestrator/backends/tests/test_backends.py b/products/query_performance_ai/orchestrator/backends/tests/test_backends.pynew file mode 100644index 000000000000..bedf38460dd1--- /dev/null+++ b/products/query_performance_ai/orchestrator/backends/tests/test_backends.py@@ -0,0 +1,317 @@+from __future__ import annotations++import json+import subprocess+from typing import Any++import pytest+from unittest import mock++from products.query_performance_ai.orchestrator.backends import _query_log+from products.query_performance_ai.orchestrator.backends.base import BackendError+from products.query_performance_ai.orchestrator.backends.local import LocalClickhouseBackend+from products.query_performance_ai.orchestrator.backends.metabase import MetabaseBackend, _tag_with_log_comment+++def _completed(stdout: str = "", stderr: str = "", returncode: int = 0) -> Any:+ return subprocess.CompletedProcess(args=["hogli"], returncode=returncode, stdout=stdout, stderr=stderr)+++def test_metabase_backend_falls_back_to_running_time_when_query_log_misses() -> None:+ """When the query_log poll returns nothing, fall back to Metabase's `running_time`."""+ body = json.dumps(+ {+ "data": {+ "cols": [{"name": "n"}],+ "rows": [[1], [2]],+ },+ "running_time": 42.5,+ }+ )+ backend = MetabaseBackend(region="us", database_id=7, team_id=2)+ with (+ mock.patch.object(subprocess, "run", return_value=_completed(stdout=body)),+ mock.patch.object(MetabaseBackend, "_fetch_query_log_metrics", return_value=None),+ ):+ result = backend.run("SELECT 1", timeout_s=30)+ assert result.rows == [[1], [2]]+ assert result.elapsed_ms == 42.5+ assert result.rows_read is None+ assert result.bytes_read is None+ assert result.query_id is None+++def test_metabase_backend_uses_query_log_metrics_when_available() -> None:+ """When the query_log poll returns a row, use those CH-side metrics — not running_time."""+ body = json.dumps(+ {+ "data": {"cols": [{"name": "n"}], "rows": [[1]]},+ "running_time": 9999.0, # Should be ignored.+ }+ )+ backend = MetabaseBackend(region="us", database_id=7, team_id=2)+ with (+ mock.patch.object(subprocess, "run", return_value=_completed(stdout=body)),+ mock.patch.object(+ MetabaseBackend, "_fetch_query_log_metrics", return_value=(123.0, 1000, 50000, "abcd-query-id")+ ),+ ):+ result = backend.run("SELECT 1", timeout_s=30)+ # The 9999ms running_time is overridden by the 123ms CH-side number.+ assert result.elapsed_ms == 123.0+ assert result.rows_read == 1000+ assert result.bytes_read == 50000+ assert result.query_id == "abcd-query-id"+++def test_metabase_backend_falls_back_to_round_trip_when_no_running_time() -> None:+ body = json.dumps({"data": {"cols": [], "rows": []}})+ backend = MetabaseBackend(region="us", database_id=7, team_id=2)+ with (+ mock.patch.object(subprocess, "run", return_value=_completed(stdout=body)),+ mock.patch.object(MetabaseBackend, "_fetch_query_log_metrics", return_value=None),+ ):+ result = backend.run("SELECT 1", timeout_s=30)+ assert result.elapsed_ms >= 0+++def test_metabase_backend_raises_backend_error_on_hogli_failure() -> None:+ backend = MetabaseBackend(region="us", database_id=7, team_id=2)+ with mock.patch.object(subprocess, "run", return_value=_completed(returncode=1, stderr="Query failed: SYNTAX")):+ with pytest.raises(BackendError, match="Query failed: SYNTAX"):+ backend.run("SELECT bad", timeout_s=30)+++def test_metabase_backend_raises_backend_error_when_response_status_failed() -> None:+ body = json.dumps({"status": "failed", "error": "no such column"})+ backend = MetabaseBackend(region="us", database_id=7, team_id=2)+ with mock.patch.object(subprocess, "run", return_value=_completed(stdout=body)):+ with pytest.raises(BackendError, match="no such column"):+ backend.run("SELECT bad", timeout_s=30)+++def test_metabase_backend_raises_backend_error_on_non_json() -> None:+ backend = MetabaseBackend(region="us", database_id=7, team_id=2)+ with mock.patch.object(subprocess, "run", return_value=_completed(stdout="not json")):+ with pytest.raises(BackendError, match="non-JSON"):+ backend.run("SELECT 1", timeout_s=30)+++def test_metabase_backend_raises_backend_error_on_timeout() -> None:+ backend = MetabaseBackend(region="us", database_id=7, team_id=2)+ with mock.patch.object(subprocess, "run", side_effect=subprocess.TimeoutExpired(cmd=["hogli"], timeout=5)):+ with pytest.raises(BackendError, match="timed out"):+ backend.run("SELECT 1", timeout_s=5)+++def test_metabase_backend_tags_candidate_with_autoresearch_run_id() -> None:+ """The candidate SQL must carry an autoresearch_run_id we can later look up."""+ body = json.dumps({"data": {"rows": []}, "running_time": 1.0})+ backend = MetabaseBackend(region="us", database_id=7, team_id=2)+ captured: dict[str, str] = {}++ def fake_run(*args: Any, **kwargs: Any) -> Any:+ captured["sql"] = kwargs.get("input") or ""+ return _completed(stdout=body)++ with (+ mock.patch.object(subprocess, "run", side_effect=fake_run),+ mock.patch.object(MetabaseBackend, "_fetch_query_log_metrics", return_value=None),+ ):+ backend.run("SELECT 1", timeout_s=30)+ assert "autoresearch_run_id" in captured["sql"]+ # The id is interpolated into the JSON inside the log_comment string.+ assert "autoresearch_test_cluster_replay" in captured["sql"]+++def test_fetch_query_log_metrics_returns_tuple_when_row_present() -> None:+ body = json.dumps({"data": {"rows": [[567.0, 12345, 6789012, "uuid-a-b-c"]]}})+ backend = MetabaseBackend(region="us", database_id=7, team_id=2)+ with mock.patch.object(subprocess, "run", return_value=_completed(stdout=body)):+ out = backend._fetch_query_log_metrics("0123456789abcdef")+ assert out == (567.0, 12345, 6789012, "uuid-a-b-c")+++def test_fetch_query_log_metrics_returns_none_when_poll_budget_exhausted() -> None:+ """No row in `data.rows` for any poll attempt → returns None (caller falls back)."""+ body = json.dumps({"data": {"rows": []}})+ backend = MetabaseBackend(region="us", database_id=7, team_id=2)+ with (+ mock.patch.object(subprocess, "run", return_value=_completed(stdout=body)),+ mock.patch("time.sleep"), # don't actually wait+ ):+ out = backend._fetch_query_log_metrics("0123456789abcdef")+ assert out is None+++def test_fetch_query_log_metrics_rejects_invalid_run_id() -> None:+ """Defence-in-depth: malformed run_id (anything but 16 hex) returns None without querying."""+ backend = MetabaseBackend(region="us", database_id=7, team_id=2)+ with mock.patch.object(subprocess, "run") as mocked:+ # Wrong length, contains non-hex, includes a quote injection attempt.+ assert backend._fetch_query_log_metrics("short") is None+ assert backend._fetch_query_log_metrics("g" * 16) is None+ assert backend._fetch_query_log_metrics("' OR 1=1 -- ") is None+ mocked.assert_not_called()+++def test_metabase_backend_target_and_prompt_addendum() -> None:+ backend = MetabaseBackend(region="us", database_id=7, team_id=2)+ assert backend.target == "test_cluster"+ addendum = backend.prompt_addendum()+ assert "team 2" in addendum.lower()+ assert "rewrite" in addendum.lower()+++def test_metabase_backend_prompt_addendum_parameterizes_team_id() -> None:+ backend = MetabaseBackend(region="us", database_id=7, team_id=42)+ addendum = backend.prompt_addendum()+ assert "team 42" in addendum.lower()+ assert "team 2" not in addendum.lower()+++ "input_sql,expected_substring",+ [+ # No existing SETTINGS clause: appended at the end.+ ("SELECT 1", "SETTINGS log_comment = '"),+ # Trailing semicolon stripped before appending.+ ("SELECT 1;", "SETTINGS log_comment = '"),+ # Existing SETTINGS clause: log_comment spliced into it.+ (+ "SELECT 1 SETTINGS max_threads = 4",+ "SETTINGS log_comment = '",+ ),+ # Multiple settings preserved alongside log_comment.+ (+ "SELECT 1 SETTINGS max_threads = 4, max_memory_usage = 1000000",+ "max_threads = 4",+ ),+ ],+)+def test_tag_with_log_comment_handles_existing_settings(input_sql: str, expected_substring: str) -> None:+ tagged = _tag_with_log_comment(input_sql, '{"feature":"autoresearch"}')+ assert expected_substring in tagged+ assert '"feature":"autoresearch"' in tagged+++def test_tag_with_log_comment_escapes_single_quotes_in_json() -> None:+ # ClickHouse string literals double-up single quotes; the JSON value must+ # be escaped so a quote in the comment doesn't terminate the string early.+ tagged = _tag_with_log_comment("SELECT 1", '{"who":"that\'s me"}')+ # The original `'` must appear as `''` inside the SQL string literal.+ assert "that''s me" in tagged+ assert "log_comment = '" in tagged+++def test_tag_with_log_comment_merges_into_last_settings_only() -> None:+ """If a query has the word `SETTINGS` in a string/comment we still inject — the+ worst-case is a parse error from CH, which is loud and trivial to debug."""+ sql = "SELECT 1 SETTINGS max_threads = 2"+ tagged = _tag_with_log_comment(sql, '{"k":"v"}')+ # log_comment is inserted right after the existing SETTINGS keyword.+ assert "SETTINGS log_comment = " in tagged+ assert "max_threads = 2" in tagged+++# ----------------------------------------------------------------------+# Shared `_query_log` helper tests (covers both backends).+# ----------------------------------------------------------------------+++ "run_id,expected_valid",+ [+ ("0123456789abcdef", True),+ ("ffffffffffffffff", True),+ ("short", False),+ ("g" * 16, False), # non-hex+ ("' OR 1=1 -- ", False), # injection attempt+ ("0123456789ABCDEF", False), # uppercase+ ("", False),+ ],+)+def test_query_log_is_valid_run_id(run_id: str, expected_valid: bool) -> None:+ assert _query_log.is_valid_run_id(run_id) is expected_valid+++def test_query_log_build_lookup_sql_returns_none_for_invalid_run_id() -> None:+ assert _query_log.build_lookup_sql("nope", table_expr="system.query_log") is None+++def test_query_log_build_lookup_sql_interpolates_table_and_run_id() -> None:+ sql = _query_log.build_lookup_sql("0123456789abcdef", table_expr="clusterAllReplicas(posthog, system, query_log)")+ assert sql is not None+ assert "clusterAllReplicas(posthog, system, query_log)" in sql+ assert "'0123456789abcdef'" in sql+ assert "type = 'QueryFinish'" in sql+++def test_query_log_parse_lookup_row_happy_path() -> None:+ parsed = _query_log.parse_lookup_row([1234.5, 1000, 50000, "abc-query-id"])+ assert parsed == (1234.5, 1000, 50000, "abc-query-id")+++ "row",+ [+ [],+ [1, 2, 3], # too short+ [1, 2, 3, 4, 5], # too long+ ["not-a-number", 1, 1, "id"], # non-numeric duration+ ],+)+def test_query_log_parse_lookup_row_rejects_malformed(row: list[Any]) -> None:+ assert _query_log.parse_lookup_row(row) is None+++# ----------------------------------------------------------------------+# LocalClickhouseBackend `_fetch_query_log_metrics` tests.+#+# We don't end-to-end test `LocalClickhouseBackend.run()` because it pulls in+# Django settings + a live `clickhouse_driver.Client` connection. The+# query_log lookup helper is the load-bearing part to verify in isolation.+# ----------------------------------------------------------------------+++def test_local_fetch_query_log_metrics_returns_tuple_when_row_present() -> None:+ backend = LocalClickhouseBackend(team_id=1)+ fake_client = mock.MagicMock()+ # First execute is `SYSTEM FLUSH LOGS` (returns []), second is the lookup.+ fake_client.execute.side_effect = [+ [], # FLUSH LOGS+ [(456.0, 999, 8888, "ch-query-id")], # lookup result+ ]+ out = backend._fetch_query_log_metrics(fake_client, "0123456789abcdef")+ assert out == (456.0, 999, 8888, "ch-query-id")+++def test_local_fetch_query_log_metrics_swallows_flush_logs_failure() -> None:+ """If FLUSH LOGS errors (e.g. permission), we should still try the lookup —+ it'll either find the row that flushed automatically or return None."""+ from clickhouse_driver.errors import Error as ClickHouseError # noqa: PLC0415++ backend = LocalClickhouseBackend(team_id=1)+ fake_client = mock.MagicMock()+ fake_client.execute.side_effect = [+ ClickHouseError("not permitted"), # FLUSH LOGS+ [(789.0, 1, 2, "id")], # lookup result+ ]+ out = backend._fetch_query_log_metrics(fake_client, "0123456789abcdef")+ assert out == (789.0, 1, 2, "id")+++def test_local_fetch_query_log_metrics_returns_none_for_invalid_run_id() -> None:+ backend = LocalClickhouseBackend(team_id=1)+ fake_client = mock.MagicMock()+ out = backend._fetch_query_log_metrics(fake_client, "not-hex")+ assert out is None+ fake_client.execute.assert_not_called()+++def test_local_fetch_query_log_metrics_returns_none_when_no_row() -> None:+ backend = LocalClickhouseBackend(team_id=1)+ fake_client = mock.MagicMock()+ fake_client.execute.side_effect = [[], []] # FLUSH ok, lookup empty+ out = backend._fetch_query_log_metrics(fake_client, "0123456789abcdef")+ assert out is Nonediff --git a/products/query_performance_ai/orchestrator/coordinator.py b/products/query_performance_ai/orchestrator/coordinator.pynew file mode 100644index 000000000000..6c29f1a52b3b--- /dev/null+++ b/products/query_performance_ai/orchestrator/coordinator.py@@ -0,0 +1,814 @@+"""Local-only autoresearch coordinator.++Source slow queries from Metabase, open an HTTP server on localhost, and+fan a sandbox per query out via SandboxBase. Sandboxes are network-isolated+to ``localhost:$PORT`` (best-effort iptables; see run_campaign.py).++Run:++ # --query-log-database-id 142 is ClickHouse PROD US - OFFLINE+ python -m products.query_performance_ai.orchestrator.coordinator \\+ --target test_cluster \\+ --metabase-region us \\+ --query-log-database-id 142 \\+ --test-cluster-database-id 146 \\+ --team-id 2 --max-queries 5++Or just stand the server up for manual experimentation:++ python -m products.query_performance_ai.orchestrator.coordinator --target local --no-spawn+"""++from __future__ import annotations++import os+import sys+import json+import time+import uuid+import shlex+import shutil+import signal+import argparse+import platform+import threading+import subprocess+from concurrent.futures import ThreadPoolExecutor, as_completed+from pathlib import Path+from typing import TYPE_CHECKING++from .backends.base import ExecutionBackend+from .backends.local import LocalClickhouseBackend+from .backends.metabase import MetabaseBackend+from .server import ServerInfo, generate_token, make_server, serve_forever_in_thread+from .slow_queries import SlowQuery, fetch_available_columns, fetch_available_dictionaries, fetch_slow_queries++if TYPE_CHECKING:+ from products.tasks.backend.services.sandbox import SandboxBase++PRODUCT_DIR = Path(__file__).resolve().parent.parent+RUNS_DIR = PRODUCT_DIR / "data" / "runs"+# Hard cap on concurrent sandboxes regardless of `--max-queries`. Each sandbox+# is ~2 GiB; this keeps total RAM around 20 GiB. Bigger fan-outs serialise+# behind the coordinator's `_query_lock` anyway, so more parallelism is just+# more idle agents waiting on the lock.+MAX_CONCURRENT_SANDBOXES = 10++# Live-sandbox registry: protects against orphan Docker containers when the+# coordinator is killed mid-run. SIGINT/SIGTERM handlers iterate this set and+# destroy each entry. Entries are added on `create()` success and removed+# after `destroy()`; the lock keeps the iteration in the signal handler safe+# vs. concurrent worker mutations.+_LIVE_SANDBOXES: dict[str, SandboxBase] = {}+_LIVE_SANDBOXES_LOCK = threading.Lock()+++def _log(msg: str) -> None:+ sys.stdout.write(f"[coordinator] {msg}\n")+ sys.stdout.flush()+++# We sandbox via Docker Desktop's `host.docker.internal` magic DNS name, which+# only resolves to the host loopback on macOS / Windows. On Linux, the daemon+# requires `--add-host=host.docker.internal:host-gateway` to point at the+# docker0 bridge IP — and even then, a `127.0.0.1`-bound coordinator is+# unreachable from the container. None of us run Linux dev boxes, so just bail.+def _require_supported_platform() -> None:+ system = platform.system()+ if system != "Darwin":+ raise SystemExit(+ f"this coordinator is macOS-only (detected {system}). "+ "It assumes Docker Desktop's `host.docker.internal` resolves to host loopback, "+ "which only holds on macOS/Windows. Run on a Mac or extend the binding logic."+ )+++def _positive_int(value: str) -> int:+ n = int(value)+ if n <= 0:+ raise argparse.ArgumentTypeError(f"must be a positive integer, got {value!r}")+ return n+++def _load_repo_dotenv() -> None:+ """Load `<repo>/.env` so the user doesn't have to source it manually.++ pi needs ``ANTHROPIC_API_KEY`` and the rest of the repo's dev env+ typically lives in ``.env``. ``override=False`` means anything the+ user already exported wins.+ """+ repo_root = _resolve_repo_root()+ env_path = repo_root / ".env"+ if not env_path.is_file():+ return+ from dotenv import load_dotenv # noqa: PLC0415 — keeps the dep on the optional path++ load_dotenv(env_path, override=False)+++def _build_backend(args: argparse.Namespace) -> ExecutionBackend:+ if args.target == "test_cluster":+ if not args.metabase_region or not args.test_cluster_database_id:+ raise SystemExit(+ "--target test_cluster requires --metabase-region and --test-cluster-database-id "+ "(point the latter at the metabase database that runs candidate SQL on the test cluster)"+ )+ return MetabaseBackend(+ region=args.metabase_region,+ database_id=args.test_cluster_database_id,+ team_id=args.team_id,+ )+ if args.target == "local":+ return LocalClickhouseBackend(team_id=args.local_team_id)+ raise SystemExit(f"unknown --target: {args.target!r}")+++def _pi_anthropic_env() -> dict[str, str]:+ """Forward the host's ``ANTHROPIC_API_KEY`` into the sandbox.++ pi-coding-agent talks to api.anthropic.com using ``ANTHROPIC_API_KEY``.+ The Claude-Code-managed ``ANTHROPIC_AUTH_TOKEN`` / ``ANTHROPIC_BASE_URL``+ pair is intentionally NOT forwarded: that token is scoped to Claude+ Code itself and pi-autoresearch isn't an authorized consumer of the+ LLM gateway. A direct first-party Anthropic key is required.++ Without ``ANTHROPIC_API_KEY`` set on the host, pi exits with+ "No API key found for unknown." — which is the right failure mode for+ "go set the key" to be the obvious next step.+ """+ out: dict[str, str] = {}+ api_key = os.environ.get("ANTHROPIC_API_KEY")+ if api_key:+ out["ANTHROPIC_API_KEY"] = api_key+ return out+++_DJANGO_READY = False+++def _ensure_django_setup() -> None:+ """Idempotent Django bootstrap so SandboxBase can be imported.++ The sandbox module transitively imports ``products.tasks.backend.models``+ which references Django ORM models, so we *do* have to call+ ``django.setup()``. Side-channel env vars suppress the parts of+ PostHog's app-init that would otherwise connect to Postgres / Redis:++ - ``OPT_OUT_CAPTURE=1`` disables ``posthoganalytics`` self-capture+ (skips ``initialize_self_capture_api_token`` Postgres call in+ ``PostHogConfig.ready``).+ - ``SKIP_ASYNC_MIGRATIONS_SETUP=1`` skips the migration-readiness+ Postgres queries.+ - ``SANDBOX_PROVIDER=docker`` makes the module-level+ ``Sandbox = get_sandbox_class()`` in sandbox.py avoid importing+ ``modal_sandbox``.+ """+ global _DJANGO_READY+ if _DJANGO_READY:+ return+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")+ os.environ.setdefault("SANDBOX_PROVIDER", "docker")+ os.environ.setdefault("OPT_OUT_CAPTURE", "1")+ os.environ.setdefault("SKIP_ASYNC_MIGRATIONS_SETUP", "1")+ import django # noqa: PLC0415++ django.setup()+ _DJANGO_READY = True+++def _detect_current_branch(cwd: Path) -> str | None:+ try:+ result = subprocess.run( # noqa: S603 — fixed argv+ ["git", "branch", "--show-current"],+ check=False,+ text=True,+ capture_output=True,+ cwd=cwd,+ timeout=5,+ )+ except (FileNotFoundError, subprocess.TimeoutExpired):+ return None+ branch = (result.stdout or "").strip()+ return branch or None+++def _spawn_one_sandbox(+ *,+ query: SlowQuery,+ coordinator_url: str,+ coordinator_token: str,+ keep_sandbox: bool,+ repo_root: Path,+ repository: str,+ branch: str,+ run_id: str,+) -> tuple[str, int]:+ """Provision a sandbox, run run_campaign.py inside, harvest, destroy.++ Returns ``(query_id, exit_code)``. Exceptions bubble up to the executor —+ we catch them at the top level so a single bad campaign doesn't tank the+ rest of the parallel fan.+ """+ # Lazy import: SandboxBase pulls in Django settings, structlog, etc.+ # Keeping it inside the worker means `--no-spawn` doesn't pay for it.+ _ensure_django_setup()+ from products.query_performance_ai.orchestrator.harvest import harvest_artifacts # noqa: PLC0415+ from products.tasks.backend.services.sandbox import ( # noqa: PLC0415+ SandboxConfig,+ SandboxTemplate,+ get_sandbox_class_for_backend,+ )++ sandbox_name = f"qp-autoresearch-{query.query_id[:12]}-{uuid.uuid4().hex[:6]}"+ sandbox_env: dict[str, str] = {+ "COORDINATOR_URL": coordinator_url,+ "COORDINATOR_TOKEN": coordinator_token,+ "CAMPAIGN_QUERY_ID": query.query_id,+ }+ sandbox_env.update(_pi_anthropic_env())+ config = SandboxConfig(+ name=sandbox_name,+ # PI_BASE bakes pi-coding-agent, the pi-autoresearch extension, and a+ # ClickHouse source snapshot at /opt/clickhouse — the agent uses the+ # source as a grounding context for hypotheses, and the toolchain+ # being pre-installed saves ~30-90s of npm + git per sandbox boot.+ template=SandboxTemplate.PI_BASE,+ # Campaigns can run for hours: the agent iterates many candidates,+ # each with a baseline + replay + correctness check. 8h is the+ # outer wall-clock; the per-call CH timeout is the inner cap.+ default_execution_timeout_seconds=8 * 60 * 60,+ # Most of pi-coding-agent's work is LLM round-trips and ClickHouse+ # queries that go through the host's `/v1/run` — the in-sandbox process+ # set is small. 2 GiB is enough for git, node, and the campaign+ # workspace; CPU stays modest since heavy lifting is remote.+ memory_gb=2.0,+ cpu_cores=1.0,+ environment_variables=sandbox_env,+ metadata={"purpose": "query-performance-autoresearch", "query_id": query.query_id},+ )++ sandbox_cls = get_sandbox_class_for_backend("docker")+ _log(f"[{query.query_id}] provisioning sandbox {sandbox_name}")+ sandbox = sandbox_cls.create(config)+ with _LIVE_SANDBOXES_LOCK:+ _LIVE_SANDBOXES[sandbox.id] = sandbox++ # Suffix the artifact directory with the per-coordinator-run id so two+ # coordinator processes that pick up the same `query_id` (e.g. the same+ # slow query surfaced twice in close succession) don't clobber each+ # other's `input.json` / `campaign.log`.+ output_dir = RUNS_DIR / f"{query.query_id}_{run_id}"+ output_dir.mkdir(parents=True, exist_ok=True)+ (output_dir / "input.json").write_text(+ json.dumps(+ {+ "query_id": query.query_id,+ "team_id": query.team_id,+ "query_duration_ms": query.query_duration_ms,+ "read_bytes": query.read_bytes,+ "event_time": query.event_time,+ "clickhouse_query": query.clickhouse_query,+ "hogql_query": query.hogql_query,+ },+ indent=2,+ )+ + "\n"+ )++ exit_code = 1+ try:+ # Hand the SQL across to the sandbox via env-file (not argv), so the+ # query string can't end up in `/proc/<pid>/cmdline` for a sibling+ # campaign to read.+ env_file = "/tmp/autoresearch-campaign.env"+ env_blob = (+ f"CAMPAIGN_SQL={shlex.quote(query.clickhouse_query)}\n"+ f"CAMPAIGN_QUERY_ID={shlex.quote(query.query_id)}\n"+ f"COORDINATOR_URL={shlex.quote(coordinator_url)}\n"+ f"COORDINATOR_TOKEN={shlex.quote(coordinator_token)}\n"+ )+ sandbox.write_file(env_file, env_blob.encode("utf-8"))++ # Clone the branch fresh inside the sandbox. We deliberately don't+ # bind-mount the host checkout: pi-coding-agent has full filesystem+ # access inside the sandbox, and a writable bind-mount means it can+ # (and did, during testing) modify the host's source tree mid-run.+ # A fresh clone gives the agent its own working copy whose+ # modifications stay sandboxed.+ org, repo = repository.lower().split("/", 1)+ repo_path = f"/tmp/workspace/repos/{org}/{repo}"+ clone_url = f"https://github.com/{org}/{repo}.git"+ clone_cmd = (+ f"rm -rf {shlex.quote(repo_path)} && "+ f"mkdir -p {shlex.quote(f'/tmp/workspace/repos/{org}')} && "+ f"cd {shlex.quote(f'/tmp/workspace/repos/{org}')} && "+ f"git clone --depth 1 --single-branch --branch {shlex.quote(branch)} "+ f"{shlex.quote(clone_url)} {shlex.quote(repo)}"+ )+ _log(f"[{query.query_id}] cloning {repository}@{branch} into sandbox")+ clone_result = sandbox.execute(clone_cmd, timeout_seconds=5 * 60)+ if clone_result.exit_code != 0:+ stderr_tail = (clone_result.stderr or "")[-2000:]+ raise RuntimeError(f"git clone failed in sandbox (exit {clone_result.exit_code}):\n{stderr_tail}")++ command = (+ f"cd {shlex.quote(repo_path)} && "+ f"trap 'rm -f {shlex.quote(env_file)}' EXIT && "+ f"chmod 600 {shlex.quote(env_file)} && "+ f"set -a && . {shlex.quote(env_file)} && set +a && "+ # `-m` (not direct script invocation) so relative imports inside+ # the package resolve. `python3 path/to/run_campaign.py` runs the+ # file with no parent package, which breaks `from .runtime import …`.+ f"python3 -m products.query_performance_ai.sandboxed_autoresearch_agent.driver.run_campaign 2>&1"+ )++ _log(f"[{query.query_id}] running run_campaign.py inside sandbox {sandbox.id}")+ stream = sandbox.execute_stream(command, timeout_seconds=8 * 60 * 60)+ log_path = output_dir / "campaign.log"+ with log_path.open("w") as log_file:+ for line in stream.iter_stdout():+ log_file.write(line)+ # Prefix with query_id so interleaved parallel logs are still readable.+ sys.stdout.write(f"[{query.query_id}] {line}")+ sys.stdout.flush()+ result = stream.wait()+ exit_code = result.exit_code++ if exit_code != 0:+ _log(f"[{query.query_id}] run_campaign.py exited {exit_code}")++ try:+ harvested = harvest_artifacts(+ sandbox,+ original_sql=query.clickhouse_query,+ query_id=query.query_id,+ campaign_stdout_tail=(result.stdout or "")[-4000:],+ )+ _write_artifacts(harvested, output_dir, repo_root=repo_root)+ _log(f"[{query.query_id}] artifacts written to {output_dir}")+ except Exception as e: # noqa: BLE001+ _log(f"[{query.query_id}] harvest failed: {e}")+ finally:+ if keep_sandbox:+ _log(f"[{query.query_id}] --keep-sandboxes set; leaving {sandbox.id} running")+ with _LIVE_SANDBOXES_LOCK:+ _LIVE_SANDBOXES.pop(sandbox.id, None)+ else:+ try:+ sandbox.destroy()+ except Exception as e: # noqa: BLE001+ _log(f"[{query.query_id}] sandbox destroy failed: {e}")+ finally:+ with _LIVE_SANDBOXES_LOCK:+ _LIVE_SANDBOXES.pop(sandbox.id, None)++ return query.query_id, exit_code+++def _destroy_all_live_sandboxes(reason: str) -> None:+ """Best-effort cleanup of every still-tracked sandbox.++ Called from SIGINT/SIGTERM handlers and from `main()`'s `finally`. Holds+ the registry lock for the snapshot but releases it before destroying+ so a slow `destroy()` doesn't block worker threads from deregistering.+ """+ with _LIVE_SANDBOXES_LOCK:+ snapshot = list(_LIVE_SANDBOXES.items())+ _LIVE_SANDBOXES.clear()+ if not snapshot:+ return+ _log(f"cleanup ({reason}): destroying {len(snapshot)} sandbox(es)")+ for sandbox_id, sandbox in snapshot:+ try:+ sandbox.destroy()+ except Exception as e: # noqa: BLE001+ _log(f" destroy {sandbox_id} failed: {e}")+++def _install_signal_handlers() -> None:+ """SIGINT/SIGTERM → destroy live sandboxes, then exit non-zero.++ Without this, Ctrl-C leaves Docker containers running (each one happily+ burning RAM until its 8-hour timeout) and a future run sees orphans+ on `docker ps`.+ """++ def _handler(signum: int, _frame: object) -> None:+ sig_name = signal.Signals(signum).name+ _log(f"received {sig_name}; cleaning up sandboxes")+ _destroy_all_live_sandboxes(reason=sig_name)+ # 128 + signal number is the conventional shell exit code for+ # signal-killed processes.+ sys.exit(128 + signum)++ signal.signal(signal.SIGINT, _handler)+ signal.signal(signal.SIGTERM, _handler)+++def _write_artifacts(harvested, dest: Path, *, repo_root: Path) -> None: # noqa: ANN001+ """Mirror what the deleted smoke command did, minus the smoke-output wipe."""+ output = dest / "output"+ output.mkdir(parents=True, exist_ok=True)+ (output / "original.sql").write_text(harvested.original_sql.rstrip() + "\n")+ if harvested.best_sql:+ (output / "best.sql").write_text(harvested.best_sql.rstrip() + "\n")+ if harvested.baseline_metrics_json:+ (output / "baseline_metrics.json").write_text(harvested.baseline_metrics_json)+ if harvested.best_metrics_json:+ (output / "best_run_metrics.json").write_text(harvested.best_metrics_json)+ if harvested.last_run_json:+ (output / "last_run.json").write_text(harvested.last_run_json)+ if harvested.out_of_scope_suggestions:+ (output / "out-of-scope-suggestions.md").write_text(harvested.out_of_scope_suggestions)+ if harvested.campaign_stdout_tail:+ (output / "campaign_stdout_tail.log").write_text(harvested.campaign_stdout_tail)+ for sub, entries in (+ ("lanes", harvested.lanes),+ ("hypotheses", harvested.hypotheses),+ ("reviews", harvested.reviews),+ ):+ if not entries:+ continue+ sub_dir = output / sub+ sub_dir.mkdir(parents=True, exist_ok=True)+ for name, contents in entries:+ (sub_dir / name).write_text(contents)++ summary = {+ "query_id": harvested.query_id,+ "best_sql": harvested.best_sql,+ "baseline_metrics_json": harvested.baseline_metrics_json,+ "best_run_metrics_json": harvested.best_metrics_json,+ "lane_count": len(harvested.lanes),+ "hypothesis_count": len(harvested.hypotheses),+ "review_count": len(harvested.reviews),+ "repo_root": str(repo_root),+ }+ (output / "summary.json").write_text(json.dumps(summary, indent=2) + "\n")+++def parse_args(argv: list[str]) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument(+ "--target",+ choices=("test_cluster", "local"),+ required=True,+ help="Where the coordinator forwards candidate SQL.",+ )+ parser.add_argument(+ "--metabase-region", choices=("us", "eu"), help="Region for slow-query sourcing and (test_cluster) execution"+ )+ parser.add_argument(+ "--query-log-database-id",+ type=int,+ help=(+ "Metabase database id used to read system.query_log when sourcing slow queries. "+ "Prefer the OFFLINE cluster — it's not under user load. (US: 142, ClickHouse PROD US - OFFLINE.)"+ ),+ )+ parser.add_argument(+ "--test-cluster-database-id",+ type=int,+ help=(+ "Metabase database id the coordinator runs candidate SQL against when --target=test_cluster. "+ "Required only for --target=test_cluster."+ ),+ )+ parser.add_argument("--team-id", type=int, default=2, help="Team to source slow queries for (default: 2)")+ parser.add_argument(+ "--local-team-id",+ type=int,+ default=1,+ help=(+ "When --target=local, the team_id the dev ClickHouse contains data for. "+ "The agent's prompt addendum will instruct it to rewrite team_id predicates "+ "to this value before capturing the baseline. (default: 1, matching `bin/start`'s seed)"+ ),+ )+ parser.add_argument("--lookback-hours", type=_positive_int, default=24)+ parser.add_argument("--max-queries", type=_positive_int, default=5)+ parser.add_argument("--port", type=int, default=8765)+ parser.add_argument("--bind-host", default="127.0.0.1", help="Host to bind the coordinator HTTP server to")+ parser.add_argument(+ "--no-spawn",+ action="store_true",+ help="Just stand up the HTTP server; don't fetch slow queries or spawn sandboxes",+ )+ parser.add_argument(+ "--print-only",+ action="store_true",+ help=(+ "Fetch the slow queries that would be analyzed, print a summary to stdout, then exit. "+ "Skips the HTTP server, the sandbox provisioning, and the ANTHROPIC_API_KEY check. "+ "Useful for dry-running the column filter and inspecting candidate SQL before burning tokens."+ ),+ )+ parser.add_argument(+ "--repository",+ default="PostHog/posthog",+ help="GitHub repository the sandbox clones from (default: %(default)s).",+ )+ parser.add_argument(+ "--branch",+ default=None,+ help=(+ "Branch the sandbox clones. Defaults to the current local git branch "+ "(falls back to 'master'). Must already exist on origin — sandboxes always pull from there."+ ),+ )+ parser.add_argument(+ "--test-query",+ action="store_true",+ help=(+ "Skip Metabase entirely and feed `SELECT 1, sleep(1)` as the campaign SQL. "+ "Useful as an end-to-end smoke: the agent should drop the sleep call within "+ "a couple of iterations. When set, --query-log-database-id is ignored."+ ),+ )+ parser.add_argument(+ "--keep-sandboxes",+ action="store_true",+ help=(+ "Don't destroy sandboxes after the campaign exits. Useful for debugging — "+ "you can `docker exec` into the container post-mortem to inspect the workspace. "+ "By default each sandbox is torn down after artifacts are harvested."+ ),+ )+ return parser.parse_args(argv)+++def _print_only(args: argparse.Namespace) -> int:+ """Dry-run: fetch the queries that would be analyzed and print them.++ Skips the HTTP server, sandbox provisioning, and ANTHROPIC_API_KEY check.+ Mirrors the production fetch+filter pipeline so the output is exactly+ the set of queries a real run would feed into sandboxes.+ """+ if not args.test_query:+ if not args.metabase_region or not args.query_log_database_id:+ raise SystemExit(+ "--print-only still needs --metabase-region and --query-log-database-id (or pass --test-query)"+ )+ if shutil.which("hogli") is None:+ raise SystemExit("`hogli` not on PATH; run from a flox environment with the workspace loaded")++ queries = _fetch_filtered_queries(args)+ _log(f"got {len(queries)} candidate queries (after filter)")++ if not queries:+ _log("no eligible slow queries found (ai_data_processing_approved=true). Nothing would run.")+ return 0++ print() # noqa: T201 — print-only mode emits structured output to stdout+ for i, q in enumerate(queries, start=1):+ print(f"[{i}/{len(queries)}] query_id={q.query_id}") # noqa: T201+ print(f" team_id={q.team_id} duration={q.query_duration_ms}ms read_bytes={q.read_bytes}") # noqa: T201+ print(f" event_time={q.event_time}") # noqa: T201+ preview = q.clickhouse_query.replace("\n", " ")[:200]+ print(f" sql_preview: {preview}{'…' if len(q.clickhouse_query) > 200 else ''}") # noqa: T201+ print() # noqa: T201+ return 0+++_TEST_QUERY_SQL = "SELECT 1, sleep(1)"+++def _synthetic_test_query() -> SlowQuery:+ """A trivial slow query for end-to-end smoke runs (`--test-query`).++ `sleep(1)` adds a deterministic ~1s, so the agent's optimisation target+ is obvious (drop the sleep) and the campaign exercises the whole+ coordinator → sandbox → agent → coordinator round-trip without+ needing a real Metabase fetch.+ """+ return SlowQuery(+ query_id="test-query-smoke",+ team_id=0,+ clickhouse_query=_TEST_QUERY_SQL,+ hogql_query="",+ query_duration_ms=1000,+ read_bytes=0,+ event_time="",+ )+++def _fetch_filtered_queries(args: argparse.Namespace) -> list[SlowQuery]:+ """Shared between --print-only and the real run: same filter, same source."""+ if args.test_query:+ # Bypass Metabase entirely. The synthetic query is well-formed+ # ClickHouse SQL with no team_id predicate, so the column /+ # dictionary filters and the team-rewrite prompt addendum are+ # all no-ops for it.+ _log("--test-query: skipping Metabase fetch and feeding `SELECT 1, sleep(1)` to the campaign")+ return [_synthetic_test_query()]++ available_columns: list[str] | None = None+ available_dictionaries: list[str] | None = None+ if args.target == "test_cluster":+ if not args.test_cluster_database_id:+ raise SystemExit("--target test_cluster needs --test-cluster-database-id (used to fetch available columns)")+ available_columns = fetch_available_columns(+ region=args.metabase_region,+ database_id=args.test_cluster_database_id,+ )+ _log(f"test cluster exposes {len(available_columns)} column names; filtering slow queries to subsets only")+ available_dictionaries = fetch_available_dictionaries(+ region=args.metabase_region,+ database_id=args.test_cluster_database_id,+ )+ _log(f"test cluster exposes {len(available_dictionaries)} dictionaries; filtering slow queries to subsets only")++ return fetch_slow_queries(+ region=args.metabase_region,+ database_id=args.query_log_database_id,+ team_id=args.team_id,+ lookback_hours=args.lookback_hours,+ limit=args.max_queries,+ available_columns=available_columns,+ available_dictionaries=available_dictionaries,+ )+++def main(argv: list[str] | None = None) -> int:+ _require_supported_platform()+ args = parse_args(argv if argv is not None else sys.argv[1:])++ _load_repo_dotenv()+ # Set DJANGO_SETTINGS_MODULE + SANDBOX_PROVIDER before any worker thread+ # might import `products.tasks.backend.services.sandbox`. Workers also+ # call this defensively (idempotent), but doing it here means the first+ # `import` from a worker thread doesn't race with the env-var write.+ _ensure_django_setup()++ if args.print_only:+ return _print_only(args)++ _install_signal_handlers()++ backend = _build_backend(args)+ prompt_addendum = backend.prompt_addendum()++ info = ServerInfo(+ target=backend.target,+ prompt_addendum=prompt_addendum,+ primary_metric="latency_ms",+ # When the backend ships a prompt addendum, the agent has to act on+ # it (rewrite team_id predicates, etc.) before the baseline is+ # meaningful. So skip the orchestrator-side baseline whenever there's+ # any addendum text and let the agent capture it after rewriting.+ capture_baseline_in_orchestrator=not prompt_addendum.strip(),+ )+ token = generate_token()+ server = make_server(host=args.bind_host, port=args.port, backend=backend, token=token, info=info)+ serve_forever_in_thread(server)+ actual_port = server.server_address[1]+ _log(f"HTTP server listening on http://{args.bind_host}:{actual_port} (backend={backend.name})")++ if args.no_spawn:+ _log("--no-spawn: server will run until Ctrl-C")+ try:+ while True:+ time.sleep(3600)+ except KeyboardInterrupt:+ _log("shutting down")+ return 0++ if not args.test_query:+ if not args.metabase_region or not args.query_log_database_id:+ raise SystemExit(+ "--metabase-region and --query-log-database-id are required (or pass --test-query for a smoke run)"+ )+ if shutil.which("hogli") is None:+ raise SystemExit("`hogli` not on PATH; run from a flox environment with the workspace loaded")++ if not os.environ.get("ANTHROPIC_API_KEY"):+ raise SystemExit(+ "ANTHROPIC_API_KEY is not set. pi-autoresearch needs a first-party Anthropic key — "+ "Claude Code's gateway token (ANTHROPIC_AUTH_TOKEN) is intentionally NOT used.\n"+ "Export ANTHROPIC_API_KEY=<your key> before running the coordinator."+ )++ repo_root = _resolve_repo_root()+ branch = args.branch or _detect_current_branch(repo_root) or "master"+ _check_branch_on_remote(repo_root, args.repository, branch)++ if not args.test_query:+ _log(+ f"fetching up to {args.max_queries} slow queries from Metabase "+ f"({args.metabase_region} query-log-db={args.query_log_database_id} team={args.team_id} "+ f"lookback={args.lookback_hours}h)"+ )+ queries = _fetch_filtered_queries(args)+ if not queries:+ _log("no eligible slow queries found (ai_data_processing_approved=true). Nothing to do.")+ return 0+ _log(f"got {len(queries)} candidate queries; sandboxes will clone {args.repository}@{branch}")++ coordinator_url = f"http://host.docker.internal:{actual_port}"+ # 8-char shared id stamped on every artifact dir for this coordinator run+ # so concurrent runs don't collide on `RUNS_DIR/<query_id>`.+ run_id = uuid.uuid4().hex[:8]++ failures: list[str] = []+ try:+ with ThreadPoolExecutor(+ max_workers=min(len(queries), MAX_CONCURRENT_SANDBOXES),+ thread_name_prefix="qp-sandbox",+ ) as pool:+ futures = {+ pool.submit(+ _spawn_one_sandbox,+ query=q,+ coordinator_url=coordinator_url,+ coordinator_token=token,+ keep_sandbox=args.keep_sandboxes,+ repo_root=repo_root,+ repository=args.repository,+ branch=branch,+ run_id=run_id,+ ): q+ for q in queries+ }+ for fut in as_completed(futures):+ q = futures[fut]+ try:+ qid, code = fut.result()+ if code != 0:+ failures.append(qid)+ except Exception as e: # noqa: BLE001+ _log(f"[{q.query_id}] FAILED: {e}")+ failures.append(q.query_id)+ finally:+ # Belt-and-braces: even if the executor exits cleanly, anything that+ # registered itself but bypassed the per-worker `finally` (e.g.+ # uncaught exception during `create()`'s post-registration code)+ # still gets cleaned up here. With `--keep-sandboxes` the registry+ # is empty by this point because the worker pops itself.+ _destroy_all_live_sandboxes(reason="main-exit")++ if failures:+ _log(f"completed with {len(failures)} failed campaign(s): {', '.join(failures)}")+ return 1+ _log("all campaigns completed")+ return 0+++def _resolve_repo_root() -> Path:+ """Walk up from the product dir until we find the repo root marker."""+ candidate = PRODUCT_DIR+ for _ in range(8):+ if (candidate / "manage.py").is_file() and (candidate / "products").is_dir():+ return candidate+ candidate = candidate.parent+ raise SystemExit(+ "could not locate the posthog repo root (looked for manage.py + products/). "+ "Run the coordinator from inside the posthog checkout."+ )+++def _check_branch_on_remote(repo_root: Path, repository: str, branch: str) -> None:+ """The sandbox clones from origin, so a missing branch fails mid-campaign.++ Fail loud here instead. Local-vs-origin SHA drift is only a warning —+ the sandbox will pull origin's snapshot, not the local one.+ """+ try:+ ls_remote = subprocess.run( # noqa: S603 — fixed argv+ ["git", "ls-remote", "--heads", "origin", branch],+ check=False,+ text=True,+ capture_output=True,+ cwd=repo_root,+ timeout=10,+ )+ except (FileNotFoundError, subprocess.TimeoutExpired):+ _log(f"warning: couldn't check whether {branch!r} exists on origin (git unavailable)")+ return+ if ls_remote.returncode != 0 or not ls_remote.stdout.strip():+ raise SystemExit(+ f"branch {branch!r} doesn't exist on origin/{repository}. The sandbox clones from origin, "+ f"so it can't check out this branch. Push it first:\n"+ f" git push -u origin {branch}\n"+ f"or rerun with --branch pointing at a branch that already exists on origin."+ )+ try:+ local = subprocess.run( # noqa: S603 — fixed argv+ ["git", "rev-parse", branch],+ check=False,+ text=True,+ capture_output=True,+ cwd=repo_root,+ timeout=5,+ )+ remote_sha = ls_remote.stdout.split()[0]+ if local.returncode == 0 and local.stdout.strip() != remote_sha:+ _log(+ f"warning: local '{branch}' differs from origin/{branch} — sandboxes will clone origin's "+ "snapshot. `git push` to publish local commits."+ )+ except Exception: # noqa: BLE001+ pass+++if __name__ == "__main__":+ sys.exit(main())diff --git a/products/query_performance_ai/orchestrator/harvest.py b/products/query_performance_ai/orchestrator/harvest.pynew file mode 100644index 000000000000..43de4c824f2d--- /dev/null+++ b/products/query_performance_ai/orchestrator/harvest.py@@ -0,0 +1,106 @@+"""Pull pi-autoresearch workspace artifacts out of a sandbox via `sandbox.execute`."""++from __future__ import annotations++import json+import shlex+from dataclasses import dataclass, field++from products.tasks.backend.services.sandbox import SandboxBase++WORKSPACE_PATH = "/tmp/autoresearch-campaign" # must match run_campaign.py+LLM_GATEWAY_PRODUCT_SLUG = "background_agents" # posthog/llm/gateway_client.py Product literal+++@dataclass+class RunAutoresearchCampaignOutput:+ original_sql: str+ query_id: str+ baseline_metrics_json: str = ""+ best_sql: str = ""+ best_metrics_json: str = ""+ last_run_json: str = ""+ out_of_scope_suggestions: str = ""+ lanes: list[tuple[str, str]] = field(default_factory=list) # (filename, contents)+ hypotheses: list[tuple[str, str]] = field(default_factory=list)+ reviews: list[tuple[str, str]] = field(default_factory=list)+ campaign_stdout_tail: str = ""+++def _read_sandbox_file(sandbox: SandboxBase, path: str) -> str:+ result = sandbox.execute(f"cat {shlex.quote(path)} 2>/dev/null || true", timeout_seconds=30)+ return result.stdout or ""+++def _list_sandbox_dir(sandbox: SandboxBase, dir_path: str) -> list[str]:+ cmd = f"find {shlex.quote(dir_path)} -maxdepth 1 -type f -printf '%f\\n' 2>/dev/null || true"+ result = sandbox.execute(cmd, timeout_seconds=15)+ return [line for line in (result.stdout or "").splitlines() if line]+++def _collect_markdown_dir(sandbox: SandboxBase, dir_path: str) -> list[tuple[str, str]]:+ out: list[tuple[str, str]] = []+ for name in sorted(_list_sandbox_dir(sandbox, dir_path)):+ if not name.endswith(".md") or name == "README.md":+ continue+ contents = _read_sandbox_file(sandbox, f"{dir_path}/{name}")+ if contents:+ out.append((name, contents))+ return out+++def _best_run_metrics(sandbox: SandboxBase) -> str:+ """Fastest run whose comparator said matches=true — a faster-but-wrong+ candidate must never be crowned the winner."""+ cmd = f'for m in {WORKSPACE_PATH}/runs/*/metrics.json; do [ -f "$m" ] && echo "$m"; done'+ result = sandbox.execute(cmd, timeout_seconds=15)+ metric_paths = [p for p in (result.stdout or "").splitlines() if p]+ best_value: float | None = None+ best_contents = ""+ for path in metric_paths:+ raw = _read_sandbox_file(sandbox, path)+ if not raw:+ continue+ try:+ data = json.loads(raw)+ except json.JSONDecodeError:+ continue+ value = (data.get("primary") or {}).get("value")+ if not isinstance(value, int | float) or value < 0:+ continue+ comparison_path = path.rsplit("/", 1)[0] + "/comparison.json"+ comparison_raw = _read_sandbox_file(sandbox, comparison_path)+ if not comparison_raw:+ continue+ try:+ comparison = json.loads(comparison_raw)+ except json.JSONDecodeError:+ continue+ if comparison.get("matches") is not True:+ continue+ if best_value is None or value < best_value:+ best_value = value+ best_contents = raw+ return best_contents+++def harvest_artifacts(+ sandbox: SandboxBase,+ *,+ original_sql: str,+ query_id: str,+ campaign_stdout_tail: str,+) -> RunAutoresearchCampaignOutput:+ return RunAutoresearchCampaignOutput(+ original_sql=original_sql,+ query_id=query_id,+ baseline_metrics_json=_read_sandbox_file(sandbox, f"{WORKSPACE_PATH}/baseline/metrics.json"),+ best_sql=_read_sandbox_file(sandbox, f"{WORKSPACE_PATH}/query/best.sql") or original_sql,+ best_metrics_json=_best_run_metrics(sandbox),+ last_run_json=_read_sandbox_file(sandbox, f"{WORKSPACE_PATH}/runtime/last_run.json"),+ out_of_scope_suggestions=_read_sandbox_file(sandbox, f"{WORKSPACE_PATH}/out-of-scope-suggestions.md"),+ lanes=_collect_markdown_dir(sandbox, f"{WORKSPACE_PATH}/lanes"),+ hypotheses=_collect_markdown_dir(sandbox, f"{WORKSPACE_PATH}/hypotheses"),+ reviews=_collect_markdown_dir(sandbox, f"{WORKSPACE_PATH}/reviews"),+ campaign_stdout_tail=campaign_stdout_tail,+ )diff --git a/products/query_performance_ai/orchestrator/server.py b/products/query_performance_ai/orchestrator/server.pynew file mode 100644index 000000000000..72162c60fe24--- /dev/null+++ b/products/query_performance_ai/orchestrator/server.py@@ -0,0 +1,203 @@+"""Coordinator HTTP server.++stdlib `http.server` so we can run with no extra deps in a fresh worktree.+The single chokepoint that the sandbox hits — token-gated, scheme-locked+to localhost, and serializing all SQL execution behind one lock so a fan+of parallel sandboxes doesn't translate into a fan of parallel ClickHouse+queries.+"""++from __future__ import annotations++import hmac+import json+import secrets+import threading+from dataclasses import dataclass+from http import HTTPStatus+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from socketserver import BaseServer+from typing import Any++from .backends.base import BackendError, ExecutionBackend+++@dataclass(frozen=True)+class ServerInfo:+ """Payload for `GET /v1/info`. Mirrors what run_campaign.py needs."""++ target: str+ prompt_addendum: str+ primary_metric: str = "latency_ms"+ capture_baseline_in_orchestrator: bool = True+++class CoordinatorServer(ThreadingHTTPServer):+ """Exposes `_backend`, `_token`, `_info`, `_query_lock` to the handler.++ `ThreadingHTTPServer` lets `/v1/info` from one sandbox not block on+ the slow `/v1/run` of another — but the lock around `_backend.run()`+ still guarantees only one query is in flight at a time.+ """++ daemon_threads = True++ def __init__(+ self,+ server_address: tuple[str, int],+ RequestHandlerClass: type[BaseHTTPRequestHandler],+ *,+ backend: ExecutionBackend,+ token: str,+ info: ServerInfo,+ ) -> None:+ super().__init__(server_address, RequestHandlerClass)+ self._backend = backend+ self._token = token+ self._info = info+ self._query_lock = threading.Lock()+++class CoordinatorHandler(BaseHTTPRequestHandler):+ server: CoordinatorServer # narrows the type for handler code++ # http.server logs every request to stderr by default; the coordinator+ # already has its own logging so suppress the duplicate noise.+ def log_message(self, format: str, *args: Any) -> None:+ return++ # ----- helpers -----+ def _read_json_body(self) -> dict[str, Any]:+ length_header = self.headers.get("Content-Length") or "0"+ try:+ length = int(length_header)+ except ValueError:+ length = 0+ if length <= 0:+ return {}+ # Cap at 1 MiB — campaign SQL is usually a few KiB; nothing legitimate+ # is bigger than this and clamping prevents a malformed Content-Length+ # from making us read forever.+ if length > 1 << 20:+ raise _BadRequest("body too large")+ raw = self.rfile.read(length)+ try:+ data = json.loads(raw.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError) as e:+ raise _BadRequest(f"invalid JSON body: {e}") from e+ if not isinstance(data, dict):+ raise _BadRequest("body must be a JSON object")+ return data++ def _check_auth(self) -> None:+ header = self.headers.get("Authorization") or ""+ prefix = "Bearer "+ if not header.startswith(prefix):+ raise _Unauthorized()+ provided = header[len(prefix) :]+ if not hmac.compare_digest(provided, self.server._token):+ raise _Unauthorized()++ def _send_json(self, status: HTTPStatus, payload: dict[str, Any]) -> None:+ body = json.dumps(payload).encode("utf-8")+ self.send_response(status.value)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.send_header("Cache-Control", "no-store")+ self.end_headers()+ self.wfile.write(body)++ # ----- routes -----+ def do_GET(self) -> None: # noqa: N802 — http.server convention+ try:+ self._check_auth()+ if self.path == "/v1/info":+ info = self.server._info+ self._send_json(+ HTTPStatus.OK,+ {+ "target": info.target,+ "prompt_addendum": info.prompt_addendum,+ "primary_metric": info.primary_metric,+ "capture_baseline_in_orchestrator": info.capture_baseline_in_orchestrator,+ },+ )+ return+ if self.path == "/v1/healthz":+ self._send_json(HTTPStatus.OK, {"ok": True})+ return+ self._send_json(HTTPStatus.NOT_FOUND, {"error": "not found"})+ except _Unauthorized:+ self._send_json(HTTPStatus.UNAUTHORIZED, {"error": "unauthorized"})++ def do_POST(self) -> None: # noqa: N802 — http.server convention+ try:+ self._check_auth()+ if self.path != "/v1/run":+ self._send_json(HTTPStatus.NOT_FOUND, {"error": "not found"})+ return++ body = self._read_json_body()+ sql = body.get("sql")+ if not isinstance(sql, str) or not sql.strip():+ raise _BadRequest("`sql` must be a non-empty string")+ timeout_s_raw = body.get("timeout_s", 300)+ try:+ timeout_s = int(timeout_s_raw)+ except (TypeError, ValueError) as e:+ raise _BadRequest("`timeout_s` must be an integer") from e+ if not 1 <= timeout_s <= 600:+ raise _BadRequest("`timeout_s` must be between 1 and 600")++ with self.server._query_lock:+ try:+ result = self.server._backend.run(sql, timeout_s=timeout_s)+ except BackendError as e:+ self._send_json(HTTPStatus.BAD_GATEWAY, {"error": str(e)})+ return++ self._send_json(+ HTTPStatus.OK,+ {+ "result": result.rows,+ "rows_returned": len(result.rows),+ "elapsed_ms": result.elapsed_ms,+ "rows_read": result.rows_read,+ "bytes_read": result.bytes_read,+ "query_id": result.query_id,+ },+ )+ except _Unauthorized:+ self._send_json(HTTPStatus.UNAUTHORIZED, {"error": "unauthorized"})+ except _BadRequest as e:+ self._send_json(HTTPStatus.BAD_REQUEST, {"error": str(e)})+++class _Unauthorized(Exception):+ pass+++class _BadRequest(Exception):+ pass+++def make_server(+ *,+ host: str,+ port: int,+ backend: ExecutionBackend,+ token: str,+ info: ServerInfo,+) -> CoordinatorServer:+ return CoordinatorServer((host, port), CoordinatorHandler, backend=backend, token=token, info=info)+++def generate_token() -> str:+ """32 bytes of entropy → 43 char URL-safe string."""+ return secrets.token_urlsafe(32)+++def serve_forever_in_thread(server: BaseServer) -> threading.Thread:+ thread = threading.Thread(target=server.serve_forever, name="coordinator-http", daemon=True)+ thread.start()+ return threaddiff --git a/products/query_performance_ai/orchestrator/slow_queries.py b/products/query_performance_ai/orchestrator/slow_queries.pynew file mode 100644index 000000000000..9f90ae772c20--- /dev/null+++ b/products/query_performance_ai/orchestrator/slow_queries.py@@ -0,0 +1,297 @@+"""Source slow queries from Metabase's view of `system.query_log`.++We always source via Metabase regardless of where the coordinator runs the+agent's candidate queries — the `ai_data_processing_approved` tag only+exists in production query_log, and that's the only thing standing+between us and replaying SQL we don't have permission to replay.+"""++from __future__ import annotations++import json+import shlex+import subprocess+from dataclasses import dataclass++# All filters from the human's reference query, minus the snippet macros and+# decorative columns. We only need: raw SQL, duration, bytes, query_id,+# team_id, event_time. Filtering ai_data_processing_approved = 'true' is+# load-bearing — do not relax it.+_SLOW_QUERIES_SQL = """+SELECT+ query_id,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ -- The actual rendered ClickHouse SQL that ran. This is what we hand to the+ -- campaign — the metabase / local-CH backends both speak ClickHouse SQL,+ -- not HogQL.+ query AS clickhouse_query,+ -- The HogQL JSON envelope kept for context only (some campaigns may want+ -- to reason about the higher-level query intent).+ JSONExtractString(log_comment, 'query') AS hogql_query,+ query_duration_ms,+ read_bytes,+ -- Aliasing the formatted string back to `event_time` collides with the+ -- DateTime column the WHERE clause uses; pick a distinct alias.+ toString(event_time) AS event_time_iso+FROM clusterAllReplicas(posthog, system, query_log)+WHERE+ event_time > now() - INTERVAL {lookback_hours} HOUR+ AND JSONExtractInt(log_comment, 'team_id') = {team_id}+ AND JSONExtractString(log_comment, 'workload') NOT IN ('Workload.OFFLINE', 'OFFLINE')+ AND JSONExtractString(log_comment, 'kind') NOT IN ('temporal')+ AND JSONExtractString(log_comment, 'access_method') NOT IN ('personal_api_key')+ AND is_initial_query+ AND (query_duration_ms > 30000 OR exception_code IN (159, 160, 241))+ AND JSONExtractString(log_comment, 'ai_data_processing_approved') = 'true'+ AND notEmpty(JSONExtractString(log_comment, 'query'))+ {column_filter_clause}+ORDER BY query_duration_ms DESC+LIMIT {limit}+"""++# When we know which columns the execution target has, drop queries that+# reference a column NAME (not table) the target lacks — saves the agent+# the wild-goose repair attempts we saw on materialized columns missing+# from the test cluster. We compare on column name only because+# prod-vs-test-cluster table names diverge (e.g. `sharded_events` on prod+# is exposed as `events` on the test cluster's metabase database).+# `system.query_log.columns` entries are formatted `database.table.column`+# with backticks around any column whose name needs quoting (e.g.+# `mat_$host`); strip the prefix and the backticks before comparing.+_COLUMN_FILTER_CLAUSE = (+ "AND hasAll({available}, arrayDistinct(arrayMap(c -> replaceAll(splitByChar('.', c)[3], '`', ''), columns)))"+)++# Same idea as the column filter, but for ClickHouse dictionaries (referenced via+# dictGet*/dictHas etc.). `system.query_log.used_dictionaries` is already in+# `database.name` form, so we compare directly without splitting.+_DICTIONARY_FILTER_CLAUSE = "AND hasAll({available}, used_dictionaries)"+++def _ch_string_array(items: list[str]) -> str:+ """Render ``items`` as a ClickHouse string-literal array.++ Uses single quotes with `''` escaping. Avoids ``repr()`` because Python's+ repr switches to double quotes when a string contains a single quote, and+ ClickHouse parses double-quoted tokens as identifier references — not+ string literals — silently turning a name like ``foo'bar`` into a column+ reference instead of a value. Curly braces in names are also passed+ through unchanged (no ``.format`` interpolation here).+ """+ quoted = ",".join("'" + s.replace("'", "''") + "'" for s in items)+ return "[" + quoted + "]"+++@dataclass(frozen=True)+class SlowQuery:+ query_id: str+ team_id: int+ # Rendered ClickHouse SQL exactly as it ran on the cluster — what we hand+ # to the campaign as `CAMPAIGN_SQL`.+ clickhouse_query: str+ # The HogQL JSON envelope (from log_comment.query). Useful as context but+ # not directly executable on the test cluster — it references HogQL+ # abstractions like saved-query views that don't exist as CH tables.+ hogql_query: str+ query_duration_ms: int+ read_bytes: int+ event_time: str+++def build_sql(+ *,+ team_id: int,+ lookback_hours: int,+ limit: int,+ available_columns: list[str] | None = None,+ available_dictionaries: list[str] | None = None,+) -> str:+ """Public for tests — keeps the formatting check trivial.++ When ``available_columns`` is provided, restricts results to queries that+ only reference columns in the list. When ``available_dictionaries`` is+ provided (entries in the form ``database.dict_name`` to match+ ``system.query_log.used_dictionaries``), restricts to queries that only+ use dictionaries in the list — pass an empty list ``[]`` to require zero+ dictionary use. Pass ``None`` to skip either filter.+ """+ clauses: list[str] = []+ if available_columns:+ clauses.append(_COLUMN_FILTER_CLAUSE.format(available=_ch_string_array(sorted(available_columns))))+ if available_dictionaries is not None:+ clauses.append(_DICTIONARY_FILTER_CLAUSE.format(available=_ch_string_array(sorted(available_dictionaries))))+ return _SLOW_QUERIES_SQL.format(+ lookback_hours=int(lookback_hours),+ team_id=int(team_id),+ limit=int(limit),+ column_filter_clause="\n ".join(clauses),+ )+++def fetch_slow_queries(+ *,+ region: str,+ database_id: int,+ team_id: int,+ lookback_hours: int = 24,+ limit: int = 10,+ timeout_s: float = 90.0,+ available_columns: list[str] | None = None,+ available_dictionaries: list[str] | None = None,+) -> list[SlowQuery]:+ """Run the slow-queries SQL via `hogli metabase:query` and parse the rows.++ We shell out to `hogli` rather than re-implementing cookie handling+ here — the cookie cache, ALB redirect detection, and SSO refresh+ instructions all live in one place that way, and the cookie value+ never lands in this process's argv or env.+ """+ sql = build_sql(+ team_id=team_id,+ lookback_hours=lookback_hours,+ limit=limit,+ available_columns=available_columns,+ available_dictionaries=available_dictionaries,+ )+ cmd = [+ "hogli",+ "metabase:query",+ "--region",+ region,+ "--database-id",+ str(database_id),+ "--format",+ "json",+ "--timeout",+ str(timeout_s),+ ]+ result = subprocess.run( # noqa: S603 — fixed argv, sql via stdin+ cmd,+ input=sql,+ text=True,+ capture_output=True,+ check=False,+ timeout=timeout_s + 30,+ )+ if result.returncode != 0:+ raise RuntimeError(+ f"hogli metabase:query failed (exit {result.returncode}):\n"+ f" cmd: {shlex.join(cmd)}\n"+ f" stderr: {(result.stderr or '').strip()[:1000]}"+ )++ return parse_metabase_response(result.stdout)+++# The user-facing tables most slow queries actually reference. We+# scope the column filter to these because the test cluster's underlying+# `sharded_events*` tables have a richer schema than its `events`+# Distributed wrapper, and the filter has to match what the query+# resolves through, not the union of every table in the database.+_USER_FACING_TABLES = ("events", "person", "raw_sessions")+++def fetch_available_columns(+ *,+ region: str,+ database_id: int,+ tables: tuple[str, ...] = _USER_FACING_TABLES,+ timeout_s: float = 60.0,+) -> list[str]:+ """Return the *set of column NAMES* the metabase database exposes on the+ ``posthog.<table>`` for each of ``tables``.++ Used to pre-filter the slow-queries query so we never hand the agent a+ campaign that's blocked on a materialized column the test cluster doesn't+ have. We return names rather than ``database.table.column`` triples+ because prod and the test cluster use different physical tables for the+ same logical thing (e.g. prod's queries record `sharded_events.foo` in+ query_log but the test cluster's `events` Distributed table is the+ actual backing target). Scoping to ``events``/``person``/``raw_sessions``+ matches what user-facing queries actually go through.+ """+ table_list = ", ".join(f"'{t}'" for t in tables)+ sql = f"SELECT DISTINCT name FROM system.columns WHERE database = 'posthog' AND table IN ({table_list})"+ cmd = [+ "hogli",+ "metabase:query",+ "--region",+ region,+ "--database-id",+ str(database_id),+ "--format",+ "json",+ "--timeout",+ str(timeout_s),+ ]+ result = subprocess.run( # noqa: S603 — fixed argv, sql via stdin+ cmd,+ input=sql,+ text=True,+ capture_output=True,+ check=False,+ timeout=timeout_s + 30,+ )+ if result.returncode != 0:+ raise RuntimeError(+ f"hogli metabase:query failed (exit {result.returncode}):\n stderr: {(result.stderr or '').strip()[:500]}"+ )+ body = json.loads(result.stdout)+ return [name for (name,) in body["data"]["rows"]]+++def fetch_available_dictionaries(*, region: str, database_id: int, timeout_s: float = 60.0) -> list[str]:+ """Return ``database.name`` for each ClickHouse dictionary on the test cluster.++ Format matches ``system.query_log.used_dictionaries`` so we can pass the+ result straight into the slow-queries dictionary filter. An empty list+ means the test cluster has no dictionaries — we'll filter out every+ query that uses one.+ """+ sql = "SELECT database, name FROM system.dictionaries WHERE database = 'posthog'"+ cmd = [+ "hogli",+ "metabase:query",+ "--region",+ region,+ "--database-id",+ str(database_id),+ "--format",+ "json",+ "--timeout",+ str(timeout_s),+ ]+ result = subprocess.run( # noqa: S603 — fixed argv, sql via stdin+ cmd,+ input=sql,+ text=True,+ capture_output=True,+ check=False,+ timeout=timeout_s + 30,+ )+ if result.returncode != 0:+ raise RuntimeError(+ f"hogli metabase:query failed (exit {result.returncode}):\n stderr: {(result.stderr or '').strip()[:500]}"+ )+ body = json.loads(result.stdout)+ return [f"{db}.{name}" for db, name in body["data"]["rows"]]+++def parse_metabase_response(raw: str) -> list[SlowQuery]:+ body = json.loads(raw)+ cols = [c["name"] for c in body["data"]["cols"]]+ out: list[SlowQuery] = []+ for row in body["data"]["rows"]:+ record = dict(zip(cols, row))+ out.append(+ SlowQuery(+ query_id=str(record["query_id"]),+ team_id=int(record["team_id"]),+ clickhouse_query=str(record["clickhouse_query"]),+ hogql_query=str(record["hogql_query"]),+ query_duration_ms=int(record["query_duration_ms"]),+ read_bytes=int(record["read_bytes"]),+ event_time=str(record["event_time_iso"]),+ )+ )+ return outdiff --git a/products/query_performance_ai/orchestrator/tests/test_server.py b/products/query_performance_ai/orchestrator/tests/test_server.pynew file mode 100644index 000000000000..8724f6f79cb1--- /dev/null+++ b/products/query_performance_ai/orchestrator/tests/test_server.py@@ -0,0 +1,176 @@+from __future__ import annotations++import json+import threading+import urllib.error+import urllib.request+from typing import Any++import pytest++from products.query_performance_ai.orchestrator.backends.base import BackendError, ExecutionBackend, ExecutionResult+from products.query_performance_ai.orchestrator.server import (+ ServerInfo,+ generate_token,+ make_server,+ serve_forever_in_thread,+)+++class _StubBackend(ExecutionBackend):+ """Returns scripted results so the server tests don't need ClickHouse."""++ def __init__(self) -> None:+ self.calls: list[tuple[str, int]] = []+ self.result: ExecutionResult | Exception = ExecutionResult(+ rows=[[1, "ok"]],+ elapsed_ms=12.5,+ rows_read=1,+ bytes_read=42,+ query_id="qid-123",+ )++ @property+ def name(self) -> str:+ return "stub"++ @property+ def target(self) -> str:+ return "stub-target"++ def run(self, sql: str, *, timeout_s: int) -> ExecutionResult:+ self.calls.append((sql, timeout_s))+ if isinstance(self.result, Exception):+ raise self.result+ return self.result++ def prompt_addendum(self) -> str:+ return "STUB ADDENDUM"+++def server_fixture() -> Any:+ backend = _StubBackend()+ token = generate_token()+ info = ServerInfo(target=backend.target, prompt_addendum=backend.prompt_addendum())+ server = make_server(host="127.0.0.1", port=0, backend=backend, token=token, info=info)+ serve_forever_in_thread(server)+ port = server.server_address[1]+ yield server, backend, token, port+ server.shutdown()+++def _request(port: int, *, path: str, method: str, token: str | None, body: dict | None = None) -> tuple[int, dict]:+ headers: dict[str, str] = {}+ if token is not None:+ headers["Authorization"] = f"Bearer {token}"+ data: bytes | None = None+ if body is not None:+ data = json.dumps(body).encode("utf-8")+ headers["Content-Type"] = "application/json"+ req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", method=method, data=data, headers=headers)+ try:+ with urllib.request.urlopen(req, timeout=5) as resp: # noqa: S310+ return resp.status, json.loads(resp.read().decode("utf-8"))+ except urllib.error.HTTPError as e:+ return e.code, json.loads(e.read().decode("utf-8"))+++def test_info_returns_target_and_addendum(server_fixture) -> None:+ _server, _backend, token, port = server_fixture+ status, body = _request(port, path="/v1/info", method="GET", token=token)+ assert status == 200+ assert body["target"] == "stub-target"+ assert body["prompt_addendum"] == "STUB ADDENDUM"+ assert body["primary_metric"] == "latency_ms"+++def test_run_happy_path(server_fixture) -> None:+ _server, backend, token, port = server_fixture+ status, body = _request(port, path="/v1/run", method="POST", token=token, body={"sql": "SELECT 1"})+ assert status == 200+ assert body["result"] == [[1, "ok"]]+ assert body["rows_returned"] == 1+ assert body["query_id"] == "qid-123"+ assert backend.calls == [("SELECT 1", 300)]+++def test_missing_token_returns_401(server_fixture) -> None:+ _server, _backend, _token, port = server_fixture+ status, body = _request(port, path="/v1/info", method="GET", token=None)+ assert status == 401+ assert body["error"] == "unauthorized"+++def test_wrong_token_returns_401(server_fixture) -> None:+ _server, _backend, _token, port = server_fixture+ status, body = _request(port, path="/v1/info", method="GET", token="not-the-token")+ assert status == 401+ assert body["error"] == "unauthorized"+++def test_run_rejects_empty_sql(server_fixture) -> None:+ _server, _backend, token, port = server_fixture+ status, body = _request(port, path="/v1/run", method="POST", token=token, body={"sql": ""})+ assert status == 400+ assert "non-empty" in body["error"]+++def test_run_rejects_out_of_range_timeout(server_fixture) -> None:+ _server, _backend, token, port = server_fixture+ status, body = _request(+ port, path="/v1/run", method="POST", token=token, body={"sql": "SELECT 1", "timeout_s": 99999}+ )+ assert status == 400+ assert "timeout_s" in body["error"]+++def test_run_returns_502_on_backend_error(server_fixture) -> None:+ _server, backend, token, port = server_fixture+ backend.result = BackendError("syntax exception")+ status, body = _request(port, path="/v1/run", method="POST", token=token, body={"sql": "SELECT bad"})+ assert status == 502+ assert "syntax" in body["error"]+++def test_query_lock_serializes_concurrent_runs(server_fixture) -> None:+ """Multiple sandboxes posting /v1/run at the same time must NOT run+ backend.run() concurrently — the lock is the whole reason this server+ isn't just a thin wrapper."""+ _server, backend, token, port = server_fixture+ enter = threading.Event()+ release = threading.Event()+ in_flight = 0+ max_in_flight = 0+ counter_lock = threading.Lock()++ def slow_run(sql: str, *, timeout_s: int) -> ExecutionResult:+ nonlocal in_flight, max_in_flight+ with counter_lock:+ in_flight += 1+ max_in_flight = max(max_in_flight, in_flight)+ enter.set()+ release.wait(timeout=2)+ with counter_lock:+ in_flight -= 1+ return ExecutionResult(rows=[[1]], elapsed_ms=1.0, rows_read=None, bytes_read=None, query_id=None)++ backend.run = slow_run++ def hit() -> int:+ status, _body = _request(port, path="/v1/run", method="POST", token=token, body={"sql": "SELECT 1"})+ return status++ t1 = threading.Thread(target=hit)+ t2 = threading.Thread(target=hit)+ t1.start()+ enter.wait(timeout=2) # first call is in flight+ t2.start()+ # Briefly let the second request reach the lock; assert in_flight stays at 1.+ import time as _time++ _time.sleep(0.1)+ assert max_in_flight == 1, "the coordinator's lock didn't serialize /v1/run"+ release.set()+ t1.join(timeout=5)+ t2.join(timeout=5)diff --git a/products/query_performance_ai/orchestrator/tests/test_slow_queries.py b/products/query_performance_ai/orchestrator/tests/test_slow_queries.pynew file mode 100644index 000000000000..96b7e94c08b7--- /dev/null+++ b/products/query_performance_ai/orchestrator/tests/test_slow_queries.py@@ -0,0 +1,126 @@+from __future__ import annotations++import json+import subprocess+from typing import Any++import pytest+from unittest import mock++from products.query_performance_ai.orchestrator import slow_queries+++def test_build_sql_substitutes_filters() -> None:+ sql = slow_queries.build_sql(team_id=42, lookback_hours=12, limit=7)+ assert "team_id') = 42" in sql+ assert "INTERVAL 12 HOUR" in sql+ assert "LIMIT 7" in sql+ assert "ai_data_processing_approved') = 'true'" in sql+ assert "hasAll(" not in sql # no available_columns filter when arg omitted+++def test_build_sql_with_available_dictionaries_adds_has_all_filter() -> None:+ sql = slow_queries.build_sql(+ team_id=2,+ lookback_hours=24,+ limit=1,+ available_dictionaries=["posthog.web_pre_aggregated_teams_dict"],+ )+ assert "used_dictionaries" in sql+ assert "'posthog.web_pre_aggregated_teams_dict'" in sql+ # Empty list (`[]`) is meaningful — it requires queries to use no+ # dictionaries at all. Distinguish from `None` (skip the filter).+ sql_empty = slow_queries.build_sql(+ team_id=2,+ lookback_hours=24,+ limit=1,+ available_dictionaries=[],+ )+ assert "used_dictionaries" in sql_empty+ sql_none = slow_queries.build_sql(team_id=2, lookback_hours=24, limit=1, available_dictionaries=None)+ assert "used_dictionaries" not in sql_none+++def test_build_sql_with_available_columns_adds_has_all_filter() -> None:+ sql = slow_queries.build_sql(+ team_id=2,+ lookback_hours=24,+ limit=1,+ available_columns=["team_id", "event", "timestamp"],+ )+ assert "hasAll(" in sql+ # Compare on column NAME only, not full database.table.column; that lets+ # prod's `sharded_events` and the test cluster's `events` match.+ assert "splitByChar('.', c)[3]" in sql+ assert "'team_id'" in sql+ assert "'event'" in sql+ # backticks must be stripped before comparison so `mat_$host` matches `mat_$host`.+ assert "'`'" in sql+++def test_ch_string_array_handles_apostrophes_and_braces() -> None:+ """Names with `'` or `{` would break a naive `repr()` interpolation; verify they're escaped safely."""+ rendered = slow_queries._ch_string_array(["foo'bar", "baz{name}", "plain"])+ # Single quotes inside the value get doubled per ClickHouse string-literal rules.+ assert rendered == "['foo''bar','baz{name}','plain']"+ # Curly braces are passed through unchanged — no `.format()` step happens+ # downstream because `build_sql` interpolates the rendered string into a+ # placeholder that's not itself `.format`'d again.+ assert "{name}" in rendered+++def test_parse_metabase_response_typed_records() -> None:+ raw = json.dumps(+ {+ "data": {+ "cols": [+ {"name": "query_id"},+ {"name": "team_id"},+ {"name": "clickhouse_query"},+ {"name": "hogql_query"},+ {"name": "query_duration_ms"},+ {"name": "read_bytes"},+ {"name": "event_time_iso"},+ ],+ "rows": [+ [+ "q1",+ 2,+ "SELECT count() FROM events",+ '{"kind":"HogQLQuery"}',+ 31000,+ 5000,+ "2026-05-01 09:00:00",+ ],+ ["q2", 2, "SELECT 2", "", 60000, 12345, "2026-05-01 09:30:00"],+ ],+ }+ }+ )+ rows = slow_queries.parse_metabase_response(raw)+ assert len(rows) == 2+ assert rows[0].query_id == "q1"+ assert rows[0].query_duration_ms == 31000+ assert rows[0].clickhouse_query == "SELECT count() FROM events"+ assert rows[0].hogql_query == '{"kind":"HogQLQuery"}'+ assert rows[1].read_bytes == 12345+ assert rows[1].clickhouse_query == "SELECT 2"+++def test_fetch_slow_queries_propagates_hogli_failure() -> None:+ completed: Any = subprocess.CompletedProcess(args=["hogli"], returncode=1, stdout="", stderr="boom")+ with mock.patch.object(subprocess, "run", return_value=completed):+ with pytest.raises(RuntimeError, match="hogli metabase:query failed"):+ slow_queries.fetch_slow_queries(region="us", database_id=1, team_id=2, limit=1)+++def test_fetch_slow_queries_passes_args_via_stdin() -> None:+ payload = json.dumps({"data": {"cols": [], "rows": []}})+ completed: Any = subprocess.CompletedProcess(args=["hogli"], returncode=0, stdout=payload, stderr="")+ with mock.patch.object(subprocess, "run", return_value=completed) as run_mock:+ slow_queries.fetch_slow_queries(region="eu", database_id=99, team_id=2, limit=3)+ args, kwargs = run_mock.call_args+ assert args[0][:5] == ["hogli", "metabase:query", "--region", "eu", "--database-id"]+ assert "99" in args[0]+ # SQL is fed via stdin, NOT argv — keeps it off /proc/.../cmdline.+ assert "INTERVAL 24 HOUR" in kwargs["input"]diff --git a/products/query_performance_ai/package.json b/products/query_performance_ai/package.jsonindex 7c5e703a8879..36cec2ae25cd 100644--- a/products/query_performance_ai/package.json+++ b/products/query_performance_ai/package.json@@ -1,6 +1,6 @@{"name": "@posthog/products-query-performance-ai","scripts": {- "backend:test": "echo 'no backend tests yet'"+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. orchestrator sandboxed_autoresearch_agent -v --tb=short"}}diff --git a/products/query_performance_ai/ruff.toml b/products/query_performance_ai/ruff.tomlnew file mode 100644index 000000000000..c8e267b29c78--- /dev/null+++ b/products/query_performance_ai/ruff.toml@@ -0,0 +1,15 @@+extend = "../ruff.toml"++[lint.extend-per-file-ignores]+# Pi plugin and in-sandbox driver scripts use stdout as their orchestration+# protocol (pi-autoresearch's `METRIC name=value` parse format, the campaign+# init's human-readable banner, structured log lines for the host-side+# coordinator) so the no-print lint doesn't apply.+"sandboxed_autoresearch_agent/pi_plugin/scripts/**" = ["T201"]+"sandboxed_autoresearch_agent/pi_plugin/templates/workspace/**" = ["T201"]+"sandboxed_autoresearch_agent/driver/run_campaign.py" = ["T201"]++# In-sandbox driver: shell-callable scripts where ANN policing isn't worth+# the noise (overrides Python stdlib base-class signatures without re-typing+# every arg).+"sandboxed_autoresearch_agent/driver/**" = ["ANN"]diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/driver/run_campaign.py b/products/query_performance_ai/sandboxed_autoresearch_agent/driver/run_campaign.pynew file mode 100755index 000000000000..1c1aae3824a0--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/driver/run_campaign.py@@ -0,0 +1,407 @@+#!/usr/bin/env python3+"""In-sandbox driver for one autoresearch campaign.++Reads ``COORDINATOR_URL`` / ``COORDINATOR_TOKEN`` / ``CAMPAIGN_SQL`` /+``CAMPAIGN_QUERY_ID`` from the environment, preflights the coordinator,+locks the network down to the coordinator port, initializes the workspace,+and hands control to ``pi /skill::clickhouse-autoresearch-campaign``.++The coordinator decides whether to capture the baseline up front+(``capture_baseline_in_orchestrator=true``) or hand the agent a+non-pre-initialized workspace and instructions to rewrite the query+first (whenever a backend ships a non-empty ``prompt_addendum``).+"""++from __future__ import annotations++import os+import sys+import json+import shutil+import argparse+import tempfile+import subprocess+import urllib.error+import urllib.parse+import urllib.request+from pathlib import Path++from .runtime import PI_PLUGIN_SCRIPTS_DIR, CampaignError, log, run+from .sandboxing import LockdownFailed, ensure_pi_toolchain, lockdown_network, prepare_pi_runtime++DEFAULT_WORKSPACE = Path("/tmp/autoresearch-campaign")++_ALLOWED_URL_SCHEMES = frozenset({"http", "https"})+++def _require_http_url(url: str) -> None:+ """URLs come from env vars; urllib also speaks ``file://``/``ftp://``."""+ scheme = urllib.parse.urlparse(url).scheme.lower()+ if scheme not in _ALLOWED_URL_SCHEMES:+ raise CampaignError(f"preflight URL scheme {scheme!r} not allowed (must be http/https): {url!r}")+++class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):+ """Sealing the redirect-bypass for `_require_http_url` (e.g. 302 → file://)."""++ def redirect_request(self, req, fp, code, msg, headers, newurl):+ raise urllib.error.HTTPError(req.full_url, code, f"refusing to follow redirect to {newurl!r}", headers, fp)+++_NO_REDIRECT_OPENER = urllib.request.build_opener(_NoRedirectHandler())+++def coordinator_request(+ url: str, token: str, *, method: str, path: str, body: dict | None = None, timeout_s: int = 15+) -> dict:+ endpoint = url.rstrip("/") + path+ _require_http_url(endpoint)+ data = json.dumps(body).encode("utf-8") if body is not None else None+ req = urllib.request.Request(+ endpoint,+ data=data,+ method=method,+ headers={+ "Authorization": f"Bearer {token}",+ **({"Content-Type": "application/json"} if data else {}),+ },+ )+ try:+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected+ with _NO_REDIRECT_OPENER.open(req, timeout=timeout_s) as resp: # noqa: S310+ raw = resp.read().decode("utf-8")+ except urllib.error.HTTPError as e:+ detail = e.read().decode("utf-8", "replace")[:500]+ raise CampaignError(f"coordinator {method} {path} → {e.code}: {detail}") from e+ except urllib.error.URLError as e:+ raise CampaignError(f"coordinator unreachable at {endpoint}: {e}") from e++ try:+ return json.loads(raw)+ except json.JSONDecodeError as e:+ raise CampaignError(f"coordinator returned non-JSON: {raw[:300]!r}") from e+++def preflight_coordinator(url: str, token: str) -> dict:+ """Confirm the coordinator answers `/v1/info` and can run a trivial SELECT.++ Returns the parsed `/v1/info` payload — `target`, `prompt_addendum`,+ `primary_metric`, `capture_baseline_in_orchestrator` — so callers can+ branch on them.+ """+ info = coordinator_request(url, token, method="GET", path="/v1/info")+ log(f"coordinator info: target={info.get('target')} primary_metric={info.get('primary_metric')}")+ select_one = coordinator_request(url, token, method="POST", path="/v1/run", body={"sql": "SELECT 1"}, timeout_s=30)+ log(f"coordinator preflight OK: SELECT 1 returned in {select_one.get('elapsed_ms')}ms")+ return info+++def init_campaign(workspace: Path, query_file: Path, *, query_id: str) -> None:+ log(f"initializing campaign at {workspace} (query_id={query_id})")+ run(+ [+ sys.executable,+ str(PI_PLUGIN_SCRIPTS_DIR / "ch_campaign_init.py"),+ "--workspace",+ str(workspace),+ "--query-id",+ query_id,+ "--query-file",+ str(query_file),+ "--branch-name",+ f"autoresearch/{query_id}",+ ]+ )+++def write_adapter_json(workspace: Path, *, coordinator_url: str, token: str) -> None:+ (workspace / "adapter.json").write_text(+ json.dumps(+ {+ "type": "coordinator",+ "url": coordinator_url,+ "token": token,+ },+ indent=2,+ )+ + "\n"+ )+ log(f"wrote adapter.json targeting {coordinator_url}")+++def append_prompt_addendum(workspace: Path, addendum: str) -> None:+ """Inject the coordinator's prompt_addendum into autoresearch.md.++ pi-coding-agent reads autoresearch.md as durable per-campaign notes, and+ the SKILL.md tells it to read the file as part of setup. Putting the+ addendum at the top is the cheapest way to make sure it's seen before+ any baseline-related decision.+ """+ md_path = workspace / "autoresearch.md"+ if not md_path.is_file():+ log(f"WARNING: autoresearch.md missing at {md_path}; addendum dropped")+ return+ existing = md_path.read_text()+ md_path.write_text(addendum.rstrip() + "\n\n" + existing)+ log(f"prepended {len(addendum)}-byte prompt addendum to autoresearch.md")+++def capture_baseline(workspace: Path) -> None:+ log("capturing baseline through the coordinator")+ run(+ [+ sys.executable,+ str(PI_PLUGIN_SCRIPTS_DIR / "ch_capture_baseline.py"),+ "--workspace",+ str(workspace),+ ]+ )+ if not (workspace / "baseline" / "result.jsonl").exists():+ raise CampaignError("baseline capture left no result.jsonl behind")+++def run_pi_campaign(workspace: Path) -> None:+ cwd = workspace.parent+ config_path = cwd / "autoresearch.config.json"+ if not config_path.is_file():+ raise CampaignError(f"missing {config_path}; campaign init must run first")++ anthropic_base = os.environ.get("ANTHROPIC_BASE_URL", "<unset>")+ anthropic_key = os.environ.get("ANTHROPIC_API_KEY") or ""+ anthropic_key_state = "set" if anthropic_key else "<unset>"+ log(f"pi env: ANTHROPIC_BASE_URL={anthropic_base}")+ log(f"pi env: ANTHROPIC_API_KEY={anthropic_key_state}")++ log(f"invoking pi campaign (cwd={cwd}, --mode json for live event stream)")+ cmd = ["pi", "--mode", "json", "/skill::clickhouse-autoresearch-campaign"]+ log("$ " + " ".join(cmd) + f" (cwd={cwd})")+ _run_pi_with_streaming_events(cmd, cwd)+++def _run_pi_with_streaming_events(cmd: list[str], cwd: Path) -> None:+ process = subprocess.Popen(+ cmd,+ cwd=str(cwd),+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ bufsize=1,+ text=True,+ )+ if process.stdout is None:+ raise CampaignError("pi process has no stdout — Popen was misconfigured")+ try:+ for raw in process.stdout:+ _print_pi_event(raw.rstrip("\n"))+ finally:+ exit_code = process.wait()+ if exit_code != 0:+ raise CampaignError(f"pi exited with {exit_code}")+++def _print_pi_event(line: str) -> None:+ """Emit only on terminal events — deltas and ``*_start`` duplicate ``*_end``."""+ if not line:+ return+ try:+ event = json.loads(line)+ except json.JSONDecodeError:+ print(line, flush=True) # noqa: T201+ return+ if not isinstance(event, dict):+ print(f"[pi] {line[:500]}", flush=True) # noqa: T201+ return++ kind = event.get("type", "event")++ if kind in (+ "agent_start",+ "agent_end",+ "turn_start",+ "turn_end",+ "tool_execution_start",+ "tool_execution_update",+ ):+ return++ if kind == "session":+ print(f"[pi:session] id={str(event.get('id', ''))[:8]}", flush=True) # noqa: T201+ return++ if kind == "message_start":+ msg = event.get("message") or {}+ if msg.get("role") == "assistant":+ model = msg.get("model") or "?"+ print(f"[pi:turn] model={model}", flush=True) # noqa: T201+ return++ if kind == "message_end":+ msg = event.get("message") or {}+ if msg.get("role") != "assistant":+ return+ usage = msg.get("usage") or {}+ bits = []+ if tokens := usage.get("totalTokens"):+ bits.append(f"tokens={tokens}")+ cost = (usage.get("cost") or {}).get("total")+ if isinstance(cost, int | float) and cost > 0:+ bits.append(f"cost=${cost:.4f}")+ print("[pi:turn_end] " + " ".join(bits), flush=True) # noqa: T201+ return++ if kind == "message_update":+ sub = event.get("assistantMessageEvent") or {}+ sub_type = sub.get("type", "")+ if sub_type == "thinking_end":+ content = sub.get("content") or ""+ print(f"[pi:thinking] {content[:800]}", flush=True) # noqa: T201+ return+ if sub_type == "text_end":+ content = sub.get("content") or ""+ print(f"[pi:text] {content[:800]}", flush=True) # noqa: T201+ return+ if sub_type == "toolcall_end":+ tc = sub.get("toolCall") or {}+ name = tc.get("name", "?")+ args = tc.get("arguments") or {}+ args_str = json.dumps(args, separators=(",", ":"))[:500]+ print(f"[pi:tool] {name}({args_str})", flush=True) # noqa: T201+ return+ return++ if kind == "tool_execution_end":+ name = event.get("toolName", "?")+ result = event.get("result") or {}+ content = result.get("content") or []+ preview = ""+ if isinstance(content, list):+ for item in content:+ if isinstance(item, dict) and isinstance(item.get("text"), str):+ preview = item["text"]+ break+ preview = preview.replace("\n", " ⏎ ")[:300]+ print(f"[pi:result] {name} -> {preview}", flush=True) # noqa: T201+ return++ print(f"[pi:{kind}] {json.dumps(event, separators=(',', ':'))[:500]}", flush=True) # noqa: T201+++def parse_args(argv: list[str]) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument(+ "--coordinator-url",+ default=os.environ.get("COORDINATOR_URL", ""),+ help="Base URL of the coordinator HTTP server (env: COORDINATOR_URL)",+ )+ parser.add_argument(+ "--coordinator-token",+ default=os.environ.get("COORDINATOR_TOKEN", ""),+ help="Random per-coordinator-run token (env: COORDINATOR_TOKEN)",+ )+ parser.add_argument(+ "--workspace",+ type=Path,+ default=Path(os.environ.get("WORKSPACE") or DEFAULT_WORKSPACE),+ help="Campaign workspace path (default: /tmp/autoresearch-campaign)",+ )+ parser.add_argument(+ "--sql",+ default=os.environ.get("CAMPAIGN_SQL"),+ help="Inline SQL for the campaign. Mutually exclusive with --sql-file. "+ "Defaults to a SELECT 1 smoke test when neither is provided.",+ )+ parser.add_argument(+ "--sql-file",+ type=Path,+ default=Path(os.environ["CAMPAIGN_SQL_FILE"]) if os.environ.get("CAMPAIGN_SQL_FILE") else None,+ help="Path to a file containing the SQL for the campaign.",+ )+ parser.add_argument(+ "--query-id",+ default=os.environ.get("CAMPAIGN_QUERY_ID", "smoke-select-one"),+ help='Campaign identifier (stored in campaign.json). Default: "smoke-select-one".',+ )+ return parser.parse_args(argv)+++def _resolve_sql_file(args: argparse.Namespace) -> tuple[Path, bool]:+ if args.sql_file is not None:+ if args.sql is not None:+ raise CampaignError("--sql and --sql-file are mutually exclusive")+ if not args.sql_file.is_file():+ raise CampaignError(f"--sql-file does not exist: {args.sql_file}")+ return args.sql_file, False++ sql_text = args.sql if args.sql is not None else "SELECT 1"+ if not sql_text.endswith("\n"):+ sql_text += "\n"+ with tempfile.NamedTemporaryFile("w", suffix=".sql", delete=False) as tmp:+ tmp.write(sql_text)+ return Path(tmp.name), True+++def main() -> int:+ args = parse_args(sys.argv[1:])+ if not args.coordinator_url:+ raise CampaignError("--coordinator-url (or COORDINATOR_URL) is required")+ if not args.coordinator_token:+ raise CampaignError("--coordinator-token (or COORDINATOR_TOKEN) is required")++ try:+ info = preflight_coordinator(args.coordinator_url, args.coordinator_token)++ # Lock down the network *before* the toolchain installs and *before*+ # any code that consumes secrets runs. On PI_BASE the toolchain is+ # pre-baked so this ordering costs nothing; on DEFAULT_BASE the+ # install would fail behind the lockdown — which is the right+ # failure mode (we should be running on PI_BASE).+ #+ # Lockdown failure is always fatal: the whole point of running pi+ # in a sandbox is that its egress is restricted to the coordinator,+ # so without the lockdown there's no point continuing.+ try:+ lockdown_network(args.coordinator_url)+ except LockdownFailed as e:+ raise CampaignError(f"network lockdown failed; refusing to run pi without it: {e}") from e++ ensure_pi_toolchain()+ prepare_pi_runtime()++ log(f"resetting workspace {args.workspace}")+ if args.workspace.exists():+ shutil.rmtree(args.workspace)++ query_file, is_temp = _resolve_sql_file(args)+ try:+ init_campaign(args.workspace, query_file, query_id=args.query_id)+ finally:+ if is_temp:+ query_file.unlink(missing_ok=True)++ write_adapter_json(+ args.workspace,+ coordinator_url=args.coordinator_url,+ token=args.coordinator_token,+ )++ addendum = info.get("prompt_addendum") or ""+ if addendum.strip():+ append_prompt_addendum(args.workspace, addendum)++ if info.get("capture_baseline_in_orchestrator", True):+ capture_baseline(args.workspace)+ else:+ log(+ "coordinator says capture_baseline_in_orchestrator=false; "+ "the agent will rewrite the query and capture the baseline itself"+ )++ run_pi_campaign(args.workspace)+ log("campaign completed")+ return 0+ except CampaignError as e:+ log(f"FAILED: {e}")+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/driver/runtime.py b/products/query_performance_ai/sandboxed_autoresearch_agent/driver/runtime.pynew file mode 100644index 000000000000..651434d2b4fe--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/driver/runtime.py@@ -0,0 +1,40 @@+"""Shared utilities for the in-sandbox campaign driver.++Used by `run_campaign.py` and `sandboxing.py`. Kept tiny — only the small+helpers and path constants that both files need. Anything campaign-flow+or sandbox-specific lives in its own module.+"""++from __future__ import annotations++import os+import sys+import subprocess+from pathlib import Path++SANDBOXED_AGENT_DIR = Path(__file__).resolve().parent.parent+PI_PLUGIN_DIR = SANDBOXED_AGENT_DIR / "pi_plugin"+PI_PLUGIN_SCRIPTS_DIR = PI_PLUGIN_DIR / "scripts"+++class CampaignError(RuntimeError):+ pass+++def log(msg: str) -> None:+ print(f"[campaign] {msg}", file=sys.stderr, flush=True) # noqa: T201+++def atomic_write(path: Path, contents: str) -> None:+ """Temp-file + rename: a SIGKILL mid-write leaves the original intact."""+ tmp = path.with_suffix(path.suffix + ".tmp")+ tmp.write_text(contents)+ os.replace(tmp, path)+++def run(cmd: list[str], *, cwd: Path | None = None) -> subprocess.CompletedProcess[str]:+ log("$ " + " ".join(cmd) + (f" (cwd={cwd})" if cwd else ""))+ result = subprocess.run(cmd, check=False, text=True, cwd=cwd) # noqa: S603 — fixed argv from caller+ if result.returncode != 0:+ raise CampaignError(f"command failed with exit {result.returncode}: {' '.join(cmd)}")+ return resultdiff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/driver/sandboxing.py b/products/query_performance_ai/sandboxed_autoresearch_agent/driver/sandboxing.pynew file mode 100644index 000000000000..601b6b09177b--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/driver/sandboxing.py@@ -0,0 +1,336 @@+"""In-sandbox setup: lockdown + pi-coding-agent toolchain provisioning.++Three concerns:++1. ``lockdown_network`` installs an iptables OUTPUT-DROP rule set that+ leaves only a narrow whitelist (loopback, the coordinator port at the+ Docker gateway, the Anthropic API host, and DNS to the configured+ resolvers). pi-coding-agent runs after this, so its egress is fully+ bounded.+2. ``ensure_pi_toolchain`` requires the PI_BASE image's pre-baked+ layout — ``pi`` on PATH and the extension at the expected location.+ Anything else fails fast: lockdown has already cut general egress, so+ even if we wanted to fall back to ``npm install`` / ``git clone`` we+ couldn't reach the registries, and we never want to run unpinned+ third-party code anyway.+3. ``prepare_pi_runtime`` patches the baked pi-ai bundle so it points+ at our ``ANTHROPIC_BASE_URL`` (when set) and patches pi-autoresearch's+ ``index.ts`` to preserve the campaign workspace dirs across pi's+ ``git clean -fd``.++The pi-ai gateway patch (`_patch_pi_ai_anthropic_baseurl`) is a no-op+for the production flow today (we forward only ``ANTHROPIC_API_KEY``;+the gateway-token path is intentionally disabled), but is kept so that+a future re-introduction of the LLM gateway can route through it again.+"""++from __future__ import annotations++import os+import json+import shutil+import subprocess+import urllib.parse+from pathlib import Path++from .runtime import PI_PLUGIN_DIR, CampaignError, atomic_write, log, run++# Layout the dedicated PI_BASE image bakes. `ensure_pi_toolchain` requires+# this exact path; the image build (Dockerfile.sandbox-pi) is the only place+# pi-coding-agent and pi-autoresearch are installed, both at their pinned+# versions/commits in the Dockerfile.+BAKED_PI_AUTORESEARCH_EXTENSION = Path("/root/.pi/agent/extensions/pi-autoresearch")+++class LockdownFailed(CampaignError):+ pass+++def _resolve_all(host: str, *, label: str) -> list[str]:+ """Return all IPv4 addresses ``host`` resolves to via ``getent hosts``.++ Raises :class:`LockdownFailed` if resolution fails. We call ``getent``+ rather than Python's resolver so the rule pinning matches what+ container-side connections will actually see.+ """+ try:+ out = subprocess.check_output( # noqa: S603+ ["getent", "ahostsv4", host],+ text=True,+ timeout=5,+ )+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError) as e:+ raise LockdownFailed(f"could not resolve {label} host {host!r}: {e}") from e++ ips: list[str] = []+ for line in out.splitlines():+ parts = line.split()+ if not parts:+ continue+ ip = parts[0]+ if ip not in ips:+ ips.append(ip)+ if not ips:+ raise LockdownFailed(f"{label} host {host!r} resolved to zero addresses")+ return ips+++def _resolv_conf_nameservers(path: str = "/etc/resolv.conf") -> list[str]:+ """Read ``nameserver`` IPs from ``/etc/resolv.conf``.++ Falls back to Docker's embedded resolver (``127.0.0.11``) if no entries+ are found, so the lockdown still produces a reachable DNS path on a+ misconfigured container instead of dropping all DNS.+ """+ ips: list[str] = []+ try:+ with open(path) as f:+ for raw in f:+ line = raw.strip()+ if not line or line.startswith("#"):+ continue+ parts = line.split()+ if len(parts) >= 2 and parts[0] == "nameserver" and parts[1] not in ips:+ ips.append(parts[1])+ except OSError:+ pass+ if not ips:+ ips.append("127.0.0.11")+ return ips+++def lockdown_network(coordinator_url: str) -> None:+ """iptables OUTPUT-DROP except: loopback, the coordinator port at the+ gateway IP, and HTTPS to the Anthropic API (so pi-coding-agent can+ reach the LLM).++ Requires NET_ADMIN, `iptables` on PATH, and DNS resolution for+ ``host.docker.internal`` plus the Anthropic API host. Raises+ :class:`LockdownFailed` on any precondition failure or rule error.++ The Anthropic host is taken from ``ANTHROPIC_BASE_URL`` if set, else+ defaults to ``api.anthropic.com``. We resolve and pin its current+ IPs at lockdown time; if Anthropic rotates IPs during the campaign,+ new connections will fail with a clean network error rather than+ silently hanging.+ """+ parsed = urllib.parse.urlparse(coordinator_url)+ port = parsed.port+ if not port:+ raise LockdownFailed(+ f"coordinator URL has no explicit port: {coordinator_url!r} — refusing to lock down without a target"+ )+ # `host.docker.internal` resolves to the gateway via `--add-host`; resolve+ # it once so the rule pins the IP rather than depending on DNS later.+ gateway_ip = _resolve_all(parsed.hostname or "host.docker.internal", label="coordinator")[0]++ anthropic_base = os.environ.get("ANTHROPIC_BASE_URL", "").strip() or "https://api.anthropic.com"+ anthropic_parsed = urllib.parse.urlparse(anthropic_base)+ anthropic_host = anthropic_parsed.hostname+ if not anthropic_host:+ raise LockdownFailed(f"ANTHROPIC_BASE_URL has no host: {anthropic_base!r}")+ anthropic_port = anthropic_parsed.port or (443 if anthropic_parsed.scheme == "https" else 80)+ anthropic_ips = _resolve_all(anthropic_host, label="anthropic")++ # Allow rules go in OUTPUT slot 1..N (insertions push earlier ones down).+ allow_rules: list[list[str]] = []+ allow_rules.append(["-o", "lo", "-j", "ACCEPT"])+ allow_rules.append(["-m", "state", "--state", "ESTABLISHED,RELATED", "-j", "ACCEPT"])+ # Outbound DNS, pinned to the resolvers in /etc/resolv.conf (typically+ # Docker's embedded 127.0.0.11 plus whatever forwarders the daemon was+ # given). Without this pin, an unrestricted UDP/53 rule lets a process+ # DNS-tunnel data (e.g. ANTHROPIC_API_KEY) by encoding it as subdomains+ # toward an attacker-controlled resolver.+ for ip in _resolv_conf_nameservers():+ allow_rules.append(["-d", ip, "-p", "udp", "--dport", "53", "-j", "ACCEPT"])+ allow_rules.append(["-d", gateway_ip, "-p", "tcp", "--dport", str(port), "-j", "ACCEPT"])+ for ip in anthropic_ips:+ allow_rules.append(["-d", ip, "-p", "tcp", "--dport", str(anthropic_port), "-j", "ACCEPT"])++ # Apply DROP first so any partial-rule failure leaves the chain in the+ # safer "everything blocked" state rather than fail-open. In practice+ # any ``LockdownFailed`` here also kills this driver process — the+ # sandbox PID 1 exits, the container terminates, and the coordinator+ # destroys it — so the half-locked window is sub-second and pi never+ # gets to run. The ordering is defense-in-depth, not load-bearing.+ rules: list[list[str]] = [["iptables", "-P", "OUTPUT", "DROP"]]+ rules.extend(["iptables", "-I", "OUTPUT", "1", *r] for r in allow_rules)++ for argv in rules:+ try:+ subprocess.run(argv, check=True, text=True, capture_output=True, timeout=5) # noqa: S603+ except FileNotFoundError as e:+ raise LockdownFailed("iptables binary missing in sandbox image") from e+ except subprocess.CalledProcessError as e:+ stderr = (e.stderr or "").strip()+ if "Operation not permitted" in stderr or "Permission denied" in stderr:+ raise LockdownFailed("iptables refused (NET_ADMIN not granted to this sandbox)") from e+ raise LockdownFailed(f"iptables rule failed ({argv[-1]}): {stderr}") from e++ # Drop IPv6 outbound entirely. Anthropic publishes AAAA records and+ # Node's HTTP client will prefer IPv6 if the resolver returns one; if+ # IPv6 routing in the container is broken (Docker default networks+ # disable IPv6) the connect fails fast and the agent reports+ # "Connection error" without falling back to IPv4. Forcing v6 to drop+ # via ip6tables makes happy-eyeballs fall through to v4 cleanly. We+ # don't whitelist any v6 destinations because our v4 whitelist is+ # already enough for pi to function.+ #+ # Failures here are fatal for the same reason iptables failures are:+ # if we can't lock v6 down, pi could exfil over v6 outside the v4+ # allowlist. PI_BASE bakes ``ip6tables`` so neither the missing-binary+ # nor the missing-NET_ADMIN branch should fire in practice; if either+ # does, the sandbox is broken and we want to know loudly.+ try:+ subprocess.run( # noqa: S603+ ["ip6tables", "-P", "OUTPUT", "DROP"], check=True, text=True, capture_output=True, timeout=5+ )+ except FileNotFoundError as e:+ raise LockdownFailed("ip6tables binary missing in sandbox image") from e+ except subprocess.CalledProcessError as e:+ stderr = (e.stderr or "").strip()+ if "Operation not permitted" in stderr or "Permission denied" in stderr:+ raise LockdownFailed("ip6tables refused (NET_ADMIN not granted to this sandbox)") from e+ raise LockdownFailed(f"ip6tables OUTPUT DROP failed: {stderr}") from e++ anthropic_ip_summary = ",".join(anthropic_ips)+ log(+ f"network locked down: coordinator {gateway_ip}:{port} + "+ f"{anthropic_host}:{anthropic_port} ([{anthropic_ip_summary}])"+ )++ # Diagnostic: prove the lockdown didn't accidentally break LLM access.+ # `curl -m 5` against the Anthropic API root will 401/404 (no API key in+ # the curl) but a non-zero TCP connection means the rules are right.+ try:+ diag = subprocess.run( # noqa: S603+ [+ "curl",+ "-sS",+ "-o",+ "/dev/null",+ "-w",+ "%{http_code} %{time_total}s",+ "-m",+ "5",+ f"https://{anthropic_host}/v1/models",+ ],+ text=True,+ capture_output=True,+ timeout=10,+ )+ log(+ f"lockdown diagnostic: curl https://{anthropic_host}/v1/models → {diag.stdout.strip()} (rc={diag.returncode})"+ )+ if diag.returncode != 0:+ log(f"lockdown diagnostic stderr: {(diag.stderr or '').strip()[:500]}")+ except (FileNotFoundError, subprocess.TimeoutExpired) as e:+ log(f"lockdown diagnostic skipped: {e}")+++def ensure_pi_toolchain() -> None:+ """Require the pre-baked pi toolchain — fail fast if missing.++ PI_BASE (Dockerfile.sandbox-pi) is the only supported sandbox image+ for autoresearch; it bakes ``pi-coding-agent`` at a pinned version+ and ``pi-autoresearch`` at a pinned commit. We refuse to fall back+ to ``npm install`` / ``git clone`` because (a) lockdown has already+ cut general egress so it wouldn't work anyway, and (b) installing+ unpinned third-party code from inside a network-isolated sandbox is+ a pattern we explicitly never want.+ """+ pi_path = shutil.which("pi")+ if pi_path is None:+ raise CampaignError(+ "pi-coding-agent binary not found on PATH — sandbox image is wrong "+ "(expected PI_BASE / Dockerfile.sandbox-pi). Refusing to bootstrap "+ "an unpinned install at runtime."+ )+ if not BAKED_PI_AUTORESEARCH_EXTENSION.is_dir():+ raise CampaignError(+ f"pi-autoresearch extension not found at {BAKED_PI_AUTORESEARCH_EXTENSION} "+ "— sandbox image is wrong (expected PI_BASE / Dockerfile.sandbox-pi). "+ "Refusing to clone the upstream repo at runtime."+ )+ log(f"pi toolchain pre-installed (pi @ {pi_path}, extension at {BAKED_PI_AUTORESEARCH_EXTENSION})")+++def prepare_pi_runtime() -> None:+ """Patch baked pi-ai / pi-autoresearch state and install the in-repo plugin."""+ _patch_pi_ai_anthropic_baseurl()+ _patch_pi_autoresearch_index_ts()++ plugin_dir = Path.home() / ".pi/packages/pi-clickhouse-autoresearch"+ if not plugin_dir.is_dir():+ log("installing local pi-clickhouse-autoresearch plugin")+ run(["pi", "install", str(PI_PLUGIN_DIR)])+ else:+ log("pi-clickhouse-autoresearch already installed")+++def _patch_pi_autoresearch_index_ts() -> None:+ index_ts = BAKED_PI_AUTORESEARCH_EXTENSION / "index.ts"+ if not index_ts.is_file():+ raise CampaignError(f"pi-autoresearch index.ts not found at {index_ts} — image is broken")+ preserve = " ".join(+ f"-e {name}"+ for name in (+ "runs lanes hypotheses reviews baseline runtime state.json "+ "campaign.json adapter.json out-of-scope-suggestions.md"+ ).split()+ )+ pre_marker = "git clean -fd 2>/dev/null"+ post_marker = f"git clean -fd {preserve} 2>/dev/null"++ contents = index_ts.read_text()+ pre_count = contents.count(pre_marker)+ if pre_count > 0:+ if pre_count != 1:+ raise CampaignError(+ f"pi-autoresearch {index_ts.name}: expected exactly 1 `{pre_marker}` "+ f"occurrence, got {pre_count} — patch needs updating"+ )+ atomic_write(index_ts, contents.replace(pre_marker, post_marker))+ log(f"patched {index_ts.name} to preserve workspace dirs")+ elif post_marker in contents:+ pass+ else:+ raise CampaignError(+ f"pi-autoresearch {index_ts.name}: neither the pre- nor post-patch marker is "+ f"present — upstream shape changed, workspace-preservation patch needs updating"+ )+++def _patch_pi_ai_anthropic_baseurl() -> None:+ gateway_base = os.environ.get("ANTHROPIC_BASE_URL", "").rstrip("/")+ if not gateway_base:+ return++ candidates = [+ Path(+ "/usr/lib/node_modules/@mariozechner/pi-coding-agent/node_modules/@mariozechner/pi-ai/dist/models.generated.js"+ ),+ Path(+ "/usr/local/lib/node_modules/@mariozechner/pi-coding-agent/node_modules/@mariozechner/pi-ai/dist/models.generated.js"+ ),+ ]+ models_file = next((p for p in candidates if p.is_file()), None)+ if models_file is None:+ raise CampaignError("pi-ai models.generated.js not found in any known location — image is broken")++ contents = models_file.read_text()+ marker = '"https://api.anthropic.com"'+ occurrences = contents.count(marker)+ if occurrences == 0:+ if gateway_base in contents:+ log(f"pi-ai models.generated.js already points at {gateway_base}")+ return+ raise CampaignError(+ "pi-ai models.generated.js: neither the Anthropic baseUrl marker nor our gateway URL "+ "is present — pi-ai's bundle shape changed, baseUrl patch needs updating"+ )++ replacement = json.dumps(gateway_base)+ patched = contents.replace(marker, replacement)+ atomic_write(models_file, patched)+ log(f"patched pi-ai models.generated.js: rewrote {occurrences} Anthropic baseUrl occurrence(s) to {replacement}")diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/package.json b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/package.jsonnew file mode 100644index 000000000000..0885460200f2--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/package.json@@ -0,0 +1,20 @@+{+ "name": "pi-clickhouse-autoresearch",+ "version": "0.1.0",+ "description": "Reusable ClickHouse query optimization orchestration for pi-autoresearch.",+ "keywords": [+ "autoresearch",+ "clickhouse",+ "pi-package"+ ],+ "license": "MIT",+ "type": "module",+ "pi": {+ "skills": [+ "./skills"+ ],+ "prompts": [+ "./prompts"+ ]+ }+}diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/prompts/campaign-review.md b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/prompts/campaign-review.mdnew file mode 100644index 000000000000..0e3a9320a9d1--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/prompts/campaign-review.md@@ -0,0 +1,23 @@+---+description: Review the full ClickHouse campaign for continuation, pivot, or closure+---++Review the full ClickHouse campaign.++Read:++- `.clickhouse-autoresearch/state.json`+- `.clickhouse-autoresearch/autoresearch.md`+- `.clickhouse-autoresearch/lanes/`+- `.clickhouse-autoresearch/hypotheses/`+- `.clickhouse-autoresearch/reviews/`+- recent artifacts in `.clickhouse-autoresearch/runs/`++Answer:++- current best kept result+- active, paused, repair, and exhausted lanes+- whether recent iterations produced significant improvement+- whether recent reflection produced meaningful new hypotheses or lanes+- whether the campaign should continue, continue with narrowed scope, pivot to integration or repair, or close+- a concise justification for the recommendationdiff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/prompts/lane-review.md b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/prompts/lane-review.mdnew file mode 100644index 000000000000..e676c4529885--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/prompts/lane-review.md@@ -0,0 +1,22 @@+---+description: Review one ClickHouse optimization lane for stagnation, exhaustion, split, merge, or continuation+---++Review the ClickHouse campaign lane `${1}`.++Read:++- `.clickhouse-autoresearch/state.json`+- `.clickhouse-autoresearch/autoresearch.md`+- `.clickhouse-autoresearch/lanes/`+- `.clickhouse-autoresearch/hypotheses/`+- recent run artifacts in `.clickhouse-autoresearch/runs/`++Answer:++- what this lane believed+- which hypotheses in this lane were validated+- which were invalidated+- whether the lane is still producing significant improvement or meaningful new hypotheses+- whether the lane should continue, narrow, split, merge, pause, or close+- whether the lane suggests an integration hypothesis with another lanediff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/prompts/next-experiment.md b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/prompts/next-experiment.mdnew file mode 100644index 000000000000..59779a416049--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/prompts/next-experiment.md@@ -0,0 +1,17 @@+---+description: Choose the next ClickHouse experiment from the current campaign state+---++Read `.clickhouse-autoresearch/state.json`, `.clickhouse-autoresearch/autoresearch.md`, `.clickhouse-autoresearch/out-of-scope-suggestions.md`, and the latest artifacts in `.clickhouse-autoresearch/runs/` and `.clickhouse-autoresearch/runtime/`.++Then decide the next experiment for the campaign.++Required output:++- active lane+- chosen hypothesis+- concise rationale+- expected metric movement+- semantic risk+- whether this is a normal, integration, or repair hypothesis+- what files should be edited before the next benchmarkdiff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/_common.py b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/_common.pynew file mode 100644index 000000000000..cca32f0411b4--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/_common.py@@ -0,0 +1,153 @@+"""Shared helpers for the autoresearch campaign scripts."""++from __future__ import annotations++import re+import sys+import json+from dataclasses import dataclass+from pathlib import Path+from typing import Any++sys.path.insert(0, str(Path(__file__).resolve().parent))+from transports import CoordinatorTransport, TransportError, load_transport # noqa: E402+++class AutoresearchError(RuntimeError):+ pass+++def info(msg: str) -> None:+ print(f"info: {msg}", file=sys.stderr, flush=True)+++def require_file(path: Path) -> Path:+ if not path.is_file():+ raise AutoresearchError(f"missing file: {path}")+ return path+++def require_dir(path: Path) -> Path:+ if not path.is_dir():+ raise AutoresearchError(f"missing directory: {path}")+ return path+++@dataclass(frozen=True)+class AdapterConfig:+ raw: dict[str, Any]++ @classmethod+ def load(cls, workspace: Path) -> AdapterConfig:+ path = workspace / "adapter.json"+ require_file(path)+ try:+ raw = json.loads(path.read_text())+ except json.JSONDecodeError as e:+ raise AutoresearchError(f"adapter.json is not valid JSON: {e}") from e+ if not isinstance(raw, dict):+ raise AutoresearchError("adapter.json must be an object at the top level")+ return cls(raw=raw)++ def transport(self) -> CoordinatorTransport:+ try:+ return load_transport(self.raw)+ except ValueError as e:+ raise AutoresearchError(str(e)) from e+++def execute_query(+ transport: CoordinatorTransport,+ sql_file: Path,+ *,+ result_file: Path,+ metrics_file: Path,+ stdout_file: Path,+ primary_metric: str = "latency_ms",+ # Above the proxy's max_execution_time=300 so overruns surface as CH+ # errors, not client-side socket timeouts that leave the query running.+ timeout_s: int = 310,+) -> None:+ require_file(sql_file)+ sql = sql_file.read_text()++ result_file.parent.mkdir(parents=True, exist_ok=True)+ metrics_file.parent.mkdir(parents=True, exist_ok=True)+ stdout_file.parent.mkdir(parents=True, exist_ok=True)++ try:+ result = transport.run(sql, timeout_s=timeout_s)+ except TransportError as e:+ stdout_file.write_text(e.stdout + f"\n{e}\n")+ raise AutoresearchError(f"transport failed: {e}") from e++ result_file.write_bytes(result.result_bytes)+ stdout_file.write_text(result.stdout + "\n")++ secondary: dict[str, int | float] = {}+ if result.rows_read is not None:+ secondary["rows_read"] = result.rows_read+ if result.bytes_read is not None:+ secondary["bytes_read"] = result.bytes_read++ payload: dict[str, Any] = {+ "primary": {+ "name": primary_metric,+ "value": round(result.elapsed_ms, 3),+ "unit": "ms",+ },+ "secondary": secondary,+ }+ if result.query_id is not None:+ payload["query_id"] = result.query_id+ metrics_file.write_text(json.dumps(payload, indent=2) + "\n")+++def emit_metrics_from_json(metrics_file: Path) -> None:+ """`METRIC name=value` lines are pi-autoresearch's parse format."""+ data = json.loads(metrics_file.read_text())+ primary = data.get("primary") or {}+ name = primary.get("name")+ value = primary.get("value")+ if isinstance(name, str) and isinstance(value, int | float):+ print(f"METRIC {name}={value}")+ for key, val in (data.get("secondary") or {}).items():+ if isinstance(val, int | float):+ print(f"METRIC {key}={val}")+++def next_run_id(workspace: Path) -> str:+ runs_dir = workspace / "runs"+ max_seen = 0+ if runs_dir.is_dir():+ for entry in runs_dir.iterdir():+ if not entry.is_dir():+ continue+ match = re.match(r"run-(\d{4})", entry.name)+ if match:+ max_seen = max(max_seen, int(match.group(1)))+ return f"run-{max_seen + 1:04d}"+++def write_last_run_json(+ output_file: Path,+ *,+ kind: str,+ run_id: str,+ label: str,+ run_dir: Path,+ result_file: Path | str,+ metrics_file: Path | str,+ comparison_file: Path | str,+) -> None:+ output_file.parent.mkdir(parents=True, exist_ok=True)+ payload = {+ "kind": kind,+ "run_id": run_id,+ "label": label,+ "run_dir": str(run_dir),+ "result_file": str(result_file),+ "metrics_file": str(metrics_file),+ "comparison_file": str(comparison_file),+ }+ output_file.write_text(json.dumps(payload, indent=2) + "\n")diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/ch_campaign_init.py b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/ch_campaign_init.pynew file mode 100644index 000000000000..6db1bc7763cd--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/ch_campaign_init.py@@ -0,0 +1,167 @@+#!/usr/bin/env python3+"""Initialize a new autoresearch campaign workspace.++Port of the former ``ch_campaign_init.sh``. Creates the workspace directory+layout, renders campaign metadata and the wrapper scripts, and seeds the+query files if a source SQL file is provided.+"""++from __future__ import annotations++import sys+import json+import shutil+import argparse+import subprocess+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _common import AutoresearchError, info # noqa: E402++PACKAGE_ROOT = Path(__file__).resolve().parent.parent+++def _current_branch() -> str:+ try:+ result = subprocess.run( # noqa: S603 — fixed argv+ ["git", "branch", "--show-current"],+ check=False,+ text=True,+ capture_output=True,+ )+ except FileNotFoundError:+ return ""+ if result.returncode != 0:+ return ""+ return result.stdout.strip()+++def _render_file(path: Path, values: dict[str, str]) -> None:+ """Replace ``__KEY__`` tokens with values in-place."""+ content = path.read_text()+ for key, value in values.items():+ content = content.replace(f"__{key}__", value)+ path.write_text(content)+++def parse_args(argv: list[str]) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--workspace", required=True, type=Path)+ parser.add_argument("--query-id", required=True)+ parser.add_argument("--query-file", type=Path)+ parser.add_argument("--primary-metric", default="latency_ms")+ parser.add_argument("--metric-unit", default="ms")+ parser.add_argument("--direction", choices=("lower", "higher"), default="lower")+ parser.add_argument("--branch-name")+ parser.add_argument("--lane-stagnation-window", type=int, default=4)+ parser.add_argument("--campaign-stagnation-window", type=int, default=8)+ parser.add_argument("--max-total-iterations", type=int, default=30)+ parser.add_argument("--significant-improvement-pct", type=float, default=3)+ parser.add_argument("--repair-budget", type=int, default=2)+ return parser.parse_args(argv)+++def main(argv: list[str] | None = None) -> int:+ args = parse_args(argv if argv is not None else sys.argv[1:])++ branch = args.branch_name or _current_branch()+ if not branch:+ raise AutoresearchError("could not determine git branch; pass --branch-name")++ workspace: Path = args.workspace+ if workspace.exists() and any(workspace.iterdir()):+ raise AutoresearchError(f"workspace already exists and is not empty: {workspace}")++ workspace.mkdir(parents=True, exist_ok=True)+ template_root = PACKAGE_ROOT / "templates" / "workspace"+ for child in template_root.iterdir():+ dest = workspace / child.name+ if child.is_dir():+ shutil.copytree(child, dest, dirs_exist_ok=True)+ else:+ shutil.copy2(child, dest)++ # Rename example files so users see writable ``adapter.json`` /+ # ``campaign.json``. The ``.example`` extension on the templates keeps+ # them off oxfmt's JSON-syntax check while they still hold ``__KEY__``+ # placeholders.+ for example_name, target_name in (+ ("adapter.json.example", "adapter.json"),+ ("campaign.json.example", "campaign.json"),+ ):+ example_path = workspace / example_name+ target_path = workspace / target_name+ if example_path.is_file() and not target_path.is_file():+ example_path.rename(target_path)++ values = {+ "QUERY_ID": args.query_id,+ "BRANCH_NAME": branch,+ "PRIMARY_METRIC": args.primary_metric,+ "METRIC_UNIT": args.metric_unit,+ "DIRECTION": args.direction,+ "SIGNIFICANT_IMPROVEMENT_PCT": str(args.significant_improvement_pct),+ "LANE_STAGNATION_WINDOW": str(args.lane_stagnation_window),+ "CAMPAIGN_STAGNATION_WINDOW": str(args.campaign_stagnation_window),+ "MAX_TOTAL_ITERATIONS": str(args.max_total_iterations),+ "REPAIR_BUDGET": str(args.repair_budget),+ "PACKAGE_ROOT": str(PACKAGE_ROOT),+ "WORKSPACE_ROOT": str(workspace),+ "WORKSPACE_RUNTIME": "./",+ }+ for name in ("campaign.json", "autoresearch.md", "autoresearch.py", "autoresearch_checks.py"):+ target = workspace / name+ if target.is_file():+ _render_file(target, values)++ for name in ("autoresearch.py", "autoresearch_checks.py"):+ target = workspace / name+ if target.is_file():+ target.chmod(0o755)++ if args.query_file is not None:+ src = args.query_file+ if not src.is_file():+ raise AutoresearchError(f"--query-file does not exist: {src}")+ for dst_name in ("original.sql", "current.sql", "best.sql"):+ shutil.copy2(src, workspace / "query" / dst_name)++ # pi-autoresearch expects autoresearch.config.json in the directory it+ # runs from — which in the reference setup is the parent of the workspace.+ # Writing it alongside the workspace keeps that layout and avoids+ # polluting the caller's cwd.+ config_path = workspace.parent / "autoresearch.config.json"+ if not config_path.exists():+ config_path.write_text(+ json.dumps(+ {"workingDir": str(workspace), "maxIterations": args.max_total_iterations},+ indent=2,+ )+ + "\n"+ )+ else:+ info(f"left existing {config_path} untouched")++ print(+ f"""\+Initialized ClickHouse autoresearch workspace.+- workspace: {workspace}+- query_id: {args.query_id}+- branch: {branch}+- package_root: {PACKAGE_ROOT}++Next steps:+1. Fill in {workspace / "adapter.json"}+2. Capture the baseline:+ python3 {PACKAGE_ROOT / "scripts" / "ch_capture_baseline.py"} --workspace {workspace}+"""+ )+ return 0+++if __name__ == "__main__":+ try:+ sys.exit(main())+ except AutoresearchError as err:+ print(f"error: {err}", file=sys.stderr)+ sys.exit(1)diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/ch_capture_baseline.py b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/ch_capture_baseline.pynew file mode 100644index 000000000000..53cd93a2d0ad--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/ch_capture_baseline.py@@ -0,0 +1,79 @@+#!/usr/bin/env python3+"""Capture a baseline run via the workspace's configured transport."""++from __future__ import annotations++import sys+import argparse+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _common import ( # noqa: E402+ AdapterConfig,+ AutoresearchError,+ emit_metrics_from_json,+ execute_query,+ info,+ require_file,+ write_last_run_json,+)+++def parse_args(argv: list[str]) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--workspace", required=True, type=Path)+ return parser.parse_args(argv)+++def main(argv: list[str] | None = None) -> int:+ args = parse_args(argv if argv is not None else sys.argv[1:])++ workspace: Path = args.workspace+ query_file = workspace / "query" / "original.sql"+ baseline_dir = workspace / "baseline"+ result_file = baseline_dir / "result.jsonl"+ metrics_file = baseline_dir / "metrics.json"+ stdout_file = baseline_dir / "stdout.log"+ profile_dir = baseline_dir / "profile"+ last_run = workspace / "runtime" / "last_run.json"++ require_file(query_file)+ profile_dir.mkdir(parents=True, exist_ok=True)+ last_run.parent.mkdir(parents=True, exist_ok=True)++ adapter = AdapterConfig.load(workspace)+ transport = adapter.transport()++ info(f"running baseline: {query_file}")+ execute_query(+ transport,+ query_file,+ result_file=result_file,+ metrics_file=metrics_file,+ stdout_file=stdout_file,+ )++ write_last_run_json(+ last_run,+ kind="baseline",+ run_id="baseline",+ label="",+ run_dir=baseline_dir,+ result_file=result_file,+ metrics_file=metrics_file,+ comparison_file="",+ )++ emit_metrics_from_json(metrics_file)++ rows = len(result_file.read_text().splitlines())+ info(f"baseline captured: {rows} result rows, metrics in {metrics_file}")+ return 0+++if __name__ == "__main__":+ try:+ sys.exit(main())+ except AutoresearchError as err:+ print(f"error: {err}", file=sys.stderr)+ sys.exit(1)diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/ch_compare_results.py b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/ch_compare_results.pynew file mode 100644index 000000000000..c1c241aeb49f--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/ch_compare_results.py@@ -0,0 +1,138 @@+#!/usr/bin/env python3+"""Compare a candidate result set to the saved baseline.++Exit codes: 0 match, 1 mismatch, 2 comparator crashed.+"""++from __future__ import annotations++import sys+import json+import argparse+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _common import AutoresearchError, require_file # noqa: E402+++def parse_args(argv: list[str]) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--workspace", required=True, type=Path)+ parser.add_argument("--candidate-result", type=Path)+ parser.add_argument("--output", type=Path)+ return parser.parse_args(argv)+++def _resolve_candidate(workspace: Path, provided: Path | None) -> Path:+ if provided is not None:+ return provided+ last_run = workspace / "runtime" / "last_run.json"+ require_file(last_run)+ data = json.loads(last_run.read_text())+ candidate = data.get("result_file")+ if not candidate:+ raise AutoresearchError(f"no result_file in {last_run}")+ return Path(candidate)+++def _resolve_output(candidate: Path, provided: Path | None) -> Path:+ if provided is not None:+ return provided+ return candidate.parent / "comparison.json"+++def _normalize_jsonl(text: str) -> list[str]:+ """Reserialize defensively so a future change to the proxy's output+ shape can't silently produce false mismatches. Non-JSON lines are+ kept verbatim so they surface as mismatches, not silent drops."""+ normalized: list[str] = []+ for raw in text.splitlines():+ stripped = raw.strip()+ if not stripped:+ continue+ try:+ parsed = json.loads(stripped)+ except json.JSONDecodeError:+ normalized.append(raw)+ continue+ normalized.append(json.dumps(parsed, separators=(",", ":"), sort_keys=True))+ return normalized+++def main(argv: list[str] | None = None) -> int:+ args = parse_args(argv if argv is not None else sys.argv[1:])++ workspace: Path = args.workspace+ baseline_result = workspace / "baseline" / "result.jsonl"+ require_file(baseline_result)++ candidate_result = _resolve_candidate(workspace, args.candidate_result)+ require_file(candidate_result)++ output_file = _resolve_output(candidate_result, args.output)+ output_file.parent.mkdir(parents=True, exist_ok=True)++ baseline_lines = sorted(_normalize_jsonl(baseline_result.read_text()))+ candidate_lines = sorted(_normalize_jsonl(candidate_result.read_text()))++ rows_baseline = len(baseline_lines)+ rows_candidate = len(candidate_lines)++ if baseline_lines == candidate_lines:+ output_file.write_text(+ json.dumps(+ {+ "matches": True,+ "mode": "sorted-line",+ "summary": "exact match after sorting",+ "details": {"rows_baseline": rows_baseline, "rows_candidate": rows_candidate},+ },+ indent=2,+ )+ + "\n"+ )+ print(f"comparison: match ({rows_candidate} rows)")+ return 0++ # Build a diff sample. Hoist the sets out of the comprehensions so the+ # mismatch path stays O(N) instead of rebuilding the set every iteration.+ baseline_set = set(baseline_lines)+ candidate_set = set(candidate_lines)+ extra_in_candidate = [ln for ln in candidate_lines if ln not in baseline_set][:10]+ missing_in_candidate = [ln for ln in baseline_lines if ln not in candidate_set][:10]+ diff_lines = len(extra_in_candidate) + len(missing_in_candidate)++ output_file.write_text(+ json.dumps(+ {+ "matches": False,+ "mode": "sorted-line",+ "summary": f"{diff_lines} lines differ",+ "details": {+ "rows_baseline": rows_baseline,+ "rows_candidate": rows_candidate,+ "extra_in_candidate": extra_in_candidate,+ "missing_in_candidate": missing_in_candidate,+ },+ },+ indent=2,+ )+ + "\n"+ )+ print(+ f"comparison: MISMATCH ({diff_lines} lines differ, baseline={rows_baseline} candidate={rows_candidate})",+ file=sys.stderr,+ )+ return 1+++if __name__ == "__main__":+ # Crashes must exit 2 — 1 is reserved for "real mismatch."+ try:+ sys.exit(main())+ except AutoresearchError as err:+ print(f"error: {err}", file=sys.stderr)+ sys.exit(2)+ except Exception as err:+ print(f"error: {err!r}", file=sys.stderr)+ sys.exit(2)diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/ch_run_candidate.py b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/ch_run_candidate.pynew file mode 100644index 000000000000..5e8d67a5323d--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/ch_run_candidate.py@@ -0,0 +1,171 @@+#!/usr/bin/env python3+"""Run one candidate query, capture artifacts, compare to baseline."""++from __future__ import annotations++import sys+import json+import argparse+import subprocess+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _common import ( # noqa: E402+ AdapterConfig,+ AutoresearchError,+ emit_metrics_from_json,+ execute_query,+ info,+ next_run_id,+ require_file,+ write_last_run_json,+)++SCRIPT_DIR = Path(__file__).resolve().parent+++def parse_args(argv: list[str]) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--workspace", required=True, type=Path)+ parser.add_argument("--label", default="")+ return parser.parse_args(argv)+++def _write_failure_metrics(metrics_file: Path, note: str) -> None:+ metrics_file.parent.mkdir(parents=True, exist_ok=True)+ metrics_file.write_text(+ json.dumps(+ {+ "primary": {"name": "latency_ms", "value": -1, "unit": "ms"},+ "secondary": {},+ "notes": note,+ },+ indent=2,+ )+ + "\n"+ )+++def main(argv: list[str] | None = None) -> int:+ args = parse_args(argv if argv is not None else sys.argv[1:])++ workspace: Path = args.workspace+ candidate_file = workspace / "query" / "current.sql"+ baseline_result = workspace / "baseline" / "result.jsonl"+ require_file(candidate_file)+ require_file(baseline_result)++ run_id = next_run_id(workspace)+ run_name = f"{run_id}-{args.label}" if args.label else run_id+ run_dir = workspace / "runs" / run_name+ profile_dir = run_dir / "profile"+ profile_dir.mkdir(parents=True, exist_ok=True)++ result_file = run_dir / "result.jsonl"+ metrics_file = run_dir / "metrics.json"+ stdout_file = run_dir / "stdout.log"+ comparison_file = run_dir / "comparison.json"+ last_run = workspace / "runtime" / "last_run.json"+ last_run.parent.mkdir(parents=True, exist_ok=True)++ adapter = AdapterConfig.load(workspace)+ transport = adapter.transport()++ info(f"running candidate ({run_name}): {candidate_file}")+ try:+ execute_query(+ transport,+ candidate_file,+ result_file=result_file,+ metrics_file=metrics_file,+ stdout_file=stdout_file,+ )+ except AutoresearchError as err:+ info(f"candidate query failed: {err}")+ _write_failure_metrics(metrics_file, str(err))+ write_last_run_json(+ last_run,+ kind="candidate",+ run_id=run_id,+ label=args.label,+ run_dir=run_dir,+ result_file="",+ metrics_file=metrics_file,+ comparison_file="",+ )+ print("METRIC latency_ms=-1")+ return 0++ # 0/1 leave a comparison.json behind; 2 doesn't — write an error-shaped+ # one ourselves so "failed to verify" can't be read as "matches baseline."+ compare_result = subprocess.run( # noqa: S603+ [+ sys.executable,+ str(SCRIPT_DIR / "ch_compare_results.py"),+ "--workspace",+ str(workspace),+ "--candidate-result",+ str(result_file),+ "--output",+ str(comparison_file),+ ],+ check=False,+ capture_output=True,+ text=True,+ )+ if compare_result.returncode not in (0, 1):+ err_detail = (compare_result.stderr or "").strip()[:500]+ info(f"comparison crashed (exit {compare_result.returncode}): {err_detail}")+ comparison_file.parent.mkdir(parents=True, exist_ok=True)+ comparison_file.write_text(+ json.dumps(+ {+ "matches": False,+ "mode": "sorted-line",+ "summary": f"comparator crashed (exit {compare_result.returncode})",+ "error": err_detail,+ },+ indent=2,+ )+ + "\n"+ )+ # latency_ms=-1 sentinel: pi-autoresearch's stagnation heuristic counts+ # this as a failed run, and harvest's `value < 0` filter skips it.+ _write_failure_metrics(metrics_file, f"comparator crashed (exit {compare_result.returncode})")+ write_last_run_json(+ last_run,+ kind="candidate",+ run_id=run_id,+ label=args.label,+ run_dir=run_dir,+ result_file=result_file,+ metrics_file=metrics_file,+ comparison_file=comparison_file,+ )+ print("METRIC latency_ms=-1")+ return 0++ write_last_run_json(+ last_run,+ kind="candidate",+ run_id=run_id,+ label=args.label,+ run_dir=run_dir,+ result_file=result_file,+ metrics_file=metrics_file,+ comparison_file=comparison_file,+ )++ emit_metrics_from_json(metrics_file)++ rows = len(result_file.read_text().splitlines())+ info(f"candidate {run_name} captured: {rows} result rows")+ return 0+++if __name__ == "__main__":+ try:+ sys.exit(main())+ except AutoresearchError as err:+ print(f"error: {err}", file=sys.stderr)+ sys.exit(1)diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/tests/test_transports.py b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/tests/test_transports.pynew file mode 100644index 000000000000..2f8001b18bf8--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/tests/test_transports.py@@ -0,0 +1,125 @@+"""Tests for the in-sandbox `CoordinatorTransport`.++The transport runs inside the sandbox and posts to the coordinator's HTTP+server. We stub the HTTP server with a stdlib BaseHTTPRequestHandler and+exercise the transport against it — black-box, no urllib mocks.+"""++from __future__ import annotations++import sys+import json+import threading+from http.server import BaseHTTPRequestHandler, HTTPServer+from pathlib import Path+from typing import Any++import pytest++# transports.py is meant to be imported as a sibling script inside the sandbox;+# load it directly so the test process doesn't have to pretend to be the sandbox.+_PLUGIN_SCRIPTS_DIR = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(_PLUGIN_SCRIPTS_DIR))+import transports # noqa: E402+++def fake_coordinator() -> Any:+ state: dict[str, Any] = {+ "expect_token": "tok",+ "response_status": 200,+ "response_body": json.dumps(+ {+ "result": [[1, "x"]],+ "rows_returned": 1,+ "elapsed_ms": 12.5,+ "rows_read": 7,+ "bytes_read": 99,+ "query_id": "qid",+ }+ ),+ "received_body": None,+ "received_auth": None,+ }++ class _Handler(BaseHTTPRequestHandler):+ def log_message(self, *_args: Any, **_kwargs: Any) -> None:+ return++ def do_POST(self) -> None: # noqa: N802+ length = int(self.headers.get("Content-Length", "0"))+ body = self.rfile.read(length)+ state["received_body"] = body.decode("utf-8")+ state["received_auth"] = self.headers.get("Authorization")+ payload = state["response_body"].encode("utf-8")+ self.send_response(state["response_status"])+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++ server = HTTPServer(("127.0.0.1", 0), _Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ port = server.server_address[1]+ yield state, port+ server.shutdown()+++def test_coordinator_transport_happy_path(fake_coordinator) -> None:+ state, port = fake_coordinator+ transport = transports.CoordinatorTransport(base_url=f"http://127.0.0.1:{port}", token="tok")+ result = transport.run("SELECT 1")+ assert result.elapsed_ms == 12.5+ assert result.rows_read == 7+ assert result.bytes_read == 99+ assert result.query_id == "qid"+ assert result.result_bytes == b'[1,"x"]\n'++ received = json.loads(state["received_body"])+ assert received["sql"] == "SELECT 1"+ assert state["received_auth"] == "Bearer tok"+++def test_coordinator_transport_4xx_raises(fake_coordinator) -> None:+ state, port = fake_coordinator+ state["response_status"] = 401+ state["response_body"] = json.dumps({"error": "unauthorized"})+ transport = transports.CoordinatorTransport(base_url=f"http://127.0.0.1:{port}", token="wrong")+ with pytest.raises(transports.TransportError, match="401"):+ transport.run("SELECT 1")+++def test_coordinator_transport_502_raises(fake_coordinator) -> None:+ state, port = fake_coordinator+ state["response_status"] = 502+ state["response_body"] = json.dumps({"error": "ch error"})+ transport = transports.CoordinatorTransport(base_url=f"http://127.0.0.1:{port}", token="tok")+ with pytest.raises(transports.TransportError, match="502"):+ transport.run("SELECT 1")+++def test_coordinator_transport_non_json_raises(fake_coordinator) -> None:+ state, port = fake_coordinator+ state["response_body"] = "this is not json"+ transport = transports.CoordinatorTransport(base_url=f"http://127.0.0.1:{port}", token="tok")+ with pytest.raises(transports.TransportError, match="non-JSON"):+ transport.run("SELECT 1")+++def test_coordinator_transport_rejects_non_http_scheme() -> None:+ transport = transports.CoordinatorTransport(base_url="file:///etc/passwd", token="tok")+ with pytest.raises(ValueError, match="scheme"):+ transport.run("SELECT 1")+++def test_load_transport_requires_coordinator_type() -> None:+ with pytest.raises(ValueError, match='must be "coordinator"'):+ transports.load_transport({"type": "posthog_proxy", "url": "http://x", "token": "t"})+++def test_load_transport_requires_url_and_token() -> None:+ with pytest.raises(ValueError, match='"url"'):+ transports.load_transport({"type": "coordinator", "token": "t"})+ with pytest.raises(ValueError, match='"token"'):+ transports.load_transport({"type": "coordinator", "url": "http://x"})diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/transports.py b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/transports.pynew file mode 100644index 000000000000..d956d0a0a366--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/transports.py@@ -0,0 +1,153 @@+"""ClickHouse transport for autoresearch campaigns.++The coordinator's HTTP server is the only transport — one wire format,+one auth path, no direct-to-CH option. Whether the bytes ultimately land+on the test cluster (via Metabase) or on a local ClickHouse (via+sync_execute) is the coordinator's business; the sandbox never knows.+"""++from __future__ import annotations++import json+import time+import urllib.error+import urllib.parse+import urllib.request+from dataclasses import dataclass+from typing import Any++_ALLOWED_URL_SCHEMES = frozenset({"http", "https"})+++def _require_http_url(url: str) -> None:+ """URLs come from `adapter.json` / env; urllib also speaks `file://`/`ftp://`."""+ scheme = urllib.parse.urlparse(url).scheme.lower()+ if scheme not in _ALLOWED_URL_SCHEMES:+ raise ValueError(f"transport URL scheme {scheme!r} not allowed (must be http/https): {url!r}")+++class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):+ """Sealing the redirect-bypass for `_require_http_url` (e.g. 302 → file://)."""++ def redirect_request(self, req, fp, code, msg, headers, newurl):+ raise urllib.error.HTTPError(req.full_url, code, f"refusing to follow redirect to {newurl!r}", headers, fp)+++_NO_REDIRECT_OPENER = urllib.request.build_opener(_NoRedirectHandler())+++@dataclass(frozen=True)+class TransportResult:+ """Mirrors the `metrics.json` contract so callers can write it directly."""++ result_bytes: bytes+ elapsed_ms: float+ rows_read: int | None+ bytes_read: int | None+ query_id: str | None+ stdout: str+++class TransportError(RuntimeError):+ def __init__(self, message: str, *, elapsed_ms: float, stdout: str):+ super().__init__(message)+ self.elapsed_ms = elapsed_ms+ self.stdout = stdout+++def load_transport(config: dict[str, Any]) -> CoordinatorTransport:+ """`type` leaves room for future transports without a workspace-format migration."""+ kind = config.get("type")+ if kind != "coordinator":+ raise ValueError(f'adapter.json "type" must be "coordinator" (got {kind!r})')+ url = config.get("url")+ token = config.get("token")+ if not url:+ raise ValueError('adapter type "coordinator" requires a "url" field')+ if not token:+ raise ValueError('adapter type "coordinator" requires a "token" field')+ return CoordinatorTransport(base_url=url, token=token)+++class CoordinatorTransport:+ """POST SQL to the coordinator's ``/v1/run`` endpoint and unwrap the response.++ Config shape::++ {+ "type": "coordinator",+ "url": "http://host.docker.internal:8765",+ "token": "<random per-coordinator-run token>"+ }+ """++ def __init__(self, *, base_url: str, token: str):+ self.base_url = base_url.rstrip("/")+ self.token = token++ def run(self, sql: str, *, timeout_s: int = 310) -> TransportResult:+ endpoint = f"{self.base_url}/v1/run"+ _require_http_url(endpoint)+ body = json.dumps({"sql": sql, "timeout_s": min(timeout_s, 600)}).encode("utf-8")+ req = urllib.request.Request(+ endpoint,+ data=body,+ method="POST",+ headers={+ "Content-Type": "application/json",+ "Authorization": f"Bearer {self.token}",+ },+ )++ start = time.monotonic()+ try:+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected+ with _NO_REDIRECT_OPENER.open(req, timeout=timeout_s) as resp: # noqa: S310+ response_body = resp.read().decode("utf-8")+ except urllib.error.HTTPError as e:+ elapsed_ms = (time.monotonic() - start) * 1000.0+ detail = e.read().decode("utf-8", "replace")[:2000]+ raise TransportError(+ f"coordinator {e.code}: {detail}",+ elapsed_ms=elapsed_ms,+ stdout=str(e.headers),+ ) from e+ except (urllib.error.URLError, TimeoutError) as e:+ elapsed_ms = (time.monotonic() - start) * 1000.0+ raise TransportError(+ f"coordinator transport failure: {e}",+ elapsed_ms=elapsed_ms,+ stdout="",+ ) from e+ round_trip_ms = (time.monotonic() - start) * 1000.0++ try:+ data = json.loads(response_body)+ except json.JSONDecodeError as e:+ raise TransportError(+ f"coordinator returned non-JSON response: {response_body[:500]}",+ elapsed_ms=round_trip_ms,+ stdout="",+ ) from e++ # Server-side elapsed excludes network latency; prefer it over round-trip.+ elapsed_ms = data.get("elapsed_ms")+ if not isinstance(elapsed_ms, int | float):+ elapsed_ms = round_trip_ms++ query_id = data.get("query_id")+ return TransportResult(+ result_bytes=_rows_to_jsonl_bytes(data.get("result")),+ elapsed_ms=float(elapsed_ms),+ rows_read=data.get("rows_read") if isinstance(data.get("rows_read"), int) else None,+ bytes_read=data.get("bytes_read") if isinstance(data.get("bytes_read"), int) else None,+ query_id=query_id if isinstance(query_id, str) else None,+ stdout=f"rows_returned={data.get('rows_returned')} query_id={query_id}",+ )+++def _rows_to_jsonl_bytes(rows: Any) -> bytes:+ if not isinstance(rows, list) or not rows:+ return b""+ lines = [json.dumps(row, separators=(",", ":"), sort_keys=True) for row in rows]+ return ("\n".join(lines) + "\n").encode("utf-8")diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/skills/clickhouse-autoresearch-campaign/SKILL.md b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/skills/clickhouse-autoresearch-campaign/SKILL.mdnew file mode 100644index 000000000000..cda38ea21f0d--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/skills/clickhouse-autoresearch-campaign/SKILL.md@@ -0,0 +1,262 @@+---+name: clickhouse-autoresearch-campaign+description: Run a ClickHouse query optimization campaign on one git branch using pi-autoresearch, dynamic lanes and hypotheses, baseline result capture, correctness checks, and stagnation-aware lane/campaign review.+---++# ClickHouse Autoresearch Campaign++This skill packages the orchestration for optimizing one ClickHouse query on one git branch.++## Required reads++Before taking action, read `orchestration.md` (sibling of this file) completely. Treat it as the operating contract.++## Preconditions++This skill assumes:++- `pi-autoresearch` is installed and its tools are available+- the current directory is a git repository+- you have a target query or enough context to identify one+- the operator will provide or help configure `.clickhouse-autoresearch/adapter.json`++## Branch rule++One campaign = one git branch.++If the current branch is not a dedicated campaign branch yet, create one before initializing the workspace.++## Workspace rule++Use a single workspace at:++```text+.clickhouse-autoresearch/+```++The branch is the campaign boundary. The workspace is just the artifact layout.++If `autoresearch.config.json` exists in the current working directory, read its `workingDir` field and use that path as the workspace instead of the default above. Automated orchestrators (for example PostHog's `run_campaign.py`) initialize the workspace at `/tmp/autoresearch-campaign/` and write the config alongside it.++## Pre-initialized workspace detection++**Before doing anything in the Setup sequence, check whether the workspace has already been prepared by an external orchestrator.** If the resolved workspace contains **all** of:++- `adapter.json`+- `baseline/metrics.json`+- `query/original.sql`++…then the workspace is pre-initialized. In that case:++- **Skip the entire Setup sequence (steps 1–6).** Do not ask the operator for a target query, connection details, or anything else — the orchestrator has already supplied them.+- Jump directly to step 7 of the Setup sequence (read the baseline and seed the first lanes and hypotheses), then continue with steps 8–9 and the normal campaign loop.+- Operate headlessly: at no point prompt the operator for input. If a decision requires judgment, apply the skill's default guidance and record the choice in `state.json` / `autoresearch.md`.++Only fall back to the interactive Setup sequence below when the workspace is empty or partially initialized.++## Adapter capabilities (what you can and cannot run)++Campaign queries flow through the adapter configured in `adapter.json`. Every campaign script (`ch_capture_baseline.py`, `ch_run_candidate.py`, any ad-hoc probe) ultimately submits SQL through this adapter, and the adapter enforces what ClickHouse sees.++When `adapter.json` has `type: "coordinator"`, your SQL is routed to whichever ClickHouse the host-side coordinator is pointed at — typically a read-only test cluster or a local dev ClickHouse. Either way the cluster runs SQL under a profile that pins `readonly = 2`, so writes (INSERT, ALTER, CREATE, OPTIMIZE, SYSTEM, TRUNCATE, DROP, ATTACH, DETACH) will fail with a ClickHouse error. **Read `GET /v1/info` (or check `autoresearch.md` — the coordinator's prompt addendum is prepended there)** before issuing any predicate that depends on a specific `team_id`: the prompt addendum tells you which `team_id` the target cluster has data for, and you must rewrite team_id predicates to match it. For experiments treat every read-only statement form as available:++- `SELECT …` — arbitrary subqueries, CTEs, joins+- `WITH … SELECT …`+- `EXPLAIN …` — every variant ClickHouse supports. Use them before proposing rewrites:+ - `EXPLAIN SELECT …` (default: PLAN)+ - `EXPLAIN AST SELECT …`+ - `EXPLAIN SYNTAX SELECT …`+ - `EXPLAIN QUERY TREE SELECT …` (post-analyzer logical tree; invaluable on modern ClickHouse)+ - `EXPLAIN PIPELINE SELECT …` — processor-level pipeline, headers, expressions+ - `EXPLAIN ESTIMATE SELECT …` — per-part row/mark estimates before execution+ - `EXPLAIN PLAN indexes = 1, actions = 1, json = 1 SELECT …` — primary-key and skip-index use, JSON for machine parsing+ - `EXPLAIN TABLE OVERRIDE …`+- `SHOW …` — `SHOW CREATE TABLE events`, `SHOW COLUMNS FROM events`, `SHOW INDEX FROM events`, `SHOW SETTINGS ILIKE '%mark_cache%'`, etc.+- `DESCRIBE` / `DESC …`++**Timeout**: every submission is wrapped with `SETTINGS max_execution_time = 60`. Keep ad-hoc probes short. If the target query itself routinely exceeds 60s, use range narrowing (see Setup step 6) and only then start the campaign.++**Cluster scoping**: depends on the coordinator's `target`. The prompt addendum prepended to `autoresearch.md` tells you which `team_id` the target cluster has data for and asks you to rewrite team_id predicates accordingly. Read the addendum first.++**Profiling ClickHouse's perspective**:++After a run, the campaign scripts capture client-side `elapsed_ms`, `rows_read`, `bytes_read`, and the server-minted `query_id` from the proxy response (persisted as `query_id` in `runs/run-XXXX-*/metrics.json` and `baseline/metrics.json`). The `autoresearch` CH user can read four `system.*` profiling tables for its own queries (RESTRICTIVE row policies hide every other user's rows):++| Table | What's in it |+| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |+| `system.query_log` | One row per finished query: `query_duration_ms`, `read_rows`, `read_bytes`, `memory_usage`, `ProfileEvents` (map of low-level counters). |+| `system.query_thread_log` | Per-thread breakdown of the query: CPU time, wait time, peak memory per thread. |+| `system.text_log` | Server-side log lines tagged with `query_id` (planner messages, mark-cache hits, merge-trigger). |+| `system.trace_log` | Sampled stack traces during query execution. Lit up by `query_profiler_real_time_period_ns`. |++Look up a finished query's headline stats:++```sql+SELECT query_duration_ms, read_rows, read_bytes, memory_usage, ProfileEvents+FROM system.query_log+WHERE type = 'QueryFinish' AND query_id = '<query_id from metrics.json>'+ORDER BY event_time DESC+LIMIT 1+```++Useful `ProfileEvents` for query-perf work:++- `SelectedParts`, `SelectedRanges`, `SelectedMarks` — how much of the table the planner chose to read (lower = better-pruned predicates).+- `OSReadChars` vs `OSReadBytes` — disk-cache hit ratio.+- `RealTimeMicroseconds`, `UserTimeMicroseconds`, `SystemTimeMicroseconds` — wall vs CPU time (gap = waiting on I/O or locks).+- `Merge*`, `*Mark*`, `*PrimaryKey*` — index usage and compaction cost.++Per-thread to find tail latency:++```sql+SELECT thread_id, query_duration_ms, peak_memory_usage, ProfileEvents['OSReadBytes']+FROM system.query_thread_log+WHERE query_id = '<query_id>'+ORDER BY query_duration_ms DESC+```++Server-side log lines for a single query (planner choices, parts pruning, etc.):++```sql+SELECT event_time, level, logger_name, message+FROM system.text_log+WHERE query_id = '<query_id>'+ORDER BY event_time+```++Sampled stack traces (only useful if `query_profiler_real_time_period_ns > 0` was active for the run):++```sql+SELECT count(), arrayStringConcat(arrayMap(x -> demangle(addressToSymbol(x)), trace), '\n') AS frames+FROM system.trace_log+WHERE query_id = '<query_id>'+GROUP BY frames+ORDER BY count() DESC+LIMIT 20+```++`system.query_log` is readable under `readonly = 2`. Use it to compare ProfileEvents across iterations, not only wall-clock latency.++**Schema inspection** before proposing rewrites is free and often decisive:++```sql+SHOW CREATE TABLE events+DESCRIBE events+SELECT name, type, default_expression, codec_expression, is_in_primary_key, is_in_partition_key+FROM system.columns WHERE database = currentDatabase() AND table = 'events'+SELECT name, expr, type FROM system.data_skipping_indices WHERE table = 'events'+```++Use these to check the primary key, partitioning, codecs, and existing skip-indexes before hypothesizing that "adding an index" would help.++**ClickHouse source code** is bundled into the sandbox at `/opt/clickhouse`, pinned to a recent ClickHouse commit. This likely matches the behavior of the cluster you're querying, but it may lag or diverge from the version actually running in prod — treat it as a strong hint, not ground truth, and be alert to cases where observed behavior disagrees with what the source suggests. `tests/`, `docs/`, `website/`, `contrib/`, and `.git` are stripped; everything else — the engine, query analyzer, storage, functions — is readable. Use it to ground hypotheses in the actual implementation:++- `grep -rn "<FunctionName>" /opt/clickhouse/src/Functions/` — find the C++ implementation of a function you're using+- `ls /opt/clickhouse/src/Storages/MergeTree/` — MergeTree internals (skip indexes, parts, marks)+- `ls /opt/clickhouse/src/Interpreters/` — query-tree rewrites, analyzer passes, join engines+- `ls /opt/clickhouse/src/Processors/` — pipeline / QueryPlan steps (what `EXPLAIN PIPELINE` is describing)++Reading the source is often the fastest way to resolve questions like "does this function short-circuit?", "how does this skip-index decide which granules to read?", "what settings does this pass consult?". Prefer reading the source over guessing or inferring from documentation.++**What this means for hypothesis formation**: start every lane by running `EXPLAIN indexes = 1, actions = 1, json = 1 SELECT <original>` and inspecting the plan. Then propose rewrites that target concrete weaknesses (full table scan, skipped PREWHERE, missing primary-key usage, etc.). Do not guess.++## Setup sequence++1. Confirm or infer the target query and query identifier.+2. Create or verify the campaign branch.+3. Run:++```bash+python3 ../../scripts/ch_campaign_init.py --workspace .clickhouse-autoresearch --query-id <id>+```++Add optional flags as needed:++- `--query-file <path>`+- `--branch-name <name>`+- `--primary-metric latency_ms`+- `--metric-unit ms`+- `--direction lower`+- `--lane-stagnation-window <n>`+- `--campaign-stagnation-window <n>`+- `--max-total-iterations <n>`+- `--significant-improvement-pct <number>`+- `--repair-budget <n>`++4. Inspect the generated workspace.+5. Fill in or update:++- `.clickhouse-autoresearch/adapter.json`+- `.clickhouse-autoresearch/state.json`+- `.clickhouse-autoresearch/autoresearch.md`++6. Capture the baseline:++```bash+python3 ../../scripts/ch_capture_baseline.py --workspace .clickhouse-autoresearch+```++If the baseline times out, enter range narrowing (see `orchestration.md` § Timeout queries):++1. Copy `query/original.sql` to `query/narrowed.sql`+2. Halve the time range in `narrowed.sql` (leave `query/original.sql` untouched — it is the full-range reference used by the escalation check)+3. Retry against the narrowed file: `python3 ../../scripts/ch_capture_baseline.py --workspace .clickhouse-autoresearch --query-file query/narrowed.sql`+4. Repeat halving until the query completes in 1–10s+5. Record narrowing state in `state.json`: `{ "narrowed": true, "original_range": "...", "working_range": "..." }`++6. Read the baseline artifacts and seed the first lanes and hypotheses.+7. Initialize the autoresearch session against the configured primary metric.+8. Start the experiment loop using:++```bash+./.clickhouse-autoresearch/autoresearch.py+```++with correctness backpressure through:++```bash+./.clickhouse-autoresearch/autoresearch_checks.py+```++## Runtime responsibilities++During the campaign, you must:++- if the workspace was pre-initialized (see "Pre-initialized workspace detection"), never prompt the operator — assume headless operation and apply default guidance for every decision+- keep `query/current.sql` as the next candidate to test+- keep `query/best.sql` aligned with the best kept result+- maintain the lane / hypothesis / review notes+- update `state.json` after every experiment+- reflect after every experiment+- trigger lane review tactically+- trigger campaign review strategically+- preserve durable learning in `autoresearch.md` and `autoresearch.jsonl`+- maintain `out-of-scope-suggestions.md` — the agent's persistent record of schema-level changes it suspects would help but cannot apply in the sandbox (materialized columns, skip indexes, projections, table-engine swaps). The orchestrator harvests this file as a deliverable, so each entry must include the change, evidence, expected impact, and which queries would benefit+- classify every kept optimization as schema-level, query-generation, or query-specific+- if narrowed: after every `keep`, run an escalation check against the original time range and log the result+- if an escalation check succeeds, graduate to the full range (re-capture baseline, update correctness reference)++## What the scripts do vs what you do++The scripts do deterministic work:++- create the workspace+- invoke environment-specific commands from `adapter.json`+- capture baseline artifacts+- run candidate queries+- compare candidate results to the saved baseline result set+- emit `METRIC ...` lines++You do the reasoning:++- choose the active lane+- choose the hypothesis+- decide whether to repair a wrong-but-fast candidate+- decide when to integrate wins across lanes+- decide when a lane is exhausted+- decide when the campaign is exhausted++## Reasoning rules++Review separation, integration, correctness, and closure are defined in+`orchestration.md` (sibling of this file). Apply them as written.diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/skills/clickhouse-autoresearch-campaign/orchestration.md b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/skills/clickhouse-autoresearch-campaign/orchestration.mdnew file mode 100644index 000000000000..3dbc2969717b--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/skills/clickhouse-autoresearch-campaign/orchestration.md@@ -0,0 +1,394 @@+# ClickHouse Query Optimization Orchestration Contract++This document is the durable reasoning contract for the ClickHouse optimization campaign.++## Mission++Find generalizable performance improvements using one slow ClickHouse query as the investigation target.++The target query is generated by PostHog's query runners. Optimizations that only help this exact query (e.g., adding a hardcoded event filter) have little value. Focus on improvements that would benefit many queries with different parameters.++Run a disciplined campaign that:++- builds a baseline dossier+- maintains a dynamic backlog of lanes and hypotheses+- runs experiments, classifying each finding as generalizable or query-specific+- compares performance against the baseline+- compares results against the saved baseline result set+- keeps validated improvements+- discards regressions+- reflects after every experiment+- maintains `out-of-scope-suggestions.md` — recommendations for schema-level changes the agent suspects would help but cannot apply in the sandbox (materialized columns, skip indexes, projections, table-engine swaps)+- decides when to continue, pivot, integrate, repair, review, or close the campaign++## Core model++- **Campaign**: one investigation for one target query on one git branch.+- **Lane**: one optimization direction tied to a suspected bottleneck or strategy.+- **Hypothesis**: one concrete, testable idea within a lane.+- **Experiment**: one executed hypothesis with benchmark and correctness evaluation.++## Fundamental rules++- One campaign corresponds to one git branch.+- The branch maintains one canonical best query candidate.+- Kept wins should normally accumulate on top of the current best candidate.+- Hypotheses come from the agent's own reasoning over the baseline dossier; treat agent-generated hypotheses as the only input.+- The backlog is dynamic and must be updated after every experiment.+- Do not overfit to the benchmark or cheat the workload.+- Semantics must be preserved relative to the saved baseline result set unless explicitly exploring a bounded repair of a promising incorrect candidate.+- Lane review may pause or close a lane, but only campaign review may close the campaign.+- Write explicit rationale summaries, not hidden chain-of-thought.++## Optimization categories++Prioritize improvements by generalizability:++### 1. Schema-level (highest priority, cannot test directly)++Materialized columns, skip indexes, projections, table engine changes. The agent cannot ALTER TABLE on the test cluster — these are out of scope for the sandbox. Instead:++- Identify the opportunity from EXPLAIN plans, row counts, and query patterns+- Record the suggestion in `out-of-scope-suggestions.md` with evidence and estimated impact (this file is the agent's persistent output for things it suspects would help but cannot validate here)+- Describe which query patterns would benefit (not just this one query)++### 2. Query generation patterns (can test by rewriting)++Changes that should be applied in PostHog's query runner code:++- Timestamp handling: `toDateTime(literal, tz)` instead of `toTimeZone(timestamp, tz)` per row+- JSON function choice: `JSONExtractString` over `replaceRegexpAll(JSONExtractRaw(...))`+- Predicate ordering: place high-selectivity filters that use the primary key first+- Unnecessary casts, redundant expressions, suboptimal JOIN strategies++Test by rewriting the query. Kept rewrites live in `query/best.sql`; if the rewrite encodes a reusable pattern, note it in `autoresearch.md` alongside the benchmark evidence.++### 3. Query-specific (lowest priority)++Hardcoded filters, literal substitutions, or structural changes that only help this exact query. Only pursue if budget remains after the above categories are explored.++### Out-of-scope suggestions file++`out-of-scope-suggestions.md` is the agent's persistent record of schema-level changes it suspects would help but cannot apply in the sandbox: materialized columns, skip indexes, projections, table-engine swaps. The orchestrator harvests this file at the end of the campaign and surfaces it as a deliverable, so each entry must be self-contained and actionable. Required fields:++- **What to change** (e.g., "materialize `JSONExtractString(properties, '$email')` as a column")+- **Evidence**: EXPLAIN plan excerpts, row counts, benchmark measurements+- **Expected impact**: estimated improvement and which queries would benefit+- **Applicability**: how broadly this applies (one query kind, many query kinds, all queries)++## Campaign initialization++Before active experimentation:++1. Identify the target query.+2. Create or verify the campaign branch.+3. Build the baseline dossier.+4. Extract initial lanes from:+ - query structure+ - profiling / EXPLAIN / ANALYZE evidence+ - schema / table characteristics+5. Create initial hypotheses.+6. Initialize the experiment session and establish the baseline.++## Timeout queries and range narrowing++Some target queries time out on the test cluster with their original time range. When this happens, narrow the range until the query is runnable, optimize there, and periodically re-test against the original range.++### When to activate++Enter range narrowing when the baseline capture fails with a timeout or exceeds `max_execution_time`.++### Narrowing phase++Reduce the time range in the query (halve it repeatedly: 30d → 14d → 7d → 3d → 1d) until the query completes. The target is a working range that is still meaningfully slow (1–10s), not trivially fast (sub-100ms). If the query becomes trivially fast at a given range, step back to the previous wider range and try intermediate values.++### File conventions++- `query/original.sql` — the full-range query, never modified+- `query/narrowed.sql` — the reduced-range working copy+- `query/current.sql` — the candidate under test (starts as a copy of the narrowed query)+- `query/best.sql` — the best kept candidate so far++### Working baseline++Capture the baseline against the narrowed query. The correctness reference is the narrowed query's result set — results will differ from the full range and that is expected.++Record the narrowing state in `state.json`:++```json+{+ "narrowed": true,+ "original_range": "30d",+ "working_range": "3d"+}+```++### Escalation checks++After every `keep` result, test whether the current best candidate is viable at the original time range:++1. Apply the same optimizations from `query/best.sql` to a copy using the original time range+2. Run it with a generous but bounded timeout (e.g., `max_execution_time=60`)+3. Record whether it completed or timed out, and if it completed, the latency++Log escalation results in `state.json` under an `escalation` key:++```json+{+ "escalation": [+ { "after_run": 5, "completed": false },+ { "after_run": 12, "completed": true, "latency_ms": 8400 }+ ]+}+```++### Graduation++When an escalation check succeeds (original range completes within a reasonable time):++1. Switch the campaign to the full range+2. Re-capture the baseline with the full-range query+3. Update the correctness reference to the full-range result set+4. Continue optimizing from the current best candidate++### Correctness rule during narrowing++During the narrowed phase, correctness is validated against the narrowed baseline. After graduation, correctness is validated against the full-range baseline.++## Baseline dossier requirements++The baseline dossier must include:++- original query text+- relevant schema / table definitions+- relevant EXPLAIN / ANALYZE / profiling artifacts+- baseline performance metrics+- saved baseline result set from actually executing the query+- assumptions required to reproduce the experiment++The saved baseline result set is the semantic reference for future correctness checks.++## Lane and hypothesis management++Treat lanes and hypotheses as a living structure.++At all times:++- maintain lane status: active, paused, repair, exhausted, or closed+- maintain hypotheses sourced from:+ - agent-generated evidence+ - reasoning over the baseline dossier and EXPLAIN output+- merge duplicates+- split overly broad hypotheses+- create new lanes when new bottlenecks appear+- create integration hypotheses when validated wins from different lanes may combine+- explicitly record when no new hypothesis can be extracted++When choosing the next experiment, prefer:++- high expected upside+- strong evidence support+- manageable semantic risk+- compatibility with already-kept improvements+- high information value++## Experiment protocol++For each experiment:++1. Select the next lane and hypothesis.+2. Record a concise rationale:+ - suspected bottleneck+ - supporting evidence+ - intended change+ - expected metric movement+ - semantic risks+3. Modify the current candidate query.+4. Run the benchmark and capture performance artifacts.+5. Run correctness comparison against the saved baseline result set.+6. Adjudicate the outcome:+ - improved and correct -> keep+ - not improved and correct -> discard+ - improved but incorrect -> evaluate repair-worthiness+ - crash / invalid -> discard unless trivially fixable+7. Reflect on the result.+8. Update the lane and hypothesis backlog.+9. Decide the next action:+ - continue current lane+ - narrow current lane+ - switch lanes+ - create a new lane+ - open an integration hypothesis+ - open a repair hypothesis or repair lane+ - trigger lane review+ - trigger campaign review++## Mandatory post-experiment reflection++After every experiment, explicitly assess:++- what prediction was confirmed+- what prediction was wrong+- what unexpected signal appeared+- whether the measured effect happened for the expected reason+- whether correctness failure, if any, looks trivial, repairable, or fundamental+- whether the result strengthens, weakens, splits, or merges any hypotheses+- whether the result suggests a new hypothesis+- whether the result suggests a new lane+- whether no meaningful new hypothesis can be extracted+- whether the optimization is generalizable (schema-level or query-generation pattern) or query-specific+- if it implies a schema change the sandbox cannot apply: record it in `out-of-scope-suggestions.md`++Reflection is mandatory even when the result is inconclusive.++## Lane-level stagnation / exhaustion review++Lane review is tactical.++Trigger lane review when the current lane shows signs of exhaustion, such as:++- no significant improvement from this lane for the configured lane stagnation window+- no meaningful new hypotheses extracted from this lane for the configured lane stagnation window+- repeated similar plans or metrics with little new signal+- only trivial variants remain+- repair attempts inside this lane are not converging++Lane review may conclude:++- continue the lane+- narrow the lane+- split the lane+- merge it with another lane+- pause / park the lane+- close the lane as exhausted++Lane review must not end the campaign.++## Campaign-level stagnation / exhaustion review++Campaign review is strategic.++Trigger campaign review when:++- the active lane is exhausted and no strong lane is ready+- the campaign has seen no significant improvement for the configured campaign stagnation window+- recent reflection is not generating meaningful new hypotheses or new lanes+- remaining lanes are low-confidence, repetitive, or low expected value+- repair paths are exhausted+- iteration budget is approaching exhaustion++Campaign review may conclude:++- continue with another lane+- continue with narrowed scope+- continue with an integration direction+- continue with a repair direction+- close the campaign++A campaign should continue only while it is still producing either:++- meaningful gains, or+- genuinely new learning with realistic upside++## Combining results from different lanes++Combining good results across lanes is expected.++Default behavior:++- explore new hypotheses on top of the current best kept candidate so wins accumulate naturally++If strong results were discovered partly in isolation:++- explicitly create an integration hypothesis to test them together++When evaluating lane combinations, classify the relationship:++- additive+- enabling+- conflicting+- redundant++Do not exhaustively combine everything. Only test combinations with credible synergy or transfer value.++A lane result is not fully banked until it has either:++- been integrated into the current best candidate, or+- been explicitly marked as incompatible, redundant, or alternative++## Correctness and repair++If a candidate is faster but fails correctness:++- do not automatically discard it without evaluation+- classify the mismatch as:+ - trivial and likely fixable+ - promising but moderately costly to repair+ - fundamental and not worth pursuing++If the candidate is materially promising and likely repairable:++- open a bounded repair hypothesis or repair lane+- try to preserve the performance gain while restoring semantics++If the mismatch is not worth fixing:++- record it as a promising dead end and move on++## Closure++Hard closure may happen when:++- total iteration budget is exhausted+- the environment becomes unusable+- the benchmark or correctness workflow is no longer operable++Soft closure requires campaign review.++When closing the campaign:++- summarize best kept result+- summarize validated lanes+- summarize exhausted or invalidated lanes+- summarize promising but unmerged or unfixable ideas+- summarize why continuation is no longer justified+- leave durable state so a future agent can resume intelligently++## Durable memory obligations++Persist durable summaries of:++- baseline dossier+- current best candidate and why it is best+- lane list and statuses+- tested hypotheses and outcomes+- key evidence learned from failures+- integration opportunities+- repair-worthy incorrect candidates+- stagnation / exhaustion review conclusions+- closure reasoning++## Workspace convention++This package assumes a campaign workspace like:++```text+.clickhouse-autoresearch/+ campaign.json+ state.json+ adapter.json+ query/+ original.sql+ current.sql+ best.sql+ baseline/+ runs/+ runtime/+ lanes/+ hypotheses/+ reviews/+ out-of-scope-suggestions.md+ autoresearch.md+ autoresearch.py+ autoresearch_checks.py+```diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/adapter.json.example b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/adapter.json.examplenew file mode 100644index 000000000000..a83704384672--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/adapter.json.example@@ -0,0 +1,6 @@+{+ "_comment": "Coordinator transport. The only supported `type` is 'coordinator' (see products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/scripts/transports.py). `url` is the coordinator's HTTP server (host.docker.internal from inside a Docker sandbox); `token` is the random per-run token the coordinator prints to its stdout at startup.",+ "type": "coordinator",+ "url": "http://host.docker.internal:8765",+ "token": "<coordinator token>"+}diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/autoresearch.md b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/autoresearch.mdnew file mode 100644index 000000000000..7b405905f73a--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/autoresearch.md@@ -0,0 +1,23 @@+# Autoresearch: ClickHouse query **QUERY_ID**++## Metrics++- **Primary**: **PRIMARY_METRIC** (**METRIC_UNIT**, **DIRECTION** is better)+- **Secondary**: rows_read, bytes_read, peak_memory_mb++## How to run++- Benchmark: `./autoresearch.py`+- Checks: `./autoresearch_checks.py`++For optimization priority, timeout handling, adapter capabilities, and the+campaign loop: see the `clickhouse-autoresearch-campaign` skill — it ships+with `SKILL.md` and `orchestration.md` (siblings of each other). This file+is your durable per-campaign log — append findings, learnings, and decisions+here as the campaign progresses.++## What's been tried++- Baseline captured: pending+- Initial lanes: pending+- Key learning: pendingdiff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/autoresearch.py b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/autoresearch.pynew file mode 100644index 000000000000..8e4f4518fce3--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/autoresearch.py@@ -0,0 +1,33 @@+#!/usr/bin/env python3+"""Workspace-local entry point invoked by pi-autoresearch's run_experiment.++Placeholders (``__KEY__``) are filled in by ``ch_campaign_init.py``.+"""++from __future__ import annotations++import sys+import subprocess+from pathlib import Path++PACKAGE_ROOT = Path("__PACKAGE_ROOT__")+WORKSPACE_DIR = Path(__file__).resolve().parent+++def main() -> int:+ result = subprocess.run( # noqa: S603+ [+ sys.executable,+ str(PACKAGE_ROOT / "scripts" / "ch_run_candidate.py"),+ "--workspace",+ str(WORKSPACE_DIR),+ "--label",+ "autoresearch",+ ],+ check=False,+ )+ return result.returncode+++if __name__ == "__main__":+ sys.exit(main())diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/autoresearch_checks.py b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/autoresearch_checks.pynew file mode 100644index 000000000000..439557b86e7f--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/autoresearch_checks.py@@ -0,0 +1,40 @@+#!/usr/bin/env python3+"""Workspace-local correctness check invoked by pi-autoresearch.++Reads ``runtime/last_run.json`` -> ``comparison.json``. Exits 0 on match,+1 on mismatch, 2 on missing artifacts.+"""++from __future__ import annotations++import sys+import json+from pathlib import Path++WORKSPACE_DIR = Path(__file__).resolve().parent+++def main() -> int:+ last_run_path = WORKSPACE_DIR / "runtime" / "last_run.json"+ if not last_run_path.is_file():+ print(f"checks failed: missing {last_run_path}", file=sys.stderr)+ return 2++ last_run = json.loads(last_run_path.read_text())+ comparison_file = last_run.get("comparison_file") or ""+ if not comparison_file or not Path(comparison_file).is_file():+ print("checks failed: missing comparison file", file=sys.stderr)+ return 2++ comparison = json.loads(Path(comparison_file).read_text())+ summary = comparison.get("summary") or "comparison failed"+ if comparison.get("matches"):+ print(f"checks passed: {summary}")+ return 0++ print(f"checks failed: {summary}", file=sys.stderr)+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/baseline/.gitkeep b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/baseline/.gitkeepnew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/campaign.json.example b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/campaign.json.examplenew file mode 100644index 000000000000..f435a000651d--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/campaign.json.example@@ -0,0 +1,23 @@+{+ "version": 1,+ "query_id": "__QUERY_ID__",+ "branch_name": "__BRANCH_NAME__",+ "workspace_root": "__WORKSPACE_ROOT__",+ "primary_metric": {+ "name": "__PRIMARY_METRIC__",+ "unit": "__METRIC_UNIT__",+ "direction": "__DIRECTION__",+ "significant_improvement_pct": __SIGNIFICANT_IMPROVEMENT_PCT__+ },+ "secondary_metrics": [+ "rows_read",+ "bytes_read",+ "peak_memory_mb"+ ],+ "review": {+ "lane_stagnation_window": __LANE_STAGNATION_WINDOW__,+ "campaign_stagnation_window": __CAMPAIGN_STAGNATION_WINDOW__,+ "max_total_iterations": __MAX_TOTAL_ITERATIONS__,+ "repair_budget_per_candidate": __REPAIR_BUDGET__+ }+}diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/hypotheses/.gitkeep b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/hypotheses/.gitkeepnew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/lanes/.gitkeep b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/lanes/.gitkeepnew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/query/best.sql b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/query/best.sqlnew file mode 100644index 000000000000..41450ef15cdb--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/query/best.sql@@ -0,0 +1 @@+-- Best known kept query for this campaign.diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/query/current.sql b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/query/current.sqlnew file mode 100644index 000000000000..637526d16c2a--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/query/current.sql@@ -0,0 +1 @@+-- Current candidate query under test.diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/query/original.sql b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/query/original.sqlnew file mode 100644index 000000000000..fb29a3251c4a--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/query/original.sql@@ -0,0 +1 @@+-- Paste or copy the original slow query here.diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/reviews/.gitkeep b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/reviews/.gitkeepnew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/runs/.gitkeep b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/runs/.gitkeepnew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/runtime/.gitkeep b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/runtime/.gitkeepnew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/state.json b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/state.jsonnew file mode 100644index 000000000000..d698359b1c15--- /dev/null+++ b/products/query_performance_ai/sandboxed_autoresearch_agent/pi_plugin/templates/workspace/state.json@@ -0,0 +1,21 @@+{+ "version": 1,+ "status": "initializing",+ "active_lane": null,+ "best_candidate": {+ "query_file": "query/best.sql",+ "primary_metric": null,+ "run_id": null,+ "summary": ""+ },+ "review_counters": {+ "since_lane_significant_improvement": 0,+ "since_campaign_significant_improvement": 0,+ "recent_new_hypotheses": 0+ },+ "lanes": [],+ "hypotheses": [],+ "integration_opportunities": [],+ "repair_candidates": [],+ "recent_learning": []+}diff --git a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-pi b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-piindex 355c3931d448..8ff31df16faf 100644--- a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-pi+++ b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-pi@@ -1,6 +1,9 @@ARG BASE_IMAGE=ghcr.io/posthog/posthog-sandbox-base:masterFROM ${BASE_IMAGE}+ARG IPTABLES_VERSION=1.8.10-3ubuntu2+RUN apt-get update && apt-get install -y --no-install-recommends "iptables=${IPTABLES_VERSION}" && rm -rf /var/lib/apt/lists/*+ARG PI_CODING_AGENT_VERSION=0.68.1RUN npm install -g "@mariozechner/pi-coding-agent@${PI_CODING_AGENT_VERSION}"diff --git a/products/tasks/backend/services/docker_sandbox.py b/products/tasks/backend/services/docker_sandbox.pyindex 4aff152b7561..0393f526a1b3 100644--- a/products/tasks/backend/services/docker_sandbox.py+++ b/products/tasks/backend/services/docker_sandbox.py@@ -57,6 +57,7 @@ logger = logging.getLogger(__name__)DEFAULT_IMAGE_NAME = "posthog-sandbox-base"NOTEBOOK_IMAGE_NAME = "posthog-sandbox-notebook"+PI_IMAGE_NAME = "posthog-sandbox-pi"AGENT_SERVER_PORT = 47821 # Arbitrary high port unlikely to conflict with dev servers@@ -146,7 +147,11 @@ class DockerSandbox(SandboxBase):return agent_path, shared_path, git_path, enricher_path@staticmethod- def _build_image_if_needed(image_name: str, dockerfile_path: str) -> None:+ def _build_image_if_needed(+ image_name: str,+ dockerfile_path: str,+ build_args: dict[str, str] | None = None,+ ) -> None:"""Build a sandbox image if it doesn't exist."""result = DockerSandbox._run(["docker", "images", "-q", image_name])if result.stdout.strip():@@ -161,18 +166,19 @@ class DockerSandbox(SandboxBase):# hogli build:skills.LocalSkillsCache().ensure_built()- DockerSandbox._run(- [- "docker",- "build",- "-f",- dockerfile_path,- "-t",- image_name,- str(settings.BASE_DIR),- ],- check=True,- )+ argv = [+ "docker",+ "build",+ "-f",+ dockerfile_path,+ "-t",+ image_name,+ ]+ for key, value in (build_args or {}).items():+ argv.extend(["--build-arg", f"{key}={value}"])+ argv.append(str(settings.BASE_DIR))++ DockerSandbox._run(argv, check=True)@staticmethoddef _build_local_image(agent_path: str, shared_path: str, git_path: str, enricher_path: str) -> None:@@ -232,6 +238,17 @@ class DockerSandbox(SandboxBase):)DockerSandbox._build_image_if_needed(DEFAULT_IMAGE_NAME, dockerfile_path)+ if template == SandboxTemplate.PI_BASE:+ pi_dockerfile = os.path.join(+ settings.BASE_DIR, "products/tasks/backend/sandbox/images/Dockerfile.sandbox-pi"+ )+ DockerSandbox._build_image_if_needed(+ PI_IMAGE_NAME,+ pi_dockerfile,+ build_args={"BASE_IMAGE": DEFAULT_IMAGE_NAME},+ )+ return PI_IMAGE_NAME+local_packages = DockerSandbox._get_local_posthog_code_packages()if local_packages:agent_path, shared_path, git_path, enricher_path = local_packages@@ -314,6 +331,10 @@ class DockerSandbox(SandboxBase):container_skill = f"/scripts/plugins/posthog/skills/{entry}"volume_args.extend(["-v", f"{host_skill}:{container_skill}:ro"])+ cap_args = ["--cap-add", "SYS_PTRACE"]+ if config.template == SandboxTemplate.PI_BASE:+ cap_args.extend(["--cap-add", "NET_ADMIN"])+docker_args = ["docker","run",@@ -322,8 +343,7 @@ class DockerSandbox(SandboxBase):container_name,"--add-host","host.docker.internal:host-gateway",- "--cap-add",- "SYS_PTRACE",+ *cap_args,"-w",WORKING_DIR,f"--memory={config.memory_gb}g",diff --git a/products/tasks/backend/services/sandbox.py b/products/tasks/backend/services/sandbox.pyindex 459aea31aa78..e7f6a66a3fdb 100644--- a/products/tasks/backend/services/sandbox.py+++ b/products/tasks/backend/services/sandbox.py@@ -45,6 +45,7 @@ class SandboxStatus(str, Enum):class SandboxTemplate(str, Enum):DEFAULT_BASE = "default_base"NOTEBOOK_BASE = "notebook_base"+ PI_BASE = "pi_base"class ExecutionResult(BaseModel):diff --git a/tach.toml b/tach.tomlindex 5260d1b5de4b..49178821cd68 100644--- a/tach.toml+++ b/tach.toml@@ -46,7 +46,6 @@ depends_on = ["products.mcp_store","products.notebooks","products.posthog_ai",- "products.product_tours","products.replay","products.revenue_analytics","products.surveys",@@ -86,7 +85,6 @@ depends_on = ["products.notifications","products.posthog_ai","products.product_tours",- "products.query_performance_ai","products.revenue_analytics","products.signals","products.slack_app",@@ -206,7 +204,6 @@ path = "products.error_tracking"depends_on = ["ee","posthog",- "products.logs","products.notifications",]layer = "modules"@@ -374,8 +371,7 @@ layer = "modules"[[modules]]path = "products.query_performance_ai"-depends_on = [- "posthog",+depends_on = ["products.tasks",]layer = "modules"@@ -409,7 +405,6 @@ layer = "modules"[[modules]]path = "products.slack_app"depends_on = [- "ee","posthog","products.dashboards",]