Skip to content

Read large diagnostic payloads as timeline pages need them - #8500

Open
lanjak wants to merge 1 commit into
get-bb:mainfrom
lanjak:fix-8302-bound-timeline-turn-reads
Open

lanjak wants to merge 1 commit into
get-bb:mainfrom
lanjak:fix-8302-bound-timeline-turn-reads

Conversation

@lanjak

@lanjak lanjak commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Human comments

What was wrong

The standard timeline loaded large raw diagnostic payloads for a whole turn before it knew which rows would fit on the page. Applying the byte floor to the turn itself changes collapsed summaries and can drop context.

What changed

Project large unhandled diagnostic events with their metadata. The page sizer reads the raw payload only when it needs the exact size of that row. The timeline still returns the full detail for rows on the page. It keeps all event sequences, turn context and scrollback cursors. Model fallbacks and item-completion events keep their full data during projection.

How you verified

On Linux x64 with Node 22.23.5, run from the repo root after installing workspace dependencies.

pnpm exec turbo run test --filter=@bb/server -- timeline-scrollback-byte-budget.test.ts -t 'diagnostic payload'

To reproduce on base 5b6a9962635b96a87b2c354d0a03d28caa1b78f3, copy the regression test file and run the same command. Both cases failed the read budget on base and pass on this branch. They walk all pages of a turn with 700 diagnostics of 16 KiB each in flat and collapsed views and check each payload and sequence, the final reply, and the collapsed summary count.

Separate flat fixture (700 diagnostics, 150-event window, no assistant reply) Base PR
Largest event payload read during a page build 11,568,924 bytes 2,564,474 bytes
Unique diagnostic rows across pages 700 700

Timeline HTTP request timing

Median full-response time in milliseconds, with min and max in brackets. Each result uses 16 timed requests over two runs per revision. The response byte counts, row counts and page endpoints match across revisions.

Diagnostics per turn Display Base PR
700 Flat 91.5 [81.5-105.6] 71.9 [65.6-85.2]
700 Collapsed 43.7 [38.5-57.6] 26.5 [22.7-33.6]
10,000 Flat 822.2 [707.5-974.0] 343.3 [324.1-375.1]
10,000 Collapsed 823.6 [651.1-955.8] 271.4 [251.9-357.4]

The fixture starts BB on a loopback port. It seeds an archived turn with 16 KiB per diagnostic and enables diagnostic rows. Requests use deferContent=true and vary the segment limit to miss the timeline cache. Timing stops before JSON parsing. This measures cold full-response time on synthetic data. The production heap failure remains unverified.

Runnable HTTP fixture

Save the fixture as apps/server/test/services/threads/timeline-audit-http.test.ts. Run the command twice on base 5b6a9962635b96a87b2c354d0a03d28caa1b78f3 and twice on PR head 3d6820b700d77f4decdb7755004d451a02d92e7c. Pool the eight ms samples from each TIMELINE_AUDIT line by revision, diagnostic count and display.

pnpm exec turbo run test --force --filter=@bb/server -- timeline-audit-http.test.ts --silent=false
import { archiveThread, getAppSettings, setAppSettings } from "@bb/db";
import { type TimelineRow } from "@bb/server-contract";
import { expect, it } from "vitest";
import { seedThreadFixture } from "../../helpers/seed.js";
import { startTestServer } from "../../helpers/test-app.js";

it("measures cold timeline reads over HTTP", async () => {
  const harness = await startTestServer();
  try {
    for (const count of [700, 10_000]) {
      for (const display of ["flat", "collapse"] as const) {
        setAppSettings(harness.db, {
          ...getAppSettings(harness.db),
          showDiagnosticEvents: true,
          providerCompletedTurnDisplay: { codex: display },
        });
        const { thread } = seedThreadFixture(harness, {
          thread: { providerId: "codex", status: "idle" },
        });
        archiveThread(harness.db, harness.hub, thread.id);
        const insert = harness.db.$client.prepare(`
          INSERT INTO events (id, thread_id, sequence, scope_kind, turn_id, type, data, created_at, provider_thread_id)
          VALUES (?, ?, ?, 'turn', 'audit-turn', ?, ?, ?, 'audit-provider')
        `);
        const timestamp = Date.now();
        const put = (sequence: number, type: string, data: string) =>
          insert.run(
            `${thread.id}-${sequence}`,
            thread.id,
            sequence,
            type,
            data,
            timestamp,
          );
        const payload = "x".repeat(16 * 1024);
        harness.db.$client.transaction(() => {
          put(1, "turn/started", "{}");
          put(
            2,
            "item/completed",
            JSON.stringify({
              item: {
                type: "agentMessage",
                id: "intro",
                text: "Running checks",
              },
            }),
          );
          for (let index = 0; index < count; index += 1) {
            put(
              index + 3,
              "provider/unhandled",
              JSON.stringify({
                providerId: "codex",
                rawType: "fixture/diagnostic",
                rawEvent: {
                  jsonrpc: "2.0",
                  method: "fixture/diagnostic",
                  params: { index, payload },
                },
              }),
            );
          }
          put(
            count + 3,
            "item/completed",
            JSON.stringify({
              item: { type: "agentMessage", id: "answer", text: "Finished" },
            }),
          );
          put(count + 4, "turn/completed", '{"status":"completed"}');
        })();

        const measurements = [];
        for (let index = 0; index < 10; index += 1) {
          const url = `${harness.baseUrl}/api/v1/threads/${thread.id}/timeline?deferContent=true&segmentLimit=${20 + index}`;
          const start = performance.now();
          const response = await fetch(url);
          const text = await response.text();
          expect(response.status, response.ok ? undefined : text).toBe(200);
          const elapsed = performance.now() - start;
          const body = JSON.parse(text) as { rows: TimelineRow[] };
          expect(body.rows.length).toBeGreaterThan(0);
          expect(text).toContain("Finished");
          const topRows = body.rows.map((row) => [
            row.kind,
            row.sourceSeqStart,
            row.sourceSeqEnd,
            row.kind === "turn" ? row.summaryCount : null,
          ]);
          if (index >= 2)
            measurements.push({
              ms: Number(elapsed.toFixed(2)),
              bytes: Buffer.byteLength(text),
              rows: topRows.length,
              first: topRows[0],
              last: topRows.at(-1),
            });
        }
        console.log(
          "TIMELINE_AUDIT",
          JSON.stringify({ count, display, measurements }),
        );
      }
    }
  } finally {
    await harness.close();
  }
}, 120_000);

Also ran 54 focused server tests, 819 database tests, 566 thread-view tests, and typecheck and type-aware lint.

Docs: Timeline settings, response fields and cursor format are unchanged. The fixture reproduces the read cost. It does not attribute the production heap failure.

Fixes #8302

AGENT GENERATED

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Thread timeline can materialize a whole diagnostic-heavy turn before enforcing its byte cap

1 participant