From eb0ffe7fa6772d6bd589119f47952bf43adb27d6 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Wed, 28 Oct 2026 04:41:17 -0500 Subject: [PATCH 1/2] fix(aggregator): serialize JSON store persists, unique temp paths, 5xx on persistence failure (#1509) Comments/Actions stores and the live session registry persisted via a pid-only temp path with no serialization: concurrent writes shared the temp file, the first rename won, the rest threw ENOENT, and fulfilled calls diverged from disk. Persists now run through a per-store promise chain with a unique temp path per write and the snapshot taken when the queued write runs. Fixing that exposed a second race the regression test caught: load() set a boolean and let concurrent first callers proceed before the read finished; the read completion then reset the in-memory array and wiped records just pushed (5 concurrent first adds -> 1 in memory). load() is now a memoized promise in both stores. POST /api/comments and /api/actions return 500 on persistence failure; 400 remains for validation/body errors only. Regression: test/store-concurrency.test.ts - 20 concurrent adds per store, fulfilled == reloaded == 20. Full aggregator suite on laptop: 303 pass / 0 fail; tsc --noEmit clean. --- pm-stack/aggregator/src/actions.ts | 33 ++++++++--- pm-stack/aggregator/src/comments.ts | 39 ++++++++++--- pm-stack/aggregator/src/server.ts | 18 +++++- pm-stack/aggregator/src/sources/live.ts | 13 ++++- .../aggregator/test/store-concurrency.test.ts | 55 +++++++++++++++++++ 5 files changed, 136 insertions(+), 22 deletions(-) create mode 100644 pm-stack/aggregator/test/store-concurrency.test.ts 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..972c012e7b --- /dev/null +++ b/pm-stack/aggregator/test/store-concurrency.test.ts @@ -0,0 +1,55 @@ +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); + }); +}); From 6bee82dcac81aed83674a9b14d1cc19fa992ff7d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Wed, 28 Oct 2026 05:22:32 -0500 Subject: [PATCH 2/2] style(aggregator): biome-format store-concurrency test (treefmt check fix) --- pm-stack/aggregator/test/store-concurrency.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/pm-stack/aggregator/test/store-concurrency.test.ts b/pm-stack/aggregator/test/store-concurrency.test.ts index 972c012e7b..365aa1706b 100644 --- a/pm-stack/aggregator/test/store-concurrency.test.ts +++ b/pm-stack/aggregator/test/store-concurrency.test.ts @@ -46,9 +46,7 @@ describe("JSON stores under concurrent adds (#1509)", () => { 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); + expect(fulfilled.every((r) => r.status === "fulfilled" && r.value.created)).toBe(true); const reloaded = new ActionsStore(file); expect((await reloaded.all()).length).toBe(20); });