: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
chore(skills): add clickhouse query-performance report skill (#60252)
Robbie46eb51e757bd
diff --git a/.agents/skills/generating-clickhouse-query-performance-reports/SKILL.md b/.agents/skills/generating-clickhouse-query-performance-reports/SKILL.mdnew file mode 100644index 000000000000..e1b28695a51d--- /dev/null+++ b/.agents/skills/generating-clickhouse-query-performance-reports/SKILL.md@@ -0,0 +1,253 @@+---+name: generating-clickhouse-query-performance-reports+description: >+ Produce and structure slow-query performance reports for PostHog's production+ ClickHouse (US and EU). Use when asked for a slow query report, query performance+ analysis over the last N days, per-team query cost, OOM or timeout investigation,+ cluster cost/memory regressions, or materialization candidates. Covers the modern+ `query_log_archive` source (typed `lc_*` columns, multi-day retention), how to+ categorize and attribute slow queries, root-cause patterns (unmaterialized+ JSONExtract, high-cardinality breakdowns, heavy joins), and the report structure.+ Runs queries via the `query-clickhouse-via-metabase` skill.+---++# Generating ClickHouse query performance reports++This skill is the _methodology_ for investigating slow ClickHouse queries and writing up a+performance report. It pairs with [`query-clickhouse-via-metabase`](../query-clickhouse-via-metabase/SKILL.md),+which is the _mechanism_ (SSO-gated auth and `hogli metabase:query`). Run every query in this skill+through that one.++Reports themselves are not public. When it exists, the private `PostHog/query-performance-analysis` repo+holds the historical reports and example query IDs; this repo holds only the tooling and methodology.+That repo is usually checked out as a **sibling folder** to the posthog checkout (e.g.+`../query-performance-analysis` relative to the repo root, or alongside it under the same parent+directory). Look for a sibling directory named `query-performance-analysis` containing an `analysis/`+folder of dated reports. If you find it, **add the new report there as a new markdown file** under+`analysis/`, named `<YYYY-MM-DD>-<topic>.md` (match the existing naming, e.g.+`2026-05-27-slow-queries-14d.md`).++**The sibling repo may not exist, and that is fine.** If you cannot find it, do not write into the public+posthog repo and do not block on it: write the report to a temp folder instead (e.g.+`/tmp/<YYYY-MM-DD>-<topic>.md`), tell the user where you put it, and skip the previous-report comparison+in step 9 (there is no history to diff against).++## Data source: `posthog.query_log_archive` (not `system.query_log`)++`system.query_log` on the production clusters retains only a few **hours**, so it cannot answer a+multi-day question. Use the Distributed archive table instead:++```sql+FROM posthog.query_log_archive+```++It retains roughly three weeks and exposes `log_comment` as typed columns, so you skip `JSONExtract`.+Query it directly (it already fans out across the cluster). Always filter `is_initial_query` so+distributed sub-queries are not double-counted. Confirm current retention with a per-day+`count()` before trusting a window (see `references/query-patterns.md`).++Key columns (full list via `system.columns WHERE table='query_log_archive'`):++| Column | Meaning |+| ----------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |+| `team_id` (Int64) | Tenant. `0` / empty means internal or unattributed. |+| `lc_kind` | How the query was issued: `request` (sync API/web), `celery` (async refresh), `temporal`, `cohort_calculation`, `dagster`. |+| `lc_product` | `product_analytics`, `warehouse`, `experiments`, `messaging`, `web_analytics`, `replay`, `llm_analytics`, `cohorts`, ... |+| `lc_access_method` | `personal_api_key`, `oauth`, `sharing_token`, or empty (logged-in web). |+| `lc_query__kind` | Product query type: `TrendsQuery`, `FunnelsQuery`, `RetentionQuery`, `HogQLQuery`, ... |+| `lc_workload` | `Workload.OFFLINE` / `ONLINE`. |+| `lc_feature`, `lc_temporal__workflow_type`, `lc_route_id`, `lc_api_key_label` | Origin detail for attribution. |+| `lc_dashboard_id`, `lc_insight_id`, `lc_experiment_id`, `lc_cohort_id` | Link a query back to the object that triggered it. |+| `query`, `query_duration_ms`, `read_bytes`, `read_rows`, `memory_usage`, `exception_code` | The query and its cost. |++Both regions have the archive. US and EU are separate clusters with different workloads and+materialized columns; run cross-region comparisons against both. Discover the current ClickHouse+database id per region with `hogli metabase:databases` (ids are not stable). Note that the ONLINE and+OFFLINE Metabase connections for a region fan out to the same logical cluster, so they return the same+`query_log_archive` data.++## What counts as a slow query++```sql+query_duration_ms > 30000 OR exception_code IN (159, 160, 241)+```++| Code | Meaning |+| ---- | --------------------- |+| 159 | TIMEOUT_EXCEEDED |+| 160 | TOO_SLOW |+| 241 | MEMORY_LIMIT_EXCEEDED |++Do **not** add `type = 'QueryFinish'`: OOM and timeout rows are `type = 'ExceptionWhileProcessing'`,+so that filter silently drops every failure. The duration/exception predicate already excludes+`QueryStart` rows (duration 0). Exclude the cluster health-poll query by `normalized_query_hash`+(pattern in `references/query-patterns.md`).++## Producing the report++The standard workflow, building from coarse to specific. Each step's SQL is in+`references/query-patterns.md`.++**Do not read previous reports until step 9.** Steps 1-8 should run against the raw data with fresh eyes,+so the analysis captures the largest surface area rather than re-walking last report's findings. Reading+the prior report early anchors you to its categories and makes it easy to miss a new problem it never+mentioned. Diff against history only after the independent pass is done.++1. **Confirm the window.** Per-day `count()` over the intended range to verify the archive actually+ covers it (retention can be shorter than you expect).+2. **Headline summary.** Total slow queries, total cluster query-hours, bytes read, teams touched,+ and the split across succeeded-but-slow / timeouts / OOMs / other. Also capture the **cluster-wide+ totals across all queries** (not just the slow set): total query-seconds, total CPU-seconds (typed+ `ProfileEvents_OSCPUVirtualTimeMicroseconds` column, not the `Map` lookup), total bytes read, and+ total OOMs (`references/query-patterns.md` §1b). The slow-set sums are a biased subset; the all-query+ totals are the honest "busier / reading more this period?" denominator and the baseline future reports+ diff against. They cannot be backfilled once a window ages past retention, so record them every run.+3. **Date distribution.** Slow count, timeouts, and OOMs per day. This is where incidents announce+ themselves: a multi-day OOM or timeout surge against a flat baseline.+4. **Categorize.** Group by `lc_kind` × `lc_product` × `lc_access_method`. This separates background+ work (data modeling, dagster pre-aggregation, batch exports) from synchronous user-facing queries.+5. **Attribute.** Drill into the worst categories by `team_id`. Rank by **total cluster-hours**+ (`sum(query_duration_ms)`) and by **OOM count** separately. Before calling anything systemic,+ check whether one team or one API key dominates a metric: a single integration querying via a+ `personal_api_key` can account for the large majority of cluster OOMs, and the "incident" is then+ really one tenant. Attribute by `team_id` + `lc_api_key_label` first. Then add a **top-consumers view+ over all queries** (not just the slow set): top teams, top API keys (`lc_api_key_label`), and top apps+ (`lc_product`) ranked by **bytes, CPU-seconds, and wall-time** (`references/query-patterns.md` §4c).+ This is where the heavy-but-fast consumers show up: a tenant or integration can dominate cluster CPU+ or bytes through millions of cheap queries while never crossing the slow threshold, so it is invisible+ to the slow-set ranking. The CPU:wall ratio per row separates compute-bound from wait/IO-bound load.+6. **Characterize user-facing slowness.** For `lc_kind='request' AND lc_product='product_analytics'`+ with empty `lc_access_method` (logged-in web), break down by `lc_query__kind` and flag+ `breakdown_value` usage and JSONExtract over `person_properties`. This is the product-actionable+ bucket. Always include the **JSON-extracted property breakdown** (`references/query-patterns.md` §7):+ the top event vs person property names pulled from JSON blobs in the slow set, and which teams use+ each. These are the materialization candidates and a required report output. `HogQLQuery` (arbitrary+ user- and AI-authored SQL) deserves its own deep dive, including how much is AI-written and why it is+ slow; see `references/hogql-deep-dive.md`.+7. **Root-cause the worst offenders.** For the top findings, do not stop at "team X is slow": pull the+ full query and form a hypothesis for _why_, then test it with EXPLAIN. Root-causing an individual+ query is the [`optimizing-clickhouse-and-hogql-queries`](../optimizing-clickhouse-and-hogql-queries/SKILL.md)+ skill's job; its [`references/investigation-playbook.md`](../optimizing-clickhouse-and-hogql-queries/references/investigation-playbook.md)+ is the playbook (pull the full query, bytes vs CPU vs duration, the runtime causes, origin tracing,+ EXPLAIN). A useful finding includes a why ("scans full history because the time filter is+ function-wrapped and can't prune granules"), even if stated as a hypothesis.+8. **Examples + write-up.** Capture `query_id` + `event_date` for the worst offenders in each finding,+ then write the report (structure below). Because `system.query_log` retention is short, examples are+ resolved from `query_log_archive` (`WHERE query_id = '…' AND event_date = '…'`), not the old Metabase+ lookup card. Link each example to a shareable self-contained Metabase URL (the `query_link` recipe in+ `references/query-patterns.md`) so a reader clicks straight through to the query. When you draft the+ recommendations, **ground the researchable ones in code** by spawning background research agents (see+ "Grounding recommendations in code" below) so a recommendation points at the actual file and change+ rather than saying "audit X".+9. **Diff against the previous report (do this last, if there is one).** If the sibling+ `query-performance-analysis` repo is not present, skip this step entirely. Otherwise, only now, after+ the independent pass above, read the most recent dated report in its `analysis/` folder+ (sort by filename date). Add a short **delta** section to the new report covering: what moved since+ last time (new incidents, findings that grew or resolved, headline numbers up or down), and a+ **follow-up check** on anything the previous report flagged as needing action (a materialization that+ was recommended, a team to watch, a pipeline to make incremental). For each prior follow-up, state+ whether it is resolved, still open, or regressed, with the current numbers as evidence. Doing this+ last is deliberate: it keeps the fresh analysis unbiased while still closing the loop on history.+ **Make the windows comparable before quoting a delta:** confirm the previous report used the same+ window length (both reports here use a trailing `now() - INTERVAL N DAY`, so equal length but with+ overlapping and partial edge days). Headline totals between two trailing windows are usually dominated+ by whichever one-off incident sits inside one window and not the other, so a large drop is rarely a+ structural improvement. Always also compare an **incident-excluded baseline** (e.g. OOMs/day with the+ spike days removed) so the delta is not misread, and say explicitly when a total moved because an+ incident aged into or out of the window. Remember the summed metrics (bytes read, cluster-hours) cover+ the **slow set only**, not total cluster I/O, so they also move when a heavy background job's runs+ cross or stop crossing the 30s threshold; attribute a big bytes/hours swing to specific categories+ (it is usually one or two background pipelines) rather than reporting it as a cluster-wide change.++## Grounding recommendations in code++A recommendation like "audit pipeline X" or "materialize property Y" is far more useful when it points at+the actual code. For each recommendation that maps to a concrete place in the PostHog codebase, **spawn a+background research agent** (the `Agent` tool, `run_in_background: true`, `subagent_type: general-purpose`+or `Explore`) to read the source and return: how the relevant code works today, the specific file /+function to change, any constraints, and whether a better mechanism already exists. Spawn **one agent per+researchable recommendation**, all in a single message so they run in parallel, as soon as the+recommendations are drafted. Let them run while you do the delta (step 9) and finalize the write-up, then+fold each finding into its recommendation: replace "audit X" with "X is implemented in `<file>` as+`<current behavior>`; the change is `<specific>`", and cite the file paths so the human can jump straight+in. The agents research and report only; they do not change code.++Not every recommendation is researchable this way. Spawn an agent only where source code is the source of+truth; skip operational / infra items:++| Recommendation shape | Researchable? | What the agent reads |+| ---------------------------------------- | ------------- | ------------------------------------------------------------------------ |+| Rewrite a slow insight / query shape | yes | the query runner under `posthog/hogql_queries/`, the HogQL it emits |+| Materialize property X | yes | the materialized-column registry (`ee/clickhouse/materialized_columns/`) |+| Make pipeline Y incremental | yes | the dagster / temporal job that builds it |+| Cap memory / add a query guard per key | yes | where ClickHouse SETTINGS and per-key throttling are applied |+| Add a breakdown cardinality guard | yes | the trends / breakdown query runner |+| Investigate an infra incident window | no | n/a (deploys, node health, cluster state) |+| Watch / confirm a tenant's intended load | no | n/a (a judgement call for a human) |++Give each agent a focused prompt: the recommendation, the specific question, and an instruction to return+file paths + current behavior + the precise change point and to change nothing. The agents read the+posthog repo (where this skill lives); the report itself is written to the separate+`query-performance-analysis` repo.++## Interpreting the results++- **Two populations live in "slow queries."** Tight-timeout API noise (queries erroring at ~10s+ against a low `max_execution_time`, usually `personal_api_key`) inflates the raw count without+ representing real compute. Genuinely expensive work is better measured by total cluster-hours and+ OOM count. Always call this distinction out; do not let timeout volume masquerade as slowness.+- **Bytes read is the truest cost signal**, more than duration (which varies with cache and cluster+ load). High bytes against low rows means heavy columns, almost always JSONExtract over a `properties`+ blob. For root-causing individual queries, see the+ [`optimizing-clickhouse-and-hogql-queries`](../optimizing-clickhouse-and-hogql-queries/SKILL.md) skill.+- **Background pipelines usually dominate raw cluster-time** (data-modeling DAGs, web-analytics+ pre-aggregation). That is expected; weigh them by whether their scan volume is necessary, separately+ from user-facing latency.++## Report structure++A report should contain, in order:++1. One-line scope: region, window, and the slow definition / exclusions used.+2. Headline numbers table + the **cluster-wide totals (all queries)** table (total query-seconds,+ CPU-seconds, bytes read, OOMs) + the two-populations caveat.+3. Daily distribution table (flag any incident window).+4. Findings, worst first. **Every finding needs at least one concrete `query_id` + `event_date`,+ linked via the shareable `query_link` URL** (see `references/query-patterns.md`) so a reader clicks+ straight through to the exact query, plus a **hypothesis for why it is slow** (from the+ [`optimizing-clickhouse-and-hogql-queries`](../optimizing-clickhouse-and-hogql-queries/SKILL.md)+ skill's investigation playbook). Group findings by what they are: a per-tenant incident, the+ heaviest cluster-time consumers, user-facing insight slowness, and tight-timeout API noise.+5. A **top-consumers-by-resource section** (all queries, not just slow): top teams, top API keys, and+ top apps (`lc_product`) ranked by bytes / CPU / wall-time (`references/query-patterns.md` §4c), calling+ out consumers that never trip the slow threshold and the compute-bound vs wait-bound split.+6. A **JSON-extracted property table**: the top event and person property names pulled from JSON blobs+ in the slow set, with the teams using each (`references/query-patterns.md` §7). These are the+ materialization candidates.+7. Concrete recommendations tied to each finding (materialize property X, cap memory per API key,+ make pipeline Y incremental, ...). Ground the researchable ones in code (see "Grounding+ recommendations in code"): cite the file / function and the specific change, not just "audit X".+8. A **delta vs the previous report** (step 9): what changed since last time, plus a follow-up check on+ each action the previous report recommended (resolved / still open / regressed, with numbers). Omit+ this section when there is no previous report.++Save the finished report as `analysis/<YYYY-MM-DD>-<topic>.md` in the sibling+`query-performance-analysis` repo, never in the public posthog repo; if that repo is not present, save to+a temp folder (e.g. `/tmp/<YYYY-MM-DD>-<topic>.md`) and tell the user the path.++## References++- `references/query-patterns.md`: ready-to-run SQL for every step above, against `query_log_archive`.+- `references/materialization-analysis.md`: finding properties to materialize and columns to drop,+ run across both US and EU.+- `references/hogql-deep-dive.md`: analyzing `HogQLQuery` (arbitrary user/AI SQL) specifically,+ including how to identify AI-written HogQL (`lc_product`/`lc_feature`, not `ai_query_source`) and the+ causes that make ad-hoc and AI queries slow.++## Related skills++This skill is fleet-level: it finds and ranks slow queries across all teams and writes the report. Once a+finding points at one query you want to explain or fix, switch to+[`optimizing-clickhouse-and-hogql-queries`](../optimizing-clickhouse-and-hogql-queries/SKILL.md) — it+owns root-causing an individual query (its `references/investigation-playbook.md`) and applying the fix at+the right layer (printer, query runner, or ClickHouse migration).diff --git a/.agents/skills/generating-clickhouse-query-performance-reports/references/hogql-deep-dive.md b/.agents/skills/generating-clickhouse-query-performance-reports/references/hogql-deep-dive.mdnew file mode 100644index 000000000000..d4972e0ccbcc--- /dev/null+++ b/.agents/skills/generating-clickhouse-query-performance-reports/references/hogql-deep-dive.md@@ -0,0 +1,110 @@+# HogQL deep dive++`lc_query__kind = 'HogQLQuery'` is its own analysis bucket because, unlike product-generated insights+(TrendsQuery, FunnelsQuery, ...), HogQL is **arbitrary user- or AI-authored SQL**. It runs from the SQL+editor / DataVisualization node (web), the `/query/` API (`personal_api_key` / `oauth`), the MCP server,+and the Max assistant. It bypasses the guardrails that shape product insights (no enforced date range,+no materialization-aware property access, arbitrary joins), so its slowness causes are more varied and+it is over-represented among OOMs and timeouts.++Two columns matter for HogQL:++- `query` — the compiled ClickHouse SQL that actually ran.+- `lc_query__query` — the **source HogQL** the user or AI wrote. Read this to see intent; it is far+ shorter and clearer than the compiled SQL, and the `query_link` recipe (`query-patterns.md` §6)+ already selects it.++## Landscape: who issues the slow HogQL++```sql+SELECT+ lc_product, lc_feature, lc_access_method,+ count() AS slow,+ uniqExact(team_id) AS teams,+ countIf(exception_code = 241) AS ooms,+ countIf(exception_code = 159) AS timeouts,+ round(avg(query_duration_ms)/1000) AS avg_s,+ formatReadableSize(sum(read_bytes)) AS total_read+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY AND is_initial_query+ AND lc_query__kind = 'HogQLQuery'+ AND (query_duration_ms > 30000 OR exception_code IN (159,160,241))+GROUP BY lc_product, lc_feature, lc_access_method+ORDER BY slow DESC LIMIT 40+```++The bulk is `product_analytics` / `query` / `personal_api_key` (data integrations and API consumers).+Tight-timeout API noise (avg ~13s, mostly timeouts) and `cache_warmup` (background insight refresh)+dominate raw counts; weigh by OOMs and cluster-hours as usual.++## Identifying AI-written HogQL++There is **no single boolean "written by AI" column.** Identify it from `lc_product` + `lc_feature`:++| Signal | Means |+| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |+| `lc_product = 'max_ai'` | PostHog's Max assistant and its tools (tagged via `tags_context(product=Product.MAX_AI)` throughout `ee/hogai/**`) |+| `lc_product = 'mcp'` or `lc_feature = 'mcp'` | Queries issued by external AI agents through the PostHog MCP server |+| `lc_feature = 'posthog_ai'` | The AI feature tag (also exists; less common in practice) |++Filter: `lc_product IN ('max_ai','mcp') OR lc_feature IN ('mcp','posthog_ai')`.++**Do not use `ai_query_source`.** Despite the name it records which AI-events table the LLM-analytics+resolver chose (`dedicated_table` / `shared_table` / `shared_table_fallback`), not "AI authored this".+It is also not materialized as an `lc_*` column in the archive.++Caveats:++- This flags queries executed _within_ an AI/MCP context. An insight Max drafts that a human then saves+ and reloads is re-tagged as normal `product_analytics`; the archive cannot tell it was AI-originated.+- Heuristic tell: AI-written HogQL often carries explanatory `-- …` comments in `lc_query__query`+ (people rarely comment ad-hoc SQL). Useful as a secondary signal, not authoritative.+- Source of truth for the tags: the `Product` / `Feature` enums and the product-from-node-kind mapping+ in `posthog/clickhouse/query_tagging.py`; call sites in `ee/hogai/**` and the MCP server.++```sql+SELECT+ lc_product, lc_feature, lc_access_method,+ count() AS slow,+ uniqExact(team_id) AS teams,+ countIf(exception_code = 241) AS ooms,+ countIf(exception_code = 159) AS timeouts,+ round(100 * countIf(exception_code = 241) / count()) AS oom_pct+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY AND is_initial_query+ AND lc_query__kind = 'HogQLQuery'+ AND (lc_product IN ('max_ai','mcp') OR lc_feature IN ('mcp','posthog_ai'))+ AND (query_duration_ms > 30000 OR exception_code IN (159,160,241))+GROUP BY lc_product, lc_feature, lc_access_method+ORDER BY slow DESC+```++AI/MCP HogQL OOMs and times out at a disproportionately high rate (the MCP-over-OAuth bucket has seen+roughly a third of its slow queries OOM in a single week), because these are ambitious analytical+queries written without the guardrails of product-generated insights.++## What makes AI / ad-hoc HogQL slow++Read `lc_query__query` on the slow set; the recurring causes:++- **Unmaterialized JSON extraction.** The AI writes `JSONExtractString(properties, 'x')` or+ `properties.x` on event or person properties. The `JSONExtract*(...)` call form bypasses+ materialization (see the+ [`optimizing-clickhouse-and-hogql-queries`](../../optimizing-clickhouse-and-hogql-queries/references/investigation-playbook.md)+ investigation playbook and `materialization-analysis.md`), forcing a full JSON-blob read per row.+- **Self-joins and cross joins on `events`.** e.g. `events e1 JOIN events e2` on person within a time+ window, or `CROSS JOIN` with a per-person aggregate. Multiplies the scan.+- **Cross-source joins.** Joining warehouse tables (`postgres.*`, `vitally.*`, `s3(...)`) against+ events; the external side has no ClickHouse indexing.+- **No or wide date range.** Ad-hoc SQL often omits a tight `timestamp` filter, scanning all history.+- **Full exports ordered by a wide column.** See the function-wrapped sort/filter-key anti-pattern in+ the [`optimizing-clickhouse-and-hogql-queries`](../../optimizing-clickhouse-and-hogql-queries/references/investigation-playbook.md)+ investigation playbook.++To inspect one AI query, pull both forms:++```sql+SELECT lc_query__query AS source_hogql, query AS compiled_sql, exception+FROM posthog.query_log_archive+WHERE query_id = '<id>' AND event_date = '<YYYY-MM-DD>' AND is_initial_query+```diff --git a/.agents/skills/generating-clickhouse-query-performance-reports/references/materialization-analysis.md b/.agents/skills/generating-clickhouse-query-performance-reports/references/materialization-analysis.mdnew file mode 100644index 000000000000..e80705d28c61--- /dev/null+++ b/.agents/skills/generating-clickhouse-query-performance-reports/references/materialization-analysis.md@@ -0,0 +1,106 @@+# Materialization analysis++Finding properties worth materializing (to stop JSONExtract scans) and materialized columns worth+dropping (to reclaim disk). **Always run on both US and EU**, since they have different materialized+columns and workloads, so the candidate lists differ. Write the result to the private+`PostHog/query-performance-analysis` repo as `analysis/<date>-materialization-candidates.md`.++Run everything via `query-clickhouse-via-metabase`. Split wide column-list checks into batches of ~5-6+to stay under the Metabase response cutoff.++## Step 1: Candidates to materialize++The candidate list is the JSON-extracted property breakdown from `query-patterns.md` §7: which property+names slow queries pull out of a JSON blob, split by `column` (event `properties`, `person_properties`,+or `group_properties`), with the teams driving each. Run that query (widen the window to ~30 days for+materialization, since a property is worth materializing if it is hit consistently). Rank by+`slow_queries` and `teams`; a property hit by many slow queries across several teams is the strongest+candidate. The `column` tells you which blob it lives on, which the dagster job needs (table,+table_column, property).++To recover the table + column for a specific candidate:++```sql+SELECT+ arrayDistinct(extractAll(query, '(\\w+)\\.\\w*properties,\\s*''<PROPERTY>''')) AS table_aliases,+ arrayDistinct(extractAll(query, '\\w+\\.(\\w*properties),\\s*''<PROPERTY>''')) AS columns+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 7 DAY AND query LIKE '%<PROPERTY>%' LIMIT 100+```++## Step 2: What is already materialized++```sql+SHOW CREATE TABLE sharded_events+```++Cross-reference against Step 1 to split "needs materializing" from "bypassing an existing mat column".+A bypass (mat column exists but queries still JSONExtract) usually means the property is accessed as+`JSONExtractString(properties, '$foo')` in user-written HogQL, which creates an `ast.Call` that skips+`visit_property_type()`, rather than `properties.$foo` which materializes. Known sources: HogQL /+DataVisualization nodes and some survey SQL.++## Step 3: Drop candidates++A materialized column is only **safe to drop** when it has zero queries over 30 days **and** zero data.+Usage must be checked across **all** queries, not just slow ones.++```sql+-- usage: does any query reference the column? (targeted countIf per column to avoid timeouts)+SELECT countIf(query LIKE '%mat_<col>%') AS uses+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 30 DAY AND is_initial_query+```++```sql+-- disk size+SELECT name, formatReadableSize(sum(data_compressed_bytes)) AS compressed+FROM clusterAllReplicas(posthog, system, columns)+WHERE table = 'sharded_events' AND name LIKE 'mat_%'+GROUP BY name ORDER BY sum(data_compressed_bytes) DESC+```++```sql+-- data presence before dropping (batch the column list)+SELECT+ countIf(mat_<col> != '') AS nonempty_<col>,+ uniqExactIf(team_id, mat_<col> != '') AS teams_<col>+FROM events+WHERE timestamp > now() - INTERVAL 7 DAY+```++Read data presence from the Distributed `events` table, not `clusterAllReplicas(...)` over the local+`sharded_events`. The Distributed table fans out to one replica per shard, so each row is counted once;+`clusterAllReplicas` hits every replica and multiplies the counts by the replication factor. Use+`clusterAllReplicas` only for non-Distributed system tables (as the disk-size query above does with+`system.columns`).++- Zero queries + zero data → safe to drop.+- Zero queries + active data → risky. Dropping does not lose data (it stays in the JSON blob) but+ re-materializing later needs an expensive backfill. Record as an optional drop with size + team info.++## Step 4: Dagster jobs++These jobs must be run by a human operator with dagster access; you cannot run them yourself. Before+running anything, the operator should sanity-check with #team-clickhouse that the cluster is not in a bad+state (backfills and materializations add load, so they must not land while the cluster is already+struggling). Hand the operator the configs below as a recommendation rather than executing them.++- Create: `create_materialized_column` (team-clickhouse location, per region). Backfilling adds cluster+ load, so schedule for a weekend.+- Drop: `drop_materialized_column` (defaults to `dry_run: true`; minimal impact).++## Report format++Start with four recommendation tables, then dagster configs, then the investigation detail.++New materializations:++| Table | Column | Property | Slow queries (30d) | Teams | Timeouts | Avg read | Max read | Est. column size |++Drop candidates:++| Column | Compressed | Non-empty events | Teams | Safe to drop? |++Put US-new, EU-new, US-drop, EU-drop as separate tables. Optional drops (no queries but active data) go+into the same dagster config as commented-out entries with their size and team info.diff --git a/.agents/skills/generating-clickhouse-query-performance-reports/references/query-patterns.md b/.agents/skills/generating-clickhouse-query-performance-reports/references/query-patterns.mdnew file mode 100644index 000000000000..84313676f0e4--- /dev/null+++ b/.agents/skills/generating-clickhouse-query-performance-reports/references/query-patterns.md@@ -0,0 +1,369 @@+# Slow-query report: ready-to-run patterns++All queries run against `posthog.query_log_archive` via `hogli metabase:query --region <us|eu>+--database-id <id>` (discover the id with `hogli metabase:databases`). Save wide results with+`--save <path>`. `now() - INTERVAL 14 DAY` = "last two weeks"; adjust the interval per request.++The health-poll exclusion below removes the cluster's own liveness probe so it does not show up as a+"slow query"; keep it in every aggregate.++```sql+AND normalized_query_hash != normalizedQueryHash('SELECT hostname(), query_id FROM clusterAllReplicas(posthog, system.processes) WHERE query_id LIKE ? SETTINGS max_execution_time = 2')+```++## 0. Confirm retention covers the window++Run this first. If the earliest day is later than your window start, the archive does not go back far+enough and the report must say so.++```sql+SELECT toDate(event_time) AS day, count() AS rows+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 21 DAY+GROUP BY day ORDER BY day+```++## 1. Headline summary++Do not wrap the slow predicate in a CTE that projects only some columns: ClickHouse's analyzer prunes+columns and then cannot resolve a column used only in `WHERE`. Filter in the main query.++```sql+SELECT+ count() AS total_slow,+ round(sum(query_duration_ms)/3600000, 0) AS total_hours,+ round(avg(query_duration_ms)/1000) AS avg_s,+ round(max(query_duration_ms)/1000) AS max_s,+ countIf(exception_code = 0) AS ok_slow,+ countIf(exception_code = 159) AS timeouts,+ countIf(exception_code = 241) AS ooms,+ countIf(exception_code NOT IN (0,159,160,241)) AS other_exc,+ countIf(lc_access_method = 'personal_api_key') AS via_api_key,+ uniqExact(team_id) AS teams,+ formatReadableSize(sum(read_bytes)) AS total_read+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY+ AND is_initial_query+ AND (query_duration_ms > 30000 OR exception_code IN (159,160,241))+ AND normalized_query_hash != normalizedQueryHash('SELECT hostname(), query_id FROM clusterAllReplicas(posthog, system.processes) WHERE query_id LIKE ? SETTINGS max_execution_time = 2')+```++Quantiles (p90/p99) over the full set are expensive and can hit the Metabase ~60s cutoff. If the query+is cancelled, drop the quantiles or shorten the window.++## 1b. Cluster-wide totals (all queries, the honest denominator)++The headline above is the slow set only, which is a biased subset (~0.2% of queries but a large share of+bytes and query-time). Capture the totals across **all** `is_initial_query` queries too, so the report+records the real denominator and a baseline future reports can diff against. Record total query-seconds,+total CPU-seconds, total bytes read, and total OOMs.++Use the **typed flattened** `ProfileEvents_OSCPUVirtualTimeMicroseconds` column for CPU time. Do **not**+use `ProfileEvents['OSCPUVirtualTimeMicroseconds']` (the `Map` form): a map lookup over the full+~180M-row window times out even at a 300s client timeout, while the typed Int64 column sums in seconds.++```sql+SELECT+ count() AS all_queries,+ round(sum(query_duration_ms)/1000, 0) AS total_query_seconds,+ round(sum(ProfileEvents_OSCPUVirtualTimeMicroseconds)/1e6, 0) AS total_cpu_seconds,+ formatReadableSize(sum(read_bytes)) AS total_read_all,+ countIf(exception_code = 241) AS total_ooms+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY AND is_initial_query+```++CPU-seconds exceed wall query-seconds because queries run multi-threaded; the ratio is rough average+parallelism. `total_ooms` here equals the slow-set OOM count (every OOM is in the slow set by+definition), so it is directly comparable across reports even when the all-query totals are not yet+available historically. These all-query totals cannot be backfilled for an old report once its window+ages past the archive's ~3-week retention.++## 2. Daily distribution++```sql+SELECT+ toDate(event_time) AS day,+ count() AS slow,+ countIf(exception_code = 159) AS timeouts,+ countIf(exception_code = 241) AS ooms,+ round(sum(query_duration_ms)/3600000, 1) AS total_hours+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY+ AND is_initial_query+ AND (query_duration_ms > 30000 OR exception_code IN (159,160,241))+ AND normalized_query_hash != normalizedQueryHash('SELECT hostname(), query_id FROM clusterAllReplicas(posthog, system.processes) WHERE query_id LIKE ? SETTINGS max_execution_time = 2')+GROUP BY day ORDER BY day+```++## 3. Category breakdown++The backbone of the report: it separates background work from synchronous user-facing queries.++```sql+SELECT+ lc_kind, lc_product, lc_access_method,+ count() AS slow,+ uniqExact(team_id) AS teams,+ countIf(exception_code = 0) AS ok_slow,+ countIf(exception_code = 159) AS timeouts,+ countIf(exception_code = 241) AS ooms,+ countIf(exception_code NOT IN (0,159,160,241)) AS other_exc,+ round(sum(query_duration_ms)/3600000, 1) AS total_hours,+ round(avg(query_duration_ms)/1000) AS avg_s,+ round(quantile(0.95)(query_duration_ms)/1000) AS p95_s,+ formatReadableSize(sum(read_bytes)) AS total_read+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY+ AND is_initial_query+ AND (query_duration_ms > 30000 OR exception_code IN (159,160,241))+ AND normalized_query_hash != normalizedQueryHash('SELECT hostname(), query_id FROM clusterAllReplicas(posthog, system.processes) WHERE query_id LIKE ? SETTINGS max_execution_time = 2')+GROUP BY lc_kind, lc_product, lc_access_method+ORDER BY slow DESC LIMIT 40+```++## 4a. Per-team offenders by total cluster-time++```sql+SELECT+ team_id, lc_product, lc_kind,+ count() AS slow,+ countIf(exception_code = 241) AS ooms,+ countIf(exception_code = 159) AS timeouts,+ round(sum(query_duration_ms)/3600000, 1) AS total_hours,+ round(avg(query_duration_ms)/1000) AS avg_s,+ round(max(query_duration_ms)/1000) AS max_s,+ formatReadableSize(sum(read_bytes)) AS total_read+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY+ AND is_initial_query+ AND (query_duration_ms > 30000 OR exception_code IN (159,160,241))+ AND team_id != 0+ AND normalized_query_hash != normalizedQueryHash('SELECT hostname(), query_id FROM clusterAllReplicas(posthog, system.processes) WHERE query_id LIKE ? SETTINGS max_execution_time = 2')+GROUP BY team_id, lc_product, lc_kind+ORDER BY total_hours DESC LIMIT 30+```++## 4b. OOM attribution++Rank OOMs by team + product + API key. If one row dominates, the cluster OOM "spike" is one tenant.++```sql+SELECT+ team_id, lc_product, lc_access_method, lc_kind, lc_api_key_label,+ countIf(exception_code = 241) AS ooms,+ round(avg(query_duration_ms)/1000) AS avg_s,+ formatReadableSize(avg(memory_usage)) AS avg_mem,+ formatReadableSize(sum(read_bytes)) AS total_read+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY+ AND is_initial_query+ AND exception_code = 241+GROUP BY team_id, lc_product, lc_access_method, lc_kind, lc_api_key_label+ORDER BY ooms DESC LIMIT 25+```++To confirm an incident's timing and source, pin to the suspect team and watch it per day:++```sql+SELECT toDate(event_time) AS day, countIf(exception_code = 241) AS ooms, count() AS total,+ any(lc_query__kind) AS qkind, any(lc_route_id) AS route, any(lc_api_key_label) AS key_label+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY AND is_initial_query AND team_id = <TEAM_ID>+GROUP BY day ORDER BY day+```++## 4c. Top consumers by resource (all queries, not just slow)++Attribute total cluster resource use across **all** `is_initial_query` queries, not just the slow set:+this catches consumers that cost the cluster through many cheap queries without ever crossing the slow+threshold (and so are invisible to 4a/4b). Report top teams, top API keys, and top apps by **all three of+bytes / CPU / wall-time** (the leader differs by metric). Use the typed+`ProfileEvents_OSCPUVirtualTimeMicroseconds` column, not the `Map` lookup (§1b). Re-run each block with a+different `ORDER BY` (`cpu_hours`, `sum(read_bytes)`, `query_hours`) to get the per-metric leaders. The+CPU:wall ratio per row separates compute-bound (ratio >> 1, highly parallel) from wait/IO-bound (ratio+~1 or below) consumers.++```sql+-- top teams (swap ORDER BY for the bytes / wall-time rankings)+SELECT team_id,+ round(sum(query_duration_ms)/3600000, 0) AS query_hours,+ round(sum(ProfileEvents_OSCPUVirtualTimeMicroseconds)/3.6e9, 0) AS cpu_hours,+ formatReadableSize(sum(read_bytes)) AS bytes_read,+ countIf(exception_code = 241) AS ooms,+ count() AS queries+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY AND is_initial_query AND team_id != 0+GROUP BY team_id ORDER BY cpu_hours DESC LIMIT 15+```++```sql+-- top named API keys / integrations (lc_api_key_label); swap ORDER BY as above+SELECT lc_api_key_label,+ round(sum(query_duration_ms)/3600000, 0) AS query_hours,+ round(sum(ProfileEvents_OSCPUVirtualTimeMicroseconds)/3.6e9, 0) AS cpu_hours,+ formatReadableSize(sum(read_bytes)) AS bytes_read,+ countIf(exception_code = 241) AS ooms, uniqExact(team_id) AS teams, count() AS queries+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY AND is_initial_query AND lc_api_key_label != ''+GROUP BY lc_api_key_label ORDER BY cpu_hours DESC LIMIT 15+```++```sql+-- top apps (lc_product), cluster-wide (this is the all-query counterpart to the §3 slow-set categories)+SELECT lc_product,+ round(sum(query_duration_ms)/3600000, 0) AS query_hours,+ round(sum(ProfileEvents_OSCPUVirtualTimeMicroseconds)/3.6e9, 0) AS cpu_hours,+ formatReadableSize(sum(read_bytes)) AS bytes_read,+ countIf(exception_code = 241) AS ooms, uniqExact(team_id) AS teams, count() AS queries+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY AND is_initial_query+GROUP BY lc_product ORDER BY cpu_hours DESC LIMIT 15+```++A grouped aggregation over the full ~180M-row window is heavier than the slow-set queries; if Metabase+returns a 502 or times out, retry (transient) or raise `--timeout`. `any(lc_product)` per team is+non-deterministic (a team spans products), so annotate notable teams by hand rather than trusting it.++## 5. User-facing insight characterization++Synchronous web product-analytics queries (the ones a logged-in user waits on), by query kind, with+the two most common slowness signals.++```sql+SELECT+ lc_query__kind AS qkind,+ count() AS slow,+ uniqExact(team_id) AS teams,+ countIf(exception_code = 241) AS ooms,+ countIf(exception_code = 159) AS timeouts,+ round(avg(query_duration_ms)/1000) AS avg_s,+ countIf(query LIKE '%person_properties%' AND query LIKE '%JSONExtract%') AS json_person_props,+ countIf(query LIKE '%breakdown_value%') AS breakdowns,+ formatReadableSize(sum(read_bytes)) AS total_read+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY AND is_initial_query+ AND lc_kind = 'request' AND lc_product = 'product_analytics' AND lc_access_method = ''+ AND (query_duration_ms > 30000 OR exception_code IN (159,160,241))+GROUP BY qkind ORDER BY slow DESC LIMIT 15+```++## 6. Example queries for the write-up++Use `--format json` and pull `query_id` + `event_date`. Bound the duration to skip a single stuck+outlier that would otherwise top the list. The `substring(query, 1, 160)` here is only for skimming the+list; when you drill into one query, pull the **full** `query` text (see the+[`optimizing-clickhouse-and-hogql-queries`](../../optimizing-clickhouse-and-hogql-queries/references/investigation-playbook.md)+investigation playbook — the `ORDER BY` / `WHERE` / `SETTINGS` tail is where the cause usually is).++```sql+SELECT query_id, event_date, team_id, lc_product, lc_kind, lc_query__kind,+ lc_temporal__workflow_type AS wf, lc_dashboard_id AS dash, lc_insight_id AS insight,+ query_duration_ms, exception_code,+ formatReadableSize(read_bytes) AS read, formatReadableSize(memory_usage) AS mem,+ substring(query, 1, 160) AS q+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY AND is_initial_query+ AND (query_duration_ms > 30000 OR exception_code IN (159,160,241))+ AND query_duration_ms BETWEEN 60000 AND 5000000+ORDER BY query_duration_ms DESC LIMIT 20+```++Resolve any example later from the archive (the short-retention `system.query_log` lookup card will+miss anything older than a few hours):++```sql+SELECT * FROM posthog.query_log_archive+WHERE query_id = '<id>' AND event_date = '<YYYY-MM-DD>' AND is_initial_query+```++### Shareable link to a single query++For each example in a report, link to a self-contained Metabase URL that carries the SQL in its hash+fragment, so a reader clicks straight through to the query in `query_log_archive`. This survives the+short `system.query_log` retention (unlike the old `795-look-up-query-by-query-id` card). Build it by+base64-encoding the native-query payload:++```python+import base64, json++BASE = {"us": "https://metabase.prod-us.posthog.dev", "eu": "https://metabase.prod-eu.posthog.dev"}++def _ch_literal(value: str) -> str:+ # query_id derives from the caller-supplied client_query_id, so it can contain a single quote.+ # Escape for a ClickHouse single-quoted literal by doubling quotes. Treat this as required, not+ # cosmetic: Metabase may execute the embedded native query on load, so an unescaped quote is a real+ # injection vector, not just malformed SQL in an editor.+ return str(value).replace("'", "''")++def query_link(query_id, event_date, region="us", database_id=43):+ # database_id is a ClickHouse connection on the cluster (US 43). IDs can change when Metabase's+ # metadata is rebuilt: rediscover with `hogli metabase:databases` and any ClickHouse id works,+ # since query_log_archive is a Distributed table. EU needs its own id.+ sql = (f" SELECT lc_query__query FROM posthog.query_log_archive\n"+ f" WHERE query_id = '{_ch_literal(query_id)}'\n"+ f" AND event_date = '{_ch_literal(event_date)}' AND is_initial_query")+ payload = {+ "dataset_query": {"type": "native", "native": {"query": sql, "template-tags": {}}, "database": database_id},+ "display": "table", "parameters": [], "visualization_settings": {},+ }+ blob = base64.b64encode(json.dumps(payload, separators=(",", ":")).encode()).decode()+ return f"{BASE[region]}/question#{blob}"+```++`SELECT lc_query__query` shows the originating product query; widen the SELECT (e.g. `*`, or `query`+for the executed ClickHouse SQL) if you want more detail in the linked view. Example output:++```text+https://metabase.prod-us.posthog.dev/question#eyJkYXRhc2V0X3F1ZXJ5Ijp7InR5cGUiOiJuYXRpdmUiLCJ...+```++## 7. JSON-extracted properties: which names, which teams++A core report output and the input to materialization. Pulls the property names that slow queries+`JSONExtract` out of a JSON blob, split by which blob (`properties` = event, `person_properties` =+person, `group_properties` = group), with the teams driving each. `extractAllGroupsVertical` returns+one `[alias, column, name]` triple per match; `ARRAY JOIN` explodes them.++```sql+SELECT+ column, -- properties (event) | person_properties | group_properties+ property,+ sum(c) AS slow_queries,+ uniqExact(team_id) AS teams,+ sum(failures) AS failures, -- OOM + timeout among them+ arraySlice(arrayReverseSort(x -> x.2, groupArray((team_id, c))), 1, 5) AS top_teams_by_count+FROM (+ SELECT g[2] AS column, g[3] AS property, team_id,+ count() AS c,+ countIf(exception_code IN (159,160,241)) AS failures+ FROM posthog.query_log_archive+ ARRAY JOIN extractAllGroupsVertical(query, 'JSONExtract\\w*\\((\\w+)\\.(\\w*properties),\\s*''([^'']+)''') AS g+ WHERE event_time > now() - INTERVAL 14 DAY+ AND is_initial_query+ AND (query_duration_ms > 30000 OR exception_code IN (159,160,241))+ AND query LIKE '%JSONExtract%'+ GROUP BY column, property, team_id+)+GROUP BY column, property+ORDER BY slow_queries DESC LIMIT 30+```++`top_teams_by_count` reads as `[[team_id, query_count], ...]`. Caveat: a query that extracts N+properties contributes one row per property after the `ARRAY JOIN`, so `slow_queries` counts+property-occurrences, not distinct queries (which is what you want for ranking materialization+candidates). The regex captures the first key only, so a nested path `JSONExtract(properties, 'a', 'b')`+shows as `a`.++To drill one property and list every team using it:++```sql+SELECT team_id, count() AS slow_queries,+ countIf(exception_code IN (159,160,241)) AS failures,+ formatReadableSize(avg(read_bytes)) AS avg_read+FROM posthog.query_log_archive+WHERE event_time > now() - INTERVAL 14 DAY AND is_initial_query+ AND (query_duration_ms > 30000 OR exception_code IN (159,160,241))+ AND match(query, 'JSONExtract\\w*\\(\\w+\\.\\w*properties,\\s*''<PROPERTY>''')+GROUP BY team_id ORDER BY slow_queries DESC LIMIT 30+```diff --git a/.agents/skills/optimizing-clickhouse-and-hogql-queries/SKILL.md b/.agents/skills/optimizing-clickhouse-and-hogql-queries/SKILL.mdindex 70195eb2da86..ac04396d14ce 100644--- a/.agents/skills/optimizing-clickhouse-and-hogql-queries/SKILL.md+++ b/.agents/skills/optimizing-clickhouse-and-hogql-queries/SKILL.md@@ -108,6 +108,14 @@ For HogQL queries, three ways to get from HogQL to executable ClickHouse SQL; piBefore reaching for tools, eyeball the SQL for the patterns that account for most slow ClickHouse queries.+The smells below are the view from the SQL: shapes that are bad on sight. When you instead have a+specific slow query (usually pulled from production) and need to work backwards from its runtime cost to+the cause, [`references/investigation-playbook.md`](references/investigation-playbook.md) is the deep+dive: pulling the full query, reading bytes vs CPU vs duration, the fuller list of runtime causes+(high-cardinality breakdowns, function-wrapped sort keys that defeat granule pruning, ratio-metric double+scans), tracing a query back to the product code that issued it, and using EXPLAIN to confirm a+hypothesis.+### `FROM <table> FINAL``FROM person FINAL`, `FROM groups FINAL`, `FROM cohortpeople FINAL`, or any other `FINAL` on a ReplacingMergeTree / CollapsingMergeTree / AggregatingMergeTree table forces ClickHouse to run an on-the-fly merge across every part it reads, deduplicating to the latest version per sort-key row. It defeats parallel reads, blows up memory, and scales badly with part count. On large tables (`person`, anything sharded) it is rarely the right answer.@@ -168,7 +176,7 @@ ClickHouse `EXPLAIN` works on a dev instance even without representative data, b- `EXPLAIN ESTIMATE SELECT ...` for per-part row/mark estimates- `EXPLAIN SYNTAX SELECT ...` for the normalized SQL after parsing-See the [ClickHouse EXPLAIN docs](https://clickhouse.com/docs/sql-reference/statements/explain) for the full option matrix.+See the [ClickHouse EXPLAIN docs](https://clickhouse.com/docs/sql-reference/statements/explain) for the full option matrix. For the hypothesis-testing technique — EXPLAINing the suspect query and a fixed variant side by side and diffing `Granules`, `ReadType`, and Prewhere-vs-primary-key — plus which variants do a small metadata read rather than being entirely free, see [`references/investigation-playbook.md`](references/investigation-playbook.md).## Step 4: measure for realdiff --git a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/investigation-playbook.md b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/investigation-playbook.mdnew file mode 100644index 000000000000..0888950ad5da--- /dev/null+++ b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/investigation-playbook.md@@ -0,0 +1,173 @@+# Root-causing an individual slow query++This is the deep-dive behind the main skill's [Step 2 (smells)](../SKILL.md) and+[Step 3 (EXPLAIN)](../SKILL.md): once you have a specific slow query in front of you, this is how to+explain _why_ it is slow before you reach for a fix. Where Step 2 scans the SQL for known-bad shapes,+this reference works the other way round, from the runtime cost back to the cause.++It is written for a query you pulled from production (via `/query-clickhouse-via-metabase` against+`posthog.query_log_archive` — the slowest real example beats a synthesized one), but the reasoning+applies to any slow query. You do not need certainty: a concrete, falsifiable hypothesis ("the sort key+is function-wrapped, so the date filter can't prune granules") is what drives the next step. Always state+one, then test it.++## Pull the full query, never a substring++When drilling into a specific query, select the **complete** `query` text plus the `exception` message,+not a `substring`. The smoking gun is almost always at the tail: the `ORDER BY`, the `WHERE` time+bound, the `LIMIT`, and the `SETTINGS` clause (`max_threads`, `max_execution_time`, `max_memory_usage`).+A scan-list preview that truncates at 160 chars will hide all of it.++```sql+SELECT query, exception, query_duration_ms,+ formatReadableSize(memory_usage) AS mem, formatReadableSize(read_bytes) AS read, read_rows+FROM posthog.query_log_archive+WHERE query_id = '<id>' AND event_date = '<YYYY-MM-DD>' AND is_initial_query+```++The `exception` message for an OOM (code 241) states the configured ceiling and the column that blew+it, e.g. `Query memory limit exceeded: would use 42.01 GiB, maximum: 42.00 GiB (while reading column+elements_chain)`. That column name is a direct pointer to what to look at.++## Read bytes, CPU time, and duration together++Three signals matter, and all three are worth pulling: **bytes read**, **CPU time**, and **duration**.+None of them on its own tells the whole story.++- **Bytes read** is the most stable measure of work done. Sort candidates by `read_bytes DESC`. Compare+ bytes against rows across queries in the same batch: if two queries read similar row counts but one+ reads ~100x more bytes, the heavy one is decompressing a wide column (almost always a `properties` JSON+ blob).++ ```text+ Query A: 210M rows, 19 GiB -- materialized columns only+ Query B: 210M rows, 2.65 TiB -- JSONExtractRaw(events.properties, '$some_prop')+ ```++- **CPU time** (`ProfileEvents['OSCPUVirtualTimeMicroseconds']`, or `query_duration_ms` vs CPU to gauge+ parallelism) catches work that bytes read misses: expensive expressions, high-cardinality+ aggregation, and grouping that burns CPU without reading much more data.++- **Duration** still matters, but with a hard rule: **never rely on the duration of the API request.**+ That number includes queueing, serialization, network, and app overhead, and does not reflect the+ ClickHouse query itself. When you report duration, it must come from `query_duration_ms` in+ `query_log` / `query_log_archive`, never from the API timing. Read against bytes and CPU, duration is+ most telling when it is _high but bytes and CPU are not_: that gap usually means the query spent its+ time **waiting** (on locks, on concurrency limits, on other queries), which is itself worth flagging.++## Common causes, most frequent first++These are the causes that come up most often, but they are only a subset: frequently the real problem is+something else entirely. Treat this list as a starting set of hypotheses to check, not an exhaustive+diagnosis, and stay open to a cause that is not listed here.++1. **Unmaterialized property access (JSONExtract).** The number-one cause of extreme byte reads.+ `JSONExtract*(events.properties, …)` or `JSONExtract*(person_properties, …)` forces a read of the+ full JSON blob per matching row. Confirm by searching the query text for `JSONExtract` / `JSONHas`;+ then check whether the property has a `mat_<property>` column. Fix: materialize it (see the+ JSON-operations smell in [`SKILL.md`](../SKILL.md) and the migration layer in its Step 5) or drop the+ property filter. Person properties are the worst because the blobs are large.+2. **Session joins.** Joining `raw_sessions` / `sharded_sessions` (for `$session_duration` etc.) adds a+ full sessions scan. Look for `raw_sessions` in the text.+3. **High-cardinality breakdowns.** A `breakdown_value` on something like a URL or an ID explodes the+ grouping. This is the dominant OOM driver for user-facing `TrendsQuery`.+4. **High-volume event as a funnel/first step.** `$pageview` as a step scans all pageviews; index+ pruning helps but the raw volume is large.+5. **Ratio / multi-series metrics with double scans.** Numerator and denominator each run their own+ scan and person-overrides join; doubles the work when both use high-volume events.+6. **All-time or multi-month date ranges.** Scans proportionally more data; check the range.+7. **Function-wrapped sort/filter keys defeating index pruning.** When the `WHERE` time bound or+ `ORDER BY` wraps the sort column in a function (e.g. `coalesce(toTimeZone(timestamp, …))` instead of+ raw `timestamp`), ClickHouse can't match it to the primary key, so the filter drops to a Prewhere+ row filter (no granule pruning) and the read scans far more than the requested window, often the+ team's full history. On a wide table (events), reading `properties` / `elements_chain` for that+ inflated row set under a high `max_threads` is a classic OOM, and where it does not OOM it hits the+ `max_execution_time` cap as a timeout. Watch for no-op wrappers like a single-argument `coalesce()`+ on a non-nullable column. Confirm with EXPLAIN by diffing granule counts (below).++## Tracing a query back to its origin++The `lc_*` columns exist **only on `query_log_archive`** — they are the pre-parsed `log_comment` tags.+`system.query_log` carries the exact same information, but unparsed, inside its `log_comment` JSON blob,+so on `query_log` you read the field out of that JSON (e.g. `JSONExtractString(log_comment, 'query_type')`)+instead of selecting an `lc_*` column. The table below uses the `query_log_archive` column names.++These tags tell you what triggered the query without reverse-engineering the SQL:++| Column | Tells you |+| ------------------------------------------------------------------------- | ---------------------------------------------------------- |+| `lc_query__kind` | Product query type (`TrendsQuery`, `ExperimentQuery`, ...) |+| `lc_route_id` | API route that handled the request |+| `lc_dashboard_id` / `lc_insight_id` / `lc_experiment_id` / `lc_cohort_id` | The object that fired it |+| `lc_feature`, `lc_temporal__workflow_type`, `lc_dagster__job_name` | Background-job origin |+| `lc_access_method`, `lc_api_key_label` | Whether it came from the web, OAuth, or a named API key |+| `lc_user_id` | Who triggered it |++The full `log_comment` (raw, on `system.query_log`) additionally carries `http_referer`, `scene`, and+`source_file`/`source_line`. These tags are defined in `posthog/clickhouse/query_tagging.py`+(`QueryTags`).++To reverse-engineer SQL, grep the PostHog codebase for the `lc_query__kind` value (e.g. `TrendsQuery`)+to find the query runner that generates it.++## EXPLAIN to test the hypothesis++Per the [ClickHouse EXPLAIN docs](https://clickhouse.com/docs/sql-reference/statements/explain), no+EXPLAIN variant executes the query or scans table data, so EXPLAIN is safe to run against prod at any+size. Two variants are not entirely free, though: `EXPLAIN ESTIMATE` and `EXPLAIN indexes=1` read primary+index marks / part metadata to do their analysis. That is a small metadata read, not a data scan, but it+is not zero, so prefer the lighter plan-only variants (`actions=1`, `PIPELINE`) when you do not+specifically need index pruning numbers, and avoid hammering `indexes=1` in a tight loop. If in doubt,+re-check the current docs before running a variant at scale. Pull the query text, strip the leading+`/* … */` tag comment, and prepend the EXPLAIN modifier that answers your question:++- `EXPLAIN actions=1` — the full plan: shows the `Sorting` step, `ReadType` (`InOrder` vs `Default`),+ and whether a filter is a primary-key condition or only a `Prewhere` row filter.+- `EXPLAIN indexes=1` — per-index granule pruning (`Granules: X/Y`, which skip indexes fired).+- `EXPLAIN PIPELINE` — the executor pipeline (thread fan-out, merge stages).+- `EXPLAIN json=1` — machine-readable, handy for diffing two plans programmatically.++The strongest technique is to **EXPLAIN the suspect query and a fixed variant side by side, then diff**.+For the function-wrapped-key case, compare the generated `ORDER BY coalesce(toTimeZone(timestamp, …))`+against raw `ORDER BY timestamp`: a large drop in `Granules` (full history shrinks to just the date+window) and the time bound moving from Prewhere into the primary-key condition confirms the wrapper is+the cause.++Signals to read off the plan:++- **`Granules: X`** — how many 8192-row blocks survive index pruning. A wrapped/opaque filter shows a+ much larger granule count than the equivalent raw-column filter; that delta is the wasted scan.+- **`ReadType: InOrder` vs `Default`** — whether `optimize_read_in_order` applies. Note the events+ table is ordered by `toDate(timestamp)`, not sub-day, so ordering by full `timestamp` still sorts;+ do not infer read-in-order from a date sort alone.+- **`Prewhere filter` vs primary-key condition** — a time bound in Prewhere is evaluated row-by-row and+ does not prune granules; in the primary-key condition it does.+- **Skip-index effectiveness** (e.g. `minmax_mat_*`) — how many granules each eliminates.+- **Bytes vs rows** — similar granule counts but wildly different bytes means a column-width problem+ (the JSON blob again).++## Concurrency and timing notes++- In `query_log`, `event_time` is the **completion** time for `QueryFinish` rows. Use+ `query_start_time_microseconds` when reconstructing concurrency, or short queries that finish first+ will look like they ran first.+- A single experiment page load fires **one query per metric**, dispatched via celery with limited+ parallelism. Wall-clock ≈ dispatch overhead + the longest single query; total data scanned is the+ **sum** across metric queries. Same query length does not mean same query; distinguish by+ `client_query_id`.+- `person_distinct_id_overrides` joins are expected and mandatory for correct person resolution. Do not+ flag them on their own; they are the cost of correctness. A query joining **both**+ `person_distinct_id_overrides` and `person_distinct_id2` is the pattern worth a closer look.++## Codebase map (in `../posthog` or the public repo)++| Path | What it explains |+| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |+| `posthog/hogql/printer/base.py` | HogQL → SQL; the materialization decision tree (`mat_*` → `dmat_*` → property groups → JSONExtract fallback) |+| `posthog/hogql/transforms/property_types.py` | Whether a property access uses a materialized column or JSON extraction |+| `posthog/hogql/property.py` | How property filters become AST (person properties → `["person","properties"]` chain) |+| `posthog/hogql/database/schema/events.py` | Events table schema; lazy joins to person, pdi, sessions, groups |+| `posthog/hogql/database/database.py` | Person-on-events mode: how `person_id` resolves via overrides vs pdi2 |+| `posthog/hogql_queries/experiments/` | How experiment queries build exposure CTEs and resolve persons |+| `ee/clickhouse/materialized_columns/analyze.py` | Auto-materialization logic (properties in 10+ slow queries reading >20GB or >5M rows) |+| `posthog/clickhouse/query_tagging.py` | The `QueryTags` model behind the `lc_*` columns |