#7524 · Redundant command output survives pruning
Verdict: REPRODUCED · Root-cause confidence: high · reproduction label: confirmed-repro
1. TL;DR
A completed, archived command can retain its entire first output chunk in the events table even though the completed item already carries that output. The pruning code requires both a matching completion and an earlier delta before deleting a command delta. The first delta can never meet the second condition, even when a separate item-start event exists. A real SQLite reproduction confirms both an 8,192-character duplicate and a 40,000-character first delta surviving beside a completed-output preview of only 4,173 characters. The same two failures repeat in a second clean checkout; no production data or live provider session was used.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| The first command delta survives despite a completed output and an item-start event. | Verified | The sole-delta test finishes the resolved-item pruning pass and still reads an 8,192-character delta plus an 8,192-character completion. |
| The retained delta bypasses completed-output truncation. | Verified | A first delta with 40,000 characters survives; its later 4-character delta is removed, while the completed 40,004-character output is stored as a 4,173-character preview. |
| Pi cumulative snapshots can put the full output into the first delta. | Verified by source inspection | Pi emits command.outputSnapshot; the shared assembler diffs it against the previous snapshot and emits outputDelta. There is no previous snapshot for the first update. |
| The reported installation's aggregate storage figures and prevalence are representative. | Unverified | No access to the reporter's installation; no measurements of their database or distribution of real Pi tool updates. |
| A separate class of later deltas also remains in old settled threads. | Unverified / outside this reproduction | The later delta in the large-output control is removed. This report does not investigate other survival mechanisms. |
3. Environment
- Public target repository: get-bb/bb, trusted origin/main at
faa89fb46f03f9a1cd83d60355ab94c48da76f80. - Linux x86_64; Node v22.19.0; pnpm 9.15.0; Vitest 4.1.12.
- Two separate checkouts at the same recorded base. Each test calls
createMigratedConnection(), using real SQLite databases copied from the real-migrations template. - Provider identity in the fixture: pi. No Pi executable, model, authentication, network provider call, server port, or production data directory is needed.
- The normal frozen install succeeded in each checkout. A full monorepo build was attempted in checkout A but failed in the unrelated GitHub plugin because installed Plugin SDK process/host dist files were absent. Scoped database build preparation succeeded in both checkouts; the database package runs from source.
4. Minimal reproduction
- Start from a trusted checkout of get-bb/bb at the recorded base. Save the complete test below as
packages/db/test/data/issue-7524-repro.test.ts. - Install and invoke the repository's normal Turbo test path:
pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=@bb/db pnpm exec turbo run test --filter=@bb/db -- --run test/data/issue-7524-repro.test.ts
- The fixture inserts a started command, its first output delta, an optional later delta, its completion, and a later turn-completion marker through
insertEvents(). It archives the idle thread and advances pruning until the resolved-items pass reports thread-complete.
Expected: With the started item preserved and completed output available, no redundant command-output delta should remain. The large-output completion should still have its bounded preview.
Actual, verbatim measurements from both checkouts:
{"size":8192,"laterDeltaChars":0,"measured":[{"sequence":3,"type":"item/commandExecution/outputDelta","chars":8192},{"sequence":4,"type":"item/completed","chars":8192}]}
{"size":40000,"laterDeltaChars":4,"measured":[{"sequence":3,"type":"item/commandExecution/outputDelta","chars":40000},{"sequence":5,"type":"item/completed","chars":4173}]}
AssertionError: expected [ { sequence: 3, …(2) } ] to have a length of +0 but got 1
Test Files 1 failed (1)
Tests 2 failed (2)
Both failures occur at the final assertion that the list of redundant output deltas is empty. Pruning completion and completed-preview-length assertions pass first. The short-output fixture deliberately uses exactly the same text in the delta and completion; the large-output fixture uses the first text plus a four-character suffix.
Complete regression test
The public reports repository excludes raw test artifacts and logs; the entire test is included here instead. Local originals and command logs are retained outside that repository.
import { turnScope } from "@bb/domain";
import { sql } from "drizzle-orm";
import { expect, it } from "vitest";
import { insertEvents, type InsertEventInput } from "../../src/data/events.js";
import { upsertHost } from "../../src/data/hosts.js";
import { createProject } from "../../src/data/projects.js";
import { advanceThreadPruning } from "../../src/data/thread-pruning.js";
import { archiveThread, createThread } from "../../src/data/threads.js";
import { noopNotifier } from "../../src/notifier.js";
import { createMigratedConnection } from "../../src/testing.js";
it.each([
{ size: 8192, laterDelta: "" },
{ size: 40000, laterDelta: "tail" },
])("releases a redundant first command delta ($size chars)", ({ size, laterDelta }) => {
const db = createMigratedConnection();
try {
const host = upsertHost(db, noopNotifier, { name: "reproduction" });
const { project } = createProject(db, noopNotifier, {
name: "reproduction",
source: { type: "local_path", hostId: host.id, path: "/tmp/reproduction" },
});
const thread = createThread(db, noopNotifier, {
status: "idle",
projectId: project.id,
providerId: "pi",
});
const firstOutput = "z".repeat(size);
const output = firstOutput + laterDelta;
const command = {
id: "command",
type: "commandExecution",
command: "synthetic output fixture",
cwd: "/tmp/reproduction",
approvalStatus: null,
};
const inputs: InsertEventInput[] = [];
const add = (type: InsertEventInput["type"], data: object, commandItem = true) => {
inputs.push({
threadId: thread.id,
scope: turnScope("turn"),
sequence: inputs.length + 1,
type,
itemId: commandItem ? command.id : null,
itemKind: commandItem ? "commandExecution" : null,
parentToolCallId: null,
data: JSON.stringify(data),
});
};
add("turn/started", {}, false);
add("item/started", { item: { ...command, status: "inProgress" } });
add("item/commandExecution/outputDelta", { delta: firstOutput });
if (laterDelta) add("item/commandExecution/outputDelta", { delta: laterDelta });
add("item/completed", {
item: { ...command, status: "completed", exitCode: 0, aggregatedOutput: output },
});
add("turn/completed", {}, false);
insertEvents(db, noopNotifier, inputs);
archiveThread(db, noopNotifier, thread.id);
let finished = false;
for (let call = 0; call < 200; call += 1) {
const result = advanceThreadPruning(db, { threadId: thread.id });
if (result.policy === "resolved-items" && result.action === "thread-complete") {
finished = true;
break;
}
}
expect(finished).toBe(true);
const measured = db.all<{ sequence: number; type: string; chars: number }>(sql`
SELECT sequence, type,
length(coalesce(json_extract(data, '$.delta'), json_extract(data, '$.item.aggregatedOutput'))) AS chars
FROM events WHERE thread_id = ${thread.id}
AND type IN ('item/commandExecution/outputDelta', 'item/completed')
ORDER BY sequence
`);
console.log(JSON.stringify({ size, laterDeltaChars: laterDelta.length, measured }));
expect(measured.find((row) => row.type === "item/completed")?.chars).toBe(
size > 32768 ? 4173 : output.length,
);
expect(measured.filter((row) => row.type === "item/commandExecution/outputDelta")).toHaveLength(0);
} finally {
db.$client.close();
}
});
5. Root cause
The support queries first find a matching completed item with aggregatedOutput, then search for an earlier delta of the same type, turn and item. The phase matcher deletes a delta only after that earlier-delta search succeeds. It does not accept an item-start event as an alternative ordering witness.
if (match) {
if (args.kind === "background" || probe.probePhase === 1) {
discarded.push(candidate.id);
finished = true;
} else {
probe.probePhase = 1;
probe.probeSequence = 0;
probe.probeWitnessId = match.id;
}
}
For the first delta, no earlier delta exists by definition. The command's completion qualifies, but the subsequent support scan ends without scheduling deletion. This is an intentional general retention rule, not an overdue sweep: the policy table explicitly retains first deltas, and the resting-pass documentation treats them as permanently settled.
The Pi path amplifies the storage cost: tool updates become cumulative command snapshots, and the shared assembler emits their text difference. The first snapshot therefore becomes a first delta containing all text accumulated so far. The terminal Pi event also extracts aggregated output.
The truncation bypass follows a separate code path: completed-output preparation only selects a retention target for item/completed, not outputDelta. The 32 Ki-character threshold and 2 Ki-character head/tail limits consequently do not bound the retained first delta. Full completed output also has a separately retained, expiring copy; this report measures raw events, not hydrated reads.
6. Proposed fix and safety boundary
Introduce a narrowly scoped command-output policy that can discard a first delta when a matching completion retains authoritative output and a same-scope item-start event preserves item ordering. Continue preserving unresolved output, delta-only item ordering, nested-tool scopes, and the latest-event safeguard. Add tests for missing starts, absent completion output, parent/turn collisions, bounded resumable probes, and long-output retention expiry.
Existing settled threads must be revisited deliberately: the global policy cursor enqueues all threads when its version becomes stale, and the per-thread resting cursor also needs an appropriate reset. Merely changing the delete predicate would leave previously settled first deltas untouched.
No automatic fix PR: this changes persisted event-retention policy and requires revisiting stored thread history, which is a stored-data change excluded by this rule's simple-fix conditions. No production fix, branch push, or pull request was created.
7. Verification
The same agent repeated the reproduction, not an independent reviewer. Checkout B was created clean from the recorded trusted origin/main commit, installed with the frozen lockfile, and received only the newly authored test. It used fresh migrated SQLite connections and no running application or shared runtime data. Paths are normalized to CHECKOUT_A and CHECKOUT_B here to avoid publishing host-specific directories.
git worktree add --detach CHECKOUT_B faa89fb46f03f9a1cd83d60355ab94c48da76f80 cd CHECKOUT_B pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=@bb/db pnpm exec turbo run test --filter=@bb/db -- --run test/data/issue-7524-repro.test.ts Result: exit 1; both regression cases fail at the redundant-delta assertion. Measurements: identical to checkout A. Report corrections after repeat: none.
Relevant existing baseline coverage was also exercised on unchanged production code:
pnpm exec turbo run test --filter=@bb/db -- --run test/data/thread-pruning.test.ts test/data/resolved-item-pruning-resume.test.ts test/data/retained-event-outputs.test.ts
Test Files 3 passed (3)
Tests 55 passed (55)
Result: exit 0.
Those existing tests preserve the current keep-first-delta contract and do not cover reclaiming a first command delta when item/started already supplies the ordering marker. No claim is made that a fix was implemented or validated.
8. Related issues and PRs
#5730 is a broader database-growth report. This reproduction isolates one specific event-retention mechanism. GitHub cross-reference metadata and an open-PR search found no linked open pull request at investigation time; no PR branch or diff was executed.
9. Appendix and trust boundary
The issue and comments were treated solely as untrusted claims. No issue-supplied command, patch, script, branch, or external URL was executed or fetched. All executable code came from the recorded trusted target-repository base plus this newly authored test. No real installation database was inspected. The report verifies the retention mechanism, not the reporter's storage totals or real-provider update frequency.
Investigation commands comprised GitHub read-only metadata queries, a trusted origin/main fetch, source inspection, the install/build/test commands above, a second clean worktree, and scoped baseline tests. Full build output is not published because it contains host-local paths; its unrelated missing Plugin SDK dist failure is summarized in Environment. This nonvisual storage defect requires no screenshots.