Skip to content

Opening a thread with repeated nested delegation messages exhausts the server heap (exponential timeline expansion) #5210

Closed

Description

@iipanda

Summary

Opening one Codex thread in bb 0.45.0 crashes the desktop app. The server builds the thread's timeline and runs out of JavaScript heap at about 4 GB. Before the crash, the same request logged RangeError: Invalid string length from JSON.stringify inside timeline pagination.

The cause is in the timeline projection. When the same delegation message id appears more than once in a thread's projected messages, each copy is attached as a separate child of its parent delegation. Every copy then expands its own descendants again, so the rendered tree grows exponentially with nesting depth. In the affected thread, 2,348 message contexts would expand to about 8.34 million rendered messages.

Versions and environment

  • bb desktop 0.45.0, macOS 26, Apple Silicon. Also reproduced in a unit test on main at f135a00.
  • Provider: Codex. The thread has about 77,000 events and about 70 MiB of stored event payloads, with nested agent delegations.

Steps to reproduce

The private thread is not shareable, so the smallest faithful reproduction is a unit test against normalizeEventProjection on main:

  1. Add this test in packages/thread-view/test/ (delegation(id, parentToolCallId) builds a completed spawn_agent delegation whose callId equals its id):

    const messages: EventProjectionMessage[] = [delegation("root")];
    for (let depth = 1; depth <= 5; depth++) {
      const parent = depth === 1 ? "root" : `child-${depth - 1}`;
      const child = delegation(`child-${depth}`, parent);
      messages.push(child, { ...child }, { ...child });
    }
    const ids = messagesIn(normalizeEventProjection(projection(messages))).map(
      (message) => message.id,
    );
  2. Run pnpm exec turbo run test --filter=@bb/thread-view -- normalize-event-projection.

Expected vs actual

Expected: six messages, root, child-1, child-2, child-3, child-4, child-5, one per message id, using each id's latest state.

Actual on f135a00:

AssertionError: expected [ Array(364) ] to deeply equal [ 'root', 'child-1', 'child-2', …(3) ]

364 = 1 + 3 + 9 + 27 + 81 + 243: each repeated level multiplies everything beneath it.

In the app, opening the affected thread does this:

RangeError: Invalid string length
    at JSON.stringify (<anonymous>)
    at omittedRows (.../bb-app/server/dist/start-server.js:69298:45)
    at paginateTimelineRows (.../bb-app/server/dist/start-server.js:69338:12)

This is logged 30 times on GET /api/v1/threads/<thread>/timeline, followed by three crashes (EXC_CRASH SIGABRT, Allocation failed - JavaScript heap out of memory, heap about 4,053 MiB).

Evidence

  • Where the duplicates multiply: SemanticProjectionBuilder attaches every context whose parentToolCallId names a delegation, without deduplicating by message id:
    constructor(contexts: SemanticMessageContext[]) {
    const referencedParentCallIds = new Set(
    contexts
    .map((context) => context.message.parentToolCallId)
    .filter((id): id is string => id !== undefined),
    );
    for (const context of contexts) {
    if (
    context.message.kind === "tool-call" &&
    (referencedParentCallIds.has(context.message.callId) ||
    isLegacyDelegationToolCall({
    tool: context.message.toolName,
    presentation: context.message.presentation,
    }))
    ) {
    context.message = toolCallAsDelegationMessage(context.message);
    }
    }
    const delegationCallIds = new Set(
    contexts
    .map((context) => context.message)
    .filter(isDelegationSourceMessage)
    .map((message) => message.callId),
    );
    for (const context of contexts) {
    const parentToolCallId = context.message.parentToolCallId;
    if (!parentToolCallId || !delegationCallIds.has(parentToolCallId)) {
    continue;
    }
    const children = this.childrenByParentCallId.get(parentToolCallId) ?? [];
    children.push(context);
    this.childrenByParentCallId.set(parentToolCallId, children);
    this.attachedMessageIds.add(context.message.id);
    }
    this.rootContexts = contexts.filter(
    (context) =>
    !this.attachedMessageIds.has(context.message.id) &&
  • Why the failure is a crash rather than a rejected response: pagination serializes the whole update subtree before comparing it with the byte budget, so a huge subtree allocates a huge string first:
    const omittedRows = (
    omittedContentSourceSeqEnd: number | null,
    windowStart: number,
    ): Pick<
    PaginatedTimelineRowsResult,
    "olderRowUpdates" | "olderRowsSourceSeqEnd"
    > => {
    const omitted = rows.filter(
    (row) =>
    row.sourceSeqStart < args.ownedSequenceEnd && !returnedRows.has(row.id),
    );
    const changed =
    page.kind === "latest"
    ? omitted.filter((row) => row.sourceSeqEnd >= windowStart)
    : [];
    const updates = changed.map((row) =>
    timelineRowChangesFrom(row, windowStart),
    );
    const reported =
    Buffer.byteLength(JSON.stringify(updates)) > remainingBytes
    ? []
    : changed;
  • Offline replay of the affected thread's last 20,000 events (18,965 after compaction) through the installed 0.45.0 server code: 2,348 message contexts, 2,247 unique ids, 10 repeated ids, up to 25 copies of one id, and about 8.34 million predicted rendered messages. With contexts deduplicated by message id, the replay returned 34 rows in 0.13 s using about 176 MB of heap.

What I ruled out

Suggested fix

A patch on my fork has fixed the affected thread locally:

  1. Deduplicate within each delegation's children. Keep one child per message id under each parent delegation, holding the latest state in the first occurrence's position. Root messages are left alone, so a later turn that reuses a call id still keeps its own item. A global "latest copy per id" dedupe breaks the existing timeline-in-turn-window test for exactly that case.
  2. Measure the byte budget incrementally. In paginateTimelineRows, add up each row's size and stop as soon as the budget is exceeded, rather than calling JSON.stringify on the whole subtree first.

An earlier version of this patch, which deduplicated globally, loaded the affected thread's latest timeline using about 315 MB in a packaged build. The scoped version above passes the full @bb/thread-view suite (462 tests) and the server timeline tests (167). It adds regression tests for repeated nested delegations, latest-state selection, unchanged distinct messages, and exact byte accounting, including multi-byte and escaped text. I'll open it as a PR once this is acknowledged.

Suggested priority: high for affected users. The app crash-loops whenever the thread is opened, and the only workaround is to avoid that thread. No data is lost.

AGENT GENERATED

Activity

  1. added theissue type on Oct 8, 2026
  2. added
    threads
    confirmed-repro
    on Oct 8, 2026
  3. bb-slop-cop commented on Oct 8, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Type Bug, Priority High, Effort Medium; area labels threads, perf.
    • Reproduction and root-cause report: REPRODUCED, root-cause confidence high; reproduction label confirmed-repro.
    • A repository-derived regression fails on trusted origin/main (f135a001e) in two clean checkouts: 29 input contexts / 15 unique ids expand to 85 messages. The fixture typechecks.
    • Root cause: duplicate children remain attached to each parent delegation, and every copy recursively expands the same descendants. Pagination also serializes whole update subtrees before checking the byte budget.
    • Limits: the private-thread macOS crash, exact heap peak, and provider source of duplicate contexts were not replayed.
    • No new PR: open #5211 already links this issue; a duplicate fix PR is not safe.

    AGENT GENERATED

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

    confirmed-reproperfthreads

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions