Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(project): stop concurrent saves from splicing project files together

Etienne Lescotd0d83662d8ab
diff --git a/electron/ai-edition/document-service.test.ts b/electron/ai-edition/document-service.test.ts
index 6baf50838..af3f8726c 100644
--- a/electron/ai-edition/document-service.test.ts
+++ b/electron/ai-edition/document-service.test.ts
@@ -1,7 +1,8 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { AxcutDocument } from "../../src/lib/ai-edition/schema";
import { DocumentNotFoundError, DocumentService, ProjectFileError } from "./document-service";
async function makeTempDir(): Promise<string> {
@@ -210,4 +211,124 @@ describe("DocumentService", () => {
await expect(service.deleteProject("proj_never-existed")).resolves.toBeUndefined();
});
});
+
+ // These reproduce a bug that destroyed two real project files: fs.writeFile
+ // truncates and writes from offset 0, so two concurrent saves of one project
+ // spliced together — a short document over a long one's head, the long one's
+ // tail surviving past its end. The file parsed as JSON up to the splice and
+ // then died, taking the user's edits with it.
+ describe("concurrent saves", () => {
+ /** A document whose serialised length is driven by `annotations`. */
+ const withBulk = (doc: AxcutDocument, count: number): AxcutDocument => ({
+ ...doc,
+ annotations: Array.from({ length: count }, (_, i) => ({
+ id: `ann_${i}`,
+ startMs: i,
+ endMs: i + 1,
+ type: "text" as const,
+ content: `annotation ${i} ${"x".repeat(200)}`,
+ position: { x: 10, y: 10 },
+ size: { width: 20, height: 10 },
+ style: {
+ color: "#ffffff",
+ backgroundColor: "transparent",
+ fontSize: 32,
+ fontFamily: "Inter",
+ fontWeight: "bold" as const,
+ fontStyle: "normal" as const,
+ textDecoration: "none" as const,
+ textAlign: "center" as const,
+ },
+ zIndex: i,
+ })),
+ });
+
+ // Repeated, because the race is a coin flip: measured on the pre-fix code,
+ // one long/short race spliced the file ~5 times out of 10. A single attempt
+ // passed against the very bug it was written for. 12 rounds miss it once in
+ // ~4000 runs; the loop is the test, not decoration.
+ it("leaves valid JSON when a long and a short save race", async () => {
+ for (let round = 0; round < 12; round++) {
+ const doc = await service.createProject(`Race ${round}`);
+ const file = path.join(tempDir, `${doc.project.id}.openscreen`);
+
+ // Unawaited on purpose: this is the exact shape of the real failure —
+ // two saves of one project in flight at once.
+ await Promise.all([
+ service.saveProject(withBulk(doc, 400)),
+ service.saveProject(withBulk(doc, 1)),
+ ]);
+
+ const raw = await fs.readFile(file, "utf8");
+ // The destroyed projects died exactly here, at the splice point: the
+ // short document's bytes, then the long one's tail past its end.
+ const parsed = JSON.parse(raw);
+ // Whichever save landed last must be on disk WHOLE — never a mix.
+ expect([1, 400]).toContain(parsed.annotations.length);
+ expect(raw.trimEnd().endsWith("}")).toBe(true);
+ }
+ });
+
+ it("applies racing saves in call order, last one winning", async () => {
+ const doc = await service.createProject("Order");
+ await Promise.all([
+ service.saveProject(withBulk(doc, 300)),
+ service.saveProject(withBulk(doc, 5)),
+ service.saveProject(withBulk(doc, 120)),
+ ]);
+ const onDisk = await service.getProject(doc.project.id);
+ expect(onDisk.annotations).toHaveLength(120);
+ });
+
+ it("survives many interleaved saves of one project", async () => {
+ const doc = await service.createProject("Storm");
+ // Sizes deliberately alternate long/short: equal-length writes overwrite
+ // each other cleanly and would prove nothing.
+ await Promise.all(
+ Array.from({ length: 20 }, (_, i) => service.saveProject(withBulk(doc, i % 2 ? 300 : 2))),
+ );
+ const onDisk = await service.getProject(doc.project.id);
+ expect(onDisk.annotations).toHaveLength(300);
+ });
+
+ it("keeps the previous document when a save fails mid-write", async () => {
+ const doc = await service.createProject("Durable");
+ await service.saveProject(withBulk(doc, 3));
+
+ // Fail the write itself, not the validation before it: a full disk or an
+ // EIO lands here, where the old pipeline had already truncated the file.
+ const open = vi.spyOn(fs, "open").mockRejectedValueOnce(new Error("ENOSPC: disk full"));
+ await expect(service.saveProject(withBulk(doc, 99))).rejects.toThrow(ProjectFileError);
+ open.mockRestore();
+
+ // The point of temp+rename: the good document is still there, intact.
+ const after = await service.getProject(doc.project.id);
+ expect(after.annotations).toHaveLength(3);
+ });
+
+ it("does not leave temp files behind", async () => {
+ const doc = await service.createProject("Tidy");
+ await Promise.all([
+ service.saveProject(withBulk(doc, 50)),
+ service.saveProject(withBulk(doc, 2)),
+ ]);
+ const entries = await fs.readdir(tempDir);
+ expect(entries.filter((name) => name.includes(".tmp-"))).toEqual([]);
+ });
+
+ it("a failed save does not block later saves of the same project", async () => {
+ const doc = await service.createProject("Recover");
+ // The queue chains one save onto the last. If it chained on success only,
+ // this rejection would strand every save behind it for the session.
+ const open = vi.spyOn(fs, "open").mockRejectedValueOnce(new Error("EIO"));
+
+ const failing = service.saveProject(withBulk(doc, 2));
+ const following = service.saveProject(withBulk(doc, 7));
+ await expect(failing).rejects.toThrow(ProjectFileError);
+ await expect(following).resolves.toBeTruthy();
+ open.mockRestore();
+
+ expect((await service.getProject(doc.project.id)).annotations).toHaveLength(7);
+ });
+ });
});
diff --git a/electron/ai-edition/document-service.ts b/electron/ai-edition/document-service.ts
index fc40d9b9a..dee364024 100644
--- a/electron/ai-edition/document-service.ts
+++ b/electron/ai-edition/document-service.ts
@@ -10,7 +10,7 @@
// ponytail: Phase 1 surface area is intentionally narrow (list / get / create
// / save / addAsset / removeAsset). ops/history/agent runtime land in Phase 6.
-import fs from "node:fs/promises";
+import fs, { type FileHandle } from "node:fs/promises";
import path from "node:path";
import { createId } from "../../src/lib/ai-edition/document/ids";
import {
@@ -78,9 +78,32 @@ function safeProjectId(raw: string): string {
return raw;
}
+/**
+ * Windows fails a rename onto an open file with EPERM/EBUSY: an indexer, an
+ * antivirus or a backup agent can hold the destination for a few milliseconds
+ * after we last touched it. The write itself is sound, so retry briefly rather
+ * than surface a save error the user cannot act on. POSIX renames don't hit this
+ * and take the first attempt.
+ */
+async function renameWithRetry(from: string, to: string): Promise<void> {
+ const RETRYABLE = new Set(["EPERM", "EACCES", "EBUSY"]);
+ for (let attempt = 0; ; attempt++) {
+ try {
+ await fs.rename(from, to);
+ return;
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException)?.code ?? "";
+ if (attempt >= 5 || !RETRYABLE.has(code)) throw error;
+ await new Promise((resolve) => setTimeout(resolve, 10 * 2 ** attempt));
+ }
+ }
+}
+
export class DocumentService {
private readonly projectsRoot: string;
private legacyMigrationDone = false;
+ /** Tail of the in-flight save chain per project id — see writeProject. */
+ private readonly writeQueues = new Map<string, Promise<void>>();
constructor(projectsRoot: string) {
this.projectsRoot = projectsRoot;
@@ -292,10 +315,79 @@ export class DocumentService {
return this.saveProject(next);
}
- private async writeProject(doc: AxcutDocument): Promise<void> {
+ /**
+ * Serialise saves per project, then write atomically.
+ *
+ * This has destroyed real project files. `fs.writeFile` opens with O_TRUNC and
+ * writes from offset 0, so two concurrent saves of the SAME project interleave
+ * onto one path: the short document lands over the long one's opening bytes and
+ * the long one's tail survives past its end. The result parses as JSON right up
+ * to the splice and then dies — the file is unreadable and the edits in it are
+ * gone. Two projects on this machine were lost exactly that way (a complete
+ * document followed by the tail of a longer, older version).
+ *
+ * Both halves are load-bearing:
+ * - the queue makes concurrent saves of one project sequential, so a save
+ * always writes over a settled file, never a half-written one;
+ * - temp + rename makes each save all-or-nothing, so a crash (or a full disk)
+ * mid-write leaves the previous document intact instead of a truncated one.
+ * The queue alone would still leave a torn file on a crash; the rename alone
+ * would still let two saves race for the same destination.
+ */
+ private writeProject(doc: AxcutDocument): Promise<void> {
+ const projectId = doc.project.id;
+ const tail = this.writeQueues.get(projectId) ?? Promise.resolve();
+ // Chained on both settlements: one save failing must not cancel the next.
+ const run = tail.then(
+ () => this.writeProjectNow(doc),
+ () => this.writeProjectNow(doc),
+ );
+ const settled = run.catch(() => undefined);
+ this.writeQueues.set(projectId, settled);
+ void settled.then(() => {
+ // Only the tail clears the entry — a later save may already own it.
+ if (this.writeQueues.get(projectId) === settled) this.writeQueues.delete(projectId);
+ });
+ return run;
+ }
+
+ private async writeProjectNow(doc: AxcutDocument): Promise<void> {
await this.ensureProjectsDir();
const filePath = this.fileFor(doc.project.id);
- await fs.writeFile(filePath, JSON.stringify(doc, null, 2), "utf8");
+ // The suffix goes AFTER the extension on purpose: listProjects matches on a
+ // trailing `.openscreen`, so an interrupted write's leftover is invisible to
+ // it rather than showing up as a corrupt project. Unique per write, so two
+ // queues (or two processes) never share a temp path.
+ const tempPath = `${filePath}.tmp-${process.pid}-${createId("w")}`;
+ const json = JSON.stringify(doc, null, 2);
+
+ let handle: FileHandle | undefined;
+ try {
+ handle = await fs.open(tempPath, "w");
+ await handle.writeFile(json, "utf8");
+ // Flush before the rename: without it the rename can reach the disk first
+ // and a power loss leaves the new name pointing at unwritten blocks.
+ await handle.sync();
+ } catch (error) {
+ await handle?.close().catch(() => undefined);
+ await fs.unlink(tempPath).catch(() => undefined);
+ throw new ProjectFileError(
+ `Failed to write project ${doc.project.id}: ${error instanceof Error ? error.message : String(error)}`,
+ doc.project.id,
+ );
+ }
+ await handle.close();
+
+ try {
+ await renameWithRetry(tempPath, filePath);
+ } catch (error) {
+ await fs.unlink(tempPath).catch(() => undefined);
+ throw new ProjectFileError(
+ `Failed to save project ${doc.project.id}: ${error instanceof Error ? error.message : String(error)}`,
+ doc.project.id,
+ );
+ }
+
// A save supersedes any legacy `.axcut` for this id (ensureProjectsDir
// usually renamed it already; this is a belt-and-braces cleanup).
await fs.unlink(this.legacyFileFor(doc.project.id)).catch(() => undefined);