OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M28-001): M25 Group B: fold the three events scans in page-filtered getMetrics, or prove it is not worth doing
ralph111fd19e3a6f
diff --git a/packages/core/src/modules/overview/src/metrics-page-filter.test.ts b/packages/core/src/modules/overview/src/metrics-page-filter.test.tsnew file mode 100644index 000000000..5447ea617--- /dev/null+++ b/packages/core/src/modules/overview/src/metrics-page-filter.test.ts@@ -0,0 +1,160 @@+/**+ * Behavioural test for `metricsWithPageFilterQuery`, executed against the+ * isolated `openpanel_test` ClickHouse (pinned by test/preload.ts) — the+ * counterpart of overview.sql.test.ts's EXPLAIN-only check.+ *+ * It pins the one property the golden master cannot reach: the query's+ * window-wide `overall_*` columns come from a different aggregate than the+ * daily rows, and `overall_bounce_rate` comes from a different *table*. The+ * seeded data therefore puts the sessions on a day the events are not on, so+ * the daily LEFT JOIN misses on every row — and the overall bounce rate must+ * still arrive. A page filter matching nothing must leave all three+ * `overall_*` columns NULL, which is what `getMetricsWithPageFilter` reads to+ * tell "no data" from "zero".+ */++import { afterAll, beforeAll, describe, expect, it } from 'bun:test';++const PROJECT_ID = 'overview-metrics-page-filter-test';+const FILTERED_PATH = '/pricing';+const SESSION_DAY = '2026-01-05';+const EVENT_DAY = '2026-01-08';+const WINDOW_START = '2026-01-01 00:00:00';+const WINDOW_END = '2026-01-15 00:00:00';+/** One bounced and one non-bounced session, both on `SESSION_DAY`. */+const EXPECTED_OVERALL_BOUNCE_RATE = 50;++interface MetricsRow {+ date: string;+ bounce_rate: number;+ unique_visitors: number;+ total_sessions: number;+ avg_session_duration: number;+ total_screen_views: number;+ views_per_session: number;+ overall_unique_visitors: number | null;+ overall_total_sessions: number | null;+ overall_bounce_rate: number | null;+}++let ch: typeof import('@openpanel/db/src/clickhouse/client').ch;+let OV: typeof import('./overview.sql');+let getRawWhereClause: typeof import('../overview.service').getRawWhereClause;++async function metricsFor(path: string): Promise<MetricsRow[]> {+ const filters = [+ { id: 'a', name: 'path', operator: 'is' as const, value: [path] },+ ];+ const { query, query_params } = OV.metricsWithPageFilterQuery({+ projectId: PROJECT_ID,+ startDate: WINDOW_START,+ endDate: WINDOW_END,+ interval: 'day',+ rawSessionFilterWhere: getRawWhereClause('sessions', filters),+ rawEventFilterWhere: getRawWhereClause('events', filters),+ }).toStatement();+ const result = await ch.query({+ query,+ query_params,+ format: 'JSONEachRow',+ clickhouse_settings: { session_timezone: 'UTC' },+ });+ return result.json<MetricsRow>();+}++const session = (id: string, isBounce: boolean) => ({+ id,+ project_id: PROJECT_ID,+ profile_id: `profile-${id}`,+ device_id: `device-${id}`,+ created_at: `${SESSION_DAY} 09:00:00`,+ ended_at: `${SESSION_DAY} 09:01:00`,+ is_bounce: isBounce,+ entry_path: FILTERED_PATH,+ exit_path: FILTERED_PATH,+ screen_view_count: 1,+ event_count: 1,+ duration: 60,+ sign: 1,+ version: 1,+});++const screenView = (id: string, index: number) => ({+ id,+ project_id: PROJECT_ID,+ name: 'screen_view',+ created_at: `${EVENT_DAY} 1${index}:00:00`,+ profile_id: `profile-event-${index}`,+ session_id: `session-event-${index}`,+ path: FILTERED_PATH,+});++beforeAll(async () => {+ ({ ch } = await import('@openpanel/db/src/clickhouse/client'));+ OV = await import('./overview.sql');+ ({ getRawWhereClause } = await import('../overview.service'));++ const { bootstrapTestDatabases } = await import(+ '../../../../../../test/bootstrap-databases'+ );+ await bootstrapTestDatabases();++ await ch.command({+ query: `DELETE FROM sessions WHERE project_id = '${PROJECT_ID}'`,+ });+ await ch.command({+ query: `DELETE FROM events WHERE project_id = '${PROJECT_ID}'`,+ });+ await ch.insert({+ table: 'sessions',+ values: [+ session('00000000-0000-0000-0000-0000000000a1', true),+ session('00000000-0000-0000-0000-0000000000a2', false),+ ],+ format: 'JSONEachRow',+ });+ await ch.insert({+ table: 'events',+ values: [+ screenView('00000000-0000-0000-0000-0000000000b1', 1),+ screenView('00000000-0000-0000-0000-0000000000b2', 2),+ ],+ format: 'JSONEachRow',+ });+});++afterAll(async () => {+ await ch.command({+ query: `DELETE FROM sessions WHERE project_id = '${PROJECT_ID}'`,+ });+ await ch.command({+ query: `DELETE FROM events WHERE project_id = '${PROJECT_ID}'`,+ });+});++describe('metricsWithPageFilterQuery — window-wide totals', () => {+ it('carries overall_bounce_rate onto days the sessions aggregate has no row for', async () => {+ const rows = await metricsFor(FILTERED_PATH);+ const eventRow = rows.find((row) => row.total_screen_views > 0);++ expect(eventRow?.date).toBe(`${EVENT_DAY} 00:00:00`);+ // The join misses: there is no session bucketed on the event day.+ expect(eventRow?.bounce_rate).toBe(0);+ expect(eventRow?.overall_bounce_rate).toBe(EXPECTED_OVERALL_BOUNCE_RATE);+ expect(eventRow?.overall_unique_visitors).toBe(2);+ expect(eventRow?.overall_total_sessions).toBe(2);+ expect(eventRow?.total_screen_views).toBe(2);+ });++ it('leaves every overall_* column NULL when the page filter matches nothing', async () => {+ const rows = await metricsFor('/no-such-page');++ expect(rows.length).toBeGreaterThan(0);+ for (const row of rows) {+ expect(row.overall_unique_visitors).toBeNull();+ expect(row.overall_total_sessions).toBeNull();+ expect(row.overall_bounce_rate).toBeNull();+ expect(row.total_screen_views).toBe(0);+ }+ });+});diff --git a/packages/core/src/modules/overview/src/overview.sql.proof.md b/packages/core/src/modules/overview/src/overview.sql.proof.mdindex 67e071c41..3a7ca0dbd 100644--- a/packages/core/src/modules/overview/src/overview.sql.proof.md+++ b/packages/core/src/modules/overview/src/overview.sql.proof.md@@ -36,6 +36,50 @@run 10 times, returned 10 different row orders and 1 identical row set**. Set-level hashes are thecomparison above for that reason.+- **Amended by M28-001 (2026-09-15): `metricsWithPageFilterQuery` reads each source table once.**+ The shipped shape referenced `overall_unique_visitors` twice and `session_agg` twice, and+ **a ClickHouse CTE is re-executed once per reference** — so the statement performed **four+ `events` scans and two `sessions FINAL` scans**, not the three `docs/ANALYTICS_PERFORMANCE.md`+ section 6.10 counted. Measured on the local prod copy, `chatpaper` 30 d filtered on its busiest+ path: the whole statement read **60,569,110 rows = 4 x 13,393,722 + 2 x 3,497,111**, and removing+ each scalar reference in turn dropped exactly one scan's worth (47,175,388 -> 33,781,666 ->+ 30,284,555). Section 6.10's *"ClickHouse may already share those scans"* is therefore **measured+ false**, and its 1,453 ms / 30,350,044-row baseline is the cost of the statement with those two+ extra references removed, i.e. roughly half the real one.+ The query now reads `events` once into `filtered_screen_views`, aggregates it once with+ `GROUP BY date WITH ROLLUP`, and broadcasts the window-wide totals off that rollup row with+ `max(if(date = <rollup>, x, NULL)) OVER ()` instead of re-scanning. Same for `sessions`. Both+ aggregates keep their rollup row through the `LEFT JOIN` so the two totals rows pair up — that is+ what carries `overall_bounce_rate` onto days the sessions aggregate has no row for — and the+ rollup row is dropped afterwards. `src/metrics-page-filter.test.ts` pins both that case and the+ NULL-when-nothing-matches nullability the old scalar subqueries had.+ Re-proved against the local prod copy on **2026-09-15**, `use_query_condition_cache=0`,+ `max_memory_usage=6 GiB`, `elapsed_ns`/`read_rows`/`memory_usage` read off `X-ClickHouse-Summary`:+ - **Result sets: `FORMAT JSONCompact` `meta` + `data`, compared byte-for-byte, old vs new —+ identical on 38 of 38 cases.** All five anchors; windows 1 d / 7 d / 30 d / 56 d; intervals+ minute / hour / day / week / month; and the edge cases that decide the rewrite: a page filter+ matching nothing (all five projects), `verdict` — which has no `screen_view` events at all — a+ path that is never any session's `entry_path`, and a `bayse` path whose event days and session+ days **do not overlap at all**, which is the case the naive fold gets wrong.+ - **Cost, 30-day window, busiest path, median of 3:**++| project | old ms | old rows_read | new ms | new rows_read |+|---|---:|---:|---:|---:|+| `bayse` | 1,554 | 68,873,974 | **495** | **17,496,956** |+| `earlysalary-production` | 1,863 | 62,275,058 | **706** | **15,875,922** |+| `website-8103` | 1,551 | 49,471,404 | **520** | **12,384,061** |+| `chatpaper` | 2,901 | 60,569,110 | **1,118** | **16,890,833** |+| `verdict` (no `screen_view` at all) | 182 | 1,673,650 | **66** | **828,633** |++ Peak memory is slightly higher (`chatpaper` 98 MiB -> 186 MiB), because one pass now holds the+ per-row `lead()` window and the daily aggregate together instead of building them in separate+ scans. At 56 days on `bayse` the statement goes 3,317 ms / 154,168,912 rows -> 1,031 ms /+ 38,968,107 rows.+ - **The M7-005 render case below** (`skills-directory`, `2026-08-01`..`2026-08-08`, no filter)+ re-run on 2026-09-15: same 7 rows, byte-identical, **65 ms / 475,054 rows -> 30 ms /+ 131,039 rows**. Its row in the per-query table further down is M7-005's original measurement+ and is left as the historical record.+- **Date**: 2026-09-04. **Data**: local prod-copy `openpanel` (319,499,000 events, static).Project: `skills-directory` (293,597 events, 75,727 sessions, 2026-07-01..2026-08-25).Window used throughout: `2026-08-01 00:00:00`..`2026-08-08 00:00:00`, UTC.diff --git a/packages/core/src/modules/overview/src/overview.sql.test.ts b/packages/core/src/modules/overview/src/overview.sql.test.tsindex 5264b3d79..38fb13ea9 100644--- a/packages/core/src/modules/overview/src/overview.sql.test.ts+++ b/packages/core/src/modules/overview/src/overview.sql.test.ts@@ -74,7 +74,7 @@ describe('overview.sql — parses against ClickHouse', () => {);});- it('metricsWithPageFilterQuery — the 5-CTE page-filtered metrics query', async () => {+ it('metricsWithPageFilterQuery — the single-scan page-filtered metrics query', async () => {await explain(OV.metricsWithPageFilterQuery({projectId: PROJECT_ID,diff --git a/packages/core/src/modules/overview/src/overview.sql.ts b/packages/core/src/modules/overview/src/overview.sql.tsindex eea3ae369..6ab65dd3b 100644--- a/packages/core/src/modules/overview/src/overview.sql.ts+++ b/packages/core/src/modules/overview/src/overview.sql.ts@@ -210,11 +210,18 @@ export function metricsWithPageFilterQuery(input: PageFilterMetricsQueryInput): SqlFragment {const rollupDate = rollupDateLiteral(input.interval);- const eventsDateBucket = toStartOf('e.created_at', input.interval);-- const rawScreenViewDurations = sql`+ const dateBucket = toStartOf('created_at', input.interval);++ // One pass over `events`, carrying the per-row duration the daily average+ // needs alongside the columns every other metric aggregates. A CTE is+ // re-executed once per reference, so each source is read exactly once here+ // and the window-wide totals are lifted off its own `WITH ROLLUP` row rather+ // than from a second scan (M28-001).+ const filteredScreenViews = sql`SELECT- ${toStartOf('created_at', input.interval)} AS date,+ ${dateBucket} AS date,+ profile_id,+ session_id,dateDiff('millisecond', created_at, lead(created_at, 1, created_at) OVER (PARTITION BY session_id ORDER BY created_at)) AS durationFROM eventsWHERE project_id = ${sql.string(input.projectId)}@@ -223,15 +230,22 @@ export function metricsWithPageFilterQuery(${rawWhere(input.rawEventFilterWhere)}`;- const avgDurationByDate = sql`- SELECT date, round(avgIf(duration, duration > 0), 2) / 1000 AS avg_session_duration- FROM raw_screen_view_durations+ const eventAgg = sql`+ SELECT+ date,+ uniq(profile_id) AS unique_visitors,+ uniq(session_id) AS total_sessions,+ count(*) AS total_screen_views,+ round((count(*) * 1.) / uniq(session_id), 2) AS views_per_session,+ round(avgIf(duration, duration > 0), 2) / 1000 AS avg_session_duration+ FROM filtered_screen_viewsGROUP BY date+ WITH ROLLUP`;const sessionAgg = sql`SELECT- ${toStartOf('created_at', input.interval)} AS date,+ ${dateBucket} AS date,round((countIf(is_bounce = 1 AND sign = 1) * 100.) / countIf(sign = 1), 2) AS bounce_rateFROM sessions FINALWHERE sign = 1@@ -243,42 +257,72 @@ export function metricsWithPageFilterQuery(ORDER BY date ASC`;- const overallUniqueVisitors = sql`- SELECT uniq(profile_id) AS unique_visitors, uniq(session_id) AS total_sessions- FROM events- WHERE project_id = ${sql.string(input.projectId)}- AND name = 'screen_view'- AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}- ${rawWhere(input.rawEventFilterWhere)}+ // `max(if(<rollup row>, x, NULL)) OVER ()` broadcasts the totals row's value+ // onto every daily row, and stays NULL when the aggregate produced no rollup+ // row at all — which is the nullability the old scalar subqueries had, and+ // which `getMetricsWithPageFilter` reads to tell "no data" from "zero".+ const overallOf = (column: string): SqlFragment =>+ sql`max(if(date = ${rollupDate}, ${sql.id(column)}, NULL)) OVER ()`;++ const eventStats = sql`+ SELECT+ date,+ unique_visitors,+ total_sessions,+ total_screen_views,+ views_per_session,+ avg_session_duration,+ ${overallOf('unique_visitors')} AS overall_unique_visitors,+ ${overallOf('total_sessions')} AS overall_total_sessions+ FROM event_agg+ `;++ const sessionStats = sql`+ SELECT date, bounce_rate, ${overallOf('bounce_rate')} AS overall_bounce_rate+ FROM session_agg+ `;++ // Both sides keep their rollup row through the join so that the two totals+ // rows meet each other: that pairing is what carries `overall_bounce_rate`+ // onto days the session aggregate has no row for. The rollup row itself is+ // dropped afterwards, once the window function has read it.+ const joined = sql`+ SELECT+ e.date AS date,+ s.bounce_rate AS bounce_rate,+ e.unique_visitors AS unique_visitors,+ e.total_sessions AS total_sessions,+ e.avg_session_duration AS avg_session_duration,+ e.total_screen_views AS total_screen_views,+ e.views_per_session AS views_per_session,+ e.overall_unique_visitors AS overall_unique_visitors,+ e.overall_total_sessions AS overall_total_sessions,+ max(s.overall_bounce_rate) OVER () AS overall_bounce_rate+ FROM event_stats AS e+ LEFT JOIN session_stats AS s ON e.date = s.date`;return sql`WITH+ filtered_screen_views AS (${filteredScreenViews}),+ event_agg AS (${eventAgg}),+ event_stats AS (${eventStats}),session_agg AS (${sessionAgg}),- overall_bounce_rate AS (SELECT bounce_rate FROM session_agg WHERE date = ${rollupDate}),- daily_session_stats AS (SELECT date, bounce_rate FROM session_agg WHERE date != ${rollupDate}),- overall_unique_visitors AS (${overallUniqueVisitors}),- raw_screen_view_durations AS (${rawScreenViewDurations}),- avg_duration_by_date AS (${avgDurationByDate})+ session_stats AS (${sessionStats}),+ joined AS (${joined})SELECT- ${eventsDateBucket} AS date,- dss.bounce_rate as bounce_rate,- uniq(e.profile_id) AS unique_visitors,- uniq(e.session_id) AS total_sessions,- coalesce(dur.avg_session_duration, 0) AS avg_session_duration,- count(*) AS total_screen_views,- round((count(*) * 1.) / uniq(e.session_id), 2) AS views_per_session,- (SELECT unique_visitors FROM overall_unique_visitors) AS overall_unique_visitors,- (SELECT total_sessions FROM overall_unique_visitors) AS overall_total_sessions,- (SELECT bounce_rate FROM overall_bounce_rate) AS overall_bounce_rate- FROM events AS e- LEFT JOIN daily_session_stats AS dss ON ${eventsDateBucket} = dss.date- LEFT JOIN avg_duration_by_date AS dur ON ${eventsDateBucket} = dur.date- WHERE e.project_id = ${sql.string(input.projectId)}- AND e.name = 'screen_view'- AND ${dateRangeWhere('e.created_at', input.startDate, input.endDate)}- ${rawWhere(input.rawEventFilterWhere)}- GROUP BY date, dss.bounce_rate, dur.avg_session_duration+ date,+ bounce_rate,+ unique_visitors,+ total_sessions,+ avg_session_duration,+ total_screen_views,+ views_per_session,+ overall_unique_visitors,+ overall_total_sessions,+ overall_bounce_rate+ FROM joined+ WHERE date != ${rollupDate}ORDER BY date ASC${fillClause(input.interval, input.startDate, input.endDate)}`;