Skip to content

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

chore(skills): teach agents to profile a slow Postgres endpoint (#95982)

Paul D'Ambra47315f13f5a3
diff --git a/.agents/skills/analyzing-experiment-query-performance/SKILL.md b/.agents/skills/analyzing-experiment-query-performance/SKILL.md
index ae57c979373b..e91b7da80894 100644
--- a/.agents/skills/analyzing-experiment-query-performance/SKILL.md
+++ b/.agents/skills/analyzing-experiment-query-performance/SKILL.md
@@ -229,7 +229,7 @@ re-check the key's scopes before anything else.
to identify which team, experiment, and metric type is responsible.
3. **Drill to ground truth**: for a specific `query_id`, the full `query_log` row
(settings, replica, ProfileEvents) needs ClickHouse —
- use the `query-clickhouse-via-metabase` skill.
+ use the `querying-production-databases-via-metabase` skill.
4. **Result-consistency questions** (precomputed vs direct results diverging) are out of scope here —
these endpoints see performance and failures, not result values.
That's the precompute result-consistency canary's territory:
diff --git a/.agents/skills/analyzing-insights-across-teams/SKILL.md b/.agents/skills/analyzing-insights-across-teams/SKILL.md
index 55ea2972bd0a..daa20b3eb552 100644
--- a/.agents/skills/analyzing-insights-across-teams/SKILL.md
+++ b/.agents/skills/analyzing-insights-across-teams/SKILL.md
@@ -76,4 +76,4 @@ Rows in these tables are customer data: team names, insight names, descriptions,
## Related
-- For cross-team **event/analytics** data (not entity metadata), see the `query-clickhouse-via-metabase` skill instead.
+- For cross-team **event/analytics** data (not entity metadata), see the `querying-production-databases-via-metabase` skill instead.
diff --git a/.agents/skills/generating-clickhouse-query-performance-reports/SKILL.md b/.agents/skills/generating-clickhouse-query-performance-reports/SKILL.md
index 53d32da0b428..999d3df72e9d 100644
--- a/.agents/skills/generating-clickhouse-query-performance-reports/SKILL.md
+++ b/.agents/skills/generating-clickhouse-query-performance-reports/SKILL.md
@@ -8,13 +8,13 @@ description: >
`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.
+ Runs queries via the `querying-production-databases-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),
+performance report. It pairs with [`querying-production-databases-via-metabase`](../querying-production-databases-via-metabase/SKILL.md),
which is the _mechanism_ (SSO-gated auth and `hogli metabase:query`). Run every query in this skill
through that one.
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.md
index e80705d28c61..ad18a509b2ab 100644
--- a/.agents/skills/generating-clickhouse-query-performance-reports/references/materialization-analysis.md
+++ b/.agents/skills/generating-clickhouse-query-performance-reports/references/materialization-analysis.md
@@ -5,7 +5,7 @@ dropping (to reclaim disk). **Always run on both US and EU**, since they have di
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
+Run everything via `querying-production-databases-via-metabase`. Split wide column-list checks into batches of ~5-6
to stay under the Metabase response cutoff.
## Step 1: Candidates to materialize
diff --git a/.agents/skills/modifying-taxonomic-filter/SKILL.md b/.agents/skills/modifying-taxonomic-filter/SKILL.md
index cf06bc836c4f..80d81106e5ae 100644
--- a/.agents/skills/modifying-taxonomic-filter/SKILL.md
+++ b/.agents/skills/modifying-taxonomic-filter/SKILL.md
@@ -1,6 +1,6 @@
---
name: modifying-taxonomic-filter
-description: Guides safe modification of the TaxonomicFilter — PostHog's multi-tab picker for events, actions, properties, cohorts, and more. Front-loads the empirical product reality (what users actually pick and search for) plus the three live variants (legacy-control, legacy-pill behind TAXONOMIC_FILTER_CATEGORY_DROPDOWN, and the opt-in rebuild menu behind TAXONOMIC_FILTER_MENU_REBUILD) so changes are judged against real behavior and mirrored across surfaces, not made against one arm in isolation. Use when adding features, fixing bugs, or refactoring TaxonomicFilter, the rebuild menu, or the headless filter panel.
+description: Guides safe changes to the TaxonomicFilter, PostHog's picker for events, actions, properties, cohorts, and more. Use when adding features, fixing bugs, improving search or loading performance, or refactoring the legacy filter, rebuild menu, or headless filter panel. Covers real selection behavior, three live variants, shared telemetry, the conditional Postgres search plan, and result reveal rules.
---
# Modifying the TaxonomicFilter
@@ -10,7 +10,7 @@ knows about" — events, properties, actions, cohorts, groups. It's the
on-ramp into almost every analytics and replay configuration. Code lives
in `frontend/src/lib/components/TaxonomicFilter/`.
-**Two unbreakable rules:**
+**Three guardrails:**
1. Changes that demote items users _actually pick_ are regressions, even
with all tests passing. Read "Product reality" before deciding any
@@ -22,6 +22,11 @@ in `frontend/src/lib/components/TaxonomicFilter/`.
**both** the legacy code and the rebuild, or the two arms of the
experiment diverge. Read "Three variants" and "Mirroring changes"
before assuming one edit is enough.
+3. Search is the main selection path. The definition endpoints select a
+ Postgres plan from the project size. The picker also shows results before
+ optional counts finish. Read
+ [references/performance.md](references/performance.md) before you change
+ search, loading, pagination, or result reveal behavior.
## Product reality (last refreshed 2026-05-02, 90-day window)
@@ -188,13 +193,16 @@ divergences; don't "fix" them into parity.
- [ ] Read references when relevant: [architecture](references/architecture.md),
[common-pitfalls](references/common-pitfalls.md) (X/Y matrix),
[call-sites](references/call-sites-and-blast-radius.md) (smoke tests),
- [testing-patterns](references/testing-patterns.md)
+ [testing-patterns](references/testing-patterns.md),
+ [performance](references/performance.md) (search plan, reveal barrier)
- [ ] Decide whether the change must mirror across legacy and rebuild
(see "Mirroring changes") — if you can only do one, say so explicitly
- [ ] Test all three surfaces if you touched tabs/groups: `legacy-control`,
`legacy-pill`, `rebuild-menu`
- [ ] Confirm shared telemetry payloads still match across both emitters
- [ ] Ordering / promotion / position-0 -> human sign-off, not agent judgement
+- [ ] If you changed search or loading, verify the plan boundary and confirm
+ that optional requests do not delay results
- [ ] Flag the ongoing experiments to the human reviewer: the
control->pill rollout and the internal `rebuild-menu` opt-in
diff --git a/.agents/skills/modifying-taxonomic-filter/references/performance.md b/.agents/skills/modifying-taxonomic-filter/references/performance.md
new file mode 100644
index 000000000000..9929b7dcb3fb
--- /dev/null
+++ b/.agents/skills/modifying-taxonomic-filter/references/performance.md
@@ -0,0 +1,46 @@
+# TaxonomicFilter performance
+
+Use this reference when you change TaxonomicFilter search, loading, pagination, or result reveal behavior.
+For the full profiling workflow, use
+[`profiling-slow-api-endpoints`](../../profiling-slow-api-endpoints/SKILL.md).
+
+## Backend search plan
+
+The definition search can use two Postgres predicate forms.
+`posthog/taxonomy/definition_search.py` selects the form from the number of definitions in the project.
+Read the current helper and threshold before you change this path.
+
+The conditional plan exists because one index strategy does not perform well for every project size.
+A global trigram index can make a small project scan index data for all projects.
+A project-scoped scan can become expensive for a very large project.
+
+Keep these properties unless new measurements support a different design:
+
+- The size check is bounded and cached per table and project.
+- A stale cache value changes performance, not results.
+- A cache failure does not fail the request.
+- The selected plan is recorded as `taxonomy_search_plan` on the request span.
+- The paginator count and result query use the same search form.
+
+When you add a searchable column or change a predicate, compare the exact endpoint SQL for both plan forms.
+Measure projects on both sides of the threshold.
+
+## Frontend result reveal
+
+`docs/internal/taxonomic-filter-search.md` is the source of truth for result reveal behavior.
+Do not restate its loading rules here.
+
+For performance work, measure the time until the first usable result.
+Check both `infiniteListLogic.ts` and `hooks/useGroupList.ts` because the legacy and rebuild paths implement loading separately.
+
+## Verification
+
+- Use an APM trace from a real TaxonomicFilter open.
+- Compare both Postgres predicate forms with safe production `EXPLAIN` queries.
+- State whether each measured query used a warm or cold cache.
+- Run the definition API tests against Postgres.
+- Test the legacy and rebuild loading paths.
+
+Result tests alone do not protect the plan choice because both plans return the same rows.
+When plan selection changes, test the boundary, cache failure, and SQL shape.
+Verify both definition endpoints when they share the changed helper.
diff --git a/.agents/skills/optimizing-clickhouse-and-hogql-queries/SKILL.md b/.agents/skills/optimizing-clickhouse-and-hogql-queries/SKILL.md
index 49e7ad5d20df..4d6d3b1e066c 100644
--- a/.agents/skills/optimizing-clickhouse-and-hogql-queries/SKILL.md
+++ b/.agents/skills/optimizing-clickhouse-and-hogql-queries/SKILL.md
@@ -1,11 +1,11 @@
---
name: optimizing-clickhouse-and-hogql-queries
-description: Workflow for optimizing ClickHouse and HogQL queries. Use when a HogQL query, query runner, insight, or report is too slow; when a hand-written ClickHouse query (via `sync_execute` or in a migration) is too slow; when ClickHouse times out or hits memory limits; when investigating a slow `system.query_log` row; or when reviewing a proposed HogQL printer change for performance. Covers extracting the ClickHouse SQL, common smells (`FROM ... FINAL`, `JSONExtract` over properties, missing skip indexes, self-joins, CTE blow-up), measuring against a real cluster, and applying the fix at the right layer (printer, query runner, or migration). Does NOT cover Postgres / Django ORM / app-database queries; those need pganalyze and the Postgres section of `query-performance-optimization.md`.
+description: Workflow for optimizing ClickHouse and HogQL queries. Use when a HogQL query, query runner, insight, or report is too slow; when a hand-written ClickHouse query (via `sync_execute` or in a migration) is too slow; when ClickHouse times out or hits memory limits; when investigating a slow `system.query_log` row; or when reviewing a proposed HogQL printer change for performance. Covers extracting the ClickHouse SQL, common smells (`FROM ... FINAL`, `JSONExtract` over properties, missing skip indexes, self-joins, CTE blow-up), measuring against a real cluster, and applying the fix at the right layer (printer, query runner, or migration). Does NOT cover Postgres / Django ORM / app-database queries; for those use `profiling-slow-api-endpoints`.
---
# Optimizing ClickHouse and HogQL queries
-Optimizes **ClickHouse and HogQL queries** (HogQL compiles to ClickHouse), not Postgres / Django ORM. For an app-DB query (`Model.objects.filter(...)`), stop and use pganalyze plus the Postgres section of [`query-performance-optimization.md`](../../../docs/published/handbook/engineering/databases/query-performance-optimization.md); Step 0 has the full triage.
+Optimizes **ClickHouse and HogQL queries** (HogQL compiles to ClickHouse), not Postgres / Django ORM. For an app-DB query (`Model.objects.filter(...)`), stop and use [`profiling-slow-api-endpoints`](../profiling-slow-api-endpoints/SKILL.md); Step 0 has the full triage.
**Work from the ClickHouse SQL, not the HogQL.** Get the ClickHouse SQL the query produces, optimize that, then translate the change back into the HogQL query, query runner, printer, or a migration. Reasoning about HogQL alone hides what ClickHouse executes.
@@ -28,12 +28,12 @@ The same query is sometimes implemented **twice** (backend runner plus frontend
Check how the query is built:
-| What you see | Where it goes | What to use |
-| ---------------------------------------------------------------------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `execute_hogql_query(...)`, `HogQLQuery`, a `*QueryRunner`, an insight, a HogQL `.ambr` | ClickHouse via the HogQL printer | This skill |
-| `sync_execute(...)`, `client.execute(...)`, hand-written `SELECT ... FROM events`, a migration | ClickHouse directly (no HogQL) | This skill (steps 2-5; skip step 1) |
-| `Model.objects.filter(...)`, `.raw(...)`, a queryset, `RawSQL` over the app DB | Postgres via Django ORM | Not this skill. [`query-performance-optimization.md`](../../../docs/published/handbook/engineering/databases/query-performance-optimization.md) (`## PostgreSQL`) + [pganalyze](https://app.pganalyze.com/) |
-| `personhog_client.*`, `get_personhog_client()`, `get_person_by_*` | personhog (gRPC, Postgres) | Not this skill. [`posthog/personhog_client/README.md`](../../../posthog/personhog_client/README.md) |
+| What you see | Where it goes | What to use |
+| ---------------------------------------------------------------------------------------------- | -------------------------------- | --------------------------------------------------------------------------------------------------- |
+| `execute_hogql_query(...)`, `HogQLQuery`, a `*QueryRunner`, an insight, a HogQL `.ambr` | ClickHouse via the HogQL printer | This skill |
+| `sync_execute(...)`, `client.execute(...)`, hand-written `SELECT ... FROM events`, a migration | ClickHouse directly (no HogQL) | This skill (steps 2-5; skip step 1) |
+| `Model.objects.filter(...)`, `.raw(...)`, a queryset, `RawSQL` over the app DB | Postgres via Django ORM | Not this skill. [`profiling-slow-api-endpoints`](../profiling-slow-api-endpoints/SKILL.md) |
+| `personhog_client.*`, `get_personhog_client()`, `get_person_by_*` | personhog (gRPC, Postgres) | Not this skill. [`posthog/personhog_client/README.md`](../../../posthog/personhog_client/README.md) |
If you were pointed at a coordinator / orchestrator / Celery task / Temporal workflow / management command, the ClickHouse query is usually **one layer in** (the dispatched activity, child workflow, or `apply_async` target). Follow the dispatch to the layer that builds the HogQL. A file may mix Postgres (pick work) and HogQL (do work); treat them as separate tasks.
@@ -78,7 +78,7 @@ Cluster topology (shards, replicas, ingestion vs data nodes): [`posthog/clickhou
- **Python:** `execute_hogql_query()` ([`query.py`](../../../posthog/hogql/query.py)) gives `response.clickhouse`. SQL only, no execute: `prepare_and_print_ast(..., dialect="clickhouse")` ([`utils.py`](../../../posthog/hogql/printer/utils.py)); for a prepared AST, `print_prepared_ast`.
- **Snapshots:** `.ambr` files under `posthog/hogql_queries/test/__snapshots__/` (and per-product test dirs) hold generated ClickHouse SQL for representative inputs.
-- **Production** (most informative): `/query-clickhouse-via-metabase` against `clusterAllReplicas(posthog, system, query_log)` (or `posthog.query_log_archive` for rows older than ~4h; ~22 day retention, typed `lc_*` columns, so prefer it). Filter `is_initial_query`, `type = 'QueryFinish'`, `query_duration_ms > <threshold>`.
+- **Production** (most informative): `/querying-production-databases-via-metabase` against `clusterAllReplicas(posthog, system, query_log)` (or `posthog.query_log_archive` for rows older than ~4h; ~22 day retention, typed `lc_*` columns, so prefer it). Filter `is_initial_query`, `type = 'QueryFinish'`, `query_duration_ms > <threshold>`.
## Step 2: scan for the common smells
@@ -140,7 +140,7 @@ ClickHouse `WITH name AS (SELECT ...)` CTEs are **inlined, not materialized**: r
**Local ClickHouse** (correctness and EXPLAIN, not timing, which is too noisy): `hogli dev:demo-data` seeds synthetic data; `hogli db:ch` opens a client. You _can_ try skip indexes / materialized columns / schema changes locally (single node), but ask the user first, and remember prod is multi-node so structural changes must round-trip through [`/clickhouse-migrations`](../clickhouse-migrations/SKILL.md); `ALTER TABLE ... MATERIALIZE INDEX ...` builds a new index over existing data. Bytes-read (`FORMAT JSON`, or local `system.query_log`) is a less-noisy proxy than wall time.
-**Test Cluster** (timing): Metabase-fronted, read-only snapshot of team 2's data, no noisy neighbors. Use [`/query-clickhouse-via-metabase`](../query-clickhouse-via-metabase/SKILL.md). Adapt the prod query first: swap `team_id`, pick an overlapping date range, substitute/skip branches that depend on properties/features team 2 lacks (judgement call). **Apply prod materialized columns before timing**: `DESCRIBE <table>` lists real `pmat_*` (events) / `pmat_*` / `mat_*` (persons, groups); swap `JSONExtract(...)` for them or you're timing a shape the printer never emits. Set `SETTINGS use_uncompressed_cache=0`, take the **median of 5**, and read `query_duration_ms` / `read_rows` / `read_bytes` / `memory_usage` / `ProfileEvents` from `system.query_log`, not the Metabase request time.
+**Test Cluster** (timing): Metabase-fronted, read-only snapshot of team 2's data, no noisy neighbors. Use [`/querying-production-databases-via-metabase`](../querying-production-databases-via-metabase/SKILL.md). Adapt the prod query first: swap `team_id`, pick an overlapping date range, substitute/skip branches that depend on properties/features team 2 lacks (judgement call). **Apply prod materialized columns before timing**: `DESCRIBE <table>` lists real `pmat_*` (events) / `pmat_*` / `mat_*` (persons, groups); swap `JSONExtract(...)` for them or you're timing a shape the printer never emits. Set `SETTINGS use_uncompressed_cache=0`, take the **median of 5**, and read `query_duration_ms` / `read_rows` / `read_bytes` / `memory_usage` / `ProfileEvents` from `system.query_log`, not the Metabase request time.
**Measure before suggesting.** For any rewrite, run original vs candidate on the same team-2-adapted query and report before/after `query_duration_ms`, `read_bytes`, `memory_usage`. A suggestion without numbers is a guess; if you couldn't measure (cluster unavailable, doesn't adapt, schema-only change), say so. The cluster is read-only, so prototype schema changes locally.
diff --git a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/investigation-playbook.md b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/investigation-playbook.md
index 253b6cbf45ae..1685e03be756 100644
--- a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/investigation-playbook.md
+++ b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/investigation-playbook.md
@@ -5,7 +5,7 @@ This is the deep-dive behind the main skill's [Step 2 (smells)](../SKILL.md) and
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
+It is written for a query you pulled from production (via `/querying-production-databases-via-metabase` against
`posthog.query_log_archive`, since 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
diff --git a/.agents/skills/profiling-slow-api-endpoints/SKILL.md b/.agents/skills/profiling-slow-api-endpoints/SKILL.md
new file mode 100644
index 000000000000..15ce31249da6
--- /dev/null
+++ b/.agents/skills/profiling-slow-api-endpoints/SKILL.md
@@ -0,0 +1,91 @@
+---
+name: profiling-slow-api-endpoints
+description: >
+ Profiles slow PostHog API endpoints when the main cost is in Postgres or
+ Python. Use when a screen, picker, or list is slow; a Django endpoint has high
+ tail latency; a query plan changes with tenant size; or a proposed database
+ fix needs production evidence. Covers APM traces, safe production EXPLAIN,
+ representative measurements, implementation choices, tests, rollout, and
+ post-deploy verification. For ClickHouse or HogQL latency, use
+ `optimizing-clickhouse-and-hogql-queries` instead.
+---
+
+# Profiling slow API endpoints
+
+Use this skill when a PostHog API request spends most of its time in Postgres or Python.
+For ClickHouse and HogQL, use
+[`optimizing-clickhouse-and-hogql-queries`](../optimizing-clickhouse-and-hogql-queries/SKILL.md).
+
+Measure the same user action before and after the change.
+A faster query does not help if the action stays slow.
+
+## Find the source of the delay
+
+Record the page action, endpoint, request shape, affected users, request volume, and a latency percentile such as p95.
+Read slow APM traces with `posthog:query-apm-spans` and the `exploring-apm-traces` skill.
+The distribution shows how often requests are slow.
+The traces show where they spend time.
+
+- Django ORM and `cursor.execute` spans point to Postgres.
+- ClickHouse work belongs in the ClickHouse skill.
+- Time outside database spans can indicate repeated calls, serialization, or excess data loading.
+
+Follow the request to the function that creates the work.
+Do not optimize a view wrapper when another function owns the delay.
+
+## Capture the exact work
+
+Get the SQL and parameters from a slow request.
+Keep its filters, ordering, and page size.
+Check for repeated queries, count queries, and work that does not block the response.
+A reduced query can use a different plan.
+Local data and statistics can also produce a different plan.
+
+Use
+[`querying-production-databases-via-metabase`](../querying-production-databases-via-metabase/SKILL.md)
+to inspect the production read replica.
+Start with `EXPLAIN`.
+Use `EXPLAIN (ANALYZE, BUFFERS)` only when the exact `SELECT` is safe to run.
+Inspect row estimates, indexes, join types, loops, filters, sorts, and buffer use.
+
+## Compare the smallest useful change
+
+Remove work that the response does not need before you change a query or add an index.
+Compare the original and candidate with the same parameters.
+Run each more than once, record the cache state, and verify equal results.
+
+Measure the tenant-size distribution when plans can change with tenant size.
+Test both sides of a plan crossover before you select a threshold.
+One tenant is not enough evidence for a conditional plan.
+
+Prefer one plan when it performs well across the measured range.
+If a size check or cache selects the plan:
+
+- keep the check cheaper than the work it avoids
+- let stale data affect latency, not results
+- keep the request working when the cache fails
+- record the selected plan on the request span
+
+Use a feature flag when behavior is uncertain or the change needs a staged rollout.
+Do not use a flag as a substitute for measurements.
+
+## Verify the change
+
+Test public behavior at the lowest useful level.
+Add plan or SQL-shape tests only when the improvement depends on that shape.
+Test each plan and the failure path when the code selects between plans.
+Use a representative database for plan and timing comparisons because unit tests cannot prove latency.
+
+After deployment, check the same latency measure, request volume, error rate, and database load.
+Compare recorded plan attributes when more than one plan exists.
+Remove the change if it does not improve the user action without a regression.
+
+## Common mistakes
+
+- Starting with a code theory instead of a slow trace.
+- Measuring only the mean or one warm query.
+- Testing SQL that differs from the endpoint SQL.
+- Selecting a threshold from one tenant.
+- Moving the first response behind optional work.
+- Adding an index before checking the current plan.
+- Declaring success from tests instead of the production measure.
diff --git a/.agents/skills/query-clickhouse-via-metabase/SKILL.md b/.agents/skills/querying-production-databases-via-metabase/SKILL.md
similarity index 70%
rename from .agents/skills/query-clickhouse-via-metabase/SKILL.md
rename to .agents/skills/querying-production-databases-via-metabase/SKILL.md
index 7cf6355c3a6e..39e75fcbe199 100644
--- a/.agents/skills/query-clickhouse-via-metabase/SKILL.md
+++ b/.agents/skills/querying-production-databases-via-metabase/SKILL.md
@@ -1,23 +1,31 @@
---
-name: query-clickhouse-via-metabase
+name: querying-production-databases-via-metabase
description: >
- Run ClickHouse `system.query_log` analysis via the internal Metabase API.
- Use when investigating slow queries, materialization candidates, per-team
- query performance, ClickHouse cost or memory issues, or any system.query_log
- question. Covers prod-us and prod-eu, SSO-gated cookie auth via `hogli`,
- and ready-to-run query patterns.
+ Runs read-only production database analysis through PostHog's internal
+ Metabase instances. Use for ClickHouse query logs, slow query cost, Postgres
+ query plans, index selection, or tenant-size analysis. Covers US and EU
+ database discovery, SSO login through `hogli`, safe query rules, and query
+ patterns for both engines.
---
-# Querying ClickHouse via Metabase
+# Querying production databases via Metabase
-PostHog's production ClickHouse clusters are reachable for ad-hoc analysis through
-internal Metabase instances. Both Metabases sit behind an AWS ALB with Cognito
-OAuth, so authentication is **SSO-gated** — Metabase API keys alone won't work.
+PostHog's production databases are reachable for ad-hoc, read-only analysis
+through internal Metabase instances. Both Metabases sit behind an AWS ALB with
+Cognito OAuth, so authentication is **SSO-gated** — Metabase API keys alone
+won't work.
-This skill is for `system.query_log` analysis from inside the posthog repo.
-For pre-built canned queries (slow query summaries, materialization analysis),
-see the `query-performance-analysis` repo, which is the source of truth for
-those and uses the same Metabase API surface.
+Two engines are behind the same API surface, and the reason to reach for each
+is different:
+
+- **ClickHouse** — `system.query_log` analysis: which queries are slow, what
+ they read, who runs them.
+- **Postgres** (the app database) — the real query plan for an app query, and
+ how a per-project table's rows spread across the fleet.
+
+For pre-built canned ClickHouse queries (slow query summaries, materialization
+analysis), see the `query-performance-analysis` repo, which is the source of
+truth for those and uses the same Metabase API surface.
## Environment
@@ -69,7 +77,7 @@ results — the session value never appears in the agent's transcript.
`metabase:cookie` exists for humans who want to hand-roll `curl` against
Metabase.
-## Running an ad-hoc query
+## Running a ClickHouse query
1. Discover the current ClickHouse DB ID: `hogli metabase:databases --region <region>`.
2. Pass that ID into `hogli metabase:query`. Pipe SQL via stdin or `--file`.
@@ -106,7 +114,7 @@ If the DB ID is wrong, `metabase:query` exits non-zero with a pointer back
to `metabase:databases`. Fail-fast is intentional — silently querying the
wrong database is worse than failing.
-## What counts as a slow query
+## ClickHouse: what counts as a slow query
```sql
query_duration_ms > 30000
@@ -119,7 +127,7 @@ OR exception_code IN (159, 160, 241)
| 160 | TOO_SLOW |
| 241 | MEMORY_LIMIT_EXCEEDED |
-## Useful query patterns
+## ClickHouse query patterns
### Top slow queries in the last 24h
@@ -183,6 +191,47 @@ https://metabase.prod-eu.posthog.dev/question/795-look-up-query-by-query-id?quer
The same can be reproduced programmatically with a `WHERE query_id = '...'`
clause via `/api/dataset` against the right region's DB ID.
+## Postgres app database
+
+Use the Postgres connection when a Django request spends time in the app database.
+Production data and statistics can select a different plan from local data.
+
+Discover the current database IDs and select the Postgres app database:
+
+```bash
+hogli metabase:databases --region us
+```
+
+The list can also contain ingestion and migration databases.
+Use [`profiling-slow-api-endpoints`](../profiling-slow-api-endpoints/SKILL.md) for the investigation workflow.
+
+### Safety
+
+The Metabase connection uses a shared read replica.
+Run only `SELECT` and `EXPLAIN` statements.
+Do not run writes or schema changes.
+Start with `EXPLAIN`, which does not run the query.
+`EXPLAIN ANALYZE` runs the query, so use it only for a narrow, safe `SELECT`.
+Keep the endpoint's filters, order, and limit because they can change the plan.
+
+A count grouped by tenant can scan a full table even when its result has a limit.
+Prefer an existing aggregate or another source approved by the database owner.
+For one tenant, bound the work inside the count:
+
+```sql
+SELECT count(*)
+FROM (
+ SELECT 1
+ FROM <table>
+ WHERE <tenant_key> = <tenant_id>
+ LIMIT <threshold_plus_one>
+) AS bounded_rows
+```
+
+Results can contain customer identifiers, query text, and private scale data.
+Do not copy them into public code, tests, pull requests, issues, or comments.
+Use placeholders and broad data shapes in public output.
+
## Parsing Metabase responses
```json
@@ -211,14 +260,14 @@ for row in d['data']['rows']:
### Error responses
-| Symptom | Cause | Fix |
-| ------------------------------ | -------------------------------------- | ---------------------------------------------------------------- |
-| HTTP 302 to `/auth/...` | Cookie expired or missing | Tell user to run `hogli metabase:login --region <region>` |
-| HTTP 401 | Cookie rejected by ALB | Same as 302 |
-| `"status": "failed"` + `error` | ClickHouse error (syntax, table, etc.) | Read `error`; fix SQL |
-| Hangs / timeout | Wide `query_log` scan | Narrow `event_time` range, add `team_id` filter, use `cluster()` |
+| Symptom | Cause | Fix |
+| ------------------------------ | ------------------------------------ | ---------------------------------------------------------------- |
+| HTTP 302 to `/auth/...` | Cookie expired or missing | Tell user to run `hogli metabase:login --region <region>` |
+| HTTP 401 | Cookie rejected by ALB | Same as 302 |
+| `"status": "failed"` + `error` | Database error (syntax, table, etc.) | Read `error`; fix SQL |
+| Hangs / timeout | Wide `query_log` scan | Narrow `event_time` range, add `team_id` filter, use `cluster()` |
-## Investigation workflow
+## ClickHouse investigation workflow
1. **Frame the question.** Slow per-team? Specific query pattern? Cost/memory regression?
2. **Pick the smallest time window** that still answers the question — `query_log` is large; default to 1h–24h, expand only when needed.
diff --git a/.agents/skills/querying-tophog/SKILL.md b/.agents/skills/querying-tophog/SKILL.md
index 5299c49a0c78..1e1aee1736cf 100644
--- a/.agents/skills/querying-tophog/SKILL.md
+++ b/.agents/skills/querying-tophog/SKILL.md
@@ -30,7 +30,7 @@ deliberately **no ClickHouse datasource for agents in Grafana**. The
sanctioned path is the internal Metabase using the **engineer's own SSO
session** — per-person identity, attributable in Metabase's query history, no
standing credential. General mechanics live in the
-`query-clickhouse-via-metabase` skill; the short version:
+`querying-production-databases-via-metabase` skill; the short version:
1. **The user must run login themselves** (the agent shell cannot access the
Keychain): `hogli metabase:login --region eu` (or `us`). macOS will prompt
diff --git a/.agents/skills/triaging-warehouse-sync-tickets/SKILL.md b/.agents/skills/triaging-warehouse-sync-tickets/SKILL.md
index 4abd295d5038..e2943615ee38 100644
--- a/.agents/skills/triaging-warehouse-sync-tickets/SKILL.md
+++ b/.agents/skills/triaging-warehouse-sync-tickets/SKILL.md
@@ -73,7 +73,7 @@ Related skills, and what is still usable from them:
Its tool calls therefore do not apply to you. Its **knowledge** does: the error-string to root-cause
table and the cause to recovery-action mapping are portable, so read those and skip the tool calls.
- `auditing-warehouse-source-health` — same limitation, and it is a project-wide sweep, not one ticket.
-- `query-clickhouse-via-metabase` — `system.query_log` performance work, not sync state.
+- `querying-production-databases-via-metabase` — `system.query_log` performance work, not sync state.
## Ground rules
diff --git a/.agents/skills/triaging-web-analytics-support/SKILL.md b/.agents/skills/triaging-web-analytics-support/SKILL.md
index d423db64d7d6..e8cdcdef89ec 100644
--- a/.agents/skills/triaging-web-analytics-support/SKILL.md
+++ b/.agents/skills/triaging-web-analytics-support/SKILL.md
@@ -55,5 +55,5 @@ Two cross-cutting rules:
## 4. Verification tools
- Runtime loading audits and traffic simulation: [references/loading-audit.md](references/loading-audit.md).
-- Production query-side checks (per-team event series, UA splits, ingestion warnings): the `query-clickhouse-via-metabase` skill covers prod-us and prod-eu access.
+- Production query-side checks (per-team event series, UA splits, ingestion warnings): the `querying-production-databases-via-metabase` skill covers prod-us and prod-eu access.
- Error tracking: MCP `query-error-tracking-issues-list` / `query-error-tracking-issue-events` with `verbosity: stack` gives sourcemapped frames.
diff --git a/.agents/skills/triaging-web-analytics-support/references/diagnostic-playbooks.md b/.agents/skills/triaging-web-analytics-support/references/diagnostic-playbooks.md
index 41ac4a82be86..42717a12667d 100644
--- a/.agents/skills/triaging-web-analytics-support/references/diagnostic-playbooks.md
+++ b/.agents/skills/triaging-web-analytics-support/references/diagnostic-playbooks.md
@@ -26,7 +26,7 @@ Key code: `products/web_analytics/backend/hogql_queries/` (overview vs stats_tab
The decisive question: **which layer dropped?**
-1. Pull the raw daily series (`count()` on events by day for their team, via `query-clickhouse-via-metabase`). If raw counts dropped, no query-time change (bot classification, exclusions, materialization) can be the cause — those never alter stored counts.
+1. Pull the raw daily series (`count()` on events by day for their team, via `querying-production-databases-via-metabase`). If raw counts dropped, no query-time change (bot classification, exclusions, materialization) can be the cause — those never alter stored counts.
2. Sanity checks that kill false leads fast: `$lib` + SDK version split (pinned version = no SDK regression), duplicate-UUID counts (dedup), day-of-week matched comparison (seasonality), hour-of-day spread (region/outage).
3. The bot fingerprint: only `$pageview` drops while `$pageleave` stays flat, loss concentrated in a few UA strings collapsing 10-50x week over week, ~2 pageviews/session with no pageleave. That is non-human traffic that stopped executing the JS SDK — typically the customer's edge (WAF, bot-fight mode, JS challenge) changed, or the scraper stopped. Their server logs still count those requests, which is why "our logs look unchanged".
4. Reply framing: PostHog stored what it received; identify the segment that vanished; ask what changed at their edge on the exact step dates; note the new lower level is closer to true human traffic.
diff --git a/.agents/skills/triaging-web-analytics-support/references/ticket-queries.md b/.agents/skills/triaging-web-analytics-support/references/ticket-queries.md
index b792ea17544e..ca9e94a71a3e 100644
--- a/.agents/skills/triaging-web-analytics-support/references/ticket-queries.md
+++ b/.agents/skills/triaging-web-analytics-support/references/ticket-queries.md
@@ -53,7 +53,7 @@ FROM eu_postgres_posthog_user u WHERE u.email = '{email}'
Also useful: `postgres.posthog_organizationdomain` (verified domains only — often empty for smaller orgs), `postgres.posthog_organization` by name, `all_posthog_team`.
EU customer data is not queryable from the US MCP project.
-For per-team event data on either region, use the `query-clickhouse-via-metabase` skill.
+For per-team event data on either region, use the `querying-production-databases-via-metabase` skill.
## Error tracking cross-reference
diff --git a/AGENTS.md b/AGENTS.md
index 6119a6262fc5..1d613fa97028 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -283,6 +283,7 @@ ALWAYS invoke the matching skill **before** writing or reviewing code in these a
- `/stacking-prs` — creating, restacking, adopting, or landing a stack of PRs (`gh stack`)
- `/implementing-mcp-tools` — adding/modifying endpoints or `tools.yaml`
- `/modifying-taxonomic-filter` — any TaxonomicFilter change
+- `/profiling-slow-api-endpoints` — an endpoint, list, picker, or scene is slow, a p95 latency number needs explaining, or a Postgres query plan needs checking against production rather than a local database
- `/placing-product-frontend-code` — adding a frontend file or directory for a product, or deciding between `products/<name>/frontend/` and `frontend/src/scenes/<name>/`
- [`products/conversations/skills/organizing-conversations-code/SKILL.md`](products/conversations/skills/organizing-conversations-code/SKILL.md) — adding, moving, renaming, or reviewing files under `products/conversations/`
- `/integrating-with-posthog-ai` — making a product surface work with PostHog AI: injecting scene context or custom instructions, reacting to the agent's tool calls, or rendering your product's tool cards in a thread
diff --git a/bin/sandbox-tools.yaml b/bin/sandbox-tools.yaml
index 22f1e236c26c..f5a4c1d909c5 100644
--- a/bin/sandbox-tools.yaml
+++ b/bin/sandbox-tools.yaml
@@ -43,7 +43,7 @@ tools:
- ~/.config/graphite
- name: metabase
- description: 'Metabase SSO cookies for the query-clickhouse-via-metabase skill (hogli metabase:*, regions us/eu/dev)'
+ description: 'Metabase SSO cookies for the querying-production-databases-via-metabase skill (hogli metabase:*, regions us/eu/dev)'
copy:
- ~/.config/posthog/metabase/cookie-us
- ~/.config/posthog/metabase/cookie-eu
diff --git a/products/notebooks/backend/sql_v2_observability.md b/products/notebooks/backend/sql_v2_observability.md
index a6976ccebe9f..297ca72fd487 100644
--- a/products/notebooks/backend/sql_v2_observability.md
+++ b/products/notebooks/backend/sql_v2_observability.md
@@ -18,7 +18,7 @@ It cannot hold per-query ClickHouse cost — scanned bytes per query is unbounde
**ClickHouse `query_log_archive`** holds the per-query cost: `read_bytes`, `result_bytes`, `result_rows`, `query_duration_ms`, `memory_usage`, `peak_threads_usage`, exception codes.
It is not in Grafana — production ClickHouse holds customer data and there is deliberately no ClickHouse datasource there.
-The sanctioned path is the internal Metabase under your own SSO session (the `query-clickhouse-via-metabase` skill).
+The sanctioned path is the internal Metabase under your own SSO session (the `querying-production-databases-via-metabase` skill).
Grafana dashboards are **not code-managed** in this repo — they are edited in the UI, reachable over Tailscale at `grafana-prod-us` / `grafana-prod-eu` (see `tools/infra-scripts/mcp/README.md`).
The JSON here is an import artifact, not a provisioned source of truth. Import it, then own it in the UI.
diff --git a/products/notebooks/observability/notebooks-query-log.sql b/products/notebooks/observability/notebooks-query-log.sql
index 8652e27434b9..e705884cd4e5 100644
--- a/products/notebooks/observability/notebooks-query-log.sql
+++ b/products/notebooks/observability/notebooks-query-log.sql
@@ -7,7 +7,7 @@
-- everything below.
--
-- Run these through the internal Metabase against "PostHog ClickHouse PROD <REGION>
--- Data Tier" (see the query-clickhouse-via-metabase skill):
+-- Data Tier" (see the querying-production-databases-via-metabase skill):
-- hogli metabase:login --region us
-- hogli metabase:databases --region us
-- hogli metabase:query --region us --database-id <id> < this-file