: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(clickhouse): log element stats aggregation findings in learnings (#68065)
Paul D'Ambra3926c21af660
diff --git a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.mdindex 15159e8be441..83ec242da7ac 100644--- a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md+++ b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md@@ -28,6 +28,37 @@ Suggested entry format:---+## 2026-07-02: GROUP BY elements_chain is scan-bound; URL filters prune by granule-spread, not row-selectivity; OFFSET re-runs the whole aggregation++**Context.** The toolbar clickmap endpoint (`/api/element/stats/`, `GET_ELEMENTS` in `posthog/models/element/sql.py`): raw single-team SQL grouping `events.elements_chain` by chain and event type over a team + date range + `$current_url` filter, ordered by count. Production p50 is fine (~250ms) but wide date ranges on pages whose URL is dense in the team's own traffic read hundreds of GiB and take seconds; the toolbar also paginates this with LIMIT/OFFSET.++**Question.** Can the wide-range tail be fixed per-query — PREWHERE, cheaper GROUP BY keys, memory bounds, or pagination — or is the scan irreducible?++**What we tried.** On the Test Cluster (team 2, 90-day window, `use_uncompressed_cache=0`): (A) the production shape — `match("mat_$current_url", '^…/project/.*/home$')`, `GROUP BY elements_chain, event`, `LIMIT 5001`; (B) the same with team/event/date/url moved to an explicit `PREWHERE`; (C) `GROUP BY cityHash64(elements_chain)` + `any(elements_chain)`; (S) the same range with an exact `has([...])` match on a URL that is rare in the range; (X) A plus `max_bytes_before_external_group_by = 4GiB`; (L) A with `LIMIT 50001`.++**Numbers.** Medians from `system.query_log` (A/S: 5 runs; B/C: 3; X: 4; L: 3):++| Variant | Duration (ms) | Read bytes | Memory |+| --------------------------------- | ------------- | ---------- | -------- |+| A dense-URL wildcard, LIMIT 5001 | 5,185 | 134.9 GiB | 12.2 GiB |+| B explicit PREWHERE | 5,710 | 143.9 GiB | 12.1 GiB |+| C cityHash64 GROUP BY keys | 5,467 | 138.9 GiB | 11.6 GiB |+| S sparse exact URL, same range | 525 | 1.0 GiB | 126 MiB |+| X external-group-by bound (4 GiB) | 5,272 | 134.4 GiB | 11.9 GiB |+| L LIMIT 50001 | ~10,900\* | 134.1 GiB | 16.1 GiB |++\* L was cancelled at ~11s all three runs by Metabase aborting the ~100MB result download (`QUERY_WAS_CANCELLED`), not by ClickHouse — the scan and memory numbers before cancellation are the signal.++**Caveats.** Single-tenant snapshot, no noisy neighbors; X's threshold may simply not have been crossed by the aggregation state alone, so it is inconclusive rather than negative; L's duration is a client artifact.++**Takeaways.**++- **Automatic PREWHERE is already optimal here; the URL predicate prunes by granule-spread, not row-selectivity.** A URL that is sparse across granules collapses the scan 134x (S) with no index at all, while a URL dense in the team's own traffic (their homepage) has a match in essentially every granule, so the fat `elements_chain` column is read for the entire range and neither explicit PREWHERE (B) nor any skip index can help — there is nothing to skip. The per-query floor is the dense-URL wide-range scan; the structural fix is pre-aggregation (a daily chain rollup), not query tuning.+- **Hashing the GROUP BY key buys only ~7%** (C): aggregation memory is dominated by the chain _values_ (needed for output), not the key hash table.+- **LIMIT size does not change the scan** (L reads what A reads) but grows the ORDER BY/LIMIT heap (+4 GiB at 50k rows of multi-KB strings), **and LIMIT/OFFSET pagination over a live GROUP BY re-runs the full aggregation per page** — and can silently _miss_ rows that shift across a page boundary between scans (deduping catches duplicates, nothing catches gaps). A client that wants more rows should re-fetch from offset 0 with a bigger limit — one extra scan, no gaps — rather than paginate.++---+## 2026-06-10: A minmax skip index on a mixed-content string column does not rescue unbounded point lookups; UUIDv7 ids carry their own time bound**Context.** Replay capture diagnostics (`frontend/src/scenes/session-recordings/components/replayCaptureDiagnosticsPanelLogic.ts`): `SELECT properties FROM events WHERE $session_id = {sid} ORDER BY timestamp DESC LIMIT 1` with no timestamp predicate. `$session_id` is a materialized column with `INDEX minmax_$session_id ... TYPE minmax GRANULARITY 1`, and session ids are UUIDv7 (time-ordered), so on paper the skip index should prune almost everything even without a timestamp bound.