#7523 · File-change lifecycle retains duplicate diff payloads
Verdict: REPRODUCED · Root-cause confidence: high · Reproduction label: confirmed-repro
1. TL;DR
A completed pi file edit leaves the same unified diff in two database event rows: the pending item and its completion. The pi translator carries the original file-change shape through both lifecycle stages, and the shared assembler builds a full diff for each event. Database ingestion persists both payloads; none of the existing maintenance policies removes or compacts this pair. A new regression test reproduces that storage behavior for both edit and write through the real translator, assembler, migrated SQLite database, and all four pruning policies. The same test fails for the same reason in a second clean trusted checkout. This verifies the duplication mechanism, not the reporter's private database sizes or macOS installation.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| Pi file changes carry identical changes in start and completion rows. | Verified | Both edit and write produce two persisted rows with equal serialized changes; each row contains a complete diff. |
| The extra copy survives completion and maintenance. | Verified | Both rows remain after every pruning policy reaches cycle-complete in each fresh database. |
| Pending diffs are useful before the operation completes. | Verified at the event boundary | The test checks a pending row with the full diff before issuing the completion event. Approval UI behavior was not exercised. |
| One installation uses about 0.44 GB for these rows. | Unverified | No access to the reporter's database. This reproduction uses synthetic 128-line changes and proves duplicate payload retention, not those totals. |
| The reported desktop and pi CLI versions exhibit the issue. | Unverified version-specific claim | Tested current trusted source on Linux, without launching the desktop app or a pi CLI process. |
| Other providers may have the same behavior. | Unverified | The assembler is shared, but this reproduction drives only the pi translation path. |
| Removing a started row is safe for every reader. | Not established | All readers and lifecycle/cursor semantics have not been audited; no blanket deletion is proposed as a safe autopilot patch. |
3. Environment
- Trusted base:
faa89fb46f03f9a1cd83d60355ab94c48da76f80, fetched from origin/main. The legacy origin repository name resolves to the publicget-bb/bbrepository. - Linux x86_64, Node
v22.19.0, pnpm9.15.0, Vitest4.1.12. - Pi provider package
bb-plugin-provider-pi@0.1.0; declared pi coding-agent dependency0.84.4. Only the source translator runs; no live model/provider process or credentials are used. - Each case uses
createMigratedConnection(): a fresh real in-memory SQLite database copied from the real migrations template. No production runtime data is used. - Two separate temporary git worktrees at the identical base commit, with separate frozen installs. No server, port, or app data directory is needed.
4. Minimal reproduction
- Obtain the trusted source and build its existing dependencies:
git clone https://github.com/get-bb/bb.git bb-repro cd bb-repro git checkout --detach faa89fb46f03f9a1cd83d60355ab94c48da76f80 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build build:types --filter=@get-bb/plugin-sdk pnpm exec turbo run build
- Save the complete test below as
packages/db/test/data/slopcop-7523.test.ts. It synthesizes valid pi lifecycle events from the trusted translator's schemas; it does not execute any command or code supplied by the issue. - Run:
pnpm exec turbo run test --force --filter=@bb/db -- test/data/slopcop-7523.test.ts
Expected: preserve the pending diff while the operation is open, preserve the completed diff afterward, and retain only one stored diff after completion and maintenance. The last assertion therefore expects one diff-bearing row. Actual: two full identical copies survive. The expected regression failure is:
AssertionError: expected [ Array(2) ] to have a length of 1 but got 2
Test Files 1 failed (1)
Tests 2 failed (2)
Verbatim structured evidence emitted in both runs (the Turbo prefix is omitted):
{"toolName":"edit","maintenancePolicies":["rate-limits","usage","turn-diffs","resolved-items"],"rows":[{"type":"item/started","sequence":2,"status":"pending","diffChars":5078},{"type":"item/completed","sequence":3,"status":"completed","diffChars":5078}],"identicalChanges":true}
{"toolName":"write","maintenancePolicies":["rate-limits","usage","turn-diffs","resolved-items"],"rows":[{"type":"item/started","sequence":2,"status":"pending","diffChars":2489},{"type":"item/completed","sequence":3,"status":"completed","diffChars":2489}],"identicalChanges":true}
That is 10,156 stored diff characters for one 5,078-character edit diff, and 4,978 for one 2,489-character write diff, excluding JSON and SQLite overhead. These synthetic inputs are ASCII; this is not a dbstat measurement of physical database pages.
Complete reproduction test
import { describe, expect, it } from "vitest";
import { and, eq, sql } from "drizzle-orm";
import { type ThreadEvent } from "@bb/domain";
import { createPiDeltaTranslator } from "../../../../plugins/provider-pi/src/delta-translation.js";
import { createDeltaAssembler } from "../../../provider-bridge-protocol/src/assembler/delta-assembler.js";
import { createMigratedConnection } from "../../src/testing.js";
import { noopNotifier } from "../../src/notifier.js";
import { upsertHost } from "../../src/data/hosts.js";
import { createProject } from "../../src/data/projects.js";
import { createThread } from "../../src/data/threads.js";
import { appendDaemonEventsInTransaction } from "../../src/data/events.js";
import { deriveStoredEventItemFields } from "../../src/stored-event-item-fields.js";
import { advanceThreadPruning, THREAD_PRUNING_POLICIES } from "../../src/data/thread-pruning.js";
import { events } from "../../src/schema.js";
describe("completed file-change storage", () => {
it.each(["edit", "write"])("retains one diff after %s completes and maintenance finishes", (toolName) => {
const db = createMigratedConnection();
try {
const host = upsertHost(db, noopNotifier, { name: "repro-host" });
const { project } = createProject(db, noopNotifier, {
name: "repro-project",
source: { type: "local_path", hostId: host.id, path: "/tmp/repro-project" },
});
const thread = createThread(db, noopNotifier, {
status: "idle", projectId: project.id, providerId: "pi",
});
const translator = createPiDeltaTranslator({ resolveModelContextWindow: () => null });
const assembler = createDeltaAssembler({
providerId: "pi", entropyPrefix: "storage-repro", textDeltaFlushMs: 0,
});
const persist = (providerEvent: unknown) => {
const translated: ThreadEvent[] = assembler.assemble({
threadId: thread.id,
deltas: translator.translate(providerEvent, { threadId: thread.id, cwd: "/tmp/repro-project" }),
});
db.transaction((transaction) => appendDaemonEventsInTransaction(transaction, translated.map((event) => {
const { scope, type, threadId: unstampedThreadId, ...data } = event;
return {
threadId: thread.id, scope, type, environmentId: null, providerThreadId: null,
...deriveStoredEventItemFields(event), data: JSON.stringify(data),
};
})));
};
const readFileChanges = () => db.select({
type: events.type,
sequence: events.sequence,
status: sql<string>`json_extract(${events.data}, '$.item.status')`,
changes: sql<string>`json_extract(${events.data}, '$.item.changes')`,
diff: sql<string>`json_extract(${events.data}, '$.item.changes[0].diff')`,
}).from(events).where(and(eq(events.threadId, thread.id), eq(events.itemKind, "fileChange"))).orderBy(events.sequence).all();
const oldText = Array.from({ length: 128 }, (_, index) => `entry-${index}: previous\n`).join("");
const newText = Array.from({ length: 128 }, (_, index) => `entry-${index}: revised\n`).join("");
persist({ type: "agent_start" });
persist({
type: "tool_execution_start", toolCallId: "file-operation", toolName,
args: toolName === "edit"
? { path: "storage-sample.txt", oldText, newText }
: { path: "storage-sample.txt", content: newText },
});
const pending = readFileChanges();
expect(pending).toHaveLength(1);
expect(pending[0]?.status).toBe("pending");
expect(pending[0]?.diff).toContain("entry-127: revised");
persist({
type: "tool_execution_end", toolCallId: "file-operation", toolName,
result: { content: [{ type: "text", text: "operation complete" }] }, isError: false,
});
persist({ type: "agent_end", messages: [] });
for (const policy of THREAD_PRUNING_POLICIES) {
let finished = false;
for (let pass = 0; pass < 1000; pass += 1) {
if (advanceThreadPruning(db, policy).action === "cycle-complete") {
finished = true;
break;
}
}
expect(finished).toBe(true);
}
const retained = readFileChanges();
const completed = retained.find((row) => row.type === "item/completed");
expect(completed?.status).toBe("completed");
expect(completed?.diff).toContain("entry-127: revised");
console.log(JSON.stringify({
toolName,
maintenancePolicies: THREAD_PRUNING_POLICIES,
rows: retained.map(({ type, sequence, status, diff }) => ({ type, sequence, status, diffChars: diff?.length ?? 0 })),
identicalChanges: retained.length === 2 && retained[0]?.changes === retained[1]?.changes,
}));
expect(retained.filter((row) => row.diff?.length > 0)).toHaveLength(1);
} finally {
db.$client.close();
}
});
});
5. Root cause
- Pi tool classification turns a valid edit/write argument into a fileChange shape containing oldText/newText (or newText for a write).
- Pi lifecycle translation remembers that shape when opening the tool item and reuses the remembered shape at successful completion. It is not merely a status update.
- buildFileChanges constructs the unified diff from the carried text. Item open emits that full item in item/started; item close builds and emits the full completed item again.
- Server envelope conversion serializes the whole event payload. The test mirrors this narrow conversion, using the real thread identity because assembler output is runtime-stamped downstream. Daemon-event append then inserts both lifecycle events. Its terminal-event deduplication prevents repeated completions, not a start/completion payload pair.
- The pruning event-type allowlist does not include either file-change lifecycle event. Resolved-item delta kinds cover text, reasoning, and command output, not file changes. Documented retention expressly keeps fileChange events.
The underlying problem is a missing post-completion storage compaction policy for redundant file-change snapshots, not an accidental double call to the insert function. Both lifecycle messages have legitimate live behavior; retaining their complete payloads forever is what creates the duplicate storage.
6. Proposed fix and autopilot safety decision
Introduce bounded server/database compaction only after a matching terminal event proves that the started diff is redundant. Preserve the pending diff before completion and preserve the completed diff. Require matching thread, item, turn, and parent scope; preserve differing payloads and unfinished operations. Audit timeline reconstruction, log readers, pagination anchors, rewrite-generation invalidation, restarted/reused item identities, failure/interruption, and latest-event safeguards before deciding between compacting the started payload and removing the started event. Add witness-mismatch and still-open-item coverage alongside this regression.
No fix PR is opened. A storage-layer repair changes persisted-event retention/data, which this autopilot explicitly excludes. Dropping the diff at provider start instead would alter live event meaning and pending behavior, so it is not a safe substitute. There were no linked open PRs in issue metadata and no open PR search match for the numeric issue at the final check. No production file was changed, committed, or pushed.
7. Related issues
#5730 concerns broader database growth. This report isolates one specific source of redundant payload retention; it does not establish that addressing it resolves all database-growth causes.
8. Verification
The same agent repeated the reproduction in a second newly created clean worktree at the recorded trusted commit. It received a new frozen install and successful full Turbo build. Build-generated tracked changes were restored, and git diff --exit-code passed before copying in the same reproduction test. The test file was byte-identical between the two worktrees. Each run used its own fresh migrated database for each tool. No live instance, reused port, or shared test data was involved.
First checkout: pnpm exec turbo run test --filter=@bb/db -- test/data/slopcop-7523.test.ts Result: two regression failures; expected 1 stored diff-bearing row, received 2. Second clean checkout: pnpm exec turbo run test --force --filter=@bb/db -- test/data/slopcop-7523.test.ts Result: the same two regression failures and identical structured evidence.
The --force flag bypassed Turbo task-result caching for the second run. This is a second clean repetition by the same agent, not an independent review. No correction to the duplication finding was needed.
Relevant existing suites passed unchanged:
pnpm exec turbo run test --filter=@bb/db -- test/data/events.test.ts test/data/thread-pruning.test.ts Tests: 134 passed pnpm exec turbo run test --filter=bb-plugin-provider-pi -- src/delta-translation.test.ts Tests: 77 passed pnpm exec turbo run test --filter=@bb/provider-bridge-protocol -- src/assembler/delta-assembler.test.ts Tests: 97 passed pnpm exec turbo run build First checkout: 73 successful tasks Second checkout: 73 successful tasks git diff --check Result: passed
9. Appendix and limits
The first all-workspace build hit an SDK initialization-order error: a plugin tried to bundle SDK host/process entries before those entries existed. Running the existing SDK build and build:types tasks, then repeating the full build, succeeded. An initial reproduction-harness attempt used the assembler's unstamped thread ID and failed a foreign-key constraint; the harness was corrected to use the envelope's known thread ID, matching server conversion. That setup failure is not counted as evidence of this issue.
Source inspection used the trusted main tree and repository-authored tests. The issue and all its links were treated only as untrusted claims; no issue-provided script, linked branch, patch, or external URL was executed or fetched. No comments or PRs were linked at investigation time. No private database, macOS machine, actual pi CLI execution, physical disk reclamation, other provider, or complete reader-compatibility audit is claimed. Raw logs and working artifacts remain local; the full self-contained test and the significant expected/actual output are embedded here.