OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M16-001): Saturation benchmark harness: a ramp driver, queue/buffer sampling, and a REAL-secret client as the primary configuration
ralph6a60778e1ab9
diff --git a/apps/api/e2e/README.md b/apps/api/e2e/README.mdindex 8b4f40333..a766e19d2 100644--- a/apps/api/e2e/README.md+++ b/apps/api/e2e/README.md@@ -1,6 +1,6 @@# Session E2E-Two harnesses over a shared foundation (`lib.ts`), both driving the **real stack**+Three harnesses over a shared foundation (`lib.ts`), all driving the **real stack**over HTTP and asserting state in **both ClickHouse and Redis**:- `session-e2e.ts` (`e2e:sessions`) — **correctness**: the full lifecycle for one@@ -10,6 +10,11 @@ over HTTP and asserting state in **both ClickHouse and Redis**:sessions, then drives reaper + buffer flushes until *everything* has drained(every `session_end` emitted, Redis cleaned, session buffer empty) and reconcilesthe ClickHouse counts. Exits only when nothing is left open.+- `saturation-sweep.ts` (`e2e:saturation`) — **the ramp driver**: runs+ `session-stress.ts` across a ladder of offered loads, one child process per+ rung, and reports the max sustainable ingest throughput and where the knee is.+ Full knob list, the knee definition and what the numbers do NOT cover:+ **`docs/BENCHMARK_HARNESS.md`**.## What it covers@@ -50,8 +55,13 @@ The harness triggers the reaper on demand via the worker's `/debug/cron`endpoint, so it never waits for the 5-minute reaper cron.### Notes-- Uses a dedicated, isolated project (`e2e-sessions`) and a throwaway client- (`ignoreCorsAndSecret`), created/upserted automatically under org `openpanel-dev`.+- Uses a dedicated, isolated project (`e2e-sessions`) and TWO throwaway clients,+ created/upserted automatically under org `openpanel-dev`: the original+ `ignoreCorsAndSecret` one, and (M16-001) a second carrying a real scrypt+ secret. `E2E_AUTH_MODE` picks which ingest auth path requests take —+ `bypass` (default, the original client), `cors` or `secret`. See+ `docs/BENCHMARK_HARNESS.md`; only `cors` and `secret` are shapes real traffic+ takes.- Each run uses fresh device IPs, so reruns don't collide with prior state.- Overridable: `E2E_API_URL` (default `:3333`), `E2E_WORKER_URL` (default `:9999`).- The harness and the stack **must share the same `SESSION_TIMEOUT_MS`** — thediff --git a/apps/api/e2e/lib.ts b/apps/api/e2e/lib.tsindex 78a3f4256..ade10e4f6 100644--- a/apps/api/e2e/lib.ts+++ b/apps/api/e2e/lib.ts@@ -4,7 +4,7 @@* fixtures, polling, and a tiny check/report framework.*/-import { getClientByIdCached } from '@openpanel/core';+import { getClientByIdCached, hashPassword } from '@openpanel/core';import { ClientType, chQuery, db } from '@openpanel/db';import { getRedisCache } from '@openpanel/redis';@@ -13,10 +13,88 @@ export const API_URL = process.env.E2E_API_URL || 'http://localhost:3333';export const WORKER_URL = process.env.E2E_WORKER_URL || 'http://localhost:9999';export const ORG_ID = 'openpanel-dev';export const PROJECT_ID = 'e2e-sessions';+/** The `ignoreCorsAndSecret` client — auth path (a), a diagnostic baseline. */export const CLIENT_ID = 'e2e1e2e1-0000-4000-8000-000000000001';+/** The client that carries a real scrypt secret — auth paths (b) and (c). */+export const SECRET_CLIENT_ID = 'e2e1e2e1-0000-4000-8000-000000000002';+/**+ * The plaintext presented as `openpanel-client-secret`. Stored on the fixture+ * client as `salt.hashKey` (scrypt, keyLength 32). Local fixture only — the+ * hash is regenerated by `ensureFixtures()` on every run.+ */+export const CLIENT_SECRET = 'e2e-saturation-secret';+/** Project CORS allow-list entry backing auth path (b). */+export const CORS_DOMAIN = 'e2e.test';+export const CORS_ORIGIN = `https://${CORS_DOMAIN}`;export const UA ='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36';+// ── Auth paths ──────────────────────────────────────────────────────────────+/**+ * The three ways a request can clear `validateIngestRequest`, in the order+ * that function checks them (packages/core/src/modules/ingest/src/client-auth.ts):+ *+ * - `bypass` — `client.ignoreCorsAndSecret` returns immediately, before any+ * I/O. NO REAL TRAFFIC TAKES THIS PATH. Diagnostic baseline only.+ * - `cors` — an allowed origin returns immediately after a regex. This is+ * what browser / web-SDK traffic does.+ * - `secret` — a presented `openpanel-client-secret` goes through+ * `getCache(...)` around a scrypt `verifyPassword`. This is what+ * server-side SDK traffic does, and it is the pessimistic path.+ *+ * Every number a harness prints must be labelled with the mode it ran under.+ */+export type AuthMode = 'bypass' | 'cors' | 'secret';+const AUTH_MODES: readonly AuthMode[] = ['bypass', 'cors', 'secret'];++export const AUTH_PATH_DESCRIPTION: Record<AuthMode, string> = {+ bypass:+ '(a) ignoreCorsAndSecret — immediate return, no I/O, not real traffic',+ cors: '(b) allowed CORS origin — immediate return after a regex (browser/web SDK)',+ secret:+ '(c) presented client secret — cached scrypt verify (server-side SDK)',+};++function parseAuthMode(raw: string | undefined): AuthMode {+ if (!raw) {+ return 'bypass';+ }+ const found = AUTH_MODES.find((mode) => mode === raw);+ if (!found) {+ throw new Error(+ `E2E_AUTH_MODE must be one of ${AUTH_MODES.join('|')}, got "${raw}"`+ );+ }+ return found;+}++/** Default `bypass` so the pre-existing suites keep the path they were written against. */+export const AUTH_MODE: AuthMode = parseAuthMode(process.env.E2E_AUTH_MODE);++export function authHeaders(+ mode: AuthMode = AUTH_MODE+): Record<string, string> {+ if (mode === 'bypass') {+ return { 'openpanel-client-id': CLIENT_ID };+ }+ if (mode === 'cors') {+ return { 'openpanel-client-id': SECRET_CLIENT_ID, origin: CORS_ORIGIN };+ }+ return {+ 'openpanel-client-id': SECRET_CLIENT_ID,+ 'openpanel-client-secret': CLIENT_SECRET,+ };+}++/**+ * The Redis key `client-auth.ts` caches the scrypt verdict under for+ * `secret`-mode requests: client id + base64 of the PRESENTED plaintext.+ * Deleting it evicts L2 only — `getCache` is called with `useLruCache`, so the+ * API process also holds an in-process L1 copy this harness cannot reach.+ */+export const authVerifyCacheKey = (secret: string = CLIENT_SECRET) =>+ `client:auth:${SECRET_CLIENT_ID}:${Buffer.from(secret).toString('base64')}`;+export const SESSION_TIMEOUT_MS = Number.parseInt(process.env.SESSION_TIMEOUT_MS || String(1000 * 60 * 30),10@@ -129,7 +207,7 @@ export async function track(body: unknown, ip: string): Promise<TrackResponse> {method: 'POST',headers: {'content-type': 'application/json',- 'openpanel-client-id': CLIENT_ID,+ ...authHeaders(),'user-agent': UA,'x-client-ip': ip,},@@ -204,6 +282,117 @@ export const screenView = (ip);+// ── Auth-cache warming and the scrypt outlier ───────────────────────────────+/**+ * Why warming matters: `client-auth.ts` shields `verifyPassword` behind+ * `VERIFY_CACHE_SECONDS = 300`, so a scrypt is a LATENCY OUTLIER, not a+ * per-request cost. A rung shorter than the TTL pays it once, at whatever+ * moment it happens to fall. Paying it before recording starts is what stops+ * a knee from being an artefact of a scrypt spike landing mid-rung.+ */+export const AUTH_WARM_REQUESTS = Number.parseInt(+ process.env.E2E_AUTH_WARM_REQUESTS || '3',+ 10+);++/** Warm/probe traffic lives outside the 100.x space the session ids use. */+const WARM_IP = '203.0.113.7';+const PROBE_IP = '203.0.113.8';++export interface AuthWarmResult {+ mode: AuthMode;+ requests: number;+ latenciesMs: number[];+ maxMs: number | null;+}++/** One raw /track round-trip that reports its status instead of throwing. */+async function timedTrack(+ headers: Record<string, string>,+ ip: string+): Promise<{ status: number; ms: number }> {+ const startedAt = performance.now();+ const res = await fetch(`${API_URL}/track`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ ...headers,+ 'user-agent': UA,+ 'x-client-ip': ip,+ },+ body: JSON.stringify({+ type: 'track',+ payload: {+ name: 'screen_view',+ properties: { __path: 'https://e2e.test/warm', __ip: ip },+ },+ }),+ });+ await res.text();+ return { status: res.status, ms: performance.now() - startedAt };+}++/**+ * Send and DISCARD `requests` authenticated requests so the auth verdict is+ * resident before the measured phase starts. Latencies are returned so the+ * caller can show where the scrypt landed.+ */+export async function warmAuthCache(+ mode: AuthMode = AUTH_MODE,+ requests: number = AUTH_WARM_REQUESTS+): Promise<AuthWarmResult> {+ const latenciesMs: number[] = [];+ const headers = authHeaders(mode);+ for (let i = 0; i < requests; i++) {+ const { status, ms } = await timedTrack(headers, WARM_IP);+ if (status < 200 || status >= 300) {+ throw new Error(+ `auth warm-up rejected (${status}) in mode "${mode}" — the fixture for this auth path is wrong, not the load`+ );+ }+ latenciesMs.push(ms);+ }+ return {+ mode,+ requests,+ latenciesMs,+ maxMs: latenciesMs.length ? Math.max(...latenciesMs) : null,+ };+}++export interface AuthCostProbe {+ coldMs: number;+ coldStatus: number;+ warmMs: number;+ warmStatus: number;+ scryptMs: number;+}++/**+ * Measure what the TTL is hiding: one request whose secret has never been seen+ * (guaranteed L1+L2 miss, so a real scrypt runs and is then refused) against+ * one on the warmed real secret. The delta is the outlier a mid-rung cache+ * expiry would inject.+ */+export async function probeAuthCost(): Promise<AuthCostProbe> {+ const neverSeenSecret = `e2e-cold-${Date.now()}-${Math.random().toString(36).slice(2)}`;+ const cold = await timedTrack(+ {+ 'openpanel-client-id': SECRET_CLIENT_ID,+ 'openpanel-client-secret': neverSeenSecret,+ },+ PROBE_IP+ );+ const warm = await timedTrack(authHeaders('secret'), PROBE_IP);+ return {+ coldMs: cold.ms,+ coldStatus: cold.status,+ warmMs: warm.ms,+ warmStatus: warm.status,+ scryptMs: cold.ms - warm.ms,+ };+}+/** Run a worker cron on demand via the local /debug/cron endpoint. */export async function triggerCron(type: string) {const res = await fetch(`${WORKER_URL}/debug/cron/${type}`, {@@ -245,8 +434,15 @@ export async function ensureFixtures() {});await db.project.upsert({where: { id: PROJECT_ID },- create: { id: PROJECT_ID, name: 'E2E Sessions', organizationId: ORG_ID },- update: {},+ create: {+ id: PROJECT_ID,+ name: 'E2E Sessions',+ organizationId: ORG_ID,+ cors: [CORS_DOMAIN],+ },+ // The allow-list is what makes auth path (b) reachable; the bypass+ // client returns before the CORS check, so this changes nothing for it.+ update: { cors: [CORS_DOMAIN] },});await db.client.upsert({where: { id: CLIENT_ID },@@ -261,7 +457,30 @@ export async function ensureFixtures() {},update: { ignoreCorsAndSecret: true, projectId: PROJECT_ID },});+ // `hashPassword` here is @openpanel/shared/server's scrypt hash, re-exported+ // by @openpanel/core under its own name (core/src/index.ts) — reached that+ // way because apps/api does not declare @openpanel/shared, and adding it+ // would move the lockfile.+ const secret = await hashPassword(CLIENT_SECRET);+ await db.client.upsert({+ where: { id: SECRET_CLIENT_ID },+ create: {+ id: SECRET_CLIENT_ID,+ name: 'e2e-secret',+ organizationId: ORG_ID,+ projectId: PROJECT_ID,+ type: ClientType.write,+ ignoreCorsAndSecret: false,+ secret,+ },+ update: {+ ignoreCorsAndSecret: false,+ projectId: PROJECT_ID,+ secret,+ },+ });await getClientByIdCached.clear({ db }, CLIENT_ID);+ await getClientByIdCached.clear({ db }, SECRET_CLIENT_ID);check('fixtures ready', true);} catch (error) {check('fixtures ready', false, (error as Error).message);diff --git a/apps/api/e2e/metrics-monitor.ts b/apps/api/e2e/metrics-monitor.tsnew file mode 100644index 000000000..473856f63--- /dev/null+++ b/apps/api/e2e/metrics-monitor.ts@@ -0,0 +1,371 @@+/**+ * Queue + buffer sampling from the Prometheus scrape endpoint.+ *+ * Carl asked how ALL the queues are doing, not just Kafka. Everything needed+ * is already on `/metrics`: the BullMQ per-queue gauges and the buffer gauges+ * and histograms. Scraping is deliberate rather than reaching into Redis or+ * into the buffer objects — V1 and V2 both expose the same endpoint, so the+ * identical sampler works against either side when the V1 comparison is run.+ *+ * Sampling costs the measured process a scrape per tick (~2,700 lines here).+ * `session-stress.ts` ties this to the same `E2E_NO_SAMPLING` lever as the+ * process/lag monitors so that cost can be ruled in or out.+ */++const QUEUE_GAUGE =+ /^([A-Za-z][A-Za-z_]*)_(waiting|active|delayed|failed)_count$/;+const BUFFER_GAUGE = /^buffer_([a-z_]+)_count$/;+const LABELLED_SUM = /^([a-z_]+)_(sum|count)$/;++/** `buffer_profile_backfill_count` and `buffer="profile-backfill"` are the same buffer. */+const gaugeNameToBufferLabel = (name: string) => name.replace(/_/g, '-');++type QueueDepths = Record<'waiting' | 'active' | 'delayed' | 'failed', number>;++interface Scrape {+ t: number;+ queues: Map<string, QueueDepths>;+ buffers: Map<string, number>;+ /** `buffer_flush_rows_total{buffer=...}` — a counter, so only deltas mean anything. */+ flushRows: Map<string, number>;+ flushDurationSumMs: Map<string, number>;+ flushDurationCount: Map<string, number>;+ chInsertSumMs: Map<string, number>;+ chInsertCount: Map<string, number>;+}++const emptyDepths = (): QueueDepths => ({+ waiting: 0,+ active: 0,+ delayed: 0,+ failed: 0,+});++function parseLabels(labelText: string): Record<string, string> {+ const labels: Record<string, string> = {};+ for (const part of labelText.matchAll(+ /([A-Za-z_][A-Za-z0-9_]*)="([^"]*)"/g+ )) {+ labels[part[1] as string] = part[2] as string;+ }+ return labels;+}++const addTo = (map: Map<string, number>, key: string, value: number) =>+ map.set(key, (map.get(key) ?? 0) + value);++export function parseScrape(body: string, t: number): Scrape {+ const scrape: Scrape = {+ t,+ queues: new Map(),+ buffers: new Map(),+ flushRows: new Map(),+ flushDurationSumMs: new Map(),+ flushDurationCount: new Map(),+ chInsertSumMs: new Map(),+ chInsertCount: new Map(),+ };++ for (const line of body.split('\n')) {+ if (line.startsWith('#') || line.length === 0) {+ continue;+ }+ const braceAt = line.indexOf('{');+ const spaceAt = line.lastIndexOf(' ');+ if (spaceAt < 0) {+ continue;+ }+ const value = Number(line.slice(spaceAt + 1));+ if (!Number.isFinite(value)) {+ continue;+ }+ const head = line.slice(0, spaceAt);+ const name = braceAt >= 0 ? head.slice(0, braceAt) : head;+ const labels = braceAt >= 0 ? parseLabels(head.slice(braceAt)) : {};++ const queueMatch = braceAt < 0 ? QUEUE_GAUGE.exec(name) : null;+ if (queueMatch) {+ const queue = queueMatch[1] as string;+ const field = queueMatch[2] as keyof QueueDepths;+ const depths = scrape.queues.get(queue) ?? emptyDepths();+ depths[field] = value;+ scrape.queues.set(queue, depths);+ continue;+ }++ const bufferMatch = braceAt < 0 ? BUFFER_GAUGE.exec(name) : null;+ if (bufferMatch) {+ scrape.buffers.set(+ gaugeNameToBufferLabel(bufferMatch[1] as string),+ value+ );+ continue;+ }++ const buffer = labels.buffer;+ if (!buffer) {+ continue;+ }+ if (name === 'buffer_flush_rows_total') {+ addTo(scrape.flushRows, buffer, value);+ continue;+ }+ const labelled = LABELLED_SUM.exec(name);+ if (!labelled) {+ continue;+ }+ const [, base, kind] = labelled as unknown as [string, string, string];+ if (base === 'buffer_flush_duration_ms') {+ addTo(+ kind === 'sum' ? scrape.flushDurationSumMs : scrape.flushDurationCount,+ buffer,+ value+ );+ } else if (base === 'buffer_ch_insert_duration_ms') {+ addTo(+ kind === 'sum' ? scrape.chInsertSumMs : scrape.chInsertCount,+ buffer,+ value+ );+ }+ }+ return scrape;+}++export interface QueueSummary {+ queue: string;+ peakWaiting: number;+ peakActive: number;+ peakDelayed: number;+ depthAtEmitEnd: number | null;+ finalDepth: number;+ /** Did waiting+active hit zero in ANY scrape at or after emit-end. */+ returnedToZero: boolean;+ /** `*_failed_count` growth over the run; a non-zero value is a real signal. */+ failedDelta: number;+}++export interface BufferSummary {+ buffer: string;+ peakPending: number;+ pendingAtEmitEnd: number | null;+ finalPending: number;+ /** Did the pending count hit zero in ANY scrape at or after emit-end. */+ returnedToZero: boolean;+ rowsFlushed: number;+ flushes: number;+ meanFlushMs: number | null;+ chInserts: number;+ meanChInsertMs: number | null;+}++export interface MetricsSummary {+ scrapeUrl: string;+ sampleCount: number;+ queues: QueueSummary[];+ buffers: BufferSummary[];+ /** Queues whose waiting+active+delayed depth never came back to zero. */+ queuesNotDrained: string[];+ /** Buffers whose pending count never came back to zero. */+ buffersNotDrained: string[];+}++const EMPTY_SUMMARY = (scrapeUrl: string): MetricsSummary => ({+ scrapeUrl,+ sampleCount: 0,+ queues: [],+ buffers: [],+ queuesNotDrained: [],+ buffersNotDrained: [],+});++const depthOf = (d: QueueDepths) => d.waiting + d.active + d.delayed;++/** Samples every queue gauge and every buffer gauge on /metrics at >=1Hz. */+export class MetricsMonitor {+ private readonly samples: Scrape[] = [];+ private timer: ReturnType<typeof setInterval> | null = null;+ private readonly url: string;++ constructor(apiUrl: string) {+ this.url = `${apiUrl.replace(/\/$/, '')}/metrics`;+ }++ async start(intervalMs = 1000): Promise<void> {+ const ok = await this.sampleOnce();+ if (!ok) {+ console.warn(+ ` ⚠ metrics-monitor: ${this.url} unreachable — queue/buffer depths will be unavailable`+ );+ return;+ }+ this.timer = setInterval(() => {+ this.sampleOnce().catch(() => {+ // One missed scrape is one fewer sample, never a failed run.+ });+ }, intervalMs);+ }++ private async sampleOnce(): Promise<boolean> {+ const res = await fetch(this.url).catch(() => null);+ if (!res?.ok) {+ return false;+ }+ this.samples.push(parseScrape(await res.text(), Date.now()));+ return true;+ }++ stop(): void {+ if (this.timer) {+ clearInterval(this.timer);+ }+ this.timer = null;+ }++ private closestTo(t: number): Scrape | null {+ if (this.samples.length === 0) {+ return null;+ }+ return this.samples.reduce((closest, s) =>+ Math.abs(s.t - t) < Math.abs(closest.t - t) ? s : closest+ );+ }++ /** `emitEndedAt` is a `Date.now()`-comparable timestamp. */+ summarize(emitEndedAt: number): MetricsSummary {+ const first = this.samples[0];+ const last = this.samples.at(-1);+ if (!(first && last)) {+ return EMPTY_SUMMARY(this.url);+ }+ const atEmitEnd = this.closestTo(emitEndedAt);+ // "Returned to zero" is asked of the whole post-emit window, not of the+ // last scrape: the cron queue picks up a scheduled job every minute+ // regardless of load, and a final scrape that happens to land on one is+ // not a backlog. Falls back to the last scrape when emit-end is past the+ // final sample, which only happens if sampling stopped early.+ const afterEmitEnd = this.samples.filter((s) => s.t >= emitEndedAt);+ const settled = afterEmitEnd.length > 0 ? afterEmitEnd : [last];++ const queueNames = new Set<string>();+ const bufferNames = new Set<string>();+ for (const s of this.samples) {+ for (const name of s.queues.keys()) {+ queueNames.add(name);+ }+ for (const name of s.buffers.keys()) {+ bufferNames.add(name);+ }+ }++ const queues: QueueSummary[] = [...queueNames].sort().map((queue) => {+ const seen = this.samples+ .map((s) => s.queues.get(queue))+ .filter((d): d is QueueDepths => d !== undefined);+ const finalDepth = depthOf(last.queues.get(queue) ?? emptyDepths());+ return {+ queue,+ peakWaiting: Math.max(...seen.map((d) => d.waiting), 0),+ peakActive: Math.max(...seen.map((d) => d.active), 0),+ peakDelayed: Math.max(...seen.map((d) => d.delayed), 0),+ depthAtEmitEnd: atEmitEnd+ ? depthOf(atEmitEnd.queues.get(queue) ?? emptyDepths())+ : null,+ finalDepth,+ // `delayed` is excluded: the cron queue permanently parks its next+ // scheduled run there, so a delayed job is steady state, not a backlog.+ returnedToZero: settled.some(+ (s) =>+ (s.queues.get(queue)?.waiting ?? 0) === 0 &&+ (s.queues.get(queue)?.active ?? 0) === 0+ ),+ failedDelta:+ (last.queues.get(queue)?.failed ?? 0) -+ (first.queues.get(queue)?.failed ?? 0),+ };+ });++ const buffers: BufferSummary[] = [...bufferNames].sort().map((buffer) => {+ const seen = this.samples+ .map((s) => s.buffers.get(buffer))+ .filter((v): v is number => v !== undefined);+ const finalPending = last.buffers.get(buffer) ?? 0;+ const delta = (m: (s: Scrape) => Map<string, number>) =>+ (m(last).get(buffer) ?? 0) - (m(first).get(buffer) ?? 0);+ const flushes = delta((s) => s.flushDurationCount);+ const flushMs = delta((s) => s.flushDurationSumMs);+ const chInserts = delta((s) => s.chInsertCount);+ const chInsertMs = delta((s) => s.chInsertSumMs);+ return {+ buffer,+ peakPending: Math.max(...seen, 0),+ pendingAtEmitEnd: atEmitEnd+ ? (atEmitEnd.buffers.get(buffer) ?? null)+ : null,+ finalPending,+ returnedToZero: settled.some((s) => (s.buffers.get(buffer) ?? 0) === 0),+ rowsFlushed: delta((s) => s.flushRows),+ flushes,+ meanFlushMs: flushes > 0 ? flushMs / flushes : null,+ chInserts,+ meanChInsertMs: chInserts > 0 ? chInsertMs / chInserts : null,+ };+ });++ return {+ scrapeUrl: this.url,+ sampleCount: this.samples.length,+ queues,+ buffers,+ queuesNotDrained: queues+ .filter((q) => !q.returnedToZero)+ .map((q) => q.queue),+ buffersNotDrained: buffers+ .filter((b) => !b.returnedToZero)+ .map((b) => b.buffer),+ };+ }+}++const num = (v: number | null, unit = '') =>+ v === null ? 'n/a' : `${v.toFixed(1)}${unit}`;++/** One line per queue/buffer that did anything, plus the not-drained verdict. */+export function formatMetricsSummary(s: MetricsSummary): string[] {+ if (s.sampleCount === 0) {+ return [`queues/buffers: no samples (${s.scrapeUrl} unreachable)`];+ }+ const lines = [+ `queues/buffers (${s.sampleCount} scrapes of ${s.scrapeUrl}):`,+ ];+ for (const q of s.queues) {+ const busy = q.peakWaiting > 0 || q.peakActive > 0 || q.failedDelta !== 0;+ if (!busy) {+ continue;+ }+ lines.push(+ ` queue ${q.queue}: peak waiting=${q.peakWaiting} active=${q.peakActive} delayed=${q.peakDelayed}, ` ++ `depth at emit-end=${q.depthAtEmitEnd ?? 'n/a'}, final=${q.finalDepth}, ` ++ `back to zero=${q.returnedToZero ? 'yes' : 'NO'}, failed+${q.failedDelta}`+ );+ }+ for (const b of s.buffers) {+ if (b.peakPending === 0 && b.rowsFlushed === 0) {+ continue;+ }+ lines.push(+ ` buffer ${b.buffer}: peak pending=${b.peakPending}, at emit-end=${b.pendingAtEmitEnd ?? 'n/a'}, ` ++ `final=${b.finalPending}, back to zero=${b.returnedToZero ? 'yes' : 'NO'}, ` ++ `rows=${b.rowsFlushed}, flushes=${b.flushes} (mean ${num(b.meanFlushMs, 'ms')}), ` ++ `ch inserts=${b.chInserts} (mean ${num(b.meanChInsertMs, 'ms')})`+ );+ }+ const stuck = [+ ...s.queuesNotDrained.map((q) => `queue:${q}`),+ ...s.buffersNotDrained.map((b) => `buffer:${b}`),+ ];+ lines.push(+ ` did not return to zero: ${stuck.length === 0 ? 'none' : stuck.join(', ')}`+ );+ return lines;+}diff --git a/apps/api/e2e/saturation-sweep.ts b/apps/api/e2e/saturation-sweep.tsnew file mode 100644index 000000000..8bf5af922--- /dev/null+++ b/apps/api/e2e/saturation-sweep.ts@@ -0,0 +1,452 @@+/**+ * Saturation sweep — the ramp driver on top of `session-stress.ts` (M16-001).+ *+ * GOAL: find the MAX SUSTAINABLE INGEST THROUGHPUT, defined as the highest+ * offered load at which the pipeline still drains. It runs `session-stress.ts`+ * at increasing concurrency, one rung per CHILD PROCESS (so no Redis/Kafka+ * connection, cached pid or latency sink leaks between rungs), parses each+ * rung's machine-readable result line, and applies the knee definition below.+ *+ * THE KNEE, exactly as implemented in `classifyRung()`. A rung DID NOT DRAIN if+ * any of these is true:+ * 1. `lag.secondsToZeroAfterEmitEnd` is null — the Kafka consumer group was+ * still behind when sampling stopped.+ * 2. That figure grew rung-over-rung rather than staying flat: more than+ * SWEEP_DRAIN_GROWTH_FACTOR x the best drain time seen so far, AND more+ * than SWEEP_DRAIN_GROWTH_MIN_S seconds worse in absolute terms (the+ * absolute floor keeps 0.4s → 0.9s from reading as a knee).+ * 3. A queue depth or a buffer pending count failed to return to zero.+ * The first such rung is the knee. The last rung BEFORE it is the max+ * sustainable throughput, reported in events/second with that rung's api and+ * worker CPU and RSS.+ *+ * A rung that fails to drain is a DATA POINT, not a harness error: it is+ * recorded, the ladder stops climbing, and the sweep still exits 0. The sweep+ * exits non-zero only when it could not measure at all (no rung produced a+ * result).+ *+ * AUTH: defaults to E2E_AUTH_MODE=secret — the pessimistic, server-side-SDK+ * path through the cached scrypt verify. The two other paths are reachable+ * with SWEEP_AUTH_MODE=cors (browser traffic) and SWEEP_AUTH_MODE=bypass+ * (diagnostic baseline, no real traffic takes it).+ *+ * Full knob list and how to read the output: docs/BENCHMARK_HARNESS.md.+ */++import { spawn } from 'node:child_process';+import {+ AUTH_PATH_DESCRIPTION,+ type AuthCostProbe,+ type AuthMode,+ authVerifyCacheKey,+ probeAuthCost,+ redis,+ sleep,+} from './lib';+import type { RunResult } from './session-stress';++const RESULT_MARKER = 'E2E_STRESS_RESULT ';+const STRESS_SCRIPT = 'e2e/session-stress.ts';++const SWEEP_RUNGS = Number.parseInt(process.env.SWEEP_RUNGS || '5', 10);+const SWEEP_START_CONCURRENCY = Number.parseInt(+ process.env.SWEEP_START_CONCURRENCY || '25',+ 10+);+const SWEEP_CONCURRENCY_FACTOR = Number.parseFloat(+ process.env.SWEEP_CONCURRENCY_FACTOR || '2'+);+/** Explicit ladder, e.g. `SWEEP_LADDER=25,50,100,200`. Wins over start/factor. */+const SWEEP_LADDER = process.env.SWEEP_LADDER;+const SWEEP_AUTH_MODE = (process.env.SWEEP_AUTH_MODE || 'secret') as AuthMode;+const SWEEP_WARM_REQUESTS = process.env.SWEEP_WARM_REQUESTS || '3';+/** Idle gap between rungs so the previous rung's flushes land before the next starts. */+const SWEEP_RUNG_COOLDOWN_MS = Number.parseInt(+ process.env.SWEEP_RUNG_COOLDOWN_MS || '5000',+ 10+);+const SWEEP_RUNG_TIMEOUT_MS = Number.parseInt(+ process.env.SWEEP_RUNG_TIMEOUT_MS || '600000',+ 10+);+const SWEEP_DRAIN_GROWTH_FACTOR = Number.parseFloat(+ process.env.SWEEP_DRAIN_GROWTH_FACTOR || '1.5'+);+const SWEEP_DRAIN_GROWTH_MIN_S = Number.parseFloat(+ process.env.SWEEP_DRAIN_GROWTH_MIN_S || '2'+);++function buildLadder(): number[] {+ if (SWEEP_LADDER) {+ const rungs = SWEEP_LADDER.split(',')+ .map((raw) => Number.parseInt(raw.trim(), 10))+ .filter((n) => Number.isFinite(n) && n > 0);+ if (rungs.length === 0) {+ throw new Error(+ `SWEEP_LADDER="${SWEEP_LADDER}" has no positive integers`+ );+ }+ return rungs.slice(0, SWEEP_RUNGS);+ }+ return Array.from({ length: SWEEP_RUNGS }, (_, i) =>+ Math.round(SWEEP_START_CONCURRENCY * SWEEP_CONCURRENCY_FACTOR ** i)+ );+}++type RungVerdict = 'drained' | 'did-not-drain' | 'no-result';++interface Rung {+ index: number;+ concurrency: number;+ verdict: RungVerdict;+ /** Why it did not drain, in the words of the knee definition. */+ reasons: string[];+ result: RunResult | null;+ error: string | null;+}++/** Run one rung as its own process; never throws — a dead rung is a data point. */+function runRung(+ index: number,+ total: number,+ concurrency: number+): Promise<{ result: RunResult | null; error: string | null }> {+ console.log(+ `\n${'='.repeat(70)}\nRung ${index + 1}/${total} — concurrency ${concurrency}\n${'='.repeat(70)}`+ );+ return new Promise((resolve) => {+ const child = spawn(process.execPath, [STRESS_SCRIPT], {+ cwd: process.cwd(),+ env: {+ ...process.env,+ E2E_CONCURRENCY: String(concurrency),+ E2E_AUTH_MODE: SWEEP_AUTH_MODE,+ E2E_AUTH_WARM_REQUESTS: SWEEP_WARM_REQUESTS,+ E2E_RUNS: '1',+ // Makes the child print the parseable result line.+ E2E_STRESS_CHILD: '1',+ },+ stdio: ['ignore', 'pipe', 'inherit'],+ });++ let buffered = '';+ let settled = false;+ const finish = (result: RunResult | null, error: string | null) => {+ if (settled) {+ return;+ }+ settled = true;+ clearTimeout(killer);+ resolve({ result, error });+ };++ const killer = setTimeout(() => {+ child.kill('SIGKILL');+ finish(+ null,+ `rung exceeded SWEEP_RUNG_TIMEOUT_MS=${SWEEP_RUNG_TIMEOUT_MS}`+ );+ }, SWEEP_RUNG_TIMEOUT_MS);++ child.stdout.on('data', (chunk: Buffer) => {+ const text = chunk.toString();+ process.stdout.write(text);+ buffered += text;+ });+ child.on('error', (error) => finish(null, error.message));+ child.on('close', (code) => {+ const line = buffered+ .split('\n')+ .find((l) => l.startsWith(RESULT_MARKER));+ if (!line) {+ finish(null, `no result line (exit ${code})`);+ return;+ }+ try {+ finish(JSON.parse(line.slice(RESULT_MARKER.length)) as RunResult, null);+ } catch (error) {+ finish(null, `unparseable result line: ${(error as Error).message}`);+ }+ });+ });+}++/**+ * The knee definition, implemented. `bestDrainSeconds` is the flattest drain+ * time seen on a rung that did drain — the baseline clause 2 compares against.+ */+function classifyRung(+ result: RunResult,+ bestDrainSeconds: number | null+): { verdict: RungVerdict; reasons: string[] } {+ const reasons: string[] = [];+ const drainSeconds = result.lag.secondsToZeroAfterEmitEnd;++ if (result.lag.sampleCount === 0) {+ reasons.push(+ 'kafka lag was never sampled — the drain clause cannot be evaluated for this rung'+ );+ } else if (drainSeconds === null) {+ reasons.push(+ 'consumer lag never returned to 0 after emit ended (still draining when sampling stopped)'+ );+ } else if (+ bestDrainSeconds !== null &&+ drainSeconds > bestDrainSeconds * SWEEP_DRAIN_GROWTH_FACTOR &&+ drainSeconds > bestDrainSeconds + SWEEP_DRAIN_GROWTH_MIN_S+ ) {+ reasons.push(+ `drain time grew rung-over-rung: ${drainSeconds.toFixed(1)}s vs ${bestDrainSeconds.toFixed(1)}s best ` ++ `(>${SWEEP_DRAIN_GROWTH_FACTOR}x and >${SWEEP_DRAIN_GROWTH_MIN_S}s worse)`+ );+ }++ for (const queue of result.metrics.queuesNotDrained) {+ reasons.push(`queue "${queue}" did not return to zero`);+ }+ for (const buffer of result.metrics.buffersNotDrained) {+ reasons.push(`buffer "${buffer}" did not return to zero`);+ }++ return {+ verdict: reasons.length === 0 ? 'drained' : 'did-not-drain',+ reasons,+ };+}++const n1 = (v: number | null | undefined, unit = '') =>+ v === null || v === undefined ? 'n/a' : `${v.toFixed(1)}${unit}`;+const mb = (kb: number | null | undefined) =>+ kb === null || kb === undefined ? 'n/a' : `${(kb / 1024).toFixed(0)}MB`;+const pad = (text: string, width: number) => text.padEnd(width);++function printRungTable(rungs: Rung[]) {+ const header = [+ pad('rung', 5),+ pad('conc', 6),+ pad('ev/s', 9),+ pad('P50', 8),+ pad('P95', 8),+ pad('P99', 9),+ pad('api cpu%', 9),+ pad('api rss', 8),+ pad('wrk cpu%', 9),+ pad('wrk rss', 8),+ pad('peak lag', 9),+ pad('drain', 8),+ 'verdict',+ ].join(' ');+ console.log(header);+ console.log('─'.repeat(header.length));+ for (const rung of rungs) {+ const r = rung.result;+ console.log(+ [+ pad(String(rung.index + 1), 5),+ pad(String(rung.concurrency), 6),+ pad(n1(r?.eventsPerSecond), 9),+ pad(n1(r?.latency.p50, 'ms'), 8),+ pad(n1(r?.latency.p95, 'ms'), 8),+ pad(n1(r?.latency.p99, 'ms'), 9),+ pad(n1(r?.api.peakCpuPct), 9),+ pad(mb(r?.api.peakRssKb), 8),+ pad(n1(r?.worker.peakCpuPct), 9),+ pad(mb(r?.worker.peakRssKb), 8),+ pad(String(r?.lag.peakLag ?? 'n/a'), 9),+ pad(n1(r?.lag.secondsToZeroAfterEmitEnd, 's'), 8),+ rung.verdict,+ ].join(' ')+ );+ for (const reason of rung.reasons) {+ console.log(` ↳ ${reason}`);+ }+ if (rung.error) {+ console.log(` ↳ ${rung.error}`);+ }+ }+}++function printQueueDetail(rungs: Rung[]) {+ console.log('\nQueue and buffer depths per rung');+ for (const rung of rungs) {+ if (!rung.result) {+ continue;+ }+ const { metrics } = rung.result;+ console.log(+ ` rung ${rung.index + 1} (concurrency ${rung.concurrency}, ${metrics.sampleCount} scrapes):`+ );+ const busy = metrics.queues.filter(+ (q) => q.peakWaiting > 0 || q.peakActive > 0 || q.failedDelta !== 0+ );+ for (const q of busy) {+ console.log(+ ` queue ${pad(q.queue, 16)} peak waiting=${q.peakWaiting} active=${q.peakActive} ` ++ `delayed=${q.peakDelayed}, at emit-end=${q.depthAtEmitEnd ?? 'n/a'}, ` ++ `final=${q.finalDepth}, zero=${q.returnedToZero ? 'yes' : 'NO'}, failed+${q.failedDelta}`+ );+ }+ for (const b of metrics.buffers.filter(+ (x) => x.peakPending > 0 || x.rowsFlushed > 0+ )) {+ console.log(+ ` buffer ${pad(b.buffer, 15)} peak pending=${b.peakPending}, at emit-end=${b.pendingAtEmitEnd ?? 'n/a'}, ` ++ `final=${b.finalPending}, zero=${b.returnedToZero ? 'yes' : 'NO'}, rows=${b.rowsFlushed}, ` ++ `flush mean=${n1(b.meanFlushMs, 'ms')}, ch insert mean=${n1(b.meanChInsertMs, 'ms')}`+ );+ }+ if (busy.length === 0) {+ console.log(' (no queue registered a waiting or active job at 1Hz)');+ }+ }+}++function printVerdict(rungs: Rung[], probe: AuthCostProbe | null) {+ const drained = rungs.filter((r) => r.verdict === 'drained');+ const knee = rungs.find((r) => r.verdict === 'did-not-drain');+ const best = drained.at(-1);++ console.log(`\n${'═'.repeat(70)}\nVERDICT\n${'═'.repeat(70)}`);+ console.log(` auth path: ${AUTH_PATH_DESCRIPTION[SWEEP_AUTH_MODE]}`);+ if (probe) {+ console.log(+ ` scrypt cost: ${probe.scryptMs.toFixed(1)}ms (cold ${probe.coldMs.toFixed(1)}ms / warmed ${probe.warmMs.toFixed(1)}ms) — ` ++ 'paid once per rung during warm-up, outside every measured window'+ );+ }+ if (best) {+ const r = best.result as RunResult;+ console.log(+ ` MAX SUSTAINABLE THROUGHPUT: ${r.eventsPerSecond.toFixed(1)} events/s ` ++ `(rung ${best.index + 1}, concurrency ${best.concurrency}, ` ++ `${r.sessions} sessions x ${r.eventsPerSession} events)`+ );+ console.log(+ ` api: CPU peak=${n1(r.api.peakCpuPct, '%')} steady=${n1(r.api.steadyCpuPct, '%')}, ` ++ `RSS peak=${mb(r.api.peakRssKb)} steady=${mb(r.api.steadyRssKb)}`+ );+ console.log(+ ` worker: CPU peak=${n1(r.worker.peakCpuPct, '%')} steady=${n1(r.worker.steadyCpuPct, '%')}, ` ++ `RSS peak=${mb(r.worker.peakRssKb)} steady=${mb(r.worker.steadyRssKb)}`+ );+ console.log(+ ` /track: P50=${n1(r.latency.p50, 'ms')} P95=${n1(r.latency.p95, 'ms')} P99=${n1(r.latency.p99, 'ms')}`+ );+ } else {+ console.log(+ ' MAX SUSTAINABLE THROUGHPUT: not established — no rung drained.'+ );+ }+ if (knee) {+ console.log(+ ` KNEE: rung ${knee.index + 1} at concurrency ${knee.concurrency} did not drain —`+ );+ for (const reason of knee.reasons) {+ console.log(` - ${reason}`);+ }+ } else if (rungs.every((r) => r.verdict === 'drained')) {+ console.log(+ ' KNEE: NOT REACHED — every rung drained. The ceiling is above the top ' ++ 'rung; extend the ladder (SWEEP_RUNGS / SWEEP_LADDER) to find it.'+ );+ }+ const unmeasured = rungs.filter((r) => r.verdict === 'no-result');+ if (unmeasured.length > 0) {+ console.log(+ ` UNMEASURED: ${unmeasured.map((r) => `rung ${r.index + 1}`).join(', ')} produced no result`+ );+ }+ console.log(+ '\n Single-node box, single api+worker process. Not a cloud capacity claim;\n' ++ ' see docs/BENCHMARK_HARNESS.md for what these numbers do NOT cover.'+ );+}++async function main() {+ const ladder = buildLadder();+ console.log(+ `Saturation sweep — ${ladder.length} rungs at concurrency ${ladder.join(', ')}\n` ++ ` auth mode: ${SWEEP_AUTH_MODE} — ${AUTH_PATH_DESCRIPTION[SWEEP_AUTH_MODE]}\n` ++ ` per rung: E2E_SESSIONS=${process.env.E2E_SESSIONS || '500'} ` ++ `E2E_EVENTS_PER_SESSION=${process.env.E2E_EVENTS_PER_SESSION || '3'}\n` ++ ` knee: secondsToZero null, or >${SWEEP_DRAIN_GROWTH_FACTOR}x and >${SWEEP_DRAIN_GROWTH_MIN_S}s worse than best, ` ++ 'or a queue/buffer that never returned to zero'+ );++ // Evict the L2 copy of the scrypt verdict so the sweep's first rung starts+ // from the same cache state as a cold production process would. The API also+ // holds an L1 LRU this harness cannot reach — which is exactly why the+ // per-rung warm-up, not this delete, is what guarantees the measured window+ // is scrypt-free.+ await redis.del(authVerifyCacheKey()).catch(() => 0);++ let probe: AuthCostProbe | null = null;+ if (SWEEP_AUTH_MODE === 'secret') {+ probe = await probeAuthCost().catch(() => null);+ if (probe) {+ console.log(+ ` scrypt probe: cold=${probe.coldMs.toFixed(1)}ms (status ${probe.coldStatus}) ` ++ `warmed=${probe.warmMs.toFixed(1)}ms (status ${probe.warmStatus}) → scrypt ≈ ${probe.scryptMs.toFixed(1)}ms`+ );+ }+ }++ const rungs: Rung[] = [];+ let bestDrainSeconds: number | null = null;++ for (const [index, concurrency] of ladder.entries()) {+ if (index > 0) {+ await sleep(SWEEP_RUNG_COOLDOWN_MS);+ }+ const { result, error } = await runRung(index, ladder.length, concurrency);+ if (!result) {+ rungs.push({+ index,+ concurrency,+ verdict: 'no-result',+ reasons: [],+ result: null,+ error,+ });+ console.log(`\n rung ${index + 1} produced no result: ${error}`);+ break;+ }++ const { verdict, reasons } = classifyRung(result, bestDrainSeconds);+ rungs.push({ index, concurrency, verdict, reasons, result, error: null });++ if (verdict === 'did-not-drain') {+ console.log(+ `\n rung ${index + 1} did not drain — recording it and stopping the climb.`+ );+ break;+ }+ const drainSeconds = result.lag.secondsToZeroAfterEmitEnd;+ if (+ drainSeconds !== null &&+ (bestDrainSeconds === null || drainSeconds < bestDrainSeconds)+ ) {+ bestDrainSeconds = drainSeconds;+ }+ }++ console.log(`\n${'═'.repeat(70)}\nRUNG TABLE\n${'═'.repeat(70)}`);+ printRungTable(rungs);+ printQueueDetail(rungs);+ printVerdict(rungs, probe);++ await redis.quit().catch(() => {+ // Teardown is best-effort; the verdict is already printed.+ });+ // A rung that did not drain is the answer, not a failure. Only a sweep that+ // measured nothing at all is an error.+ process.exit(rungs.some((r) => r.result !== null) ? 0 : 1);+}++main().catch(async (error) => {+ console.error('\nFATAL:', error);+ await redis.quit().catch(() => {+ // Already failing; a stuck redis connection must not mask the cause.+ });+ process.exit(1);+});diff --git a/apps/api/e2e/session-stress.ts b/apps/api/e2e/session-stress.tsindex 9590c31ee..258fbd497 100644--- a/apps/api/e2e/session-stress.ts+++ b/apps/api/e2e/session-stress.ts@@ -8,11 +8,16 @@** Also instruments the run (BENCH-001): per-request /track latency* (P50/P95/P99, emit phase only), RSS/CPU of the api + worker processes- * (>=1Hz, peak + steady-state), and Kafka consumer-group lag on the events- * topic (>=1Hz; peak, lag at emit-end, seconds-to-zero after emit stops).+ * (>=1Hz, peak + steady-state), Kafka consumer-group lag on the events+ * topic (>=1Hz; peak, lag at emit-end, seconds-to-zero after emit stops),+ * and every BullMQ queue depth + buffer pending count scraped off /metrics+ * (>=1Hz; peak, depth at emit-end, whether it returned to zero — M16-001).* None of it changes what the run asserts — see `check()` calls below,* unchanged from the un-instrumented version.*+ * `saturation-sweep.ts` drives this script across a ladder of offered loads;+ * see docs/BENCHMARK_HARNESS.md.+ ** Run (shrink the idle window; start the stack with the SAME value):* SESSION_TIMEOUT_MS=4000 pnpm dev* SESSION_TIMEOUT_MS=4000 pnpm --filter @openpanel/api e2e:sessions:stress@@ -26,12 +31,23 @@* still records; it's inherent to what's measured, not background* polling). Control lever for isolating whether the >=1Hz sampling itself* is dragging on throughput, e.g. `E2E_RUNS=3 E2E_NO_SAMPLING=1`.+ * E2E_AUTH_MODE (bypass) — which ingest auth path every request takes:+ * `bypass` | `cors` | `secret`; see AUTH_PATH_DESCRIPTION in lib.ts. The+ * default keeps this script on the path the pre-existing suites were+ * written against; `saturation-sweep.ts` defaults to `secret`.+ * E2E_AUTH_WARM_REQUESTS (3) — authenticated requests sent and discarded+ * before recording starts, so the scrypt verify behind VERIFY_CACHE_SECONDS+ * is paid outside the measured window.*/import { spawn } from 'node:child_process';import { formatLagSummary, LagMonitor, type LagSummary } from './lag-monitor';import {API_URL,+ AUTH_MODE,+ AUTH_PATH_DESCRIPTION,+ AUTH_WARM_REQUESTS,+ type AuthWarmResult,beginLatencyRecording,check,checkCount,@@ -62,7 +78,13 @@ import {triggerReaper,WORKER_URL,wallclockKey,+ warmAuthCache,} from './lib';+import {+ formatMetricsSummary,+ MetricsMonitor,+ type MetricsSummary,+} from './metrics-monitor';import {formatProcessSummary,ProcessMonitor,@@ -115,16 +137,24 @@ const SAMPLING_ENABLED = process.env.E2E_NO_SAMPLING !== '1';type Session = { sessionId: string; deviceId: string };-interface RunResult {+export interface RunResult {ok: boolean;failedChecks: number;totalChecks: number;+ /** The offered load this run was configured with, so a sweep can label its rungs. */+ sessions: number;+ eventsPerSession: number;+ concurrency: number;+ /** Which of the three ingest auth paths every measured request took. */+ authMode: string;+ authWarm: AuthWarmResult | null;emitSeconds: number;eventsPerSecond: number;latency: LatencyStats;api: ProcessSummary;worker: ProcessSummary;lag: LagSummary;+ metrics: MetricsSummary;samplingEnabled: boolean;}@@ -378,23 +408,46 @@ async function reconcile(sessions: Session[], since: Date) {const portFromUrl = (url: string) => Number(new URL(url).port);+/**+ * Pay the auth cost BEFORE recording starts, so the scrypt behind+ * `VERIFY_CACHE_SECONDS` can never land inside the measured window and be read+ * as a knee. Discarded on purpose: the warm requests are not in the latency+ * series, not in the reconcile counts (they use their own ip), and the+ * sessions they open are reaped by the same drain loop as the rest.+ */+async function warmAuth(): Promise<AuthWarmResult | null> {+ if (AUTH_WARM_REQUESTS <= 0) {+ return null;+ }+ const warm = await warmAuthCache(AUTH_MODE, AUTH_WARM_REQUESTS);+ console.log(+ ` auth cache warmed: ${warm.requests} discarded requests, ` ++ `${warm.latenciesMs.map((ms) => ms.toFixed(1)).join('/')}ms (max ${warm.maxMs?.toFixed(1)}ms)`+ );+ return warm;+}+async function runOnce(): Promise<RunResult> {console.log(`Session STRESS — api=${API_URL} worker=${WORKER_URL} timeout=${SESSION_TIMEOUT_MS}ms ` +`sessions=${SESSIONS} events=${EVENTS_PER_SESSION} concurrency=${CONCURRENCY}` +(SAMPLING_ENABLED ? '' : ' [sampling disabled — control run]'));+ console.log(` auth path: ${AUTH_PATH_DESCRIPTION[AUTH_MODE]}`);await preflight();await ensureFixtures();+ const authWarm = await warmAuth();const apiMonitor = new ProcessMonitor('api', portFromUrl(API_URL));const workerMonitor = new ProcessMonitor('worker', portFromUrl(WORKER_URL));const lagMonitor = new LagMonitor();+ const metricsMonitor = new MetricsMonitor(API_URL);if (SAMPLING_ENABLED) {await Promise.all([apiMonitor.start(SAMPLE_INTERVAL_MS),workerMonitor.start(SAMPLE_INTERVAL_MS),lagMonitor.start(SAMPLE_INTERVAL_MS),+ metricsMonitor.start(SAMPLE_INTERVAL_MS),]);}@@ -410,33 +463,46 @@ async function runOnce(): Promise<RunResult> {apiMonitor.stop();workerMonitor.stop();+ metricsMonitor.stop();await lagMonitor.stop();const api = apiMonitor.summary();const worker = workerMonitor.summary();const lag = lagMonitor.summarize(emitEndedAt);+ const metrics = metricsMonitor.summarize(emitEndedAt);scenario('instrumentation summary');+ console.log(` auth path: ${AUTH_PATH_DESCRIPTION[AUTH_MODE]}`);console.log(` ${formatProcessSummary(api)}`);console.log(` ${formatProcessSummary(worker)}`);console.log(` ${formatLagSummary(lag)}`);+ for (const line of formatMetricsSummary(metrics)) {+ console.log(` ${line}`);+ }const failedChecks = summarize();return {ok: failedChecks === 0,failedChecks,totalChecks: checkCount(),+ sessions: SESSIONS,+ eventsPerSession: EVENTS_PER_SESSION,+ concurrency: CONCURRENCY,+ authMode: AUTH_MODE,+ authWarm,emitSeconds,eventsPerSecond: (SESSIONS * EVENTS_PER_SESSION) / emitSeconds,latency,api,worker,lag,+ metrics,samplingEnabled: SAMPLING_ENABLED,};} finally {apiMonitor.stop();workerMonitor.stop();+ metricsMonitor.stop();await lagMonitor.stop();}}diff --git a/apps/api/package.json b/apps/api/package.jsonindex 2090e45c8..9cc8108d3 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -10,6 +10,7 @@"test:manage": "bun scripts/test-manage-api.ts","e2e:sessions": "LOG_LEVEL=warn dotenv -e ../../.env -- bun e2e/session-e2e.ts","e2e:sessions:stress": "LOG_LEVEL=warn dotenv -e ../../.env -- bun e2e/session-stress.ts",+ "e2e:saturation": "LOG_LEVEL=warn dotenv -e ../../.env -- bun e2e/saturation-sweep.ts","e2e:legacy-jobs": "bash e2e/legacy-job-proof.sh","test": "bun test --isolate","typecheck": "tsc --noEmit"diff --git a/docs/BENCHMARK_HARNESS.md b/docs/BENCHMARK_HARNESS.mdnew file mode 100644index 000000000..d7d0bb91d--- /dev/null+++ b/docs/BENCHMARK_HARNESS.md@@ -0,0 +1,319 @@+# Benchmark harness — saturation sweep++How to find the **max sustainable ingest throughput** of OpenPanel V2: the rate+at which the Kafka consumer starts falling behind and does not catch up.++The harness is three files under `apps/api/e2e/`:++| File | Role |+|---|---|+| `session-stress.ts` (`bun run e2e:sessions:stress`) | one rung. Emits load, drains to completion, reconciles ClickHouse, and reports latency, api/worker RSS+CPU, Kafka lag, and every queue/buffer depth. |+| `saturation-sweep.ts` (`bun run e2e:saturation`) | the ramp driver. Runs `session-stress.ts` across a ladder of offered loads, one child process per rung, applies the knee definition and prints a verdict. |+| `metrics-monitor.ts` | the `/metrics` scraper the queue and buffer numbers come from. |++`process-monitor.ts` (RSS/CPU) and `lag-monitor.ts` (Kafka consumer-group lag)+are BENCH-001's and are used unchanged.++---++## Running it++The dev stack must be up and **must share `SESSION_TIMEOUT_MS` with the+harness** — `.env` sets `4000`, and both sides read it through+`dotenv -e ../../.env`. With the real 30-minute default every rung would sit in+`drain()` for half an hour.++```bash+# stack (operator keeps this running; no --watch)+cd apps/api && API_PORT=3333 bun run dev++# full sweep — the operator run, no agent time limit+cd apps/api+E2E_WORKER_URL=http://localhost:3333 \+ SWEEP_LADDER=25,50,100,200,400,800 \+ E2E_SESSIONS=2000 E2E_EVENTS_PER_SESSION=3 \+ bun run e2e:saturation++# short proof that the driver works (this is what M16-001 ran)+E2E_WORKER_URL=http://localhost:3333 \+ SWEEP_RUNGS=2 E2E_SESSIONS=20 E2E_EVENTS_PER_SESSION=2 \+ timeout 900 bun run e2e:saturation+```++Budget roughly `E2E_SESSIONS x E2E_EVENTS_PER_SESSION / offered-rate` seconds of+emit plus ~25 s of fixed drain/reconcile per rung (the 6 s idle wait, the reaper+loop and the reconcile stability window dominate at small sizes).++---++## Env knobs++### The sweep (`saturation-sweep.ts`)++| Variable | Default | Meaning |+|---|---|---|+| `SWEEP_RUNGS` | `5` | number of rungs to climb |+| `SWEEP_LADDER` | — | explicit ladder, e.g. `25,50,100,200`. Wins over start/factor; truncated to `SWEEP_RUNGS` |+| `SWEEP_START_CONCURRENCY` | `25` | first rung's concurrency when no explicit ladder |+| `SWEEP_CONCURRENCY_FACTOR` | `2` | geometric step between rungs |+| `SWEEP_AUTH_MODE` | `secret` | which ingest auth path every request takes: `secret` \| `cors` \| `bypass` |+| `SWEEP_WARM_REQUESTS` | `3` | authenticated requests sent and discarded before each rung records |+| `SWEEP_RUNG_COOLDOWN_MS` | `5000` | idle gap between rungs |+| `SWEEP_RUNG_TIMEOUT_MS` | `600000` | per-rung wall clock before the child is SIGKILLed and recorded as `no-result` |+| `SWEEP_DRAIN_GROWTH_FACTOR` | `1.5` | knee clause 2, relative |+| `SWEEP_DRAIN_GROWTH_MIN_S` | `2` | knee clause 2, absolute floor (seconds) |++### Per rung (`session-stress.ts`, passed through by the sweep)++| Variable | Default | Meaning |+|---|---|---|+| `E2E_SESSIONS` | `500` | sessions per rung |+| `E2E_EVENTS_PER_SESSION` | `3` | events per session; each session also produces a synthetic `session_start` and `session_end` |+| `E2E_CONCURRENCY` | `25` | in-flight sessions — **the sweep overrides this per rung** |+| `E2E_AUTH_MODE` | `bypass` | as `SWEEP_AUTH_MODE`; the standalone default stays `bypass` so the pre-existing suites keep the path they were written against |+| `E2E_AUTH_WARM_REQUESTS` | `3` | discarded warm-up requests; `0` disables warming |+| `E2E_DRAIN_TIMEOUT_MS` | `120000` | reaper/flush loop budget |+| `E2E_RECONCILE_TIMEOUT_MS` | `30000` | ClickHouse count-settling budget |+| `E2E_NO_SAMPLING` | `0` | `1` skips the process, lag **and** metrics monitors — the control lever for "is the 1 Hz sampling itself costing throughput" |+| `E2E_RUNS` | `1` | BENCH-001's repeat mode. Not used by the sweep |+| `E2E_API_URL` / `E2E_WORKER_URL` | `http://localhost:3333` / `http://localhost:9999` | stack endpoints |+| `SESSION_TIMEOUT_MS` | from `.env` (`4000`) | must match the running stack |++---++## The three auth paths — and which one each number came from++`validateIngestRequest`+(`packages/core/src/modules/ingest/src/client-auth.ts`) can clear a request+three different ways, and they are **not** the same amount of work. Every+number this harness prints is labelled with the mode it ran under, on the rung+line and again in the verdict block.++| Mode | What the request carries | What the API does | Real traffic? |+|---|---|---|---|+| `bypass` (a) | client id of the `ignoreCorsAndSecret` fixture client | returns at `client-auth.ts:197` immediately, before any I/O | **No.** Diagnostic baseline only |+| `cors` (b) | client id of the real-secret client + an allowed `Origin` | returns at `client-auth.ts:200` after a regex against the project CORS list | Yes — browser / web-SDK traffic |+| `secret` (c) | client id + `openpanel-client-secret` header, no `Origin` | `client-auth.ts:205`'s `getCache(...)` around a scrypt `verifyPassword` | Yes — server-side SDK traffic |++**`secret` is the headline number and the sweep's default**, because a+self-host capacity claim should be the pessimistic one. `cors` is the second+data point. `bypass` exists only so the (a)↔(c) delta isolates what the auth+path costs; no production request takes it.++Both clients are created by `ensureFixtures()` in `apps/api/e2e/lib.ts`, on the+same project:++- `e2e1e2e1-…-000000000001` — the pre-existing bypass client, unchanged, so the+ 29 checks in `e2e:sessions` keep passing.+- `e2e1e2e1-…-000000000002` — new. Carries a real scrypt secret in+ `salt.hashKey` form, hashed with `hashPassword` (the `@openpanel/shared/server`+ scrypt helper, reached through its re-export on the `@openpanel/core` barrel —+ `apps/api` does not declare `@openpanel/shared` and adding it would move+ `bun.lock`, which M16-001 could not touch).++The project's `cors` list is set to `e2e.test` so path (b) is reachable. That+changes nothing for the bypass client, which returns before the CORS check.++---++## Cache warming: why the 300 s TTL is not saturation++`verifyPassword` is **scrypt** (`packages/shared/src/server/crypto.ts:40`,+keyLength 32, `timingSafeEqual`) — tens of milliseconds of CPU per call. It is+shielded by `VERIFY_CACHE_SECONDS = 300` (`client-auth.ts:34`), keyed on client+id plus the base64 of the presented secret. So **a scrypt is a latency outlier,+not a per-request cost**: a rung shorter than the TTL pays it once, at whatever+moment it lands; a rung longer than the TTL pays it periodically. Read naively,+one such spike inside a measured window looks exactly like a knee.++What the harness does about it:++1. **Warm before recording, every rung.** `warmAuth()` in `session-stress.ts`+ sends `E2E_AUTH_WARM_REQUESTS` (default 3) fully authenticated requests and+ **discards them** — they are not in the latency series and not in the+ reconcile counts (they use a dedicated `203.0.113.7` source ip, outside the+ `100.x` space the measured sessions use). Only then does `emit()` start+ recording. Each rung is a fresh child process, so this happens identically at+ every rung.+2. **Print the warm-up latencies**, so it is visible where the scrypt landed.+3. **Probe the outlier's size directly**, once per sweep, before the ladder:+ `probeAuthCost()` sends one request with a secret that has never been+ presented — guaranteeing a miss in both cache layers and therefore a real+ scrypt, which then refuses with 401 — and one request on the warmed real+ secret. The delta is what a mid-rung expiry would have injected.++**How this was confirmed** (runs 2026-09-12, this box, rev `8175c3f4`): the+sweep's own output shows the split. On one rung the warm-up latencies came back+as `45.5 / 2.9 / 4.1 ms` — the first discarded request paid the scrypt, the next+two did not, and the measured window that followed had a P99 of 58.9 ms with no+40 ms outlier in it. **That three-number split is the load-bearing evidence**,+because it shows the scrypt inside the warm-up and its absence afterwards, on+the same rung.++The standalone `probeAuthCost()` figure is a useful order-of-magnitude check but+is a single unpaired sample and is itself noisy: across four sweeps it measured+cold `37.0 / 37.4 / 53.1 / 57.9 ms` against warmed `3.4 / 2.8 / 10.3 / 47.6 ms`,+i.e. a delta of 34.6, 34.6, 42.8 and 10.3 ms. The 10.3 ms reading is the probe+landing while the box was still busy, not a cheaper scrypt — treat the probe as+"tens of milliseconds, same order as a whole rung's P99" and not as a+calibrated constant.++One caveat, stated plainly. `getCache` is called with `useLruCache`+(`client-auth.ts:205`), so the verdict is held in a **process-local LRU as well+as in Redis** (`packages/redis/cachable.ts:22`). The harness can delete the+Redis copy — the sweep does, once, before the ladder — but it cannot reach the+API process's L1. The per-rung warm-up, not that delete, is what guarantees the+measured window is scrypt-free.++---++## The knee, as implemented++`classifyRung()` in `saturation-sweep.ts`. A rung **did not drain** if any of:++1. `lag.secondsToZeroAfterEmitEnd` is `null` — the Kafka consumer group was+ still behind when sampling stopped.+2. That figure **grew rung-over-rung rather than staying flat**: more than+ `SWEEP_DRAIN_GROWTH_FACTOR` × the best drain time seen so far on a rung that+ did drain, **and** more than `SWEEP_DRAIN_GROWTH_MIN_S` seconds worse in+ absolute terms. The absolute floor is what keeps 0.4 s → 0.9 s from reading+ as a knee.+3. **A queue depth or a buffer pending count failed to return to zero** — any+ `*_waiting_count` / `*_active_count`, or any `buffer_*_count`, that never+ reads 0 in any scrape at or after emit-end.++The first such rung is the knee. **The last rung before it is the max+sustainable throughput**, reported in events/second together with that rung's+api and worker CPU and RSS and its /track P50/P95/P99.++Two deliberate exclusions from clause 3:++- `*_delayed_count` is ignored. The cron queue permanently parks its next+ scheduled run there; a delayed job is steady state, not a backlog.+- "returned to zero" is asked of the **whole post-emit window**, not of the last+ scrape, because the cron queue picks up a scheduled job every minute+ regardless of load and a final scrape that lands on one is not a backlog.+ `*_failed_count` is reported as a delta over the run but is **not** a knee+ clause.++**A rung that fails to drain is a data point, not a harness error.** It is+recorded, the ladder stops climbing, and the sweep still exits 0. The sweep+exits non-zero only if it measured nothing at all. A rung that hangs is+SIGKILLed at `SWEEP_RUNG_TIMEOUT_MS` and recorded as `no-result`.++---++## What is sampled, at ≥1 Hz, for the whole run++| Source | What |+|---|---|+| `process-monitor.ts` (`/proc`) | api and worker RSS (kB→MB) and CPU% — peak and steady-state (median) |+| `lag-monitor.ts` (Kafka admin API) | consumer-group lag on the events topic — peak, lag at emit-end, seconds-to-zero after emit-end (`null` = still draining) |+| `metrics-monitor.ts` (`GET /metrics`) | per queue: `*_waiting_count`, `*_active_count`, `*_delayed_count`, `*_failed_count`. Per buffer: `buffer_*_count` pending, `buffer_event_pending_local_count`, and the run-deltas of `buffer_flush_rows_total`, `buffer_flush_duration_ms`, `buffer_ch_insert_duration_ms` |+| in-request | /track latency P50/P95/P99, **emit phase only** |++Queues covered on this tree: `sessions`, `cron`, `notification`, `import`,+`insights`, `gsc`, `cohortCompute`. Buffers: `event`, `event-pending-local`,+`profile`, `profile-backfill`, `session`, `replay`, `group`, `bot`.++Scraping was chosen over reaching into Redis or the buffer objects **because V1+exposes the same endpoint**: the identical sampler will work against V1 when the+comparison run happens, with no second implementation to keep honest.++---++## SMOKE RESULT — not a capacity claim++> **These numbers are not a benchmark.** They come from the bounded proof runs+> M16-001 ran to show the driver works. 20–100 sessions is far too small, the+> ladder is two rungs, and no rung ever saturated anything. They are recorded+> only so the harness's output shape is on the record and the next operator can+> tell a regression in the *tooling* from a change in the *system*.++**Labelling.** rev `8175c3f420ae5aaba327f9d6fbe6b7657d0b43d6` (`rewrite/v2`);+2026-09-12, ~07:00 UTC; 4 vCPU AMD EPYC-Milan, 15 GiB RAM, no swap, Linux+6.8.0-137; Bun 1.4.0; local single-node Postgres / Redis / ClickHouse /+Redpanda. All figures are **per process**, from `/proc/<pid>`, never whole-box.+RSS is in MB (uncompressed, resident). Latency is milliseconds, wall clock,+client-side round trip including the harness's own `fetch` overhead.++### The verification sweep — `SWEEP_RUNGS=2 E2E_SESSIONS=20 E2E_EVENTS_PER_SESSION=2`, auth path (c)++| rung | concurrency | ev/s | P50 | P95 | P99 | api CPU peak | api RSS peak | Kafka peak lag | drain | verdict |+|---|---|---|---|---|---|---|---|---|---|---|+| 1 | 25 | 519.5 | 29.7 ms | 51.5 ms | 53.5 ms | 23.0 % | 552 MB | 1 | 0.9 s | drained |+| 2 | 50 | 540.5 | 29.4 ms | 50.8 ms | 52.7 ms | 21.0 % | 550 MB | 1 | 0.9 s | drained |++Verdict printed: *knee NOT REACHED — every rung drained*. Correct, and exactly+why it is not a capacity number: at this size the whole emit phase finishes in+under 100 ms, which measures the harness's ramp, not the pipeline's ceiling. An+earlier identical sweep gave 347.8 and 459.8 ev/s for the same two rungs — a+~50 % spread on the same command, on the same tree, minutes apart. That spread+is the real message of this table.++It also exercised the "returned to zero" rule the knee depends on: rung 2 caught+the cron queue with `active=1` mid-scrape and `final=20`, and was still+correctly classified `drained`, because the rule asks the whole post-emit window+rather than the last scrape.++### The three auth paths — one rung each, concurrency 25, 100 sessions × 3 events++| path | ev/s | P50 | P95 | P99 | api CPU peak | api RSS peak |+|---|---|---|---|---|---|---|+| (a) `bypass` | 508.5 | 46.7 ms | 58.7 ms | 80.0 ms | 92.9 % | 636 MB |+| (b) `cors` | 550.5 | 43.9 ms | 49.0 ms | 67.4 ms | 73.9 % | 647 MB |+| (c) `secret` | 635.6 | 37.9 ms | 42.3 ms | 61.3 ms | 64.0 % | 630 MB |++**Read this as "no measurable auth-path delta at this size", not as "the secret+path is faster".** The ordering is monotonic in *run order*, not in work done,+which is the signature of a warming box rather than of a real effect; 300+requests per mode on a 4-vCPU box shared with the stack under test cannot+resolve a difference this small. The (a)↔(c) delta the sweep exists to isolate+needs the full operator run.++There is a mechanical reason to expect the delta to be small, which is worth+recording because it contradicts the premise the harness was commissioned under+("a cache round-trip per request that the bypass does not do"). **After the+first hit, neither cache in the auth path touches Redis.** `getCache` is called+with `useLruCache` and returns from a process-local LRU before any Redis call+(`packages/redis/cachable.ts:22-27`), and `getClientByIdCached` is a+`cacheablePerDb`, which holds its own L1 too. So within the 300 s TTL the extra+work the secret path does is one in-process map lookup, not a network round+trip. Whether that holds at 5,000 events/s — where the LRU's `max: 5000` is+shared across every `getCache` caller and eviction becomes possible — is+precisely what the full sweep would answer. **This is a finding, not a change:+no application source was touched.**++---++## What these numbers do NOT cover++- **No V1 comparison.** `verification/benchmarks/02-api-throughput.md` and+ `03-clickhouse-queries.md` are still BLOCKED with no V1 number. The comparison+ is a separate follow-on; `lindesvard/openpanel-api:2` is published, so V1 can+ be pulled as an image rather than built, and `main` is frozen at the fork point+ `663959db`, which makes it a clean comparator.+- **api and worker are the same process here.** The dev stack runs `ROLE=all`,+ and the verification command points `E2E_WORKER_URL` at the api's own port, so+ `process-monitor` resolves the same pid twice and the api and worker rows are+ **identical by construction**. They are not two independent measurements. To+ separate them, boot two processes (`ROLE=api` and `ROLE=worker`) on distinct+ ports and point `E2E_API_URL`/`E2E_WORKER_URL` at each.+- **Single node.** One Postgres, one Redis, one ClickHouse, one Redpanda, all on+ the same 4-vCPU box as the load generator and the API. Production is 2 shards ×+ 2 replicas (`/home/deploy/rewrite-openpanel/docs/ENVIRONMENT.md`). Nothing here+ is a Cloud per-node prediction, and the load generator competing for the same+ 4 cores is itself a ceiling.+- **Not a fixed-rate load test.** The driver ramps *concurrency*, so offered load+ is closed-loop: it falls as latency rises, which is the opposite of what an+ open-loop generator does at saturation. It finds the drain knee, which is what+ was asked for; it does not produce a "requests/s at fixed rate" curve.+- **Latency is emit-phase only** and includes client-side `fetch` overhead. It is+ not a server-side histogram; `http_request_duration_seconds` on `/metrics` is.+- **The 1 Hz `/metrics` scrape costs the measured process something.** It is+ ~2,700 lines per scrape. Set `E2E_NO_SAMPLING=1` for a control run to bound it.+- **Nothing here measures dashboard query performance**, ClickHouse read latency,+ or the heavy-query set in `03-clickhouse-queries.md`.+- **Never mix these figures with the image numbers** in+ `verification/benchmarks/04-images-and-boot.md`: those are compressed registry+ sizes and container-level RSS, these are per-process host RSS.