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

fix: batch tombstone base-hash flushes (#5539)

Adam Eivy1567c821e5f5
diff --git a/server/lib/README.md b/server/lib/README.md
index 9b7828fb87..3652d585c9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -209,7 +209,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `borderKey.js` | Sharp-free image primitives shared by sprites and image-to-3D: statistics median, subsampled border-band sampling, solid-border coverage detection, and alpha meaningfulness/variation checks. |
| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `loadAllResult` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. `loadAll` silently drops corrupt records; `loadAllResult()` → `{ records, failedIds }` keeps the "which ids failed to load" signal so a caller can tell a partial set from a complete one. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. **Type-index `config` slot** holds cross-record state (see the `TypeIndexConfig` typedef + header convention): `{ runs?: [], featureFlags?: {}, lockPolicies?: {} }` — `runs` is the shipped slot (universeBuilder's capped history log), the other two are reserved names; consumers may add their own keys but should reuse a reserved name when it fits and document the shape next to the consumer. `saveTypeIndex({ config })` shallow-merges `config` one level deep (a patched `runs` replaces the whole array), so a read-modify-write of a slot must load → mutate a copy → write inside `queueTypeIndexWrite(fn)`. |
-| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record loop — the peer:online convergence push and batched `pruneTombstoned*` eviction loops — collapses N `sync_base_hashes.json` rewrites into one terminal write (depth-counted, so concurrent batches merge too; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned, so covered prune paths don't let the side store grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
+| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record loop — the peer:online convergence push and every base-hash-evicting `pruneTombstoned*` loop — collapses N `sync_base_hashes.json` rewrites into one terminal write (depth-counted, so concurrent batches merge too; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned, so those paths don't let the side store grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |
| `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. |
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.js
index 182e4f97f3..104a7b3481 100644
--- a/server/lib/conflictJournal.js
+++ b/server/lib/conflictJournal.js
@@ -290,13 +290,12 @@ export async function deleteSyncBaseHash(kind, id) {
/**
* Sweep base-hash entries whose record no longer resolves to a live record.
*
- * The per-record prune paths (`pruneTombstonedUniverses` / `…Series` / `…Issues`
- * / `…Collections`) already evict a record's base hash when they hard-delete its
- * tombstone. This is the BACKSTOP for keys that escaped those paths: a record
- * hand-deleted on disk, a key left behind by an older version before the prune
- * paths evicted, or any future kind that seeds a base hash without a matching
- * eviction. Without it the side store accumulates dead keys forever on a
- * long-lived federated install.
+ * The per-record prune paths that own base hashes already evict them when they
+ * hard-delete tombstones. This is the BACKSTOP for keys that escaped those
+ * paths: a record hand-deleted on disk, a key left behind by an older version
+ * before the prune paths evicted, or any future kind that seeds a base hash
+ * without a matching eviction. Without it the side store accumulates dead keys
+ * forever on a long-lived federated install.
*
* `resolves` is an async predicate `(kind, id) => boolean` — return true if the
* key still maps to a record we want to keep a base hash for. Keys whose kind
@@ -364,9 +363,9 @@ export function flushBaseHashes() {
*
* Two caller shapes use it: the `peer:online` convergence walk
* `retryPendingPushesForPeer` (pushes — and stamps — every subscribed record in
- * sequence), and `pruneTombstoned*` hard-prune loops that evict a base hash per
- * hard-deleted record. Eviction only marks `_baseDirty` for a key the map
- * actually held, so a prune that removed nothing still costs zero writes.
+ * sequence), and every base-hash-evicting `pruneTombstoned*` hard-prune loop.
+ * Eviction only marks `_baseDirty` for a key the map actually held, so a prune
+ * that removed nothing still costs zero writes.
*
* Re-entrant (depth-counted) so nested scopes collapse to the outermost batch,
* and the terminal flush runs in `finally` so a thrown/rejected `fn` still
@@ -381,10 +380,9 @@ export function flushBaseHashes() {
*
* Depth is module-level, not per-async-context, so CONCURRENT batches merge
* rather than nest. The tombstone GC fans its `pruneTombstoned*` calls out
- * through one `Promise.all`, so the batched ones overlap: the last scope to
- * close flushes every eviction they accumulated, and an unbatched sibling's
- * flush that landed while depth was still >0 rides along in that same write.
- * Nothing is dropped either way — a deferred flush leaves `_baseDirty` set.
+ * through one `Promise.all`, so their scopes overlap: the last scope to close
+ * flushes every eviction they accumulated. Nothing is dropped — a deferred
+ * flush leaves `_baseDirty` set.
*/
export async function withBaseHashFlushBatch(fn) {
_flushBatchDepth += 1;
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.js
index f556707875..53c8632fb8 100644
--- a/server/services/mediaCollections.js
+++ b/server/services/mediaCollections.js
@@ -33,6 +33,7 @@ import { compareNewerWins, compareEarlierWins } from '../lib/lwwTimestamp.js';
import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from './sharing/recordEvents.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+ withBaseHashFlushBatch,
} from '../lib/conflictJournal.js';
export const ERR_NOT_FOUND = 'NOT_FOUND';
@@ -979,20 +980,21 @@ export async function pruneTombstonedCollections(olderThanMs) {
// has settled, preserving the throw-on-failure contract without leaking
// background writes.
let firstError = null;
- const outcomes = await mapWithConcurrency(candidates, COLLECTION_WRITE_CONCURRENCY, (c) =>
- store().queueRecordWrite(c.id, async () => {
- // Re-check inside the queue (deleteOneNow spans the load→delete boundary)
- // so a concurrent re-create at the same id isn't blown away.
- const cur = await store().loadOne(c.id);
- if (!cur || cur.deleted !== true) return false;
- const ms = Date.parse(cur.deletedAt || '');
- if (!(Number.isFinite(ms) && ms < olderThanMs)) return false;
- await store().deleteOneNow(c.id);
- // Evict the conflict-journal base hash so the side store doesn't grow
- // dead keys (mirrors pruneTombstonedUniverses / pruneTombstonedSeries).
- await deleteSyncBaseHash('mediaCollection', c.id);
- return true;
- }).catch((err) => { if (!firstError) firstError = err; return false; }));
+ const outcomes = await withBaseHashFlushBatch(() =>
+ mapWithConcurrency(candidates, COLLECTION_WRITE_CONCURRENCY, (c) =>
+ store().queueRecordWrite(c.id, async () => {
+ // Re-check inside the queue (deleteOneNow spans the load→delete boundary)
+ // so a concurrent re-create at the same id isn't blown away.
+ const cur = await store().loadOne(c.id);
+ if (!cur || cur.deleted !== true) return false;
+ const ms = Date.parse(cur.deletedAt || '');
+ if (!(Number.isFinite(ms) && ms < olderThanMs)) return false;
+ await store().deleteOneNow(c.id);
+ // Evict the conflict-journal base hash so the side store doesn't grow
+ // dead keys (mirrors pruneTombstonedUniverses / pruneTombstonedSeries).
+ await deleteSyncBaseHash('mediaCollection', c.id);
+ return true;
+ }).catch((err) => { if (!firstError) firstError = err; return false; })));
if (firstError) throw firstError;
return { pruned: outcomes.filter(Boolean).length };
}
diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.js
index 990b412031..f60f549f15 100644
--- a/server/services/mediaCollections.test.js
+++ b/server/services/mediaCollections.test.js
@@ -12,10 +12,18 @@ import { mockNoPeerSync } from '../lib/mockPathsDataRoot.js';
// readdir/lstat/rm operate against a real fs tree.
const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'media-collections-test-'));
const COLLECTIONS_DIR = join(TEST_DATA_ROOT, 'media-collections');
+const writeCounter = vi.hoisted(() => ({ baseHash: 0 }));
vi.mock('../lib/fileUtils.js', async (importOriginal) => {
const actual = await importOriginal();
- return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT },
+ atomicWrite: async (path, data) => {
+ if (typeof path === 'string' && path.endsWith('sync_base_hashes.json')) writeCounter.baseHash += 1;
+ return actual.atomicWrite(path, data);
+ },
+ };
});
// Suppress the fire-and-forget dynamic import so tests don't load the real
@@ -48,6 +56,7 @@ function resetStore() {
rmSync(join(TEST_DATA_ROOT, 'conflict-journal'), { recursive: true, force: true });
mkdirSync(COLLECTIONS_DIR, { recursive: true });
cj.__resetBaseHashCacheForTests();
+ writeCounter.baseHash = 0;
uuidCounter = 0;
}
@@ -1723,11 +1732,21 @@ describe('pruneTombstonedCollections', () => {
createdAt: oldTs, updatedAt: futureTs, deleted: true, deletedAt: futureTs,
});
await seedState({ collections });
+ for (let i = 0; i < 10; i++) {
+ await cj.setSyncBaseHash('mediaCollection', `c-old-${i}`, `hash-old-${i}`);
+ }
+ await cj.flushBaseHashes();
+ writeCounter.baseHash = 0;
const result = await svc.pruneTombstonedCollections(Date.now());
expect(result).toEqual({ pruned: 10 }); // 10 old tombstones; live + recent survive
+ expect(writeCounter.baseHash).toBe(1);
const surviving = (await svc.listCollections({ includeDeleted: true })).map((c) => c.id).sort();
expect(surviving).toEqual(['c-live', 'c-recent']);
+ cj.__resetBaseHashCacheForTests();
+ for (let i = 0; i < 10; i++) {
+ expect(await cj.getSyncBaseHash('mediaCollection', `c-old-${i}`)).toBeNull();
+ }
});
it('does NOT prune a live collection', async () => {
diff --git a/server/services/pipeline/issueSync.js b/server/services/pipeline/issueSync.js
index 8744d550b0..bd349ff003 100644
--- a/server/services/pipeline/issueSync.js
+++ b/server/services/pipeline/issueSync.js
@@ -12,7 +12,7 @@ import { emitRecordUpdated } from '../sharing/recordEvents.js';
import * as seriesSvc from './series.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord,
- flushBaseHashes, deleteSyncBaseHash,
+ flushBaseHashes, deleteSyncBaseHash, withBaseHashFlushBatch,
} from '../../lib/conflictJournal.js';
import { store, readState, saveIssuesNow, renumberInline, sanitizeIssue } from './issuesShared.js';
@@ -185,7 +185,8 @@ export async function pruneTombstonedIssues(beforeMs) {
// pushRecordToPeer), but no eviction existed — so a pruned issue's key
// would linger in sync_base_hashes.json forever. Mirrors the universe /
// series / collection prune paths.
- await Promise.all(prunable.map((i) => deleteSyncBaseHash('issue', i.id)));
+ await withBaseHashFlushBatch(() =>
+ Promise.all(prunable.map((i) => deleteSyncBaseHash('issue', i.id))));
return { pruned: prunable.length };
});
}
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
index a1075425e8..41d2841096 100644
--- a/server/services/pipeline/issues.test.js
+++ b/server/services/pipeline/issues.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';
const fileStore = new Map();
+const writeCounter = vi.hoisted(() => ({ baseHash: 0 }));
// One-shot write delay hook for the concurrency regression test: when set, the
// first atomicWrite whose (path, data) matches is held for `ms` before landing,
// letting a test force a specific read→write interleaving deterministically.
@@ -13,6 +14,7 @@ tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
atomicWrite: vi.fn(async (path, data) => {
+ if (typeof path === 'string' && path.endsWith('sync_base_hashes.json')) writeCounter.baseHash += 1;
if (pendingWriteDelay && pendingWriteDelay.match(path, data)) {
const { ms } = pendingWriteDelay;
pendingWriteDelay = null; // one-shot
@@ -42,6 +44,8 @@ const { recordEvents } = await import('../sharing/recordEvents.js');
describe('pipeline issues service', () => {
beforeEach(() => {
fileStore.clear();
+ cj.__resetBaseHashCacheForTests();
+ writeCounter.baseHash = 0;
uuidCounter = 0;
pendingWriteDelay = null;
coverRefresh.refreshSeriesCoverImage.mockClear();
@@ -1180,33 +1184,43 @@ describe('pipeline issues service', () => {
describe('pruneTombstonedIssues', () => {
it('removes tombstones older than the cutoff and leaves newer ones + live records', async () => {
const live = await svc.createIssue({ seriesId: 'ser-prune', title: 'Live' });
- const oldT = await svc.createIssue({ seriesId: 'ser-prune', title: 'Old' });
+ const oldT = await svc.createIssue({ seriesId: 'ser-prune', title: 'Old A' });
+ const oldT2 = await svc.createIssue({ seriesId: 'ser-prune', title: 'Old B' });
const newT = await svc.createIssue({ seriesId: 'ser-prune', title: 'New' });
await svc.deleteIssue(oldT.id);
+ await svc.deleteIssue(oldT2.id);
await svc.deleteIssue(newT.id);
- // Back-date the old tombstone via merge so the GC sees it as 100s ago.
+ // Back-date both old tombstones via merge so the GC sees them as 100s ago.
const oldDeletedAt = new Date(Date.now() - 100_000).toISOString();
const oldIssue = await svc.getIssue(oldT.id, { includeDeleted: true });
- await svc.mergeIssuesFromSync([{
- ...oldIssue,
- deletedAt: oldDeletedAt,
- updatedAt: new Date(Date.now() + 10_000).toISOString(),
- }]);
- // Seed base hashes for the old (to-be-pruned) and live issues so we can
- // confirm only the pruned one's key is evicted.
+ const oldIssue2 = await svc.getIssue(oldT2.id, { includeDeleted: true });
+ const mergeUpdatedAt = new Date(Date.now() + 10_000).toISOString();
+ await svc.mergeIssuesFromSync([
+ { ...oldIssue, deletedAt: oldDeletedAt, updatedAt: mergeUpdatedAt },
+ { ...oldIssue2, deletedAt: oldDeletedAt, updatedAt: mergeUpdatedAt },
+ ]);
+ // Seed base hashes for both old (to-be-pruned) issues and the live issue
+ // so we can confirm the two evictions share one side-store write.
await cj.setSyncBaseHash('issue', oldT.id, 'hash-old');
+ await cj.setSyncBaseHash('issue', oldT2.id, 'hash-old-2');
await cj.setSyncBaseHash('issue', live.id, 'hash-live');
+ await cj.flushBaseHashes();
+ writeCounter.baseHash = 0;
const cutoff = Date.now() - 50_000;
const result = await svc.pruneTombstonedIssues(cutoff);
- expect(result.pruned).toBe(1);
+ expect(result.pruned).toBe(2);
+ expect(writeCounter.baseHash).toBe(1);
const remaining = await svc.listIssues({ seriesId: 'ser-prune', includeDeleted: true });
const ids = remaining.map((i) => i.id);
expect(ids).toContain(live.id);
expect(ids).toContain(newT.id);
expect(ids).not.toContain(oldT.id);
- // The pruned issue's conflict-journal base hash is evicted; the live
- // issue's key is untouched.
+ expect(ids).not.toContain(oldT2.id);
+ // Both pruned issues' conflict-journal base hashes are evicted; the
+ // live issue's key is untouched.
+ cj.__resetBaseHashCacheForTests();
expect(await cj.getSyncBaseHash('issue', oldT.id)).toBeNull();
+ expect(await cj.getSyncBaseHash('issue', oldT2.id)).toBeNull();
expect(await cj.getSyncBaseHash('issue', live.id)).toBe('hash-live');
});
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index a6e3eefaca..2e6c5f35a9 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -27,7 +27,7 @@ import { EFFORT_LEVELS } from '../../lib/providerModels.js';
import { DIAGNOSIS_MAX_FILED } from './seriesAutopilot/diagnosisCore.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,
- deleteSyncBaseHash,
+ deleteSyncBaseHash, withBaseHashFlushBatch,
} from '../../lib/conflictJournal.js';
import {
emitRecordUpdated, emitRecordDeleted,
@@ -1314,17 +1314,18 @@ export async function pruneTombstonedSeries(beforeMs) {
// queued delete; without the re-check we'd rm -rf a freshly un-deleted
// record. Mirrors pruneTombstonedUniverses. Uses deleteOneNow (not deleteOne —
// that re-enters queueRecordWrite for the same id and would deadlock).
- const results = await Promise.allSettled(candidates.map((id) =>
- s.queueRecordWrite(id, async () => {
- const fresh = await s.loadOne(id);
- if (!fresh?.deleted) return false; // un-deleted between snapshot and queue
- const t = Date.parse(fresh.deletedAt || '');
- if (!Number.isFinite(t) || t >= beforeMs) return false;
- await s.deleteOneNow(id);
- await deleteSyncBaseHash('series', id);
- return true;
- })
- ));
+ const results = await withBaseHashFlushBatch(() =>
+ Promise.allSettled(candidates.map((id) =>
+ s.queueRecordWrite(id, async () => {
+ const fresh = await s.loadOne(id);
+ if (!fresh?.deleted) return false; // un-deleted between snapshot and queue
+ const t = Date.parse(fresh.deletedAt || '');
+ if (!Number.isFinite(t) || t >= beforeMs) return false;
+ await s.deleteOneNow(id);
+ await deleteSyncBaseHash('series', id);
+ return true;
+ })
+ )));
let pruned = 0;
for (const r of results) {
if (r.status === 'fulfilled' && r.value === true) pruned += 1;
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
index d9a09807d5..1b2b1916b7 100644
--- a/server/services/pipeline/series.test.js
+++ b/server/services/pipeline/series.test.js
@@ -2,12 +2,16 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';
const fileStore = new Map();
+const writeCounter = vi.hoisted(() => ({ baseHash: 0 }));
vi.mock('../../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
- atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
+ atomicWrite: vi.fn(async (path, data) => {
+ if (typeof path === 'string' && path.endsWith('sync_base_hashes.json')) writeCounter.baseHash += 1;
+ fileStore.set(path, data);
+ }),
readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),
}));
@@ -21,11 +25,14 @@ vi.mock('../instances.js', () => mockNoPeers());
vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());
const svc = await import('./series.js');
+const cj = await import('../../lib/conflictJournal.js');
const { recordEvents, registerSubscriptionAdapter, __resetSubscriptionAdapter } = await import('../sharing/recordEvents.js');
describe('pipeline series service', () => {
beforeEach(() => {
fileStore.clear();
+ cj.__resetBaseHashCacheForTests();
+ writeCounter.baseHash = 0;
uuidCounter = 0;
});
@@ -423,26 +430,38 @@ describe('pipeline series service', () => {
describe('pruneTombstonedSeries', () => {
it('removes tombstones older than the cutoff and leaves newer ones + live records', async () => {
const live = await svc.createSeries({ name: 'Live' });
- const oldT = await svc.createSeries({ name: 'Old tombstone' });
+ const oldT = await svc.createSeries({ name: 'Old tombstone A' });
+ const oldT2 = await svc.createSeries({ name: 'Old tombstone B' });
const newT = await svc.createSeries({ name: 'New tombstone' });
await svc.deleteSeries(oldT.id);
+ await svc.deleteSeries(oldT2.id);
await svc.deleteSeries(newT.id);
- // Back-date the old tombstone via merge so the GC sees it as 100s ago.
+ // Back-date both old tombstones via merge so the GC sees them as 100s ago.
const oldDeletedAt = new Date(Date.now() - 100_000).toISOString();
const oldSeries = await svc.getSeries(oldT.id, { includeDeleted: true });
- await svc.mergeSeriesFromSync([{
- ...oldSeries,
- deletedAt: oldDeletedAt,
- updatedAt: new Date(Date.now() + 10_000).toISOString(),
- }]);
+ const oldSeries2 = await svc.getSeries(oldT2.id, { includeDeleted: true });
+ const mergeUpdatedAt = new Date(Date.now() + 10_000).toISOString();
+ await svc.mergeSeriesFromSync([
+ { ...oldSeries, deletedAt: oldDeletedAt, updatedAt: mergeUpdatedAt },
+ { ...oldSeries2, deletedAt: oldDeletedAt, updatedAt: mergeUpdatedAt },
+ ]);
+ await cj.setSyncBaseHash('series', oldT.id, 'hash-old-a');
+ await cj.setSyncBaseHash('series', oldT2.id, 'hash-old-b');
+ await cj.flushBaseHashes();
+ writeCounter.baseHash = 0;
const cutoff = Date.now() - 50_000;
const result = await svc.pruneTombstonedSeries(cutoff);
- expect(result.pruned).toBe(1);
+ expect(result.pruned).toBe(2);
+ expect(writeCounter.baseHash).toBe(1);
const remaining = await svc.listSeries({ includeDeleted: true });
const ids = remaining.map((s) => s.id);
expect(ids).toContain(live.id);
expect(ids).toContain(newT.id);
expect(ids).not.toContain(oldT.id);
+ expect(ids).not.toContain(oldT2.id);
+ cj.__resetBaseHashCacheForTests();
+ expect(await cj.getSyncBaseHash('series', oldT.id)).toBeNull();
+ expect(await cj.getSyncBaseHash('series', oldT2.id)).toBeNull();
});
it('keeps tombstones with unparseable deletedAt (conservative — never silently delete)', async () => {
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 4e8c7e8476..cc0d5518a6 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -9,6 +9,7 @@ import { mockNoPeerSync, mockNoPeers } from "../lib/mockPathsDataRoot.js";
// tree in beforeEach. The fileUtils mock below overrides PATHS.data so the
// universeBuilder + collectionStore land here instead of the real ./data.
const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), "universe-builder-test-"));
+const writeCounter = vi.hoisted(() => ({ baseHash: 0 }));
// Per-test reference-sheet "what exists on disk" — keys are filenames the
// referenceSheetImageRef preservation guard / pruner asks about. Default
@@ -25,6 +26,10 @@ vi.mock("../lib/fileUtils.js", async (importOriginal) => {
// (atomicWrite, readJSONFile, ensureDir, etc.) uses the real impl so
// collectionStore's readdir/stat/rm operate against a real fs tree.
PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT },
+ atomicWrite: async (path, data) => {
+ if (typeof path === 'string' && path.endsWith('sync_base_hashes.json')) writeCounter.baseHash += 1;
+ return actual.atomicWrite(path, data);
+ },
// mustExist: true → return a non-null path when the filename either
// appears in refSheetFilesByName or has no explicit "missing" entry.
// Tests opt into "this file is gone" by calling
@@ -80,6 +85,7 @@ vi.mock("crypto", async () => {
});
const svc = await import("./universeBuilder.js");
+const cj = await import("../lib/conflictJournal.js");
const { recordEvents, registerSubscriptionAdapter, __resetSubscriptionAdapter } = await import("./sharing/recordEvents.js");
// Default universe with non-empty influences. Override `influences` for tests
@@ -122,6 +128,8 @@ describe("universeBuilder service", () => {
// universes/ tree.
rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
mkdirSync(TEST_DATA_ROOT, { recursive: true });
+ cj.__resetBaseHashCacheForTests();
+ writeCounter.baseHash = 0;
uuidCounter = 0;
refSheetFilesByName.clear();
});
@@ -1325,26 +1333,45 @@ describe("universeBuilder service", () => {
it("removes tombstones older than the cutoff and leaves newer ones + live records", async () => {
const live = await seedWorld();
const oldTombstone = await seedWorld();
+ const oldTombstone2 = await seedWorld();
const newTombstone = await seedWorld();
await svc.deleteUniverse(oldTombstone.id);
+ await svc.deleteUniverse(oldTombstone2.id);
await svc.deleteUniverse(newTombstone.id);
- // Backdate the old tombstone's deletedAt directly via merge.
+ // Backdate both old tombstones' deletedAt directly via merge.
const oldDeletedAt = new Date(Date.now() - 100_000).toISOString();
- await svc.mergeUniversesFromSync([{
- ...(await svc.getUniverse(oldTombstone.id, { includeDeleted: true })),
- deletedAt: oldDeletedAt,
- updatedAt: new Date(Date.now() + 10_000).toISOString(),
- }]);
+ const mergeUpdatedAt = new Date(Date.now() + 10_000).toISOString();
+ await svc.mergeUniversesFromSync([
+ {
+ ...(await svc.getUniverse(oldTombstone.id, { includeDeleted: true })),
+ deletedAt: oldDeletedAt,
+ updatedAt: mergeUpdatedAt,
+ },
+ {
+ ...(await svc.getUniverse(oldTombstone2.id, { includeDeleted: true })),
+ deletedAt: oldDeletedAt,
+ updatedAt: mergeUpdatedAt,
+ },
+ ]);
+ await cj.setSyncBaseHash('universe', oldTombstone.id, 'hash-old-a');
+ await cj.setSyncBaseHash('universe', oldTombstone2.id, 'hash-old-b');
+ await cj.flushBaseHashes();
+ writeCounter.baseHash = 0;
// Cutoff = now - 50s — old (100s ago) is past, new (just now) is not.
const cutoff = Date.now() - 50_000;
const result = await svc.pruneTombstonedUniverses(cutoff);
- expect(result.pruned).toBe(1);
+ expect(result.pruned).toBe(2);
+ expect(writeCounter.baseHash).toBe(1);
const remaining = await svc.listUniverses({ includeDeleted: true });
const ids = remaining.map((u) => u.id);
expect(ids).toContain(live.id);
expect(ids).toContain(newTombstone.id);
expect(ids).not.toContain(oldTombstone.id);
+ expect(ids).not.toContain(oldTombstone2.id);
+ cj.__resetBaseHashCacheForTests();
+ expect(await cj.getSyncBaseHash('universe', oldTombstone.id)).toBeNull();
+ expect(await cj.getSyncBaseHash('universe', oldTombstone2.id)).toBeNull();
});
it("keeps tombstones with unparseable deletedAt (conservative)", async () => {
diff --git a/server/services/universeBuilder/sync.js b/server/services/universeBuilder/sync.js
index ef3440ddf4..be3cbc1939 100644
--- a/server/services/universeBuilder/sync.js
+++ b/server/services/universeBuilder/sync.js
@@ -11,7 +11,7 @@
import { isStr, preserveLegacyCharacterProductionPackages } from '../../lib/storyBible.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,
- deleteSyncBaseHash,
+ deleteSyncBaseHash, withBaseHashFlushBatch,
} from '../../lib/conflictJournal.js';
import { sanitizeTemplate } from './sanitize.js';
import { isValidUniverseId } from './store.js';
@@ -216,17 +216,18 @@ export async function pruneTombstonedUniverses(beforeMs) {
// we'd rm -rf a freshly un-deleted record. Counts only the records we
// actually pruned (the candidates set minus any rescued by a concurrent
// un-delete).
- const results = await Promise.allSettled(candidates.map((id) =>
- s.queueRecordWrite(id, async () => {
- const fresh = await s.loadOne(id);
- if (!fresh?.deleted) return false; // un-deleted between snapshot and queue
- const t = Date.parse(fresh.deletedAt || '');
- if (!Number.isFinite(t) || t >= beforeMs) return false;
- await s.deleteRecord(id);
- await deleteSyncBaseHash('universe', id);
- return true;
- })
- ));
+ const results = await withBaseHashFlushBatch(() =>
+ Promise.allSettled(candidates.map((id) =>
+ s.queueRecordWrite(id, async () => {
+ const fresh = await s.loadOne(id);
+ if (!fresh?.deleted) return false; // un-deleted between snapshot and queue
+ const t = Date.parse(fresh.deletedAt || '');
+ if (!Number.isFinite(t) || t >= beforeMs) return false;
+ await s.deleteRecord(id);
+ await deleteSyncBaseHash('universe', id);
+ return true;
+ })
+ )));
let pruned = 0;
for (const r of results) {
if (r.status === 'fulfilled' && r.value === true) pruned += 1;