Skip to content

[Bug]: ThreadHandoff.start_ replays entire orchestration_events table from sequence 0 on startup, OOM-crashing backend every ~20 min #46286

Description

@cyppe

Before submitting

  • I searched existing issues and did not find a duplicate.
  • I included enough detail to reproduce or investigate the problem.

Area

apps/server

Summary / Root Cause

Introduced in #44774 (3f63afc1f80f, first shipped in v0.1.14-nightly.20261130.5479 and still present in v0.1.14-nightly.20261130.5492 / 801da69aafe4):

  1. ThreadHandoff.start_() replays the entire event log from sequence 0 on every startup while buffering all live events in an unbounded PubSub:

    • apps/server/src/peer/handoff/ThreadHandoff.ts:947-962 subscribes to threads.streamStoredEvents (already after lines 936–946 handled pending/departing shells from getShellSnapshot()).
    • apps/server/src/orchestration-v2/Orchestrator.ts:18262 defines streamStoredEvents as eventSink.stream() — with no afterSequence, no eventType, and no bounded: true (compare streamDomainEvents right below it, which starts at afterSequence: latest).
    • apps/server/src/orchestration-v2/EventSink.ts:1034-1078 defaults afterSequence to 0, subscribes to the unbounded liveEvents PubSub (line 1069), and returns Stream.concat(replay(highWater), live) (line 1075).
    • While replay(highWater) scans every historical event in orchestration_events from sequence 1 to highWater, live is never pulled, so all live events from active sessions accumulate in the unbounded PubSub subscription.
  2. ThreadHandoff.settle() loads full thread runs and user messages before checking whether the thread has a handoff:

    • apps/server/src/peer/handoff/ThreadHandoff.ts:880-886:
      const records = yield* threads.getThreadRecords(threadId, ["runs", "messages"], {
        messageRoles: ["user"],
      });
      const handoff = records.thread.handoff;
      if (handoff === undefined) return;
    • For every historical terminal run.updated event replayed since sequence 0, settle() runs ProjectionStore.readCanonicalProjection for runs + user messages even when 0 threads in the database have a handoff field.
  3. Result: infinite ~19–20 minute SIGABRT crash loop in Electron's shared 4 GiB V8 pointer-compression cage.

    • On a mature statev2.sqlite (15.7M rows in orchestration_events, including long-running threads with thousands of runs/messages), the replay cannot finish before the main thread + SQLite reader worker_threads exhaust Electron's process-wide 4 GiB V8 pointer-compression cage.
    • Once the shared 4 GiB cage fills, even a freshly spawned worker thread with only 2–3 MB of live heap hits FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory → node::OOMErrorHandler → abort() (SIGABRT).
    • The desktop process automatically restarts the backend 500 ms later (desktop.backendInstance.scheduleRestartFiber), which starts replaying from sequence 0 all over again, killing all active agent sessions every ~19–20 minutes.

Steps to reproduce

  1. Run T3 Code desktop v0.1.14-nightly.20261130.5479 or v0.1.14-nightly.20261130.5492 against an existing statev2.sqlite with a large orchestration_events history (millions of events) and long-running threads (thousands of runs/messages), with active provider sessions running.
  2. Observe server.trace.ndjson immediately after startup: OrchestrationEventStore.readAgentEvents and ThreadHandoff.settle → ProjectionStore.readCanonicalProjection run continuously (~8.5 calls/s) even though zero threads have handoff set.
  3. Watch backend child RSS / /proc/<pid>/smaps: the 4 GiB V8 pointer-compression cage climbs steadily to 4096 MiB and aborts with SIGABRT (~19 minutes in my environment), then restarts and loops indefinitely.

Expected behavior

  • ThreadHandoff.start_() should only watch new run.updated events after startup (e.g. starting from latestSequence() / using streamDomainEvents or streamStoredEventsFrom({ afterSequence: latest, eventType: "run.updated" })), since lines 936–946 already reconcile any pending/departing shells on startup.
  • ThreadHandoff.settle() should check thread.handoff via a lightweight lookup (e.g. getThreadShell or getThreadRecords(threadId, [])) before loading runs and messages.

Actual behavior

Backend child process (apps/server/dist/bin.mjs) enters an infinite ~19–20 minute SIGABRT OOM crash loop (4 crashes in 60 minutes, tearing down active agent sessions each time).

Impact

Blocks work completely

Version or commit

0.1.14-nightly.20261130.5492 (801da69aafe4); regression introduced in 0.1.14-nightly.20261130.5479 via #44774 (3f63afc1f80f).

Environment

  • Arch Linux (x86_64, 93 GiB RAM with ~39 GiB available, no kernel OOM kills)
  • T3 Code Desktop (t3code-nightly-bin AUR)
  • statev2.sqlite: 46.2 GiB, orchestration_events sequence 1..15,724,989, 19,892 threads (0 threads with handoff); largest thread has 4,686 runs / 12,166 messages / 46,822 turn items

Logs or stack traces

# 4 consecutive identical SIGABRT crashes every ~19-20 min after upgrading to 5492:
Mon 2026-11-30 19:16:40 CET 3081909 1000 1000 SIGABRT present /opt/t3code-nightly-bin/t3code 841.7M
Mon 2026-11-30 19:36:58 CET 3641391 1000 1000 SIGABRT present /opt/t3code-nightly-bin/t3code 843.3M
Mon 2026-11-30 19:56:28 CET 3873332 1000 1000 SIGABRT present /opt/t3code-nightly-bin/t3code 839.3M
Mon 2026-11-30 20:15:13 CET 4180684 1000 1000 SIGABRT present /opt/t3code-nightly-bin/t3code 822.7M

# /proc/4180684/smaps aggregated by 4 GiB address bucket, 42 seconds before crash:
0x1eeb_00000000: RSS=3942.9 MiB, VSZ=4096.0 MiB, regions=1276   <-- shared 4 GiB V8 pointer cage 96.3% full

# Top heap-growth spans in a single ~2-minute server.trace.ndjson rotation:
sql.transaction:                       count=648, sum=24837.9 MiB, max=225.7 MiB
ProjectionStore.readCanonicalProjection: count=472, sum=22972.2 MiB, max=223.0 MiB
OrchestratorV2.getThreadRecords:       count=462, sum=22042.6 MiB, max=165.9 MiB
ThreadManagementService.getThreadRecords: count=456, sum=21727.2 MiB, max=165.9 MiB
ThreadHandoff.settle:                  count=455, sum=21704.2 MiB, max=165.9 MiB
OrchestrationEventStore.readAgentEvents: count=662 (in fresh post-restart trace)

# server-child.log immediately before SIGABRT (PID 3873332):
OrchestratorProjectionError: Failed to load orchestration projection for thread <redacted>.
    at ProjectionStore.readCanonicalProjection (...)
    at OrchestratorV2.getThreadRecords (...)
    at ThreadManagementService.getThreadRecords (...)
    at ThreadHandoff.settle (...) {
  [cause]: ProjectionStoreReadError: ... {
    [cause]: effect/sql/SqlError: Failed to execute statement {
      [cause]: Error: Database reader failed: Worker terminated due to reaching memory limit: JS heap out of memory
    }
  }
}

<--- Last few GCs --->
[3873332:0x127007634000]      503 ms: Mark-Compact (reduce) 3.7 (37.2) -> 2.3 (5.2) MB, pooled: 0.0 MB, 4.06 / 0.00 ms last resort; GC in old space requested
[3873332:0x127007634000]      505 ms: Mark-Compact (reduce) 2.3 (5.2) -> 2.2 (3.5) MB, pooled: 0.0 MB, 1.55 / 0.00 ms last resort; GC in old space requested

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

# systemd-coredump stack trace of crashing worker thread (PID 3873332, TID 4178898):
#0  abort (libc.so.6)
#2  node::OOMErrorHandler(char const*, v8::OOMDetails const&) (t3code)
#15 v8::ValueDeserializer::ReadValue(v8::Local<v8::Context>) (t3code)
#16 node::worker::Message::Deserialize(...) (t3code)
#17 node::worker::MessagePort::ReceiveMessage(...) (t3code)
#18 node::worker::MessagePort::OnMessage(...) (t3code)
#23 node::worker::Worker::Run() (t3code)

# Crash 4 (PID 4180684, TID 4181535) hit the same OOM handler inside sqlite row extraction:
#0  abort (libc.so.6)
#2  node::OOMErrorHandler(char const*, v8::OOMDetails const&) (t3code)
#20 v8::String::NewFromUtf8(...) (t3code)
#21 node::sqlite::ExtractRowValues(...) (t3code)
#22 node::sqlite::StatementSyncIterator::Next(...) (t3code)

Workaround

Downgrading to 0.1.14-nightly.20261129.5452 (the last nightly before #44774; no DB migrations were added in 5479/5492) immediately stopped the crash loop and kept backend RSS flat at ~847 MiB with zero OrchestrationEventStore.readAgentEvents replay storm.

Activity

  1. alexskatell commented on Nov 30, 2026

    @alexskatell

    Confirming the exact same regression on macOS arm64 (Apple Silicon) — 6 JS heap OOM crashes in 5.5 hours (every 46–68 min) starting immediately after upgrading to v0.1.14-nightly.20261130.5479 and continuing on v0.1.14-nightly.20261130.5492 (0 crashes prior to .5479).

    Environment & observations

    • Platform: macOS arm64 (Mac Mini, ~34 GB RAM, machine.pressure all none)
    • DB: ~53 GiB statev2.sqlite with long-lived threads (~26k runs) and 0 active thread handoffs
    • Trace metrics (server.trace.ndjson):
      • 16 min before Crash feat: Cloud Agents #6: ThreadHandoff.settle ran 5,042 times (~315/min, 961.3s cumulative wall time, 259.8 GB cumulative positive heap growth, up to 397.7 MB/call).
      • First 19 min after restart: ThreadHandoff.settle ran 6,936 times (~365/min, 390.9 GB cumulative positive heap growth, up to 404.5 MB/call), pushing RSS past 3.9 GB within ~25 min.

    Both crash modes & compound collision with #45047

    Across the 6 .ips crash reports:

    • 4/6 crashes (Main thread): FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory at 2,604–3,045 MB heap inside MessagePort::OnMessage -> v8::ValueDeserializer::ReadValue (Mark-Compact (reduce) reclaiming <1 MB).
    • 2/6 crashes (fresh WorkerThread): OOM at only 19.8–21.9 MB heap (0.4s–4.0s worker uptime) inside MessagePort::OnMessage -> AsyncWrap::MakeCallback, consistent with the shared 4 GiB V8 pointer-compression cage being exhausted.
    • Compound trigger with #45047 (getTurnStartContext): In 3 of the 6 crashes, provider-turn.start logged Database reader failed: Worker terminated due to reaching memory limit: JS heap out of memory right before abort. In Crash feat: Cloud Agents #6's trace, an unfinished getTurnStartContext (projection_run_attempts +299.3 MB, ~435 MB across 4 tables) and an unfinished ThreadHandoff.settle (projection_messages +164.5 MB) were deserializing concurrently on the exact second of the abort.

    Notes for the fix & workaround

    • Fix ordering: In ThreadHandoff.start_(), capturing latestSequence before calling projections.getShellSnapshot() and subscribing from { afterSequence: latest } avoids missing a run.updated event between snapshot and subscription while eliminating the replay-from-0 storm and unbounded liveEvents buffering. In ThreadHandoff.settle(), a lightweight thread/shell check (handling missing/deleted threads cleanly) before getThreadRecords(threadId, ["runs", "messages"], ...) prevents full-history loads on non-handoff threads.
    • Workaround: v0.1.14-nightly.20261130.5465 (published 9 min before #44774 merged, with zero persistence/SQLite migrations added between .5465 and .5492) is the latest pre-regression nightly.
  2. alexskatell commented on Nov 30, 2026

    @alexskatell

    Thanks for the quick fix in #46293! One quick note: #46293 switches ThreadHandoff.start_() to streamDomainEvents (which stops the startup replay-from-0 storm), but ThreadHandoff.settle() (ThreadHandoff.ts:882) still loads all runs and user messages before checking records.thread.handoff === undefined. On large threads (~26k runs), every live turn completion still triggers a ~165–400 MB heap spike alongside #45047. Opened a focused follow-up issue to track that remaining half: #46314

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