Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

invalidate the review-store cache on write instead of re-seeding it from a post-write stat (#6853)

[._.]/ Adam Eivy1ee854ff2c58
diff --git a/server/services/review.js b/server/services/review.js
index ef10550770..95a3070ab0 100644
--- a/server/services/review.js
+++ b/server/services/review.js
@@ -37,8 +37,13 @@ const ARCHIVE_ELIGIBLE_STATUSES = new Set(['completed', 'dismissed']);
// `review` as archivable/deletable, so `data/review/` can be archived or
// deleted out from under this process while it runs, and a flag-based cache
// would keep serving a since-deleted file's contents forever. `saveItems`
-// re-stats after every write and seeds the cache directly from what it just
-// wrote, so a read immediately following a write is a cache hit, not a re-parse.
+// INVALIDATES the cache after every write rather than seeding it from what it
+// wrote: two saveItems calls can interleave (a route and a cosEvents handler
+// — the same window as the documented lost-update race), and a post-write
+// stat could then pin one writer's content under the other writer's identity
+// and serve it until the next write. Invalidation keeps the invariant simple —
+// the cache only ever holds content read from the file under its own identity
+// — at the cost of one re-parse per write.
//
// `loadItems()` hands every caller a fresh shallow clone (see `cloneItems`),
// never the cached array/objects themselves — `getItems` is a public export
@@ -48,9 +53,9 @@ const ARCHIVE_ELIGIBLE_STATUSES = new Set(['completed', 'dismissed']);
// `saveItems` call. The internal mutation paths below (createItem/
// updateItemStatus/bulkUpdateStatus/updateItem/deleteItem/
// updateStatusByReferenceId) mutate the clone `loadItems()` gave them and
-// then immediately call `saveItems` with it — `saveItems` seeds the cache
-// from a clone of what it wrote, so the objects those paths return to their
-// callers are theirs to mutate too.
+// then immediately call `saveItems` with it — nothing they hold is ever
+// cached, so the objects those paths return to their callers are theirs to
+// mutate too.
let itemsCache = null; // { mtimeMs, size, items }
let lastRetentionAt = 0; // 0 so the first save after boot always evaluates retention
@@ -171,18 +176,15 @@ async function applyRetention(items) {
}
/**
- * Save items to file atomically, applying retention first and re-priming the
- * read cache from what was actually written.
+ * Save items to file atomically, applying retention first and invalidating
+ * the read cache (see the cache comment above for why it is not re-seeded
+ * from what was written).
*/
async function saveItems(items) {
await ensureDir(DATA_DIR);
const retained = await applyRetention(items);
await atomicWrite(ITEMS_FILE, retained);
- const stats = await stat(ITEMS_FILE).catch(() => null);
- // Seed from a clone, not the caller's array: the mutation paths return the
- // objects they just saved to their callers, and the cache must never share
- // a reference with anything outside this module (see the cache comment).
- itemsCache = stats ? { mtimeMs: stats.mtimeMs, size: stats.size, items: cloneItems(retained) } : null;
+ itemsCache = null;
}
/**
diff --git a/server/services/review.test.js b/server/services/review.test.js
index f035ebb6c1..895bdf6041 100644
--- a/server/services/review.test.js
+++ b/server/services/review.test.js
@@ -387,19 +387,19 @@ describe('review service', () => {
expect(readFile).toHaveBeenCalledTimes(2);
});
- it('reflects a write in the very next read without a second parse', async () => {
+ it('invalidates the cache on a write, so the very next read re-parses the file', async () => {
stat.mockResolvedValueOnce({ mtimeMs: 814001, size: 1 }); // loadItems() inside createItem
readFile.mockResolvedValueOnce('[]');
- stat.mockResolvedValueOnce({ mtimeMs: 814002, size: 2 }); // saveItems' post-write stat
- stat.mockResolvedValueOnce({ mtimeMs: 814002, size: 2 }); // getPendingCounts' loadItems — same identity
+ stat.mockResolvedValueOnce({ mtimeMs: 814002, size: 2 }); // getPendingCounts' loadItems after the write
+ readFile.mockResolvedValueOnce(JSON.stringify([{ id: 'a', type: 'todo', status: 'pending' }]));
await createItem({ type: 'todo', title: 'First item' });
const counts = await getPendingCounts();
expect(counts.total).toBe(1);
- // Only createItem's own cache-miss read — getPendingCounts hit the
- // cache saveItems seeded from the write, not a re-parse.
- expect(readFile).toHaveBeenCalledTimes(1);
+ // createItem's own cache-miss read plus the re-parse the write forces —
+ // never the pre-write cached list.
+ expect(readFile).toHaveBeenCalledTimes(2);
});
});
@@ -533,11 +533,14 @@ describe('review service', () => {
expect(survivingIds).not.toEqual(expect.arrayContaining(['c-old']));
expect(survivingIds).not.toEqual(expect.arrayContaining(['d-old']));
- // getPendingCounts must still be correct post-retention, and served
- // from the cache saveItems just seeded rather than a fresh parse.
+ // The write invalidated the cache: the next read re-parses items.json —
+ // now holding exactly what retention left behind — so the counts reflect
+ // the trimmed list, not the pre-retention fixture.
+ readFile.mockImplementation((path) =>
+ Promise.resolve(String(path).endsWith('archive.json') ? JSON.stringify(archiveData) : JSON.stringify(itemsData)));
const counts = await getPendingCounts();
expect(counts.total).toBe(2); // p1 + the new item createItem just added
- expect(readFile).toHaveBeenCalledTimes(2); // items.json once + archive.json once — no third parse
+ expect(readFile).toHaveBeenCalledTimes(3); // items.json + archive.json during the save, items.json again after it
});
it('does not block a live write when archive.json is unreadable — retention is skipped, items.json still saves', async () => {
@@ -674,18 +677,6 @@ describe('review service', () => {
expect(original.injected).toBeUndefined();
expect(original.metadata.injected).toBeUndefined();
});
-
- it('does not let a caller mutating a createItem() result pollute the cache seeded by that save', async () => {
- stat.mockResolvedValue({ mtimeMs: 829001, size: 1 });
- readFile.mockResolvedValue('[]');
-
- const created = await createItem({ type: 'todo', title: 'Original title' });
- created.title = 'mutated after return';
-
- // Same file identity → cache hit: the cached copy must not carry the mutation.
- const [cached] = await getItems({ status: 'pending' });
- expect(cached.title).toBe('Original title');
- });
});
describe('bulkUpdateStatus events', () => {