← reports

#7399 · Outline reuse gaps on busy threads

Bug Priority: Medium Effort: Medium threads perf partial-repro

GitHub issue · 2026-11-10 · Base f241192234ed3ca14d121c36f37e43b7447951ec

PARTIALLY REPRODUCED · Root-cause confidence: high for the two measured replay paths

1. TL;DR

Some busy-thread changes still cause full outline history replay on trusted main. Changing only the supplied thread status from active to idle reselected all 3,000 synthetic event rows, versus three rows on a warm active load. Appending one manager message to a thread containing only manager messages reselected all 1,001 rows. However, the broad claim that there is no incremental builder is false on this base: appending a completed turn to 1,000 completed turns selected only six rows. These database-only reproductions establish avoidable synchronous work, not the reported production latency distribution, multi-megabyte payloads, or browser skeleton duration.

2. Claims vs findings

ClaimFindingEvidence
Outline sequence and thread status invalidate the stored outline.VerifiedBoth fields are in the persisted projection key. The same key builder, with sequence zero, also keys the incremental checkpoint; status changes invalidate that checkpoint.
Active revisions are not materialized.Verified, with qualificationOnly idle/error loads write the stored row. An outer route response cache and an incremental in-process cache still serve active threads.
Every stored miss rebuilds the whole history; there is no incremental build.Refuted as a general claimThe incremental builder is called on a miss. A 3,003-event completed-turn history selected only six rows after an append.
Busy threads can replay the full history repeatedly.Verified in two bounded casesStatus-only transition: 3,000 rows. Manager-only history plus one new message: 1,001 rows. Both replay contracts failed in both clean checkouts.
Repeated identical opens of an active thread always rebuild.Not supportedThe HTTP route returns a cached response when its key matches. The service's warm completed-turn load also selected only three rows.
Reported multi-megabyte outlines, event counts, network timings and visible loading duration.UnverifiedNo access to the reporter's runtime data; no browser or connect session used. Synthetic outputs were approximately 0.30–0.36 MB.

3. Environment

4. Minimal reproduction

  1. Clone trusted main and pin the tested commit:
    git clone --branch main https://github.com/get-bb/bb.git bb-7399-a
    cd bb-7399-a
    git checkout --detach f241192234ed3ca14d121c36f37e43b7447951ec
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@get-bb/plugin-sdk
    pnpm exec turbo run build --filter=@bb/server
  2. Save the complete test below as apps/server/test/services/threads/outline-7399-repro.test.ts. It instruments the real SQLite driver to count selected event rows; it does not replace query results. The status case changes the thread object passed to the service without changing events, isolating status-based invalidation.
  3. Run:
    pnpm exec turbo run test --filter=@bb/server -- test/services/threads/outline-7399-repro.test.ts --silent=false
  4. Expected performance invariant: appends and a status-only change should not reread a settled prefix (fewer than 25 event rows in these fixtures). Actual result on unchanged production code, in both checkouts:
    AssertionError: expected 3000 to be less than 25
    AssertionError: expected 1001 to be less than 25
    Tests  2 failed | 1 passed (3)

The row-count threshold is deliberately generous relative to the six-row successful append control. It is not a wall-clock timing assertion. The test proves an unbounded history-read shape rather than requiring a particular machine speed.

Complete reproduction test (copy into the path above)
import { performance } from "node:perf_hooks";
import { describe, expect, it } from "vitest";
import {
  getLatestStoredConversationOutlineSequence,
  getLatestThreadSequence,
} from "@bb/db";
import { loadThreadConversationOutline } from "../../../src/services/threads/timeline.js";
import {
  appendRows,
  withTestThread,
  type RowSpec,
  type TestThread,
} from "../../helpers/timeline-cache-fixture.js";

function measure(testThread: TestThread, label: string) {
  const raw = testThread.db.$client;
  const originalPrepare = raw.prepare;
  let selectedRows = 0;
  raw.prepare = function (source: string) {
    const statement = originalPrepare.call(raw, source);
    if (source.includes('from "events"') && source.includes('"created_at"')) {
      const originalAll = statement.all.bind(statement);
      statement.all = function (...params: unknown[]) {
        const rows = originalAll(...params);
        selectedRows += rows.length;
        return rows;
      };
    }
    return statement;
  };
  const started = performance.now();
  try {
    const threadId = testThread.thread.id;
    const result = loadThreadConversationOutline(testThread.db, testThread.thread, {
      completedTurnDisplay: "collapse",
      includeClearedContextHistory: false,
      maxSeq: getLatestThreadSequence(testThread.db, { threadId }),
      outlineSequence: getLatestStoredConversationOutlineSequence(testThread.db, {
        threadId,
      }),
    });
    const observation = {
      label,
      selectedRows,
      items: result.items.length,
      bytes: Buffer.byteLength(JSON.stringify(result.items)),
      elapsedMs: Math.round(performance.now() - started),
    };
    console.log(JSON.stringify(observation));
    return observation;
  } finally {
    raw.prepare = originalPrepare;
  }
}

function turn(index: number): RowSpec[] {
  const turnId = `repro-turn-${index}`;
  return [
    { type: "turn/started", turnId },
    {
      type: "item/completed",
      turnId,
      itemId: `repro-message-${index}`,
      itemKind: "agentMessage",
      data: {
        item: {
          id: `repro-message-${index}`,
          type: "agentMessage",
          text: "Synthetic completed response. ".repeat(10),
        },
      },
    },
    { type: "turn/completed", turnId, data: { status: "completed" } },
  ];
}

describe("outline reuse across busy-thread changes", () => {
  it("appends to completed history without replaying the prefix", () => {
    withTestThread((testThread) => {
      appendRows(testThread, Array.from({ length: 1000 }, (_, index) => turn(index)).flat());
      measure(testThread, "completed-cold");
      appendRows(testThread, turn(1000));
      expect(measure(testThread, "completed-append").selectedRows).toBeLessThan(25);
    });
  });

  it("retains completed history across a status-only transition", () => {
    withTestThread((testThread) => {
      appendRows(testThread, Array.from({ length: 1000 }, (_, index) => turn(index)).flat());
      measure(testThread, "status-cold-active");
      measure(testThread, "status-warm-active");
      testThread.thread = { ...testThread.thread, status: "idle" };
      expect(measure(testThread, "status-idle").selectedRows).toBeLessThan(25);
    });
  });

  it("does not replay notification-only history after an append", () => {
    withTestThread((testThread) => {
      const notification: RowSpec = {
        type: "system/manager/user_message",
        data: { text: "Synthetic manager update. ".repeat(10) },
      };
      appendRows(testThread, Array.from({ length: 1000 }, () => notification));
      measure(testThread, "notifications-cold");
      appendRows(testThread, [notification]);
      expect(measure(testThread, "notifications-append").selectedRows).toBeLessThan(25);
    });
  });
});

5. Root cause

Status invalidates both cache layers

The key builder includes both outline sequence and thread status. A stored miss calls the incremental projection with the same key builder, passing zero for sequence. Sequence advances therefore do not inherently invalidate that inner checkpoint, but a status change does. The reuse check requires equal keys and otherwise starts from the empty checkpoint:

entry.key === args.key
...
let checkpoint = canReuseEntry && ... ? entry.checkpoint : empty;

This explains the warm three-row load followed by a full 3,000-row load when only status changes. The work runs inside runEventLoopWorkSync, so synchronous history selection, decoding and projection delay other work in that process.

Turn-free history never advances the checkpoint

Checkpoint construction advances its boundary through turn-start/completion bookkeeping. Thread-scope manager messages skip this logic:

if (event.scope.kind !== "turn") continue;
...
if (boundary <= previous.sequenceStart) return previous;

A manager-only fixture never creates a nonempty reusable checkpoint. A new message changes the route and stored projection keys, so the next service load selects the entire history again. This is a particularly clear instance of a broader concern: turn-boundary checkpoints cannot bound an indefinitely growing turn-free tail. The experiment does not prove that every mixed coordinator history has the same behavior.

Important qualifications

The HTTP route's response cache returns a matching response before calling this service; unchanged active opens do not necessarily rebuild. Idle/error-only materialization is real, but not equivalent to the absence of active-thread caching. The existing incremental implementation also predates this report: incremental outlines landed October 2, 2026, and a further projection improvement landed November 9, 2026.

6. Proposed fix and simple-fix assessment

Preserve a status-independent, demonstrably settled prefix while rebuilding the status-dependent tail; define safe checkpoints for thread-scope messages between turns. Validate prefix reuse against full projection through active/idle/error transitions, pending requests, late child events, rewinds and context clears. Persisting a resumable projection across restarts is a separate concern: the current stored JSON is an exact response, not the incremental builder's checkpoint state.

No pull request opened. Simply removing status from the key is not a proven-safe repair: status controls pending-message preservation and projection finalization. Correctly splitting stable and mutable history requires checkpoint-design work, not a safe key deletion. Pagination changes the public response contract; adding resumable stored checkpoint state changes stored data. Neither is eligible for the authorized simple-fix path. No production edits, branch push or PR were attempted. No linked open PR was found in issue cross-references or the open-PR search at investigation time.

7. Related issues

8. Verification

The same agent repeated the reproduction, not an independent reviewer. Checkout A was a detached worktree at the full base SHA. Checkout B was a second freshly created detached worktree at the identical SHA, with its own frozen install and successful SDK/server builds. Before copying the authored test, Checkout B had unchanged tracked production files. Each test invocation created new temporary migrated SQLite fixtures and removed them afterward. No ports or persistent data directories were needed.

git worktree add --detach ../bb-7399-b f241192234ed3ca14d121c36f37e43b7447951ec
cp apps/server/test/services/threads/outline-7399-repro.test.ts ../bb-7399-b/apps/server/test/services/threads/
cd ../bb-7399-b
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@get-bb/plugin-sdk --filter=@bb/server
pnpm exec turbo run test --filter=@bb/server -- test/services/threads/outline-7399-repro.test.ts --silent=false

Both executions exited with code 1 for the intended two row-budget failures. The append control passed in both. No report claim required correction after the second completed run. An early second-checkout command was issued before install had completed and could not find Turbo; it did not execute tests and is not counted as a reproduction.

ScenarioCheckout A rowsCheckout B rowsCheckout B elapsed / payload
Cold 1,000 completed turns3,000 (status fixture)3,000116 ms / 359,781 bytes (append fixture)
Append completed turnUnder 25 (passed)69 ms / 360,143 bytes
Warm, unchanged active status335 ms / 359,781 bytes
Status-only active → idle3,0003,00057 ms / 359,781 bytes
Append manager message to 1,000 manager messages1,0011,00127 ms / 301,196 bytes

Timings are illustrative measurements from this synthetic run, not a reproduction of production percentiles. Counts include event reads returning created-at data; they do not count all SQL work or all rows internally scanned by SQLite.

Relevant existing suites passed on unchanged production code:

pnpm exec turbo run test --filter=@bb/server -- test/services/threads/conversation-outline-incremental.test.ts test/services/threads/conversation-outline-performance.test.ts

conversation-outline-performance.test.ts (6 tests)
conversation-outline-incremental.test.ts (32 tests)
Test Files  2 passed (2)
Tests  38 passed (38)

9. Appendix

Second clean-run measurement lines, verbatim:

{"label":"completed-cold","selectedRows":3000,"items":1000,"bytes":359781,"elapsedMs":116}
{"label":"completed-append","selectedRows":6,"items":1001,"bytes":360143,"elapsedMs":9}
{"label":"status-cold-active","selectedRows":3000,"items":1000,"bytes":359781,"elapsedMs":86}
{"label":"status-warm-active","selectedRows":3,"items":1000,"bytes":359781,"elapsedMs":5}
{"label":"status-idle","selectedRows":3000,"items":1000,"bytes":359781,"elapsedMs":57}
{"label":"notifications-cold","selectedRows":1000,"items":1000,"bytes":300894,"elapsedMs":32}
{"label":"notifications-append","selectedRows":1001,"items":1001,"bytes":301196,"elapsedMs":27}

Evidence collection also used git fetch origin main, git rev-parse origin/main, file reads at the recorded base, file-scoped git log, issue Type/field/label reads, issue cross-reference reads, and gh pr list --repo get-bb/bb --state open --search '7399'. A final fetch found no later main changes to the inspected outline paths. git diff --check passed; no tracked production files changed. Full raw local logs are retained privately; the complete runnable reproduction and relevant output are inline here, following this public report repository's artifact policy.

Trust boundary: issue text and comments were used only as untrusted claims. Suggested changes were evaluated against trusted source; no issue-supplied script, branch, patch, or external URL was executed or fetched.

> AGENT GENERATED