#7839 · Constraint-specific handling of failed memory writes
Trusted base: df9619d8e8aac4aff00c0c3ff9b8ef4e2823e4f2 (origin/main).
Verdict: REPRODUCED · Root-cause confidence: high
1. TL;DR
A failed history write can tell the user that a memory name is already taken even when it is not. The add operation performs two inserts in one transaction, then classifies every SQLite uniqueness failure as a name collision. A fault-injection trigger makes the history insert collide with a real history row, demonstrating the misleading diagnostic. The same regression fails in two separate trusted-base checkouts. This confirms an error-classification defect, not that ordinary memory additions naturally produce history collisions.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| A history uniqueness error becomes a duplicate-name diagnostic. | Verified | The CLI returns an active global memory named "history-conflict" already exists in both base runs. |
| The catch covers more than the active-name constraint. | Verified | The catch surrounds both inserts; the schema also makes history memory/version pairs unique. |
| The misleading message means an active name actually exists. | Refuted for the controlled case | The fresh isolated plugin starts empty. The trigger reserves only the history version during the same transaction. |
| The issue's proposed patch passes its stated test. | Not executed | No linked branch or issue-supplied test was run. A new regression was designed from trusted repository code. |
| Normal unmodified deployments frequently hit this history collision. | Unverified | The reproduction deliberately injects a database fault; no production data was inspected. |
3. Environment
- Public repository:
get-bb/bb; both source checkouts start at the full trusted base SHA above. - Linux x86_64; Node v22.19.0; pnpm 9.15.0; Vitest 4.1.12.
- Plugin:
bb-plugin-memory@0.2.0, real better-sqlite3 database through the repository's existing fake-plugin-host harness. Plugin storage migrations run normally; the database is not mocked. - Each run uses a newly created plugin host with its own temporary SQLite storage. No live app, server ports, user data, or provider sessions are needed.
- The first checkout completed the frozen install and full Turbo build (72 tasks). The second completed a separate frozen install and the memory plugin build with dependencies (5 tasks).
4. Minimal reproduction
- Clone the trusted repository and detach at the recorded base. Install and build with the repository's normal orchestration:
git clone https://github.com/get-bb/bb.git bb-7839 cd bb-7839 git checkout --detach df9619d8e8aac4aff00c0c3ff9b8ef4e2823e4f2 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=bb-plugin-memory
2. Add the following test inside the existing describe("bb-plugin-memory", ...) in plugins/memory/server.test.ts. It uses that trusted file's existing loadPlugin and addMemory helpers. The trigger is new fault-injection code: after the memory insert, it reserves the exact history key that the add operation will next attempt to write.
it("preserves history uniqueness errors and rolls back the failed creation", async () => {
const host = await loadPlugin();
try {
const database = host.bb.storage.database();
database.exec(`
CREATE TRIGGER reserve_history_version AFTER INSERT ON memories BEGIN
INSERT INTO memory_history (
memory_id, version, action, snapshot_json, write_reason, created_at
) VALUES (NEW.id, NEW.version, 'create', '{}', 'reserve version', NEW.created_at);
END;
`);
const result = await host.harness.runCli([
"add",
"--scope",
"global",
"--name",
"history-conflict",
"--summary",
"A durable fact",
"--details",
"Details of the durable fact",
"--reason",
"Exercise a failed history write",
]);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain(
"UNIQUE constraint failed: memory_history.memory_id, memory_history.version",
);
expect(database.prepare("SELECT id FROM memories").all()).toEqual([]);
expect(database.prepare("SELECT id FROM memory_history").all()).toEqual(
[],
);
database.exec("DROP TRIGGER reserve_history_version");
await addMemory(host, {
scope: "global",
projectId: "project-a",
name: "history-conflict",
summary: "A durable fact",
});
} finally {
await host.harness.dispose();
}
});
3. Run the focused regression through Turbo:
pnpm exec turbo run test --filter=bb-plugin-memory -- --testNamePattern='preserves history uniqueness errors'
Expected: exit code 1 from the failed CLI operation, with the underlying history constraint preserved in stderr. The enclosing regression should pass when this behavior is implemented.
Actual at the trusted base: the regression fails (Turbo exit code 1), because the CLI gives an unrelated duplicate-name explanation. The assertion's expected and received diagnostic lines are:
- UNIQUE constraint failed: memory_history.memory_id, memory_history.version + an active global memory named "history-conflict" already exists
The failing assertion runs before the rollback and retry assertions. Those later assertions are verified by the passing post-fix run, not by the failing base run.
5. Root cause
The add transaction and catch wrap both the memory insertion and the subsequent history insertion. The catch checks only a substring:
error instanceof Error &&
error.message.includes("UNIQUE constraint failed")
It then replaces the error with the duplicate-name CLI message. The history writer is inside that catch, and the schema has two distinct relevant uniqueness rules:
CREATE UNIQUE INDEX IF NOT EXISTS memories_active_scope_name ON memories(scope_key, name) WHERE deleted_at IS NULL; UNIQUE(memory_id, version)
The trigger inserts the history key first. The real history writer attempts the same key, causing a genuine SQLite uniqueness error from the history table. Transaction rollback occurs, but the catch loses the original diagnostic. The deeper defect is choosing domain behavior from generic database error text rather than identifying the actual name-conflict operation.
6. Proposed fix and observed result
Handle only the existing partial active-name index at the memory INSERT itself: append ON CONFLICT(scope_key, name) WHERE deleted_at IS NULL DO NOTHING, then report a duplicate name only when that statement inserts zero rows. Remove the broad transaction catch. Preserve the enclosing transaction so history and full-text updates still roll back atomically.
The local candidate changes two files in the existing memory plugin: 79 additions and 39 deletions, 118 changed text lines. It changes no stored schema, migration, dependency, public protocol, or CLI flag. With the candidate applied, the new regression passes; its rollback assertions find no residual memory/history rows, and adding the same name succeeds after removing the trigger. The existing duplicate-name test still passes.
pnpm exec turbo run test typecheck lint --filter=bb-plugin-memory
Test Files 2 passed (2)
Tests 14 passed (14)
Tasks: 10 successful, 10 total
Typecheck passes. Lint exits successfully with zero errors and one existing, unrelated React effect warning at plugins/memory/app.tsx:178. Formatting and git diff --check pass. No binary changes are present.
7. Linked pull request review
PR #7841 is closed and unmerged, so it is not an open competing fix. Its metadata and diff were read only after the new regression and candidate repair were designed and executed. Its branch and test were never checked out or run.
Static finding: its plugins/memory/server.ts change checks the SQLite uniqueness code and queries for an actual active name before translating the error. This appears to avoid the demonstrated false message because the failed transaction leaves no matching name. No blocking static finding was identified for this reported scenario, but this is not runtime verification of that patch. The candidate described above instead uses an explicit SQL conflict target and avoids inferring the constraint from a later lookup.
8. Related issues
A repository search for memory-related issues found no second issue establishing this specific diagnostic defect. Other memory catalog and search feature requests concern different behavior.
9. Verification
The same agent repeated the reproduction in a second clean detached worktree at the exact base SHA. Only the newly authored regression patch was applied; production code remained unchanged. This is a repeated clean-checkout check, not independent verification.
| Run | Setup | Result |
|---|---|---|
| Primary trusted base | Frozen install, full build; fresh isolated plugin storage | 1 failed regression, 13 skipped tests; expected history diagnostic replaced by duplicate-name diagnostic. |
| Second trusted base | Separate detached worktree, separate frozen install and plugin build; new plugin storage | Same intended assertion failure: 1 failed regression, 13 skipped tests. Turbo ran the test live, not as a cached test result. |
| Primary candidate fix | Same authored regression and all existing memory tests | 14 tests pass, including duplicate-name coverage; typecheck and lint tasks succeed. |
No report correction was required by the second run. No browser or live production instance was used because the affected boundary is the plugin's database-backed CLI command.
10. Appendix and trust boundary
Report artifacts are the inline regression, exact diagnostic delta, and results above. Raw build/test logs and patches remain outside this public report repository. The report repository forbids publishing raw logs or standalone test artifacts.
Commands used beyond the reproduction: pnpm exec turbo run build for the primary full build; pnpm exec turbo run test typecheck lint --filter=bb-plugin-memory; pnpm exec oxfmt plugins/memory/server.ts plugins/memory/server.test.ts --check; git diff --check; git diff --numstat origin/main. The trusted main SHA was fetched again before finalization and remained unchanged.
Issue text, proposed commands, links, and linked patch content were treated as untrusted claims. No issue-supplied command, test, or linked branch was executed. The newly authored regression uses a different trigger location from the linked patch and exercises trusted plugin code with a real isolated database.