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

feat([conflict-journal-base-hash-prune]): evict + sweep orphaned sync base hashes

[._.]/ Adam Eivy9d28a340eb0a
diff --git a/server/lib/README.md b/server/lib/README.md
index 35180e2abb..c7c3affe17 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -95,7 +95,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
| `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` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. 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. |
-| `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 push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from `pruneTombstonedUniverses`/`pruneTombstonedSeries`) so the side store doesn't grow without bound. `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 push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't 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. |
| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, `expandHome` (`~/foo` → absolute), JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.js
index 699a66b531..ac5af03301 100644
--- a/server/lib/conflictJournal.js
+++ b/server/lib/conflictJournal.js
@@ -172,6 +172,45 @@ export async function deleteSyncBaseHash(kind, id) {
await flushBaseHashes();
}
+/**
+ * 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.
+ *
+ * `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
+ * the caller doesn't recognize are LEFT ALONE (the predicate should return true
+ * for unknown kinds) so a partial resolver can never strip live entries it
+ * simply didn't know how to check. Coalesces into one disk write via the dirty
+ * flag + a single trailing flush.
+ *
+ * Returns `{ pruned }`.
+ */
+export async function pruneOrphanedBaseHashes(resolves) {
+ if (typeof resolves !== 'function') return { pruned: 0 };
+ const map = await ensureBaseLoaded();
+ let pruned = 0;
+ for (const key of [...map.keys()]) {
+ const sep = key.indexOf(':');
+ if (sep < 0) continue; // malformed key — leave it, never guess
+ const kind = key.slice(0, sep);
+ const id = key.slice(sep + 1);
+ const keep = await resolves(kind, id).catch(() => true); // resolver error → conservative keep
+ if (keep) continue;
+ map.delete(key);
+ _baseDirty = true;
+ pruned += 1;
+ }
+ if (pruned > 0) await flushBaseHashes();
+ return { pruned };
+}
+
/** Persist the base-hash map if dirty. Serialized so concurrent flushes can't
* interleave file writes. Call once after a merge's write loop.
*
diff --git a/server/lib/conflictJournal.test.js b/server/lib/conflictJournal.test.js
index 8396d6f414..b485dbbce6 100644
--- a/server/lib/conflictJournal.test.js
+++ b/server/lib/conflictJournal.test.js
@@ -281,6 +281,42 @@ describe('conflictJournal', () => {
await expect(cj.deleteSyncBaseHash('universe', 'nonexistent')).resolves.toBeUndefined();
expect(await cj.getSyncBaseHash('universe', 'nonexistent')).toBeNull();
});
+
+ describe('pruneOrphanedBaseHashes', () => {
+ it('drops keys whose record no longer resolves, keeps the rest', async () => {
+ await cj.setSyncBaseHash('universe', 'live', cj.contentHashForRecord('universe', uni({ id: 'live' })));
+ await cj.setSyncBaseHash('universe', 'dead', cj.contentHashForRecord('universe', uni({ id: 'dead' })));
+ await cj.setSyncBaseHash('series', 'live-s', cj.contentHashForRecord('universe', uni({ id: 'live-s' })));
+ // Resolver: only 'live' and 'live-s' still exist.
+ const liveKeys = new Set(['universe:live', 'series:live-s']);
+ const { pruned } = await cj.pruneOrphanedBaseHashes(async (kind, id) => liveKeys.has(`${kind}:${id}`));
+ expect(pruned).toBe(1);
+ expect(await cj.getSyncBaseHash('universe', 'live')).not.toBeNull();
+ expect(await cj.getSyncBaseHash('universe', 'dead')).toBeNull();
+ expect(await cj.getSyncBaseHash('series', 'live-s')).not.toBeNull();
+ });
+
+ it('keeps keys of an unknown kind (resolver returns true) so a partial resolver never strips live entries', async () => {
+ await cj.setSyncBaseHash('issue', 'iss-1', cj.contentHashForRecord('issue', iss({ id: 'iss-1' })));
+ // Resolver mirrors the real one: unknown kinds → true (never strip).
+ const { pruned } = await cj.pruneOrphanedBaseHashes(async (kind) => (kind === 'issue' ? true : true));
+ expect(pruned).toBe(0);
+ expect(await cj.getSyncBaseHash('issue', 'iss-1')).not.toBeNull();
+ });
+
+ it('treats a resolver that throws as a conservative keep', async () => {
+ await cj.setSyncBaseHash('universe', 'u-x', cj.contentHashForRecord('universe', uni({ id: 'u-x' })));
+ const { pruned } = await cj.pruneOrphanedBaseHashes(async () => { throw new Error('lookup blew up'); });
+ expect(pruned).toBe(0);
+ expect(await cj.getSyncBaseHash('universe', 'u-x')).not.toBeNull();
+ });
+
+ it('returns {pruned:0} when given a non-function', async () => {
+ await cj.setSyncBaseHash('universe', 'u-y', cj.contentHashForRecord('universe', uni({ id: 'u-y' })));
+ expect(await cj.pruneOrphanedBaseHashes(null)).toEqual({ pruned: 0 });
+ expect(await cj.getSyncBaseHash('universe', 'u-y')).not.toBeNull();
+ });
+ });
});
// A minimal collection-shaped record (sanitizeRecordForWire('mediaCollection')
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.js
index 98ca78b88e..89da73150e 100644
--- a/server/services/mediaCollections.js
+++ b/server/services/mediaCollections.js
@@ -30,7 +30,7 @@ import { ITEM_KIND, REF_MAX_LENGTH, itemKey } from '../lib/mediaItemKey.js';
import { sanitizeOrigin } from '../lib/sharingOrigin.js';
import { emitRecordUpdated, emitRecordDeleted } from './sharing/recordEvents.js';
import {
- maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,
+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
} from '../lib/conflictJournal.js';
export const ERR_NOT_FOUND = 'NOT_FOUND';
@@ -901,6 +901,9 @@ export async function pruneTombstonedCollections(olderThanMs) {
const ms = Date.parse(cur.deletedAt || '');
if (!(Number.isFinite(ms) && ms < olderThanMs)) return;
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);
pruned += 1;
});
}
diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.js
index c1a719d5b3..b36b2cccce 100644
--- a/server/services/mediaCollections.test.js
+++ b/server/services/mediaCollections.test.js
@@ -1618,9 +1618,15 @@ describe('pruneTombstonedCollections', () => {
const stored = await readStored(c.id);
await seedState({ collections: [{ ...stored, deleted: true, deletedAt: oldTs, updatedAt: oldTs, items: [] }] });
+ // Seed a base hash so we can confirm the prune evicts it.
+ await cj.setSyncBaseHash('mediaCollection', c.id, cj.contentHashForRecord('mediaCollection', stored));
+ expect(await cj.getSyncBaseHash('mediaCollection', c.id)).not.toBeNull();
+
const result = await svc.pruneTombstonedCollections(Date.now());
expect(result).toEqual({ pruned: 1 });
expect(await svc.listCollections({ includeDeleted: true })).toHaveLength(0);
+ // The conflict-journal base hash is evicted so the side store doesn't leak.
+ expect(await cj.getSyncBaseHash('mediaCollection', c.id)).toBeNull();
});
it('does NOT prune a live collection', async () => {
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index f39e214df4..66403f1a78 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -36,7 +36,7 @@ import { isStr, trimTo } from '../../lib/storyBible.js';
import { sanitizeCoverLike } from '../../lib/renderSlot.js';
import { emitRecordUpdated } from '../sharing/recordEvents.js';
import { applyVolumeOrderedNumbers, UNSCOPED_ANCHOR } from '../../lib/pipelineIssueOrder.js';
-import { maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes } from '../../lib/conflictJournal.js';
+import { maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash } from '../../lib/conflictJournal.js';
import * as seriesSvc from './series.js';
// TYPE-level (storage layout) schema version stamped on
@@ -1243,6 +1243,12 @@ export async function pruneTombstonedIssues(beforeMs) {
return t < beforeMs;
});
await Promise.all(prunable.map((i) => store().deleteOne(i.id)));
+ // Evict each pruned issue's conflict-journal base hash. Issues seed an
+ // `issue:<id>` base hash when their parent series is pushed (peerSync's
+ // 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)));
return { pruned: prunable.length };
});
}
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
index 646506be44..31cb054a79 100644
--- a/server/services/pipeline/issues.test.js
+++ b/server/services/pipeline/issues.test.js
@@ -954,6 +954,10 @@ describe('pipeline issues service', () => {
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.
+ await cj.setSyncBaseHash('issue', oldT.id, 'hash-old');
+ await cj.setSyncBaseHash('issue', live.id, 'hash-live');
const cutoff = Date.now() - 50_000;
const result = await svc.pruneTombstonedIssues(cutoff);
expect(result.pruned).toBe(1);
@@ -962,6 +966,10 @@ describe('pipeline issues service', () => {
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(await cj.getSyncBaseHash('issue', oldT.id)).toBeNull();
+ expect(await cj.getSyncBaseHash('issue', live.id)).toBe('hash-live');
});
it('keeps tombstones with unparseable deletedAt (conservative — never silently delete)', async () => {
diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.js
index b32292a99e..73d1bb42ec 100644
--- a/server/services/sharing/tombstoneGc.js
+++ b/server/services/sharing/tombstoneGc.js
@@ -26,14 +26,29 @@
* cohort for issue tombstones is "peers subscribed to series".
*/
-import { pruneTombstonedUniverses } from '../universeBuilder.js';
-import { pruneTombstonedSeries } from '../pipeline/series.js';
-import { pruneTombstonedIssues } from '../pipeline/issues.js';
-import { pruneTombstonedCollections } from '../mediaCollections.js';
+import { pruneTombstonedUniverses, getUniverse } from '../universeBuilder.js';
+import { pruneTombstonedSeries, getSeries } from '../pipeline/series.js';
+import { pruneTombstonedIssues, getIssue } from '../pipeline/issues.js';
+import { pruneTombstonedCollections, getCollection } from '../mediaCollections.js';
+import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';
import { listPeerSubscriptions } from './peerSync.js';
import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';
import { getPeers } from '../instances.js';
+// Resolver for pruneOrphanedBaseHashes: does this base-hash key still map to a
+// LIVE record? A getter that returns null/undefined (missing or tombstoned —
+// default excludes deleted) means the key is dead. Unknown kinds return true so
+// the sweep never strips a key it can't authoritatively check (a base hash for
+// a future kind, or a key shape this version doesn't recognize). getCollection
+// rejects when not found, so the `.catch(() => null)` maps that to "dead".
+async function baseHashKeyResolves(kind, id) {
+ if (kind === 'universe') return !!(await getUniverse(id).catch(() => null));
+ if (kind === 'series') return !!(await getSeries(id).catch(() => null));
+ if (kind === 'issue') return !!(await getIssue(id).catch(() => null));
+ if (kind === 'mediaCollection') return !!(await getCollection(id).catch(() => null));
+ return true; // unknown kind → never strip
+}
+
const GRACE_MS = 24 * 60 * 60 * 1000;
// `peer_subscriptions.json` rows outlive peer removal (no cleanup hook on
@@ -196,11 +211,19 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
issueCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedIssues(issueCutoff),
collectionCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedCollections(collectionCutoff),
]);
+ // Backstop AFTER the tombstone prunes: the prune paths already evict a freshly
+ // hard-deleted record's base hash, so this sweep mops up only keys that
+ // escaped (records deleted outside the prune path, pre-existing accumulation
+ // on long-lived installs, or a future kind without per-record eviction). Runs
+ // every kind regardless of which were refused — orphan keys aren't gated on
+ // snapshot coverage.
+ const orphan = await pruneOrphanedBaseHashes(baseHashKeyResolves);
return {
universes: u.pruned,
series: s.pruned,
issues: i.pruned,
collections: c.pruned,
+ orphanBaseHashes: orphan.pruned,
refused: refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff),
};
}
diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.js
index a04ff13c5a..79d731b857 100644
--- a/server/services/sharing/tombstoneGc.test.js
+++ b/server/services/sharing/tombstoneGc.test.js
@@ -6,15 +6,22 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// covered by their own service tests.
vi.mock('../universeBuilder.js', () => ({
pruneTombstonedUniverses: vi.fn().mockResolvedValue({ pruned: 0 }),
+ getUniverse: vi.fn().mockResolvedValue(null),
}));
vi.mock('../pipeline/series.js', () => ({
pruneTombstonedSeries: vi.fn().mockResolvedValue({ pruned: 0 }),
+ getSeries: vi.fn().mockResolvedValue(null),
}));
vi.mock('../pipeline/issues.js', () => ({
pruneTombstonedIssues: vi.fn().mockResolvedValue({ pruned: 0 }),
+ getIssue: vi.fn().mockResolvedValue(null),
}));
vi.mock('../mediaCollections.js', () => ({
pruneTombstonedCollections: vi.fn().mockResolvedValue({ pruned: 0 }),
+ getCollection: vi.fn().mockResolvedValue(null),
+}));
+vi.mock('../../lib/conflictJournal.js', () => ({
+ pruneOrphanedBaseHashes: vi.fn().mockResolvedValue({ pruned: 0 }),
}));
vi.mock('./peerSync.js', () => ({
listPeerSubscriptions: vi.fn(),
@@ -35,6 +42,7 @@ import { pruneTombstonedUniverses } from '../universeBuilder.js';
import { pruneTombstonedSeries } from '../pipeline/series.js';
import { pruneTombstonedIssues } from '../pipeline/issues.js';
import { pruneTombstonedCollections } from '../mediaCollections.js';
+import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';
import { listPeerSubscriptions } from './peerSync.js';
import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';
import { getPeers } from '../instances.js';
@@ -89,6 +97,32 @@ describe('sweepTombstones — no peers subscribed', () => {
});
});
+describe('sweepTombstones — orphaned base-hash sweep', () => {
+ it('runs the orphan sweep and surfaces its count, regardless of refusals', async () => {
+ // A snapshot-mode peer with no per-record sub refuses every tombstone kind
+ // (cutoff null) — but the orphan sweep is NOT gated on coverage, so it must
+ // still run.
+ getPeers.mockResolvedValue([
+ { instanceId: 'peer-a', enabled: true, syncEnabled: true, syncCategories: { universe: true, pipeline: true, mediaCollections: true } },
+ ]);
+ mockSubs({}); // no per-record subscriptions → all kinds refused
+ pruneOrphanedBaseHashes.mockResolvedValueOnce({ pruned: 3 });
+
+ const res = await sweepTombstones({ now: NOW });
+ expect(pruneOrphanedBaseHashes).toHaveBeenCalledTimes(1);
+ // The resolver passed in is the kind-aware predicate (a function).
+ expect(typeof pruneOrphanedBaseHashes.mock.calls[0][0]).toBe('function');
+ expect(res.orphanBaseHashes).toBe(3);
+ // Tombstone prunes were refused, but the orphan sweep still reported.
+ expect(res.refused).toEqual(expect.arrayContaining(['universe', 'series', 'issue', 'mediaCollection']));
+ });
+
+ it('reports orphanBaseHashes:0 when nothing is orphaned', async () => {
+ const res = await sweepTombstones({ now: NOW });
+ expect(res.orphanBaseHashes).toBe(0);
+ });
+});
+
describe('sweepTombstones — peers behind', () => {
it("clamps the universe cutoff to the laggiest universe-subscribed peer (can't prune past min-ack)", async () => {
// Regression: if we used `now - GRACE` even when peers are subscribed,
@@ -220,7 +254,7 @@ describe('sweepTombstones — return shape', () => {
pruneTombstonedIssues.mockResolvedValueOnce({ pruned: 5 });
pruneTombstonedCollections.mockResolvedValueOnce({ pruned: 3 });
const result = await sweepTombstones({ now: NOW });
- expect(result).toEqual({ universes: 2, series: 0, issues: 5, collections: 3, refused: [] });
+ expect(result).toEqual({ universes: 2, series: 0, issues: 5, collections: 3, orphanBaseHashes: 0, refused: [] });
});
it('lists kinds whose cutoff was null in `refused` so the manual-trigger UI can explain why nothing pruned', async () => {
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index 149372e550..8a884497e1 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -790,6 +790,9 @@ async function runTombstoneSweep() {
const collections = `${result.collections} collection${result.collections === 1 ? '' : 's'}`;
console.log(`🪦 Tombstone GC: pruned ${universes}, ${result.series} series, ${issues}, ${collections}`);
}
+ if (result && result.orphanBaseHashes > 0) {
+ console.log(`🧹 Tombstone GC: swept ${result.orphanBaseHashes} orphaned base-hash entr${result.orphanBaseHashes === 1 ? 'y' : 'ies'}`);
+ }
}
/**