Operate

Doctor RCA agent

LLM-powered root-cause explainer for a slow or failing ClickHouse query. Streams a report over SSE, keys off system.* reads only, checks the optimizer's rewrite against the original before offering it, mutates nothing.

Doctor takes a query that ran badly - a runaway, an out-of-memory, an exception - and returns a structured root-cause report: a verdict, a set of nodes it looked at, a set of prioritised recommendations, and a before-and-after EXPLAIN ESTIMATE on the rewrite the LLM proposes, with a check of whether that rewrite returns the same result as your query. The whole thing streams over Server-Sent Events so the UI can render the report as it forms.

Doctor currently works only for workspaces on Goni’s trial server: its system.* reads go to that server, so it cannot yet diagnose a query that ran on a ClickHouse you attached yourself.

You’ll learn:

  • Where the entry point lives and which role gates it
  • The four-stage lifecycle - prepare, model call, finalize, persist - and what each stage does
  • The guarded read behind the prepare stage, and every guardrail on it
  • How every proposed rewrite is checked before it is offered
  • How Doctor picks its provider (it re-uses your existing BYOK config)
  • Where reports are stored, how long they live, and how the auto-run cooldown behaves
  • What Doctor deliberately does NOT do

What it is

Doctor reads the same system.* tables you would read by hand when a query goes sideways: system.query_log for the failing row, EXPLAIN PLAN for the plan, system.parts for storage layout, system.processes for the current heaviest queries. It rolls those readings into a prompt, makes one call to your configured chat provider with no tools, and parses the reply into a structured report the UI renders in place. When the report proposes a rewrite, a second call reviews it (see The rewrite check). The model answers only from what the prompt carries; it cannot ask for more reads. What leaves your warehouse lists every field the prompt carries. EXPLAIN ESTIMATE and DESCRIBE run after the reply, on the original query and the proposed rewrite, and their results stay in the report.

The click path is simple. On the Query log drawer, hit “Diagnose” on a row. That opens /ops/doctor?query_id=<id> and starts a fresh Doctor run against that query. Doctor can also be triggered automatically off a pulse_threshold alert firing (see below).

URL and access

Doctor lives at /ops/doctor. It accepts either ?query_id=<id> (the common path from the Query log drawer) or ?sql=<encoded> (paste-a-query flow from the IDE). Same admin gate as the rest of the operational tier: the page and the backing endpoint check AllowAdminPolicies and return 403 otherwise. See Access control.

The backing endpoint is a POST that streams SSE:

POST /api/ops/doctor/run
Content-Type: application/json

{
  "query_id": "abcdef12-3456-7890-abcd-ef1234567890",
  "window_hours": 24
}

sql and window_hours are optional. tenant_id is derived from the caller’s JWT and does not need to be sent.

What it does

Doctor is a four-stage pipeline, each stage of which emits one or more SSE frames so the UI stays honest about what is happening:

  • event: prepare frames fire while Doctor is gathering the context: the failing row from system.query_log, EXPLAIN PLAN, a system.parts snapshot on the query’s tables, and the top memory queries currently running. One frame per step, each with a short detail string.
  • event: tool fires before each round trip: provider.diagnose before the diagnosis call (with the first 200 bytes of the SQL under diagnosis), clickhouse.describe before the column check, and provider.check_rewrites before the review call. Full bodies are never streamed.
  • event: verdict fires once, with the final DoctorReport JSON: a verdict (healthy | attention | critical plus a one-sentence summary), a set of nodes (tables, partitions, queries, and plan stages Doctor cited), a set of prioritised recommendations, and a heavy_queries array where each entry carries the LLM’s optimized_query plus a before-and-after EXPLAIN ESTIMATE (scanned_bytes, scanned_rows, parts_read; a leg that could not be measured is null) and the rewrite’s check. The two estimates are collected in parallel via an errgroup so the finalize step does not sit on one leg blocking the other.
  • event: error fires once on any failure - unreachable warehouse, provider refusal, malformed JSON in the reply - and carries a plain {"message": "..."} payload so the UI can render the failure without swallowing it. Provider failures are fixed sentences; the network detail behind them stays in Goni’s server log.
  • Comment lines (: keep-alive) go out every 15 seconds while the model works, so proxies keep the stream open. SSE clients skip them.

The rewrite check

A rewrite the model proposes is only useful if it returns what your query returns. Doctor checks every optimized_query twice before the page offers it:

  1. Columns, on ClickHouse. DESCRIBE TABLE (<query>) returns the output columns of a query without reading any rows. Doctor runs it on your query and on the rewrite, on your workspace’s own database user, and the two lists must match in name, type and order. A rewrite that renames a column, drops one, or turns an integer into a float fails here.
  2. Meaning, by the model. One more call to your provider reviews all the rewrites at once. It gets both queries, their columns and their EXPLAIN ESTIMATE figures, and judges what a column list cannot show: a column that kept its name but holds a different expression, a filter added or dropped, a changed join or grouping.

Each rewrite then carries a check with a status:

  • verified - both checks passed. The page offers it under “Optimized query” with a plain Copy to IDE.
  • not_safe - either check failed. The page shows the reasons and does not offer the copy.
  • not_checked - the check could not finish: no database connection for your workspace, a query ClickHouse could not analyse, or a review call that failed. The page shows the reason and copies the rewrite only as an unverified suggestion.

column_shape_matches and cardinality_ok carry the two results, and null means “not established”, never “passed”. A rewrite that names a table outside your workspace is never run, so it is not_checked.

The system.* reads go through one guarded function, described next.

The guarded read: RunSystemSelect

RunSystemSelect is the function Doctor’s own server-side steps use to read system.query_log, system.parts, and system.processes. The model cannot call it. EXPLAIN takes a separate path: it runs on the workspace’s own database user after the read-only check assertReadOnly. EXPLAIN ESTIMATE and DESCRIBE on the model’s rewrite take that same path; they are the only things Doctor takes from the reply and runs, and neither reads a row.

Six layers of guard on every call, enforced server-side before the SQL touches the driver:

  1. The first keyword must be SELECT or WITH. SHOW, DESCRIBE, EXPLAIN (as a top-level statement), and any DDL is rejected outright.
  2. No semicolons anywhere in the body. Multi-statement smuggling is rejected before any parse.
  3. Banned-keyword scan on top of assertReadOnly: INSERT, UPDATE, DELETE, ALTER, DROP, TRUNCATE, CREATE, GRANT, REVOKE, ATTACH, DETACH, OPTIMIZE, SYSTEM, RENAME, KILL. KILL is here specifically so no read can kill an unrelated query.
  4. Every non-CTE table reference must match system.<name>. Bare table names, default.*, and goni_meta.* are all rejected. CTE aliases used as FROM cte_alias are allowed because the CTE body itself is scanned by the outer check.
  5. Session settings are forced on the per-call context: readonly=1, max_execution_time=8, max_result_rows=200, max_result_bytes=16 MiB. readonly=1 is a driver-level ban on INSERT and DDL even if a mutation slipped past the keyword scan.
  6. The costgate quota pre-hook is bypassed so a Doctor session does not charge the caller’s per-tenant query budget. The post-hook still runs and still writes a query_attribution row stamped with artifact_kind=doctor, so tenants can see what Doctor was doing on their behalf.

The wrapper still routes through chClient.RunSelect, so every Doctor probe carries the same telemetry as a user query: the concurrent-query gauge, the attribution splice, the Sentry breadcrumb.

Provider configuration

Doctor uses the tenant’s configured chat provider. Any BYOK setup that works for Ask works for Doctor - anthropic, openai, mistral, or ollama - and there is no separate gating switch. Air-gapped tenants that cannot reach a cloud provider can point at a self-hosted ollama on 127.0.0.1:11434 with a local model such as llama3.1:70b-instruct-q4_0 and everything downstream continues to work; the SSRF guard has a loopback exception for exactly this case.

Reads and writes to the provider config go through GET / PATCH / DELETE /api/settings/ai, documented under LLM providers and BYOK.

Persistence

Every Doctor run lands as one row in Goni’s control-plane database. The row carries the report JSON, the target query_id (when set), the provider and model that answered, and the wall time the run took. Best-effort - an insert failure on persistence never bubbles up to the SPA. The report you just watched stream in is still valid; it just did not make it into the history table.

Reports are kept for 180 days. Older ones are deleted automatically.

Cooldown on auto-run

Doctor can be triggered automatically by a pulse_threshold alert firing - e.g. “any query has been running longer than 10 minutes” auto-opens a Doctor session against that query and posts the report to the alert’s channel. To keep a flapping threshold from firing Doctor in a loop, an auto-triggered run holds a 15-minute cooldown keyed on (rule_id, tenant_id). Subsequent breaches inside the window are logged and skipped; a real recovery followed by a fresh breach resets the cooldown and lets the next run go through.

Manual click-to-diagnose has no cooldown. A human clicking “Diagnose” on the query-log drawer always gets a fresh run.

What it does NOT do

  • It does not mutate the warehouse. readonly=1 at the driver level, banned-keyword scan at the wrapper level, and the KILL keyword is specifically in the banned list. No INSERT, no ALTER, no OPTIMIZE, no KILL.
  • It does not run the query itself. The rewrite the LLM proposes is delivered in the report as optimized_query. You choose whether to run it. EXPLAIN ESTIMATE and DESCRIBE on both queries, which analyse a query without reading its rows, are the closest the pipeline gets to executing anything user-supplied.
  • It does not send the failing query out to a cloud provider unless you configured a cloud provider. Doctor uses whatever chat provider is set on the tenant’s AI settings; the routing does not silently fall back to a shared key.
  • It does not touch goni_meta.* or any application schema. Its reads only accept system.<name> targets. Data in your marts is unreachable through Doctor.

Last updated