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

refactor([conflict-journal-base-hash-prune]): batch the orphan resolver from /simplify pass

[._.]/ Adam Eivy0b197226bd4f
diff --git a/server/lib/conflictJournal.test.js b/server/lib/conflictJournal.test.js
index b485dbbce6..6cea74eecb 100644
--- a/server/lib/conflictJournal.test.js
+++ b/server/lib/conflictJournal.test.js
@@ -296,10 +296,12 @@ describe('conflictJournal', () => {
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 () => {
+ it('keeps every key when the resolver returns true (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));
+ // The contract: a resolver that returns true (e.g. for a kind it doesn't
+ // recognize) must leave that key in place. The tombstoneGc resolver maps
+ // unknown kinds to true for exactly this reason.
+ const { pruned } = await cj.pruneOrphanedBaseHashes(async () => true);
expect(pruned).toBe(0);
expect(await cj.getSyncBaseHash('issue', 'iss-1')).not.toBeNull();
});
diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.js
index 73d1bb42ec..7415fde4cb 100644
--- a/server/services/sharing/tombstoneGc.js
+++ b/server/services/sharing/tombstoneGc.js
@@ -26,27 +26,44 @@
* cohort for issue tombstones is "peers subscribed to series".
*/
-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 { pruneTombstonedUniverses, listUniverses } from '../universeBuilder.js';
+import { pruneTombstonedSeries, listSeries } from '../pipeline/series.js';
+import { pruneTombstonedIssues, listIssues } from '../pipeline/issues.js';
+import { pruneTombstonedCollections, listCollections } 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
+// Each kind's live-record lister (default args exclude tombstoned/deleted).
+// Used to build the orphan-sweep resolver's per-kind id-sets. A kind absent
+// from this map is unknown → the resolver keeps its keys (never strips).
+const LIVE_ID_LISTERS = Object.freeze({
+ universe: listUniverses,
+ series: listSeries,
+ issue: () => listIssues({}),
+ mediaCollection: listCollections,
+});
+
+// Build the `pruneOrphanedBaseHashes` resolver for ONE sweep: load each kind's
+// live-id Set once on first use (lazily — a sweep with no keys of a given kind
+// never lists it) and check membership in memory. This collapses what would be
+// one record read PER base-hash key into at most one directory listing per kind
+// per sweep. Unknown kinds resolve to `true` so the sweep can never strip a key
+// it can't authoritatively check (a base hash for a future kind, or a shape
+// this version doesn't recognize); a listing that throws also keeps the kind's
+// keys (the `pruneOrphanedBaseHashes` resolver-error path is conservative too).
+function makeBaseHashKeyResolver() {
+ const idSets = new Map(); // kind → Set<liveId>
+ return async (kind, id) => {
+ const lister = LIVE_ID_LISTERS[kind];
+ if (!lister) return true; // unknown kind → never strip
+ if (!idSets.has(kind)) {
+ const records = await lister();
+ idSets.set(kind, new Set(records.map((r) => r.id)));
+ }
+ return idSets.get(kind).has(id);
+ };
}
const GRACE_MS = 24 * 60 * 60 * 1000;
@@ -217,7 +234,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
// 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);
+ const orphan = await pruneOrphanedBaseHashes(makeBaseHashKeyResolver());
return {
universes: u.pruned,
series: s.pruned,
diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.js
index 79d731b857..ebcbd0644e 100644
--- a/server/services/sharing/tombstoneGc.test.js
+++ b/server/services/sharing/tombstoneGc.test.js
@@ -6,19 +6,19 @@ 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),
+ listUniverses: vi.fn().mockResolvedValue([]),
}));
vi.mock('../pipeline/series.js', () => ({
pruneTombstonedSeries: vi.fn().mockResolvedValue({ pruned: 0 }),
- getSeries: vi.fn().mockResolvedValue(null),
+ listSeries: vi.fn().mockResolvedValue([]),
}));
vi.mock('../pipeline/issues.js', () => ({
pruneTombstonedIssues: vi.fn().mockResolvedValue({ pruned: 0 }),
- getIssue: vi.fn().mockResolvedValue(null),
+ listIssues: vi.fn().mockResolvedValue([]),
}));
vi.mock('../mediaCollections.js', () => ({
pruneTombstonedCollections: vi.fn().mockResolvedValue({ pruned: 0 }),
- getCollection: vi.fn().mockResolvedValue(null),
+ listCollections: vi.fn().mockResolvedValue([]),
}));
vi.mock('../../lib/conflictJournal.js', () => ({
pruneOrphanedBaseHashes: vi.fn().mockResolvedValue({ pruned: 0 }),
@@ -38,10 +38,10 @@ import {
getSweepStatus,
TOMBSTONE_GRACE_MS,
} from './tombstoneGc.js';
-import { pruneTombstonedUniverses } from '../universeBuilder.js';
-import { pruneTombstonedSeries } from '../pipeline/series.js';
-import { pruneTombstonedIssues } from '../pipeline/issues.js';
-import { pruneTombstonedCollections } from '../mediaCollections.js';
+import { pruneTombstonedUniverses, listUniverses } from '../universeBuilder.js';
+import { pruneTombstonedSeries, listSeries } from '../pipeline/series.js';
+import { pruneTombstonedIssues, listIssues } from '../pipeline/issues.js';
+import { pruneTombstonedCollections, listCollections } from '../mediaCollections.js';
import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';
import { listPeerSubscriptions } from './peerSync.js';
import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';
@@ -121,6 +121,28 @@ describe('sweepTombstones — orphaned base-hash sweep', () => {
const res = await sweepTombstones({ now: NOW });
expect(res.orphanBaseHashes).toBe(0);
});
+
+ it('passes a resolver that keeps live records, drops dead ones, keeps unknown kinds, and lists each kind once', async () => {
+ listUniverses.mockResolvedValue([{ id: 'u-live' }]);
+ listSeries.mockResolvedValue([{ id: 's-live' }]);
+ listIssues.mockResolvedValue([{ id: 'i-live' }]);
+ listCollections.mockResolvedValue([{ id: 'c-live' }]);
+ // Capture the resolver the sweep hands to pruneOrphanedBaseHashes and drive
+ // it directly — this is the real makeBaseHashKeyResolver closure.
+ let resolver;
+ pruneOrphanedBaseHashes.mockImplementationOnce(async (fn) => { resolver = fn; return { pruned: 0 }; });
+ await sweepTombstones({ now: NOW });
+
+ expect(await resolver('universe', 'u-live')).toBe(true);
+ expect(await resolver('universe', 'u-gone')).toBe(false);
+ expect(await resolver('issue', 'i-live')).toBe(true);
+ expect(await resolver('mediaCollection', 'c-gone')).toBe(false);
+ // Unknown kind is always kept and never triggers a listing.
+ expect(await resolver('brain', 'whatever')).toBe(true);
+ // A second probe of an already-listed kind reuses the cached id-set —
+ // listUniverses is called exactly once across both universe probes.
+ expect(listUniverses).toHaveBeenCalledTimes(1);
+ });
});
describe('sweepTombstones — peers behind', () => {