Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(outbox): atomically persist empty recovery snapshots

Linuxdazhao3a61e4cde1ad
diff --git a/apps/desktop/electron/main/persistence-outbox.ts b/apps/desktop/electron/main/persistence-outbox.ts
index 1bdc0309d..691765bc5 100644
--- a/apps/desktop/electron/main/persistence-outbox.ts
+++ b/apps/desktop/electron/main/persistence-outbox.ts
@@ -340,14 +340,6 @@ export class PersistenceOutbox {
private async persist(): Promise<void> {
const write = this.persistChain.then(async () => {
await mkdir(dirname(this.path), { recursive: true });
- if (this.entries.length === 0) {
- try {
- await writeFile(this.path, "[]\n", "utf8");
- } catch (error) {
- this.logger("warn", "session persistence outbox clear failed", String(error));
- }
- return;
- }
await writeFile(this.tempPath, `${JSON.stringify(this.entries.map(encodeBinaryStorage))}\n`, "utf8");
await rename(this.tempPath, this.path);
});
@@ -358,14 +350,6 @@ export class PersistenceOutbox {
private async persistDeadLetters(): Promise<void> {
const write = this.persistChain.then(async () => {
await mkdir(dirname(this.deadLetterPath), { recursive: true });
- if (this.deadLetters.length === 0) {
- try {
- await writeFile(this.deadLetterPath, "[]\n", "utf8");
- } catch (error) {
- this.logger("warn", "session persistence outbox dead letter clear failed", String(error));
- }
- return;
- }
await writeFile(this.tempDeadLetterPath, `${JSON.stringify(this.deadLetters.map(encodeBinaryStorage))}\n`, "utf8");
await rename(this.tempDeadLetterPath, this.deadLetterPath);
});
diff --git a/apps/desktop/test/persistence-outbox-atomic-clear.test.mjs b/apps/desktop/test/persistence-outbox-atomic-clear.test.mjs
new file mode 100644
index 000000000..b03733516
--- /dev/null
+++ b/apps/desktop/test/persistence-outbox-atomic-clear.test.mjs
@@ -0,0 +1,70 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { PersistenceOutbox } from "../electron/main/persistence-outbox.ts";
+
+for (const file of ["session-message-outbox.json", "session-message-outbox.dead-letter.json"]) {
+ for (const failure of ["interrupted write", "failed rename"]) {
+ test(`${file}: clearing survives ${failure}`, async (t) => {
+ const dir = await mkdtemp(join(tmpdir(), "pi-outbox-atomic-clear-"));
+ t.after(() => rm(dir, { recursive: true, force: true }));
+ const entry = { key: "message:s:m", sessionId: "s", message: { id: "m" } };
+ const records = file.includes("dead-letter")
+ ? [{ ...entry, quarantinedAt: "2026-11-12T00:00:00.000Z", reason: "fixture" }]
+ : [entry];
+ const path = join(dir, file);
+ const raw = JSON.stringify(records) + "\n";
+ await writeFile(path, raw);
+ const moduleUrl = new URL("../electron/main/persistence-outbox.ts", import.meta.url).href;
+ const child = spawnSync(process.execPath, ["--input-type=module", "-e", `
+ import assert from "node:assert/strict";
+ import fs from "node:fs/promises";
+ import { syncBuiltinESMExports } from "node:module";
+ const originalWrite = fs.writeFile;
+ const originalRename = fs.rename;
+ const path = ${JSON.stringify(path)};
+ const failure = ${JSON.stringify(failure)};
+ if (failure === "interrupted write") {
+ fs.writeFile = async (target, data, ...args) => {
+ if (String(target).startsWith(path) && data === "[]\\n") {
+ // Model process termination after open(O_TRUNC), before payload write.
+ await originalWrite(target, "", ...args);
+ process.exit(77);
+ }
+ return originalWrite(target, data, ...args);
+ };
+ } else {
+ fs.rename = async (from, to) => {
+ if (to === path) throw Object.assign(new Error("fixture rename denied"), { code: "EPERM" });
+ return originalRename(from, to);
+ };
+ }
+ syncBuiltinESMExports();
+ const { PersistenceOutbox } = await import(${JSON.stringify(moduleUrl)});
+ const outbox = new PersistenceOutbox(${JSON.stringify(dir)}, () => {});
+ if (failure === "interrupted write") {
+ await outbox.dropSession("s");
+ assert.fail("fault injection did not interrupt the empty write");
+ } else {
+ await assert.rejects(outbox.dropSession("s"), { code: "EPERM" });
+ }
+ `], { encoding: "utf8", timeout: 10_000 });
+ assert.equal(child.status, failure === "interrupted write" ? 77 : 0, child.stderr || child.stdout);
+ assert.equal(await readFile(path, "utf8"), raw, "the committed recovery file must remain intact");
+
+ const recovered = new PersistenceOutbox(dir, () => {});
+ const replayed = [];
+ await recovered.flush(() => ({
+ isAvailable: () => true,
+ call: async (_method, params) => replayed.push(params.message),
+ }));
+ assert.deepEqual(replayed, file.includes("dead-letter") ? [] : [entry.message]);
+ await recovered.dropSession("s");
+ assert.deepEqual(JSON.parse(await readFile(path, "utf8")), []);
+ await new PersistenceOutbox(dir, () => {}).flush(() => null);
+ });
+ }
+}
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index c8632f8c7..a3d5f4e9a 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -1983,6 +1983,12 @@ and host error, so one unclassifiable head cannot starve every session's writes
(D656). A restarted host is a new generation and retries the head at once.
Quarantined appends are never replayed automatically, and `session.delete`
drops that session's quarantined appends too.
+Every outbox and dead-letter snapshot, including an empty array, is written
+to its sibling temporary file before replacing the committed file by rename.
+Interrupted writes leave the previous committed snapshot readable; a failed
+replacement rejects the persistence operation instead of reporting success.
+This prevents process termination during clearing from truncating recovery
+files. Existing corrupt files still fail closed without rewriting their bytes.
When the 1024-entry cap remains
full after a flush attempt, enqueue logs the rejected key/session and rejects;
it does not report that entry as queued. Generic foreign-key errors are not
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 5ee166e85..874869cd9 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -2612,6 +2612,23 @@ identify the platform validation still needed.
quarantine, dead-letter persistence and cap tests); desktop journey
outstanding
+#### E2E-SESSION-outbox-empty-snapshot-is-atomic
+
+- **Preconditions**: An isolated profile has one queued append or dead letter.
+- **Steps**: Delete its session through `PersistenceOutbox.dropSession` and
+ terminate the writer after the empty write opens/truncates its target but
+ before writing the payload. Restart the outbox. Repeat with an injected
+ `EPERM` at rename, then clear normally and restart again.
+- **Expected**: Both failures preserve the previous committed bytes. A pending
+ append remains replayable; a dead letter remains readable without replay.
+ Rename failure rejects the caller. A successful clear commits `[]` and
+ remains readable on restart. Already-corrupt files still fail closed.
+- **Specs linked**: `03-runtime/04-data-storage.md`, ADR 0041
+- **Acceptance**: F (persistence)
+- **Status**: Process/filesystem regression coverage in
+ `persistence-outbox-atomic-clear.test.mjs`; full Electron and native Windows
+ force-close journeys not run.
+
#### E2E-011: Switch between project and temporary sessions