diff --git a/pm-stack/aggregator/src/actions.ts b/pm-stack/aggregator/src/actions.ts index 5550048727..3f4ec38097 100644 --- a/pm-stack/aggregator/src/actions.ts +++ b/pm-stack/aggregator/src/actions.ts @@ -416,13 +416,22 @@ export function newClientToken(): string { export class ActionsStore { private actions: DashAction[] = []; - private loaded = false; + private loadPromise: Promise | null = null; + private writeChain: Promise = Promise.resolve(); + private writeSeq = 0; constructor(private readonly file: string) {} + // The load is memoized as a single promise (#1509): the old + // loaded-flag version let concurrent first callers proceed before + // the read finished, and the read's completion then reset the + // in-memory array, wiping records those callers had just pushed. async load(): Promise { - if (this.loaded) return; - this.loaded = true; + if (!this.loadPromise) this.loadPromise = this.doLoad(); + return this.loadPromise; + } + + private async doLoad(): Promise { try { const parsed: unknown = JSON.parse(await readFile(this.file, "utf8")); if (typeof parsed === "object" && parsed !== null && Array.isArray((parsed as ActionsFile).actions)) { @@ -435,12 +444,18 @@ export class ActionsStore { } } - private async persist(): Promise { - const data: ActionsFile = { version: 1, actions: this.actions }; - await mkdir(dirname(this.file), { recursive: true }); - const tmp = `${this.file}.tmp-${process.pid}`; - await writeFile(tmp, JSON.stringify(data, null, 2)); - await rename(tmp, this.file); + // Serialized persists + unique temp path per write - see + // CommentsStore.persist (#1509). + private persist(): Promise { + const run = this.writeChain.then(async () => { + const data: ActionsFile = { version: 1, actions: this.actions }; + await mkdir(dirname(this.file), { recursive: true }); + const tmp = `${this.file}.tmp-${process.pid}-${++this.writeSeq}`; + await writeFile(tmp, JSON.stringify(data, null, 2)); + await rename(tmp, this.file); + }); + this.writeChain = run.catch(() => {}); + return run; } async all(): Promise { diff --git a/pm-stack/aggregator/src/comments.ts b/pm-stack/aggregator/src/comments.ts index 1bc4241f60..78c53c33bc 100644 --- a/pm-stack/aggregator/src/comments.ts +++ b/pm-stack/aggregator/src/comments.ts @@ -96,13 +96,22 @@ export function newCommentId(now = new Date()): string { export class CommentsStore { private comments: DashComment[] = []; - private loaded = false; + private loadPromise: Promise | null = null; + private writeChain: Promise = Promise.resolve(); + private writeSeq = 0; constructor(private readonly file: string) {} + // The load is memoized as a single promise (#1509): the old + // loaded-flag version let concurrent first callers proceed before + // the read finished, and the read's completion then reset the + // in-memory array, wiping records those callers had just pushed. async load(): Promise { - if (this.loaded) return; - this.loaded = true; + if (!this.loadPromise) this.loadPromise = this.doLoad(); + return this.loadPromise; + } + + private async doLoad(): Promise { try { const parsed: unknown = JSON.parse(await readFile(this.file, "utf8")); if (typeof parsed === "object" && parsed !== null && Array.isArray((parsed as CommentsFile).comments)) { @@ -115,12 +124,24 @@ export class CommentsStore { } } - private async persist(): Promise { - const data: CommentsFile = { version: 1, comments: this.comments }; - await mkdir(dirname(this.file), { recursive: true }); - const tmp = `${this.file}.tmp-${process.pid}`; - await writeFile(tmp, JSON.stringify(data, null, 2)); - await rename(tmp, this.file); + // Persists are serialized through a per-store promise chain and each + // write lands on a unique temp path (#1509): concurrent adds used to + // share one pid-only temp path, so the first rename won and the rest + // threw ENOENT while their records stayed in memory - fulfilled calls + // diverged from what was on disk. The snapshot is taken when the + // queued write actually runs, so the last write always carries the + // full current state; a failed write still rejects its own caller but + // does not poison the chain for later writes. + private persist(): Promise { + const run = this.writeChain.then(async () => { + const data: CommentsFile = { version: 1, comments: this.comments }; + await mkdir(dirname(this.file), { recursive: true }); + const tmp = `${this.file}.tmp-${process.pid}-${++this.writeSeq}`; + await writeFile(tmp, JSON.stringify(data, null, 2)); + await rename(tmp, this.file); + }); + this.writeChain = run.catch(() => {}); + return run; } async all(): Promise { diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 341cb5193a..5ddf82b7c2 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -325,7 +325,14 @@ async function handler(req: Request): Promise { try { const parsed = validateNewComment(await readJsonBody(req)); if (!parsed.ok) return json({ error: parsed.error }, 400); - const comment = await commentsStore.add(parsed.value); + // #1509: a persistence failure is a server error, not bad input - + // only the validation/body-parse path above earns a 400. + let comment; + try { + comment = await commentsStore.add(parsed.value); + } catch (err) { + return json({ error: `comment persistence failed: ${err instanceof Error ? err.message : err}` }, 500); + } return json({ comment }, 201); } catch (err) { return json({ error: `invalid comment: ${err instanceof Error ? err.message : err}` }, 400); @@ -379,7 +386,14 @@ async function handler(req: Request): Promise { if (problem) return json({ error: problem }, 400); } } - const { action, created } = await actionsStore.add(parsed.value); + // #1509: persistence failure -> 5xx (see /api/comments above). + let added; + try { + added = await actionsStore.add(parsed.value); + } catch (err) { + return json({ error: `action persistence failed: ${err instanceof Error ? err.message : err}` }, 500); + } + const { action, created } = added; return json(created ? { action } : { action, deduped: true }, created ? 201 : 200); } catch (err) { return json({ error: `invalid action: ${err instanceof Error ? err.message : err}` }, 400); diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index 8612f3dfdf..69595ad1a7 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -601,6 +601,8 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise = Promise.resolve(); + let registryWriteSeq = 0; async function loadRegistryStore(): Promise { if (registryStore) return registryStore; try { @@ -617,11 +619,18 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise r !== current[i]); registryStore = merged; if (changed) { - try { + // Serialized writes + unique temp path per write (#1509): the + // pid-only temp path raced concurrent merges the same way the + // comments/actions stores did, and the catch below hid the loss. + const write = registryWriteChain.then(async () => { await mkdir(dirname(cfg.registryFile), { recursive: true }); - const tmp = `${cfg.registryFile}.tmp-${process.pid}`; + const tmp = `${cfg.registryFile}.tmp-${process.pid}-${++registryWriteSeq}`; await writeFile(tmp, JSON.stringify(merged, null, 2)); await rename(tmp, cfg.registryFile); + }); + registryWriteChain = write.catch(() => {}); + try { + await write; } catch { /* durability is best-effort; the in-memory merge still serves */ } diff --git a/pm-stack/aggregator/test/store-concurrency.test.ts b/pm-stack/aggregator/test/store-concurrency.test.ts new file mode 100644 index 0000000000..365aa1706b --- /dev/null +++ b/pm-stack/aggregator/test/store-concurrency.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { ActionsStore, type NewAction } from "../src/actions.ts"; +import { CommentsStore, type NewComment } from "../src/comments.ts"; + +// #1509: the JSON stores persisted through a temp file named only by pid +// with no write serialization, so concurrent adds shared one temp path — +// the first rename won, the rest threw ENOENT, and records on disk +// diverged from calls that succeeded (triage repro: 20 concurrent adds +// -> 2 fulfilled, 18 ENOENT, 19 records on disk). Persists are now +// serialized per store with a unique temp path per write; these tests +// pin fulfilled == persisted for both stores. +describe("JSON stores under concurrent adds (#1509)", () => { + const author = { kind: "drew" as const, id: "drew", label: "Drew" }; + + test("20 concurrent comment adds all fulfill and all persist", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-comments-conc-")); + const file = join(dir, "comments.json"); + const store = new CommentsStore(file); + const inputs: NewComment[] = Array.from({ length: 20 }, (_, i) => ({ + objectRef: "orch:item-1", + kind: "note" as const, + author, + body: `note ${i}`, + })); + const results = await Promise.allSettled(inputs.map((x) => store.add(x))); + expect(results.filter((r) => r.status === "fulfilled").length).toBe(20); + const reloaded = new CommentsStore(file); + expect((await reloaded.all()).length).toBe(20); + }); + + test("20 concurrent action adds all fulfill and all persist", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-actions-conc-")); + const file = join(dir, "actions.json"); + const store = new ActionsStore(file); + const inputs: NewAction[] = Array.from({ length: 20 }, (_, i) => ({ + clientToken: `ct-conc-${i}-abcdefgh`, + kind: "triage" as const, + verb: "acknowledge", + objectRef: "orch:item-1", + payload: {}, + author, + })); + const results = await Promise.allSettled(inputs.map((x) => store.add(x))); + const fulfilled = results.filter((r) => r.status === "fulfilled"); + expect(fulfilled.length).toBe(20); + expect(fulfilled.every((r) => r.status === "fulfilled" && r.value.created)).toBe(true); + const reloaded = new ActionsStore(file); + expect((await reloaded.all()).length).toBe(20); + }); +});