Skip to content

Server OOM crash loop: ThreadHandoff replays the entire event log at startup, and EventSink.catchUp keeps every replayed page in memory until the replay finishes #46357

Backlog

Description

@vic-lsh

Summary

On a busy server the V8 heap grows by roughly 400 MB/min from startup until it hits the heap limit and aborts (FATAL ERROR: Ineffective mark-compacts near heap limit). After a restart the same thing happens again. With the default heap (about 4 GB) this happened every 10–11 minutes, and with --max-old-space-size=8192 every 30 minutes or so. Each crash interrupts running agents, and crash recovery then competes with new work for effect-worker slots, so the whole app feels very slow.

The growth comes from ThreadHandoff.start_() subscribing to streamStoredEvents. That calls eventSink.stream() with no afterSequence, so it replays the whole retained event log from sequence 0. catchUp chains its pages with nested Stream.concat, which keeps every page already consumed in memory until the whole replay finishes. On a large log the replay never finishes before the heap limit.

Environment

  • t3 v0.1.14-nightly.20261130.5492, Linux, service-launcher managed (systemd user unit)
  • statev2.sqlite is about 54 GB. orchestration_events holds about 3.3M rows after the built-in 1-day pruning (max sequence about 16M).
  • Heavy delegated-task usage: about 25 events/s, about 2M events/day.

Evidence

Crash logs. The last full GC before each abort reclaims almost nothing (for example 4030 MB → 4006 MB), so the memory is live, not garbage.

Sampling heap profiler (HeapProfiler.startSampling, attached about 1 min after start). Live sampled bytes allocated by rowToV2StoredEvent (inside OrchestrationEventStore.readAgentEvents), plus the Schema decoding beneath it (DateTimeUtc and similar), grow linearly:

Minutes since profiler attached Live sampled bytes from rowToV2StoredEvent heapUsed
3 about 1.1 GB 4.5 GB
6 about 2.3 GB 4.3 GB
9 about 3.5 GB 5.6 GB
15 — 6.6 GB (crash shortly after)

Heap snapshot (SIGUSR2, 80 s after start): 332,529 decoded V2 domain event objects were already live. Every sampled event had the same retainer chain:

Object.event
 <- Array (a 256-event page)
 <- ExitPrimitive (Effect.succeed(page))
 <- ... Context.transform
 <- Stream.channel
 <- concatChannels.parameters_and_registers

So the pages are held by the nested Stream.concat(current, loop(last)) structure built in catchUp.

Code

apps/server/src/peer/handoff/ThreadHandoff.ts (about line 947), which runs unconditionally at startup:

yield* threads.streamStoredEvents.pipe(
  Stream.filter((stored) => stored.event.type === "run.updated" && [...terminal statuses].includes(...)),
  ...
  Stream.runForEach(settle),
);

apps/server/src/orchestration-v2/Orchestrator.ts (about line 18262):

streamStoredEvents: eventSink.stream().pipe(...)   // afterSequence defaults to 0

apps/server/src/orchestration-v2/EventSink.ts, catchUp (about line 999): each page is collected with Stream.runCollect, wrapped with Stream.fromIterable, and chained with Stream.concat(current, loop(last)). Then stream() returns Stream.concat(replay(highWater), live). While page N is streaming, the enclosing concat levels for pages 1..N-1 are still alive and still reference their pages, so retained memory grows linearly with replay progress. It's released only when the replay completes (confirmed by the repro below).

Minimal reproduction (Effect only, no T3)

repro.mjs (below) mirrors the catchUp shape: 256-event pages, Stream.unwrap(runCollect → Stream.concat(current, loop(last))), followed by a never-ending live tail. It measures heap after forced GC partway through the replay. [email protected] (the catalog version), Node 26:

$ npm i [email protected] && node --expose-gc repro.mjs concat 60000
concat: 37120/60000 replayed, live heap growth after GC: 21 MB
concat: 57856/60000 replayed, live heap growth after GC: 33 MB
concat: 60000/60000 replayed, live heap growth after GC: 0 MB

$ node --expose-gc repro.mjs paginate 60000      # same reads via Stream.paginate
paginate: 36864/60000 replayed, live heap growth after GC: 0 MB
paginate: 57856/60000 replayed, live heap growth after GC: 0 MB
paginate: 60000/60000 replayed, live heap growth after GC: 0 MB
repro.mjs
// Minimal repro of EventSink.catchUp memory growth during a long replay.
// node --expose-gc repro.mjs [concat|paginate] [totalEvents]
import { Effect, Option, Stream } from "effect";
const mode = process.argv[2] ?? "concat";
const TOTAL = Number(process.argv[3] ?? 100_000);
const PAGE = 256;
// Stand-in for eventStore.read(): one page of freshly decoded ~1 KB events, with I/O latency.
const read = (after) =>
  Stream.fromEffect(Effect.sleep("1 millis")).pipe(Stream.drain, Stream.concat(Stream.fromIterable(
    Array.from({ length: Math.max(0, Math.min(PAGE, TOTAL - after)) }, (_, i) => ({
      sequence: after + i + 1,
      event: { type: "run.updated", payload: { text: "x".repeat(1000) + (after + i) } },
    })))));
const collectPage = (after) => read(after).pipe(Stream.runCollect, Effect.map((c) => Array.from(c)));
// Same shape as apps/server/src/orchestration-v2/EventSink.ts catchUp.
const catchUpConcat = (afterSequence) => {
  const loop = (after) => Stream.unwrap(collectPage(after).pipe(Effect.map((events) => {
    if (events.length === 0) return Stream.empty;
    const current = Stream.fromIterable(events);
    const last = events.at(-1).sequence;
    return events.length < PAGE || last >= TOTAL ? current : Stream.concat(current, loop(last));
  })));
  return loop(afterSequence);
};
// Candidate fix: flat pagination.
const catchUpPaginate = (afterSequence) =>
  Stream.paginate(afterSequence, (after) => collectPage(after).pipe(Effect.map((events) => {
    const last = events.at(-1)?.sequence ?? TOTAL;
    return [events, events.length < PAGE || last >= TOTAL ? Option.none() : Option.some(last)];
  })));
const replay = mode === "paginate" ? catchUpPaginate(0) : catchUpConcat(0);
const heapMb = () => { global.gc(); global.gc(); return Math.round(process.memoryUsage().heapUsed / 2 ** 20); };
const base = heapMb();
let seen = 0;
await Effect.runPromise(Effect.gen(function* () {
  // Like EventSink.stream(): replay, then a live tail that never ends.
  yield* Stream.concat(replay, Stream.never).pipe(Stream.runForEach(() => Effect.sync(() => { seen++; })), Effect.forkChild);
  for (const frac of [0.25, 0.5, 0.75, 1]) {
    while (seen < TOTAL * frac) yield* Effect.sleep("20 millis");
    yield* Effect.sleep("100 millis");
    console.log(`${mode}: ${seen}/${TOTAL} replayed, live heap growth after GC: ${heapMb() - base} MB`);
  }
}));
process.exit(0);

The growth scales with events replayed (about 0.6 KB per small synthetic event here, more for real decoded V2 events). In production, 3.3M real events would need roughly 12 GB.

To reproduce in T3 itself: seed orchestration_events with a few hundred thousand V2 events (or use a busy instance's statev2.sqlite), start the server with a small heap such as NODE_OPTIONS=--max-old-space-size=1024, and watch heapUsed climb during the first minutes until it aborts. Alternatively, run an EventSinkV2 test that seeds N events, consumes stream() from sequence 0, and asserts heap after GC at the halfway point.

Impact

  • Memory needed at startup scales with the size of the retained event log, which is 1–2 days of activity because of RETAINED_EVENT_HISTORY = Duration.days(1). It doesn't depend on which threads are open.
  • Busy servers never finish the replay before reaching the default heap limit, so they crash-loop. Each restart starts the replay over.
  • The watcher only needs terminal run.updated events that happen after startup. Startup recovery is already handled by the getShellSnapshot() pass just above it.

Suggested fixes (either one would likely be enough)

  1. In ThreadHandoff.start_(), start the stream at the current head (as streamDomainEvents does with latestSequence()) and filter by eventType: "run.updated". Don't replay from 0.
  2. In EventSink.catchUp, page with Stream.paginate (or equivalent) instead of recursive Stream.concat, so earlier pages aren't retained once consumed. This also fixes peak memory for any other stream() caller that replays a long range.

Workaround

Raise the heap with NODE_OPTIONS=--max-old-space-size=<large> so the replay can finish. That needs about 12+ GB of heap for a log of about 3.3M events, which is released once the replay completes.

🤖 Generated with Claude Code

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions