← reports

#5210 · Delegation snapshots duplicate descendant trees

BugHighEffort: Mediumthreadsperfconfirmed-reproGitHub issueOctober 8, 2026 · base f135a001e72942cee9118d2693208ec0725e2f18

Verdict: REPRODUCED · Root-cause confidence: high for the projection amplification mechanism. The private-thread desktop crash and its specific heap size were not replayed.

1. TL;DR

A timeline can become much larger than its stored message contexts when nested delegations have repeated snapshots. The projection builder attaches every matching snapshot as a separate child, then recursively builds the same descendants beneath each snapshot. A synthetic branching tree with 29 contexts and 15 distinct message ids produces 85 messages instead of 15 on unchanged main. Two separate clean checkouts give the same result. The server also serializes omitted update subtrees before checking their byte budget, which cannot prevent that serialization allocation; the reported desktop out-of-memory event itself remains unverified here.

2. Claims vs findings

ClaimStatusEvidence
Repeated nested delegation contexts multiply descendants.VerifiedBoth runs return 5, 21 and 85 messages for 3, 7 and 15 logical ids at depths 1, 2 and 3.
The fault remains on current main.VerifiedTrusted origin/main was fetched at f135a001e72942cee9118d2693208ec0725e2f18; production source was unchanged in both runs.
Pagination checks the byte budget after whole-subtree serialization.Verified by source inspectiontimeline-pagination.ts:175–178 calls JSON.stringify(updates) inside Buffer.byteLength before the comparison.
The user's private thread crashes a macOS desktop process at a specific heap size.UnverifiedNo private thread or macOS desktop data was accessed. No intentional heap exhaustion was performed.
The specific private replay expands to millions of messages.UnverifiedThe growth mechanism is confirmed, not the private dataset's counts.
A provider or ingest path creates the repeated snapshots.UnverifiedThis test starts at the typed projection boundary and does not establish the origin of duplicate contexts.

3. Environment

4. Minimal reproduction

The reproduction below was authored from the repository's projection types and implementation. It is not the issue's test or a pull-request test. Each non-root logical delegation has a pending and a completed snapshot; two distinct children branch from each parent. The observable contract is one child per identity, preserving distinct sibling order and selecting the final state.

  1. Clone and prepare the trusted base:
    git clone https://github.com/get-bb/bb.git bb-5210
    cd bb-5210
    git fetch origin main
    git checkout --detach f135a001e72942cee9118d2693208ec0725e2f18
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build
  2. Save the complete test in the expandable test section as packages/thread-view/test/issue-5210-expansion.test.ts. The report is self-contained; no separate test download is required.
  3. Run the regression against unchanged production code:
    pnpm exec turbo run typecheck --filter=@bb/thread-view
    pnpm exec turbo run test --filter=@bb/thread-view --force -- test/issue-5210-expansion.test.ts

Expected: 3, 7 and 15 messages for depths 1, 2 and 3; each identity appears once under its parent with completed status and output. Actual: 5, 21 and 85 messages; all three cardinality assertions fail. Exit status: 1, as expected for this bug reproduction. Typecheck passes.

@bb/thread-view:test: {"depth":1,"inputContexts":5,"uniqueInputIds":3,"normalizedMessages":5}
@bb/thread-view:test: {"depth":2,"inputContexts":13,"uniqueInputIds":7,"normalizedMessages":21}
@bb/thread-view:test: {"depth":3,"inputContexts":29,"uniqueInputIds":15,"normalizedMessages":85}
@bb/thread-view:test: AssertionError: expected [ 'message-leader', …(4) ] to deeply equal [ 'message-leader', …(2) ]
@bb/thread-view:test: AssertionError: expected [ 'message-leader', …(20) ] to deeply equal [ 'message-leader', …(6) ]
@bb/thread-view:test: AssertionError: expected [ 'message-leader', …(84) ] to deeply equal [ 'message-leader', …(14) ]
@bb/thread-view:test:  Test Files  1 failed (1)
@bb/thread-view:test:       Tests  3 failed (3)

Binary branching alone yields 2level logical nodes. With two retained snapshots per child, the builder instead yields 4level expanded nodes. At depth 3: input contexts = 1 + 2 × (2 + 4 + 8) = 29; expected messages = 1 + 2 + 4 + 8 = 15; actual messages = 1 + 4 + 16 + 64 = 85.

Evidence is included inline: regression test and the run evidence. Raw logs remain local, outside the public reports repository.

Complete reproduction test
import { describe, expect, it } from "vitest";
import type {
  EventProjection,
  EventProjectionDelegationMessage,
  EventProjectionMessage,
} from "../src/event-projection-types.js";
import { getProjectionEntryMessages } from "../src/event-projection-flatten.js";
import { normalizeEventProjection } from "../src/normalize-event-projection.js";

function emptyProjection(): EventProjection {
  return {
    state: {
      activeThinking: null,
      activeWorkflows: [],
      activeBackgroundCommands: [],
    },
    entries: [],
  };
}

function makeSnapshot(
  callId: string,
  sequence: number,
  status: "pending" | "completed",
  parentToolCallId?: string,
): EventProjectionDelegationMessage {
  return {
    kind: "delegation",
    id: `message-${callId}`,
    threadId: "synthetic-thread",
    sourceEvent: { seq: sequence, part: 0 },
    sourceSeqStart: sequence,
    sourceSeqEnd: sequence,
    createdAt: sequence,
    scope: { kind: "turn", turnId: "synthetic-turn" },
    toolName: "Task",
    callId,
    childRef: null,
    background: false,
    output: status === "completed" ? "done" : "",
    completedAt: status === "completed" ? sequence : null,
    status,
    childProjection: emptyProjection(),
    ...(parentToolCallId === undefined ? {} : { parentToolCallId }),
  };
}

function collectMessages(
  projection: EventProjection,
): EventProjectionMessage[] {
  return projection.entries.flatMap((entry) =>
    getProjectionEntryMessages(entry).flatMap((message) => [
      message,
      ...(message.kind === "delegation"
        ? collectMessages(message.childProjection)
        : []),
    ]),
  );
}

describe("delegation snapshot cardinality", () => {
  it.each([1, 2, 3])(
    "keeps each logical child once with its final state in a branching tree of depth %i",
    (depth) => {
      const input = emptyProjection();
      const expectedIds: string[] = [];
      let sequence = 0;
      const appendBranch = (
        callId: string,
        remainingDepth: number,
        parentToolCallId?: string,
      ): void => {
        expectedIds.push(`message-${callId}`);
        const statuses: ("pending" | "completed")[] =
          parentToolCallId === undefined
            ? ["completed"]
            : ["pending", "completed"];
        for (const status of statuses) {
          sequence += 1;
          input.entries.push({
            kind: "projected-message",
            message: makeSnapshot(callId, sequence, status, parentToolCallId),
          });
        }
        if (remainingDepth > 0) {
          appendBranch(`${callId}-left`, remainingDepth - 1, callId);
          appendBranch(`${callId}-right`, remainingDepth - 1, callId);
        }
      };
      appendBranch("leader", depth);
      const actual = collectMessages(normalizeEventProjection(input));
      console.log(
        JSON.stringify({
          depth,
          inputContexts: input.entries.length,
          uniqueInputIds: expectedIds.length,
          normalizedMessages: actual.length,
        }),
      );
      expect(actual.map((message) => message.id)).toEqual(expectedIds);
      expect(
        actual.every(
          (message) =>
            message.kind === "delegation" &&
            message.status === "completed" &&
            message.output === "done",
        ),
      ).toBe(true);
    },
  );
});

5. Root cause

The normalizer's parent-attachment loop appends every context to an array keyed only by parent call id. The attached-id set suppresses root items; it does not deduplicate the children.

const children = this.childrenByParentCallId.get(parentToolCallId) ?? [];
children.push(context);
this.childrenByParentCallId.set(parentToolCallId, children);
this.attachedMessageIds.add(context.message.id);

Each retained child is then passed through recursive semantic expansion. A repeated delegation call id looks up the same descendants again, producing a new expanded subtree for every copy. This work and allocation happens before the response budget can reject any content.

entries: contexts.map((context) => ({
  kind: "projected-message",
  message: this.toSemanticMessage(context.message),
}))

const childProjection = this.buildFlatChildProjection(
  this.childrenByParentCallId.get(message.callId) ?? [],
);

buildDetailedProjection calls this normalizer in the normal projection path. The server's omitted-row pagination check is an additional allocation risk:

const reported =
  Buffer.byteLength(JSON.stringify(updates)) > remainingBytes
    ? []
    : changed;

This serializes the complete updates array before deciding it is too large. An already-enormous tree may exhaust memory or string capacity here. The exact desktop abort, heap peak and private input distribution are not established by this bounded test.

6. Proposed fix

At the attachment boundary, key child contexts by both parent call id and message identity. Replace a child's earlier context with its final context while keeping its first position; keep different child identities intact. Avoid a global identity deduplication that could collapse call-id reuse across root turns. The repository already has a later-turn call-id reuse test for that constraint.

Separately, measure serialized row shells and child-array overhead incrementally and stop once the remaining byte budget is exceeded. Verify exact UTF-8 and escaping accounting at the pagination boundary. This prevents whole-update serialization, but is not a universal heap ceiling: individual row payloads and earlier projection allocation still need their own bounds.

7. Linked PR review

PR #5211 — static review only

GitHub metadata confirms an open, ready PR against main with a closing reference to #5210. Its diff changes five files, including parent-scoped child replacement in normalize-event-projection.ts and incremental row-budget measurement in the server. These changes target the two source-level mechanisms identified above. The added tests cover repeated delegation snapshots and byte accounting.

Findings: No definite defect in the scoped child-replacement logic was established by this static inspection. The row-budget helper still serializes individual row shells, so its claim should remain limited to avoiding whole-subtree serialization; arbitrary payload-size protection is not demonstrated here. This is a scope limitation, not a verified blocker.

Verdict: Root-cause-aligned by static inspection; runtime effectiveness and full compatibility not verified. Only the trusted-base regression and trusted-base typecheck were run. No PR branch, patch or test was checked out or executed. No duplicate fix PR was created.

8. Related issues

#4162 concerns server heap policy and diagnostics. That could help detect excessive allocation, but cannot correct the child-attachment amplification established here. This is context from repository metadata, not a second issue investigation.

9. Verification

The same agent repeated the reproduction in a second clean checkout; this is a repeat, not an independent review. Checkout B was created with git worktree add --detach ../verify f135a001e72942cee9118d2693208ec0725e2f18, showed an empty git status before the authored test was copied, and received a separate frozen install. The focused test used --force so Turbo executed it rather than replaying a cached failure.

pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@bb/thread-view
pnpm exec turbo run test --filter=@bb/thread-view --force -- test/issue-5210-expansion.test.ts

The scoped build has no build task in this source-only package; Turbo still builds declared test dependencies. Both checkouts produced the same counts and the same three intended assertion failures, with unchanged production code. The final artifact typechecks. An initial authored fixture omitted the required scope kind; that fixture typo was corrected before the final two logged runs. No report finding changed.

10. Appendix and trust boundary

The issue and linked PR were treated as untrusted evidence. No instructions, commands or code from either were executed. The repro was written after reading trusted main's exported projection types and attachment logic. No private runtime data, credentials or live application instance was read. All source links identify the recorded trusted commit.

Final two runs and validation

Checkout A — trusted base, production unchanged; test exit status 1:
{"depth":1,"inputContexts":5,"uniqueInputIds":3,"normalizedMessages":5}
{"depth":2,"inputContexts":13,"uniqueInputIds":7,"normalizedMessages":21}
{"depth":3,"inputContexts":29,"uniqueInputIds":15,"normalizedMessages":85}
 Test Files  1 failed (1)
      Tests  3 failed (3)

Checkout B — separate clean checkout at the same base; test exit status 1:
{"depth":1,"inputContexts":5,"uniqueInputIds":3,"normalizedMessages":5}
{"depth":2,"inputContexts":13,"uniqueInputIds":7,"normalizedMessages":21}
{"depth":3,"inputContexts":29,"uniqueInputIds":15,"normalizedMessages":85}
 Test Files  1 failed (1)
      Tests  3 failed (3)

pnpm exec turbo run typecheck --filter=@bb/thread-view — exit status 0:
 Tasks:    1 successful, 1 total
Cached:    0 cached, 1 total
  Time:    4.198s

pnpm exec turbo run build — exit status 0:
 Tasks:    65 successful, 65 total
Cached:    4 cached, 65 total
  Time:    1m45.873s

Reproduction test SHA-256, identical in both checkouts:
1b28395f84cf46695396a98b841f9c2465a78e69993e12dee488a04c8957dec6

No fix branch was pushed and no new pull request was opened because PR #5211 already links this issue. No servers or other persistent processes were started.