perf(server): replay stored events about twice as fast #26719
main fromrefs/pull/26719/head·merged by juliusmarminge View on GitHubProblem#
Replaying stored orchestration events (readAgentEvents / readApplicationEvents) is slow for large threads: it powers projection rebuilds, EventSink catch-up, thread and shell resume, and command idempotency reads. Each row was validated twice (once from JSON, then the already-decoded event again as an OrchestrationV2StoredEvent), row JSON went through a Schema.fromJsonString(Unknown) wrapper, every row opened a named span that the always-on local file tracer wrote to the trace file (one large-thread replay wrote ~2 MB / 5.7k spans), and each page query waited until the previous page finished decoding.
Fix#
All in apps/server/src/persistence/OrchestrationEventStore.ts:
- Decode each event once; validate only the
{ sequence, commandId }header with the same field schemas (OrchestrationV2StoredEvent.mapFieldswithoutevent). - Parse row JSON with
JSON.parse; non-string or malformed input falls back to the existing schema decoder, so errors keep the exactSchemaError. rowToV2StoredEvent/rowToProjectEventuseEffect.fnUntraced(per-row work; the stream owns the span).- Install the unknown-event-type filter only when
skipUnknownEventTypesis set. Stream.bufferArray({ capacity: 1 })afterStream.paginate: the next page runs on the reader worker while the current page decodes (one page of read-ahead).
No wire, schema, or output change.
Measurements#
Harness: a script outside the repo imports the real ProjectionStore / EventStore layers over NodeSqliteClient.layer({ readerWorker: true }) on a migrated copy of a real database (27.6k events, 310 threads), with the production local file tracer installed as Observability.ts does. It times Stream.runCount(eventStore.read({ threadId })) (12 iterations, first 2 dropped, median) and counts allocated bytes as summed heap growth between GCs (v8.GCProfiler). Base (origin/main) and new runs are interleaved, 4 rounds each, on the same machine (macOS, Node 24.18, other load present).
| Thread | Events | Base median | New median | Base alloc | New alloc |
|---|---|---|---|---|---|
| A (production tracer) | 5,744 | 178 ms | 80 ms (2.2x) | 228 MB | 118 MB (−48%) |
| B (production tracer) | 5,079 | 153 ms | 72 ms (2.1x) | 200 MB | 111 MB (−45%) |
| A (no tracer) | 5,744 | 156 ms | 79 ms (2.0x) | 210 MB | 118 MB (−44%) |
Process CPU per replay (main + reader worker) drops 237 → 137 ms; the read-ahead overlaps worker time rather than removing it. What limits the new number: schema decoding of OrchestrationV2DomainEventJson itself (≈45% of main-thread time, including DateTimeUtcFromString), JSON.parse of payloads (≈15%), and the reader worker's page queries (~12 ms per replay).
Benchmark script (reads.ts + helpers)
// Bench: projection reads on a copy of real data (read-only use of the copy).
import { ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import { startAlloc } from "./alloc.ts";
import { tracerLayer } from "./tracer.ts";
const R = process.env.REPO!;
const ProjectionStore = await import(`${R}/apps/server/src/orchestration-v2/ProjectionStore.ts`);
const EventStore = await import(`${R}/apps/server/src/orchestration-v2/EventStore.ts`);
import * as Stream from "effect/Stream";
const db = NodeSqliteClient.layer({ filename: process.env.DB ?? "/tmp/orch-bench/real.sqlite", readerWorker: process.env.WORKER !== "0" });
const layer = Layer.mergeAll(ProjectionStore.layer, EventStore.layer).pipe(Layer.provideMerge(db));
const big = ThreadId.make(process.env.THREAD!);
const which = (process.env.ONLY ?? "window,full,shell,threadShell,replay").split(",");
const program = Effect.gen(function* () {
const ps = yield* ProjectionStore.ProjectionStoreV2;
const es = yield* EventStore.EventStoreV2;
const cases: Record<string, Effect.Effect<unknown, unknown>> = {
window: ps.getThreadSnapshotWindow(big, { rowLimit: 202, userTurnLimit: 10 }),
full: ps.getThreadSnapshot(big),
shell: ps.getShellSnapshot(),
threadShell: ps.getThreadShell(big),
replay: Stream.runCount(es.read({ threadId: big })),
};
for (const name of which) {
const eff = cases[name]!;
const ms: number[] = [], mb: number[] = [];
yield* eff; yield* eff; yield* Effect.sleep("400 millis"); const c0 = process.cpuUsage();
for (let r = 0; r < Number(process.env.ITER ?? 9); r++) {
const m = startAlloc(); const t0 = performance.now(); yield* eff; ms.push(performance.now() - t0); mb.push(m() / 1e6);
}
const c1 = process.cpuUsage(c0); yield* Effect.sleep("400 millis"); const c2 = process.cpuUsage(c0);
console.log("cpu/run(ms) excl-flush", ((c1.user + c1.system) / 1000 / ms.length).toFixed(1), "incl-flush", ((c2.user + c2.system) / 1000 / ms.length).toFixed(1));
const med = (x: number[]) => { const y = x.slice(2).sort((a, b) => a - b); return y[Math.floor(y.length / 2)]; };
console.log(name.padEnd(12), `${med(ms).toFixed(2)}ms`, `${med(mb).toFixed(2)}MB`, ms.slice(2).map((x) => x.toFixed(1)).join(" "));
}
});
await Effect.runPromise(Effect.scoped(program.pipe(Effect.provide(layer), Effect.provide(tracerLayer))) as never);
process.exit(0);
// alloc.ts
import v8 from "node:v8";
// Allocated bytes = heap growth between GCs, summed (GCProfiler reports before/after each GC).
export function startAlloc() {
globalThis.gc?.();
const startUsed = process.memoryUsage().heapUsed;
const prof = new v8.GCProfiler();
prof.start();
return () => {
const endUsed = process.memoryUsage().heapUsed;
const { statistics } = prof.stop() as { statistics: Array<{ beforeGC: { heapStatistics: { usedHeapSize: number } }; afterGC: { heapStatistics: { usedHeapSize: number } } }> };
let prev = startUsed, total = 0;
for (const s of statistics) { total += s.beforeGC.heapStatistics.usedHeapSize - prev; prev = s.afterGC.heapStatistics.usedHeapSize; }
return total + endUsed - prev;
};
}
// tracer.ts
// Production-like tracing: server always installs the local file tracer (Observability.ts).
import * as Layer from "effect/Layer";
import * as Tracer from "effect/Tracer";
import * as References from "effect/References";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { makeLocalFileTracer } from "@t3tools/shared/observability";
export const tracerLayer = process.env.TRACE === "0" ? Layer.empty : Layer.mergeAll(
Layer.effect(Tracer.Tracer, makeLocalFileTracer({ filePath: "/tmp/orch-bench/trace/server.trace.ndjson", maxBytes: 10 * 1024 * 1024, maxFiles: 10, batchWindowMs: 200 })),
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
Layer.succeed(References.TracerTimingEnabled, true),
).pipe(Layer.provide(NodeServices.layer));
Validation#
vp run check:changed: format, lint, knip, typecheck, tests all pass.vp test runonOrchestrationEventStore.test.ts,OrchestrationEventStore.sequence.test.ts,ProjectionRecovery,TurnItemCompaction,FoundationPersistence,ProjectionStore,ThreadStream,boundedSnapshotTransport,LiveStreamBudget,EffectWorker,Orchestrator.control-reads,ws.test.ts,runtimeLayer.test.ts: all pass.- Differential harness (old vs new module on the same database copy):
readAgentEvents(all,skipUnknownEventTypes, per-thread withafterSequence/limit) andreadApplicationEvents(with and without skip) return deep-equal events. Nine corrupted-row variants (bad payload JSON, bad metadata JSON, unknown event type, invalid payload,nullmetadata, wrong metadata type, blankcommand_id, BLOB payload, bad project payload) produce identical exits (samePersistenceDecodeError/SchemaErrorcause) and the same emitted prefix before the failure.
Not checked: replays on Windows/Linux file systems, and databases larger than the 27.6k-event copy.
Authored with Claude Opus 5.5 via the Claude Code harness in T3 Code.
🤖 Generated with Claude Code
- 1
- 2
- 3
Pushed56baa5b
Evidence#
Generated one synthetic Replay (dev) thread through the real app, completed 184 follow-up turns without failures, and replayed the identical 5,746-event snapshot on both commits. Same Mac, macOS 26.6.2 arm64, Node 26.13.1, production file tracing and heap attribution enabled. Six alternating rounds, 60 measured replays per side after warmups.
Before After 977b7c7932 56baa5b7df 

Median 176.9 ms; range 171.0–198.5 ms Median 82.7 ms; range 78.8–88.4 ms Approximate allocation 207.8 MB/replay Approximate allocation 109.3 MB/replay Head was 2.14× faster. The 94.2 ms median improvement exceeds either side's full measured spread, and the ranges do not overlap. All decoded event counts and full-output SHA-256 hashes matched. All twelve runtime error/compatibility captures matched. The first 14-replay process emitted 80,444 rowToV2StoredEvent spans on base and zero on head.
Measurement output · Raw timings · Runtime error comparison · Raw process captures
Benchmark driver · All reproduction scripts and instructions
Not shown:
- The author's exact 5,744-event and 5,079-event datasets and larger 310-thread database were unavailable; this proof used 5,746 synthetic agent events generated through the real app.
- The measurement used Node 26.13.1 rather than the author's Node 24.18. Allocation captures approximate main-isolate allocation; they do not measure total process or worker allocation.
- Measured the replay-service action used by triage, not full-server startup or client rendering latency.
juliusmarminge added labelstakeover:ready
juliusmarminge removed labelstakeover:in-progress
juliusmarminge merged this9292b03
juliusmarminge closed this
juliusmarminge removed labelstakeover:ready
Sign in to join this conversation.
coderabbitai[bot](GitHub profile, opens in a new tab) reviewed
e8e93cb8-f33c-4d62-aec9-d74de0f4ebacReviewing files that changed from the base of the PR and between 6dfe2f64e9130c361a0a7c560700d3b7f003222f and 56baa5b7dfdf0ad21337ed87d8678bd977704d34.
apps/server/src/persistence/OrchestrationEventStore.tsIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.