: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(ingestion): add tophog diagnosis skill (#68687)
Zach Brown4de37d78da76
diff --git a/.agents/skills/monitoring-ingestion-pipeline/SKILL.md b/.agents/skills/monitoring-ingestion-pipeline/SKILL.mdindex 9023459f36c0..a72e34e3d6a7 100644--- a/.agents/skills/monitoring-ingestion-pipeline/SKILL.md+++ b/.agents/skills/monitoring-ingestion-pipeline/SKILL.md@@ -423,5 +423,7 @@ Scope: `namespace=~"ingestion-.*"`, `pod=~"ingestion-.*"` (or `namespace="clickhSee [references/investigation-playbooks.md](./references/investigation-playbooks.md)for step-by-step workflows covering: health checks, event drops, latency, consumer lag,-person processing, Kafka/MSK issues, Redis, Postgres, session replay, ClickHouse-downstream health, and cross-environment comparison.+person processing (including the pganalyze query-level view of the persons DB),+Kafka/MSK issues, Redis, Postgres, session replay, ClickHouse downstream health,+single-partition lag (keyed-cost diagnosis, handing off to the `querying-tophog`+skill for actor identification), and cross-environment comparison.diff --git a/.agents/skills/monitoring-ingestion-pipeline/references/investigation-playbooks.md b/.agents/skills/monitoring-ingestion-pipeline/references/investigation-playbooks.mdindex 1e9afa281f90..88201a5b0c58 100644--- a/.agents/skills/monitoring-ingestion-pipeline/references/investigation-playbooks.md+++ b/.agents/skills/monitoring-ingestion-pipeline/references/investigation-playbooks.md@@ -55,11 +55,16 @@ Diagnose layer by layer, from consumer to output:This is the total time to consume + process a batch. High values mean slow processing.Compare across consumer groups to identify which pipeline is slow.-2. **Pipeline step latency** — `events_pipeline_step_ms` by `step_name`.- Identify which step is the bottleneck. Common culprits:+2. **Pipeline step latency** — `ingestion_pipeline_step_duration_seconds` by `step_name`+ (histogram; avg = `rate(_sum)/rate(_count)`, tail via `histogram_quantile` on `_bucket`).+ The older `events_pipeline_step_ms` is legacy. Identify which step is the bottleneck.+ Common culprits:- `processPersonsStep` / `processGroupsStep` — database writes- - `produceEventsStep` — Kafka production- - `extractHeatmapDataStep` — CPU-intensive parsing+ - `hogTransformEventStep` — customer-defined transformations (CPU or fetch)+ - `emitEventStep` — Kafka production+ Compare **p50 vs p99**: a heavy tail (p50 fine, p99 in seconds) means a+ _minority_ of events is expensive — a pattern that never shows up in+ volume-ranked views.3. **Person store latency** — `person_*` metrics for flush duration and DB write time.`personhog_latency_seconds` for PersonHog gRPC call latency.@@ -103,7 +108,26 @@ Diagnose layer by layer, from consumer to output:Large person properties = slow reads/writes.5. **Postgres health** — check PgBouncer metrics and CloudWatch RDS for thepersons DB (`posthog-cloud-persons-prod-us-east-1`).-6. **Group processing** — `group_*` metrics for similar DB operation patterns.+6. **pganalyze — query-level view of the persons DB** (the pganalyze MCP is+ available in agent sessions; `list_servers` / `get_databases` to find the+ persons DB for the environment):+ - `get_query_stats` sorted by **`avgTime` and `avgTimeDelta`** — never by+ `pctOfTotal`. A low-volume contention query (e.g. 143 calls at ~2.5s+ each, 0.2% of total runtime) is invisible by total-runtime share but can+ stall a whole team's person processing. `avgTimeDelta` surfaces what+ _regressed_ in the incident window.+ - Watch the person write-path tables: `posthog_person`,+ `posthog_persondistinctid`, `posthog_personlessdistinctid`,+ `posthog_featureflaghashkeyoverride`.+ - Known contention signature (real incident): a team-scoped+ `DELETE … WHERE id IN (SELECT … FOR UPDATE SKIP LOCKED)` on+ `posthog_personlessdistinctid`, ~2.4s of I/O per call at ~85% buffer hit+ (disk-bound ⇒ bloat), colliding with the hot+ `addPersonlessDistinctIdsBatch` insert path — stalls that team's person+ processing, and with it the Kafka partition(s) carrying that team.+ - `get_query_explains` for plan history; table stats for dead tuples /+ TOAST bloat when a query is I/O-bound.+7. **Group processing** — `group_*` metrics for similar DB operation patterns.`group_update_version_mismatch` for optimistic update conflicts.## 6. "Kafka / MSK problems" — broker and topic health@@ -226,7 +250,71 @@ ClickHouse lag means users see stale data even if ingestion workers are healthy.10. **CH cluster overview** — dashboard `vm-clickhouse-cluster-overview`.QPS, memory tracking, disk capacity, connection count, ZooKeeper health.-## 11. "Comparing prod-us vs prod-eu" — cross-environment+## 11. "A single partition is lagging" — keyed-cost diagnosis++One partition lagging while the rest of the topic is healthy is a distinct+failure class with its own method. Distilled from a real multi-hour incident;+following the order below turns it into minutes.++1. **Topology reasoning first — it eliminates whole categories.** Analytics+ events are keyed by `token:distinct_id`, so a single lagging partition+ means the cost is tied to what hashes there: one team, or a small set of+ `distinct_id` values. Anything fleet-wide (a team-wide transformation, a+ deploy, a global config change, shared-infra degradation) would lag every+ partition and is structurally excluded — don't spend time on those.+ Corollary: **one partition = one consumer**; adding pods can never drain+ it. Restarts only help if a stuck connection was the cause (rare — verify+ before restarting; if lag growth continues unchanged after a restart, the+ cost is in the traffic itself).++2. **Locate it.** `ingestion_lag_ms{app="…", partition="N"}` for the lag+ curve and onset time. Find the owning pod and live offsets from the batch+ logs in Loki: `{app="ingestion-analytics-main"} |= "KAFKA_BATCH_START" |= "\"partition\":N"`.++3. **Slow or busy? Compute it, don't guess.** From two batch-log samples:+ offset delta ÷ elapsed = events/sec; batch duration ÷ batch size =+ ms/event.+ - **Busy** (high events/sec, normal ms/event): a _volume_ hot key —+ identify it with tophog ranked by volume, and the lever is overflow+ routing.+ - **Slow** (low events/sec, high ms/event): _expensive_ per-event work —+ continue below. Nothing will show up in volume rankings; a "no hot key"+ result from volume tools is expected, not exculpatory.++4. **Which stage.** Per-pod step breakdown:+ `sum by (step_name) (rate(ingestion_pipeline_step_duration_seconds_sum{pod="…"}[5m]))+/ sum by (step_name) (rate(…_count{pod="…"}[5m]))`, then rank the suspect+ pod against the fleet for the top step. **Two traps:**+ - A pod usually carries ~2 partitions — elevation on the pod can come from+ either one, and two different steps can implicate two _different_+ partitions. Treat pod-level attribution as a hint, not proof.+ - During backlog drain the pod saturates and _all_ steps inflate together+ — measure during the lagging phase, or re-measure after drain.+ Also check p50 vs p99 for the suspect step (`histogram_quantile` on+ `_bucket`): a heavy tail means a minority of poisoned events.++5. **Who.** tophog ranked by **cost, not volume** — see the+ `querying-tophog` skill. `process_persons_time` summed by+ `key['team_id'], key['distinct_id']` with an ms-per-event ratio separates+ hot keys from expensive actors; data written after 2026-07-06 can filter+ `key['partition'] = 'N'` directly, and `merge_events_per_distinct_id`+ identifies merge storms.++6. **If `processPersonsStep` is implicated** → playbook 5 step 6 (pganalyze,+ sorted by `avgTime`/`avgTimeDelta`). The root cause can be a single+ low-volume contention query on the persons write path that no+ volume-ranked view will ever surface.++7. **If `hogTransformEventStep` is implicated** → inspect the suspect team's+ enabled transformations (Data pipelines UI, or `posthog_hogfunction` where+ `type = 'transformation' AND enabled`). Two traps: `app_metrics2` failure+ counts mislead — _destinations_ fail noisily but run in CDP, **off** the+ ingestion path; only `type='transformation'` runs inline and can wedge a+ partition. And a _slow but succeeding_ fetch inside a transformation lands+ in `succeeded`, invisible in failure counts — judge by latency evidence,+ not failure evidence.++## 12. "Comparing prod-us vs prod-eu" — cross-environmentMost ingestion app metrics use the `app` / `ingestion_pipeline` labels but**no environment label** — the environment is implicit in which Grafana you're connected to.diff --git a/.agents/skills/querying-tophog/SKILL.md b/.agents/skills/querying-tophog/SKILL.mdnew file mode 100644index 000000000000..5299c49a0c78--- /dev/null+++ b/.agents/skills/querying-tophog/SKILL.md@@ -0,0 +1,215 @@+---+name: querying-tophog+description: >+ Query tophog — the ingestion pipeline's heavy-hitter store in ClickHouse — to+ identify hot or expensive actors (team_id, distinct_id, session_id,+ partition) during incident triage. Use when investigating ingestion lag, a+ hot or lagging Kafka partition, expensive person processing, merge storms,+ or any "which team or distinct_id is causing this" question. Covers the+ internal Metabase access path (SSO via hogli), the tophog schema, and the+ cost-vs-volume query lens. Internal-only: results contain cross-customer+ identifiers.+---++# Querying tophog++tophog is the ingestion pipeline's heavy-hitter tracker: workers accumulate+per-key aggregates (counts, timers) in memory and periodically flush them to+the `tophog` ClickHouse table via Kafka (`clickhouse_tophog` topic). It answers+"which actor is responsible" questions that fleet-level Prometheus metrics+cannot — per-metric label cardinality is unbounded (`distinct_id`,+`session_id`), so this data lives only in ClickHouse. Retention is 30 days.++The staff-only Django admin has a dashboard over it, but for agent-driven+triage query it directly through the internal Metabase.++## Access — internal Metabase, never Grafana++The production ClickHouse clusters hold customer data, so there is+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:++1. **The user must run login themselves** (the agent shell cannot access the+ Keychain): `hogli metabase:login --region eu` (or `us`). macOS will prompt+ about "Chrome Safe Storage" — that's `browser_cookie3` decrypting the+ browser's cookie store to capture the SSO session; one-time Allow is the+ right choice.+2. Discover the database id — it is not stable across Metabase rebuilds:++ ```bash+ hogli metabase:databases --region eu+ ```++ Pick **"PostHog ClickHouse PROD <REGION> Data Tier"** (the data tier, not+ the query tier — tophog lives with the events data).++3. Run queries; the cookie is read internally and never enters the transcript:++ ```bash+ hogli metabase:query --region eu --database-id <id> <<'SQL'+ SELECT ...+ SQL+ ```++## Schema++Table `tophog` (Distributed over `sharded_tophog`), ordered by+`(pipeline, lane, metric, timestamp, key)`, partitioned by day:++| Column | Type | Notes |+| ----------- | ---------------------- | ---------------------------------------------------------------------------------------------------- |+| `timestamp` | DateTime64(6) | Flush-window time; always bound it (daily partitions) |+| `metric` | LowCardinality(String) | See inventory below |+| `type` | LowCardinality(String) | Aggregation semantics: `sum` (default), `max`, `avg` |+| `key` | Map(String, String) | The actor: access as `key['team_id']`, `key['distinct_id']`, `key['partition']`, `key['session_id']` |+| `value` | Float64 | The aggregated value for this flush window |+| `count` | UInt64 | Observations in the window |+| `pipeline` | LowCardinality(String) | e.g. `analytics` |+| `lane` | LowCardinality(String) | `main`, `overflow`, `historical`, `async`, `turbo` |+| `labels` | Map(String, String) | Extra non-key labels |++One row is one worker's flush window for one (metric, key) — always aggregate+on read. Read-side semantics per `type` (matches the admin dashboard):++```sql+CASE type+ WHEN 'max' THEN max(value)+ WHEN 'avg' THEN sum(value * count) / sum(count)+ ELSE sum(value)+END+```++## Metric inventory — discover live, don't trust lists++Metrics are defined inline in the ingestion pipelines (grep `topHog(` /+`timer(` / `sum(` in `nodejs/src/ingestion/pipelines/analytics/`), so the set+evolves. Always start with discovery:++```sql+SELECT metric, type, count() AS rows, sum(count) AS observations+FROM tophog+WHERE timestamp > now() - INTERVAL 1 HOUR+GROUP BY metric, type+ORDER BY metric+```++As of 2026-07-06 (master), the analytics metrics include+`process_persons_time` (timer; key: team_id, distinct_id, partition),+`emitted_events[_per_distinct_id|_per_partition]`,+`transformations_run[_per_partition]`,+`events_dropped_by_transformation[_per_partition]`,+`merge_events_per_distinct_id` (merge-intent events: `$create_alias` /+`$merge_dangerously` with alias, `$identify` with `$anon_distinct_id`),+`group_identify_events_per_distinct_id`, `resolved_teams`, and session-replay+`*_by_session_id` timers.++**Dimensions are deploy-gated and rows are immutable**: the `partition` key on+`process_persons_time` and the merge/group-identify metrics merged 2026-07-06+and only exist in data written after that deploy reaches the environment.+Check before relying on them:++```sql+SELECT countIf(key['partition'] != '') AS with_partition, count() AS total+FROM tophog+WHERE timestamp > now() - INTERVAL 1 HOUR AND metric = 'process_persons_time'+```++## The lens: cost vs volume++This is the load-bearing idea. Volume ranking finds **busy** actors; cost+ranking finds **slow** ones — and a single lagging partition is usually a+_cost_ problem (a real incident: the top-cost actor was invisible in every+volume view). Rank by summed timer value, and compute the per-event ratio to+classify what you found:++| Pattern | Reading |+| ---------------------------- | ---------------------------------------------------------------------------------------------------- |+| High events, normal ms/event | Hot key (volume) — overflow/rebalance is the lever |+| Low events, high ms/event | Expensive actor — fat person properties, merge-heavy, or contended writes; scaling out will not help |++## Canned queries++Top actors by person-processing cost (the incident query):++```sql+SELECT+ key['team_id'] AS team_id,+ key['distinct_id'] AS distinct_id,+ round(sum(value)) AS total_ms,+ sum(count) AS events,+ round(sum(value) / sum(count), 1) AS ms_per_event,+ arraySort(groupUniqArray(lane)) AS lanes+FROM tophog+WHERE timestamp > now() - INTERVAL 1 HOUR+ AND metric = 'process_persons_time'+GROUP BY team_id, distinct_id+ORDER BY total_ms DESC+LIMIT 10+```++Scoped to one lagging partition (data written after the partition dimension+deployed):++```sql+-- add to WHERE:+ AND key['partition'] = '434'+```++Merge storms (merges are the classic person-processing cost driver):++```sql+SELECT key['team_id'] AS team_id, key['distinct_id'] AS distinct_id,+ key['partition'] AS partition, sum(value) AS merge_events+FROM tophog+WHERE timestamp > now() - INTERVAL 1 HOUR+ AND metric = 'merge_events_per_distinct_id'+GROUP BY team_id, distinct_id, partition+ORDER BY merge_events DESC+LIMIT 10+```++Generic top-10 per metric with correct type semantics (the admin dashboard's+query shape) — filter by `pipeline` / `lane` as needed:++```sql+SELECT metric, type, key, total, obs+FROM (+ SELECT *, ROW_NUMBER() OVER (PARTITION BY metric, type ORDER BY total DESC) AS rn+ FROM (+ SELECT metric, type, key,+ CASE type+ WHEN 'max' THEN max(value)+ WHEN 'avg' THEN sum(value * count) / sum(count)+ ELSE sum(value)+ END AS total,+ sum(count) AS obs+ FROM tophog+ WHERE timestamp > now() - INTERVAL 1 HOUR+ AND pipeline = 'analytics' AND lane = 'main'+ GROUP BY metric, type, key+ )+)+WHERE rn <= 10+ORDER BY metric, type, rn+```++## Cautions++- **`distinct_id` and `session_id` values are customer PII** (often emails).+ Internal triage use only — never paste them into public PRs, issues, or+ commit messages.+- Always bound `timestamp` — the table is partitioned by day and holds 30+ days.+- Queries run under the engineer's Metabase identity and appear in their+ query history.++## Related++- `monitoring-ingestion-pipeline` — the Grafana-side diagnosis, including the+ single-partition-lag playbook that hands off to this skill for actor+ identification.+- The pganalyze MCP — the next hop when person processing is implicated+ (query-level view of the persons Postgres).