perf(product-analytics): one-pass trends, pruned funnel attempts, a covering index and in-memory sorts for insights (A2)

Trends aggregate per bucket and in total with grouping sets and take the
breakdown's top values from a first small query. Funnels drop attempts that
a later attempt always beats (same counts, ties go to the latest attempt),
so a 3-step funnel joins about 17 000 entries instead of 340 000.
Retention aggregates returns once. A covering index (event, timestamp)
include (person_id) lets person-level insights skip the table; insight
transactions use work_mem 32MB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
caelum0x 2026-09-30 05:44:07 +03:00
parent c92a0cbd3e
commit 48af24242e
9 changed files with 203 additions and 49 deletions

View File

@ -0,0 +1,6 @@
-- Insights (A2): person-level insights (unique people, retention, lifecycle,
-- stickiness, cohorts) read (event, timestamp, person_id) only, so this
-- covering index lets them skip the table (index-only scans). Measured in
-- docs/analytics/CAPACITY.md. It makes events_project_event_ts_idx (0002)
-- redundant; dropping that one is left to its owner (hand-off in oss/A2.md).
create index if not exists events_project_event_ts_person_idx on pa.events (project_id, event, "timestamp") include (person_id);

View File

@ -10,8 +10,16 @@
// unordered steps in any order within the window of the first of them;
// breakdown the entry event's value (first touch), top values kept;
// people are counted once per breakdown value at their furthest step;
// the furthest-reaching attempt (then the earliest) is kept,
// the furthest-reaching attempt (then the latest) is kept,
// which also gives time to convert between steps.
// Attempts that can never beat a later one are pruned before the joins
// (this is what keeps a 3-step funnel over a million events in budget):
// ordered/strict an entry event followed by another entry event of the
// same breakdown value before any step-2 event;
// unordered a step event followed directly by a step event that
// matches the same steps (and breakdown value).
// The later attempt reaches at least as far with a later deadline, so
// counts are unchanged; ties go to the latest attempt.
// Two fixes over the vendored shape: the window is measured from the first
// step (not the previous one), and a per-person event sequence number keeps
// one event from filling two steps.
@ -61,12 +69,14 @@ function core(q: FunnelsQuery, range: ResolvedRange, ctx: BuildContext): Core {
const se = `se as materialized (
select ${actor} as pid, e."timestamp" as ts, ${bv} as bv,
${flags},
row_number() over (partition by ${actor} order by e."timestamp", e.uuid) as seq
row_number() over w as seq${order === "unordered" ? "" : `,
count(*) filter (where coalesce((${steps[1]}), false)) over w as c2`}
from pa.events e
${PERSON_JOIN}
${J.sql()}
where ${base.join("\n and ")}
and ${scope}
window w as (partition by ${actor} order by e."timestamp", e.uuid)
)`;
const topFrom = order === "unordered" ? `se where ${Array.from({ length: n }, (_, i) => `s${i + 1}`).join(" or ")}` : "se where s1";
const top = `top as (select bv from (select distinct pid, bv from ${topFrom}) x group by bv order by count(*) desc, bv nulls last limit ${limit})`;
@ -83,7 +93,18 @@ function core(q: FunnelsQuery, range: ResolvedRange, ctx: BuildContext): Core {
const sorted = `(select array_agg(x order by x) from unnest(array[${Array.from({ length: n }, (_, i) => `r.f${i + 1}`).join(", ")}]) as x where x is not null)`;
ctes = `${se},
${top},
anchors as (select pid, ts as t0, seq as q0, ${keep("bv")} from se where ${any}),
marked as (
select pid, ts, seq, bv, ${Array.from({ length: n }, (_, i) => `s${i + 1}`).join(", ")},
lead(array[${Array.from({ length: n }, (_, i) => `s${i + 1}`).join(", ")}]) over w as next_sig,
lead(bv) over w as next_bv,
lead(seq) over w as next_seq
from se where ${any}
window w as (partition by pid order by seq)
),
anchors as (
select pid, ts as t0, seq as q0, ${keep("bv")} from marked
where next_seq is null or next_sig <> array[${Array.from({ length: n }, (_, i) => `s${i + 1}`).join(", ")}] or next_bv is distinct from bv
),
reach as (
select a.pid, a.bk, a.bv, a.t0, ${doneExpr} as reached, ${firsts}
from anchors a join se s on s.pid = a.pid and s.seq >= a.q0 and s.ts <= a.t0 + ${win}
@ -93,10 +114,22 @@ reach as (
ranked as (select r.*, ${sorted} as ts_sorted from reach r),
best as (
select distinct on (pid, bk, bv) pid, bk, bv, reached, t0, ${tcols.map((c, i) => `ts_sorted[${i + 1}] as ${c}`).join(", ")}
from ranked order by pid, bk, bv, reached desc, t0
from ranked order by pid, bk, bv, reached desc, t0 desc
)`;
} else {
const levels: string[] = [`l1 as (select pid, ts as t0, seq as q1, ts as t1, ${keep("bv")} from se where s1)`];
const levels: string[] = [
// c2 counts step-2 events up to each event, so "a step-2 event lies in (this entry, the next entry]" is next_c2 > c2.
`entries as (
select pid, ts, seq, bv, c2,
lead(c2) over (partition by pid, bv order by seq) as next_c2
from se where s1
),
l1 as (
select x.pid, x.ts as t0, x.seq as q1, x.ts as t1, ${keep("x.bv")}
from entries x
where x.next_c2 is null or x.next_c2 > x.c2
)`,
];
for (let k = 2; k <= n; k += 1) {
const prev = `l${k - 1}`;
const carry = ["pid", "bk", "bv", "t0", ...Array.from({ length: k - 1 }, (_, i) => `t${i + 1}`), ...Array.from({ length: k - 1 }, (_, i) => `q${i + 1}`)];
@ -125,7 +158,7 @@ cand as (
from l1
${joins}
),
best as (select distinct on (pid, bk, bv) * from cand order by pid, bk, bv, reached desc, t0)`;
best as (select distinct on (pid, bk, bv) * from cand order by pid, bk, bv, reached desc, t0 desc)`;
}
return { P, proj, n, ctes };
}

View File

@ -73,11 +73,13 @@ cohort_size as (select cohort, count(*) as people from cohort_items group by coh
cohort_period as (select cohort, k, count(distinct pid) as people from user_activities where k between 1 and ${nParam}::int - 1 group by cohort, k),
axis as (
select generate_series(${firstBucket}, ${bucketExpr(`${to}::timestamptz`, period, tz)}, interval '1 ${period}') as cohort
)
),
returned as (select cohort, jsonb_object_agg(k, people) as j from cohort_period group by cohort)
select to_char(a.cohort, ${LABEL_FORMAT}) as cohort, row_number() over (order by a.cohort) - 1 as row_index, coalesce(s.people, 0) as size,
coalesce((select jsonb_object_agg(cp.k, cp.people) from cohort_period cp where cp.cohort = a.cohort), '{}'::jsonb) as returned
coalesce(rt.j, '{}'::jsonb) as returned
from axis a
left join cohort_size s on s.cohort = a.cohort
left join returned rt on rt.cohort = a.cohort
order by a.cohort`;
return { sql, params: P.values };
}

View File

@ -11,7 +11,7 @@ import { buildPaths } from "./paths.ts";
import { buildRetention } from "./retention.ts";
import { previousRange, resolveRange, type ResolvedRange } from "./sql.ts";
import { rolledTo } from "./rollups.ts";
import { buildAxis, buildTrendRollup, buildTrendSeries, rollupEligible } from "./trends.ts";
import { buildAxis, buildBreakdownTop, buildTrendRollup, buildTrendSeries, rollupEligible } from "./trends.ts";
import type {
ActionDef,
BuildContext,
@ -29,6 +29,8 @@ import type {
import { QueryError } from "./types.ts";
export const QUERY_TIMEOUT_MS = 30_000;
/** Per insight transaction; the pool runs at most 5, so at most 5 x this at once. */
export const INSIGHT_WORK_MEM = "32MB";
export interface TrendLine {
label: string;
@ -130,7 +132,8 @@ async function trendLines(c: Client, q: TrendsQuery, range: ResolvedRange, ctx:
const watermark = q.series.some((s) => rollupEligible({ ...q, interval }, s, range)) ? await rolledTo(c, ctx.projectId) : null;
for (let si = 0; si < q.series.length; si += 1) {
const s = q.series[si];
const built = watermark && rollupEligible({ ...q, interval }, s, range) ? buildTrendRollup({ ...q, interval }, s, range, ctx, watermark) : buildTrendSeries(q, s, range, ctx);
const top = q.breakdown ? (await run(c, buildBreakdownTop(q, s, range, ctx))).map((r) => String(r.bv)) : [];
const built = watermark && rollupEligible({ ...q, interval }, s, range) ? buildTrendRollup({ ...q, interval }, s, range, ctx, watermark) : buildTrendSeries(q, s, range, ctx, top);
const rows = await run(c, built);
const byKey = new Map<string, TrendLine>();
for (const r of rows) {
@ -269,6 +272,8 @@ export interface RunOptions {
async function withTimeout<T>(db: Db, projectId: string, timeoutMs: number, fn: (c: Client) => Promise<T>): Promise<T> {
return db.asProject(projectId, async (c) => {
await c.query(`set local statement_timeout = ${Math.max(1000, Math.floor(timeoutMs))}`);
// Sorts and hashes for distinct counts stay in memory (see docs/analytics/CAPACITY.md).
await c.query(`set local work_mem = '${INSIGHT_WORK_MEM}'`);
return fn(c);
});
}

View File

@ -37,11 +37,21 @@ export function axisSql(interval: Interval, P: Params, from: string, to: string,
return `select generate_series(${bucketExpr(`${from}::timestamptz`, interval, tz)}, ${bucketExpr(`${to}::timestamptz`, interval, tz)}, interval '${INTERVAL_SQL[interval]}') as bucket`;
}
/**
* One series of a trends query. Rows: (bucket text, bk, bv, value, total)
* where bk is 0 for a missing value, 1 for a kept value, 2 for "(other)".
*/
export function buildTrendSeries(q: TrendsQuery, s: Series, range: ResolvedRange, ctx: BuildContext): Built {
interface SeriesParts {
P: Params;
J: Joins;
tz: string;
from: string;
to: string;
interval: Interval;
lookback: string | null;
where: string[];
actor: string;
mv: string;
bv: string;
}
function seriesParts(q: TrendsQuery, s: Series, range: ResolvedRange, ctx: BuildContext): SeriesParts {
const interval = q.interval ?? "day";
const math = s.math ?? "total";
if ((math === "weekly_active" || math === "monthly_active") && interval !== "day") {
@ -72,40 +82,72 @@ export function buildTrendSeries(q: TrendsQuery, s: Series, range: ResolvedRange
}
const mv = PROPERTY_MATH.includes(math) ? numberOf(`e.properties ->> ${P.add(s.math_property)}`) : "null::double precision";
const bv = q.breakdown ? breakdownValue(q.breakdown, P, J) : "null::text";
const limit = P.add(Math.min(MAX_BREAKDOWN_LIMIT, Math.max(1, q.breakdown?.limit ?? DEFAULT_BREAKDOWN_LIMIT)));
const ev = `select ${bucketExpr('e."timestamp"', interval, tz)} as bucket, e."timestamp" at time zone ${tz} as lt, ${bv} as bv, ${actor} as pid, ${mv} as mv
return { P, J, tz, from, to, interval, lookback, where, actor, mv, bv };
}
/**
* The breakdown values a series keeps: the most frequent present values in
* the range (at most the limit). Rows: (bv). Run before buildTrendSeries.
*/
export function buildBreakdownTop(q: TrendsQuery, s: Series, range: ResolvedRange, ctx: BuildContext): Built {
if (!q.breakdown) throw new QueryError("Pick a property to break down by.");
const x = seriesParts(q, s, range, ctx);
const inRange = x.lookback ? `and e."timestamp" >= (${bucketExpr(`${x.from}::timestamptz`, x.interval, x.tz)} at time zone ${x.tz})` : "";
const limit = x.P.add(Math.min(MAX_BREAKDOWN_LIMIT, Math.max(1, q.breakdown.limit ?? DEFAULT_BREAKDOWN_LIMIT)));
const sql = `select bv from (
select ${x.bv} as bv
from pa.events e
${PERSON_JOIN}
${x.J.sql()}
where ${x.where.join("\n and ")} ${inRange}
) v where bv is not null group by bv order by count(*) desc, bv limit ${limit}`;
return { sql, params: x.P.values };
}
/**
* One series of a trends query. Rows: (bucket text, bk, bv, value, total)
* where bk is 0 for a missing breakdown value, 1 for a kept value and 2
* for "(other)". `top` is the kept values (buildBreakdownTop); a missing
* value always keeps its own "(none)" line.
*/
export function buildTrendSeries(q: TrendsQuery, s: Series, range: ResolvedRange, ctx: BuildContext, top: string[] = []): Built {
const x = seriesParts(q, s, range, ctx);
const { P, tz, from, to, interval, lookback } = x;
const math = s.math ?? "total";
const topP = q.breakdown ? P.add(top) : "";
const bk = q.breakdown ? `case when b.bv is null then 0 when b.bv = any(${topP}::text[]) then 1 else 2 end` : "0";
const bvKept = q.breakdown ? `case when b.bv = any(${topP}::text[]) then b.bv end` : "null::text";
const ev = `select b.bucket, b.lt, ${bk} as bk, ${bvKept} as bv, b.pid, b.mv from (
select ${bucketExpr('e."timestamp"', interval, tz)} as bucket, e."timestamp" at time zone ${tz} as lt, ${x.bv} as bv, ${x.actor} as pid, ${x.mv} as mv
from pa.events e
${PERSON_JOIN}
${J.sql()}
where ${where.join("\n and ")}`;
const rolling = lookback !== null;
const agg = AGG[rolling ? "dau" : math];
const inRange = rolling ? `where ev.lt >= ${bucketExpr(`${from}::timestamptz`, interval, tz)}` : "";
const sql = `with axis as (${axisSql(interval, P, from, to, tz)}),
ev as materialized (${ev}),
top as (select bv from ev ${inRange} group by bv order by count(*) desc, bv nulls last limit ${limit}),
kept as (
select ev.bucket, ev.lt, ev.pid, ev.mv,
case when exists (select 1 from top where top.bv is not distinct from ev.bv) then (case when ev.bv is null then 0 else 1 end) else 2 end as bk,
case when exists (select 1 from top where top.bv is not distinct from ev.bv) then ev.bv end as bv
from ev
),
${
rolling
? `agg as (
select a.bucket, k.bk, k.bv, ${agg} as v
from axis a join kept k on k.lt >= a.bucket - interval '${lookback}' and k.lt < a.bucket + interval '1 day'
group by a.bucket, k.bk, k.bv
),
tot as (select bk, bv, null::double precision as v, count(*) as n from kept where kept.lt >= (select min(bucket) from axis) group by bk, bv)`
: `agg as (select bucket, bk, bv, ${agg} as v from kept group by bucket, bk, bv),
tot as (select bk, bv, ${agg} as v, count(*) as n from kept group by bk, bv)`
}
select to_char(a.bucket, ${LABEL_FORMAT}) as bucket, t.bk, t.bv, coalesce(agg.v, 0) as value, t.v as total
from axis a
cross join tot t
left join agg on agg.bucket = a.bucket and agg.bk = t.bk and agg.bv is not distinct from t.bv
${x.J.sql()}
where ${x.where.join("\n and ")}
) b`;
const final = (agg: string, tot: string) => `select to_char(a.bucket, ${LABEL_FORMAT}) as bucket, t.bk, t.bv, coalesce(agg.v, 0) as value, t.v as total
from (${axisSql(interval, P, from, to, tz)}) a
cross join (${tot}) t
left join (${agg}) agg on agg.bucket = a.bucket and agg.bk = t.bk and agg.bv is not distinct from t.bv
order by t.bk = 2, t.n desc, t.bv nulls last, a.bucket`;
if (lookback) {
const first = bucketExpr(`${from}::timestamptz`, interval, tz);
const sql = `with ev as materialized (${ev})
${final(
`select a.bucket, k.bk, k.bv, count(distinct k.pid)::double precision as v
from (${axisSql(interval, P, from, to, tz)}) a join ev k on k.lt >= a.bucket - interval '${lookback}' and k.lt < a.bucket + interval '1 day'
group by a.bucket, k.bk, k.bv`,
`select bk, bv, null::double precision as v, count(*) as n from ev where lt >= ${first} group by bk, bv`,
)}`;
return { sql, params: P.values };
}
const agg = AGG[math];
// One pass: per bucket and in total, with grouping sets.
const sql = `with res as materialized (
select bucket, bk, bv, ${agg} as v, count(*) as n, grouping(bucket) as whole
from (${ev}) k
group by grouping sets ((bucket, bk, bv), (bk, bv))
)
${final("select bucket, bk, bv, v from res where whole = 0", "select bk, bv, v, n from res where whole = 1")}`;
return { sql, params: P.values };
}

View File

@ -18,8 +18,6 @@ const target = Number(process.argv[2] ?? 1_000_000);
const runs = Number(process.argv[3] ?? 20);
const NOW = new Date("2026-09-30T00:00:00Z");
const DAYS = 90;
// The generator yields about 44 events per person over 90 days (measured on small runs).
const PER_PERSON = 44;
const cluster = scratchPg();
const out: Record<string, unknown> = { target_events: target, days: DAYS, runs, postgres: "", machine: `${process.platform} ${process.arch}` };
@ -30,7 +28,7 @@ try {
out.postgres = (await owner.query("show server_version")).rows[0].server_version;
const projectId = randomUUID();
const t0 = Date.now();
const stats = await loadFixture(owner, { projectId, persons: Math.round(target / PER_PERSON), days: DAYS, end: NOW, seed: 2026 });
const stats = await loadFixture(owner, { projectId, persons: 10_000_000, maxEvents: target, days: DAYS, end: NOW, seed: 2026 });
out.load_seconds = (Date.now() - t0) / 1000;
out.events = stats.events;
out.persons = stats.persons;

View File

@ -0,0 +1,28 @@
// Prints the plan of one insight on the kept perf cluster (test/a2/perf-cluster.ts):
// node test/a2/explain.ts '{"kind":"trends",...}' [work_mem] (FULL=1 for the whole plan)
import pg from "pg";
import { buildTrendSeries } from "../../src/insights/trends.ts";
import { buildFunnel } from "../../src/insights/funnels.ts";
import { buildRetention } from "../../src/insights/retention.ts";
import { buildLifecycle, buildStickiness } from "../../src/insights/lifecycle.ts";
import { buildPaths } from "../../src/insights/paths.ts";
import { parseQuery } from "../../src/insights/validate.ts";
import { resolveRange } from "../../src/insights/sql.ts";
const url = `postgresql://postgres@localhost/postgres?host=${encodeURIComponent(process.env.TMPDIR + "pa-perf")}&port=45432`;
const projectId = "0e0e0e0e-0000-4000-8000-000000000001";
const now = new Date("2026-09-30T00:00:00Z");
const q: any = parseQuery(JSON.parse(process.argv[2]));
const ctx = { projectId, now, actions: new Map() };
const r = resolveRange(q.date_range, now);
const b = q.kind === "trends" ? buildTrendSeries(q, q.series[0], r, ctx) : q.kind === "funnels" ? buildFunnel(q, r, ctx) : q.kind === "retention" ? buildRetention(q, r, ctx) : q.kind === "lifecycle" ? buildLifecycle(q, r, ctx) : q.kind === "stickiness" ? buildStickiness(q, r, ctx, 0) : buildPaths(q, r, ctx);
const c = new pg.Client({ connectionString: url });
await c.connect();
await c.query("begin");
await c.query("set local role pa_app");
await c.query("select set_config('pa.project_id', $1, true)", [projectId]);
if (process.argv[3]) await c.query(`set local work_mem = '${process.argv[3]}'`);
const res = await c.query(`explain (analyze, buffers, format text) ${b.sql}`, b.params);
const lines = res.rows.map((x: any) => x["QUERY PLAN"]);
console.log(process.env.FULL ? lines.join("\n") : lines.filter((l: string) => /actual time|Execution|Sort Method|Disk|Planning/.test(l)).slice(0, 60).join("\n"));
await c.query("rollback");
await c.end();

View File

@ -15,6 +15,8 @@ export interface FixtureOptions {
seed?: number;
/** Chance a person comes back on a later day (default 0.3). */
returnRate?: number;
/** Stop adding people once this many events are generated. */
maxEvents?: number;
}
export interface FixtureStats {
@ -105,6 +107,7 @@ export async function loadFixture(client: pg.Client | pg.PoolClient, o: FixtureO
};
for (let i = 0; i < o.persons; i += 1) {
if (o.maxEvents && events + buf.length >= o.maxEvents) break;
const personId = uuidFrom(r);
const user = `user_${i}`;
const mergedAnon = r() < 0.3;

View File

@ -0,0 +1,37 @@
// A kept scratch cluster with the 1 000 000-event fixture, for looking at
// query plans while tuning (node test/a2/perf-cluster.ts start|stop).
// Lives in $TMPDIR/pa-perf; never a hosted database.
import { execFileSync, spawnSync } from "node:child_process";
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import pg from "pg";
import { migrate } from "../../scripts/migrate.ts";
import { loadFixture } from "./fixtures.ts";
const dir = join(tmpdir(), "pa-perf");
const port = "45432";
const url = `postgresql://postgres@localhost/postgres?host=${encodeURIComponent(dir)}&port=${port}`;
const cmd = process.argv[2] ?? "start";
if (cmd === "stop") {
spawnSync("pg_ctl", ["-D", join(dir, "data"), "-m", "fast", "stop"], { stdio: "ignore" });
rmSync(dir, { recursive: true, force: true });
process.exit(0);
}
if (!existsSync(join(dir, "data"))) {
mkdirSync(dir, { recursive: true });
execFileSync("initdb", ["-D", join(dir, "data"), "-U", "postgres", "-A", "trust", "--no-sync"], { stdio: "ignore" });
}
execFileSync("pg_ctl", ["-D", join(dir, "data"), "-o", `-p ${port} -k ${dir} -c listen_addresses='' -c timezone=UTC`, "-w", "start"], { stdio: "ignore" });
await migrate(url);
const c = new pg.Client({ connectionString: url });
await c.connect();
const n = Number((await c.query("select count(*) as n from pa.events")).rows[0].n);
if (n === 0) {
const projectId = "0e0e0e0e-0000-4000-8000-000000000001";
const s = await loadFixture(c, { projectId, persons: 10_000_000, maxEvents: Number(process.argv[3] ?? 1_000_000), days: 90, end: new Date("2026-09-30T00:00:00Z"), seed: 2026 });
await c.query("vacuum analyze");
writeFileSync(join(dir, "stats.json"), JSON.stringify(s));
}
await c.end();
process.stdout.write(`${url}\n`);