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([prune-orphan-subscriptions-for-deleted-records]): sweep orphaned peer subscriptions in tombstone GC

[._.]/ Adam Eivyc197f34eb5c4
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index e9abdaa10a..53a4b1ec4c 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -532,6 +532,47 @@ export async function unsubscribeAllForRecord(recordKind, recordId) {
return { removed, failed };
}
+/**
+ * Drop peer subscriptions whose target record no longer resolves AT ALL —
+ * not even as a tombstone. The tombstone GC path (`pruneTombstonedUniverses`
+ * / `pruneTombstonedSeries` in tombstoneGc.js) rm's a pruned record's
+ * directory but leaves its rows in `peer_subscriptions.json`: on the next
+ * `peer:online`, `retryPendingPushesForPeer` walks them, `buildPushPayload`
+ * returns null ("record-not-found"), and the push silently no-ops — harmless,
+ * but it inflates the "retrying N pending pushes" log count and keeps the
+ * peer's tombstone cursor pinned by a dead row.
+ *
+ * `resolver(recordKind, recordId) => Promise<boolean>` returns true when the
+ * record still exists in ANY form (live OR tombstoned). Only subs whose
+ * resolver returns false are dropped. A tombstoned-but-not-yet-pruned record
+ * still resolves true, so its sub survives to push the delete to peers — we
+ * strip a sub only once the underlying record directory is actually gone.
+ *
+ * Mirrors the orphan-base-hash sweep's conservative contract: a resolver that
+ * throws is treated as "still resolves" so a transient listing failure can
+ * never trigger a false strip. Malformed rows (missing recordKind/recordId)
+ * are left untouched — they're a separate concern from the dir-gone orphan
+ * this sweep targets.
+ *
+ * Returns `{ pruned, removed }` — count and ids of dropped subscriptions.
+ */
+export async function pruneOrphanedPeerSubscriptions(resolver) {
+ if (typeof resolver !== 'function') return { pruned: 0, removed: [] };
+ const subs = await listPeerSubscriptions();
+ const removed = [];
+ for (const sub of subs) {
+ if (!isNonEmptyStr(sub?.recordKind) || !isNonEmptyStr(sub?.recordId)) continue;
+ const exists = await resolver(sub.recordKind, sub.recordId).catch(() => true);
+ if (exists) continue;
+ const ok = await unsubscribePeer(sub.id).then(() => true).catch((err) => {
+ console.log(`⚠️ peerSync: orphan-subscription sweep failed for ${sub.id}: ${err.message}`);
+ return false;
+ });
+ if (ok) removed.push(sub.id);
+ }
+ return { pruned: removed.length, removed };
+}
+
// --- Asset manifest -----------------------------------------------------
/**
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 2b73244d3c..227de47b71 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -75,6 +75,7 @@ import {
unsubscribePeer,
unsubscribeAllForPeer,
unsubscribeAllForRecord,
+ pruneOrphanedPeerSubscriptions,
pushRecordToPeer,
applyIncomingPush,
diffAssetManifestAgainstLocal,
@@ -459,6 +460,52 @@ describe('peerSync', () => {
});
});
+ describe('pruneOrphanedPeerSubscriptions', () => {
+ beforeEach(() => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1' });
+ vi.mocked(getSeries).mockResolvedValue({ id: 's1' });
+ vi.mocked(listIssues).mockResolvedValue([]);
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });
+ });
+
+ it('drops subs whose record no longer resolves and keeps the rest', async () => {
+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u-gone' });
+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u-live' });
+ await subscribePeer({ peerId: 'peer-b', recordKind: 'series', recordId: 's-gone' });
+ // Resolver: only u-live still exists.
+ const live = new Set(['universe:u-live']);
+ const res = await pruneOrphanedPeerSubscriptions(async (kind, id) => live.has(`${kind}:${id}`));
+ expect(res.pruned).toBe(2);
+ expect(await findPeerSubscription('peer-a', 'universe', 'u-gone')).toBeNull();
+ expect(await findPeerSubscription('peer-b', 'series', 's-gone')).toBeNull();
+ // u-live survives.
+ expect(await findPeerSubscription('peer-a', 'universe', 'u-live')).not.toBeNull();
+ });
+
+ it('keeps a sub whose resolver throws (conservative — never a false strip)', async () => {
+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });
+ const res = await pruneOrphanedPeerSubscriptions(async () => { throw new Error('listing blew up'); });
+ expect(res.pruned).toBe(0);
+ expect(await findPeerSubscription('peer-a', 'universe', 'u1')).not.toBeNull();
+ });
+
+ it('returns {pruned:0, removed:[]} for a non-function resolver', async () => {
+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });
+ expect(await pruneOrphanedPeerSubscriptions(undefined)).toEqual({ pruned: 0, removed: [] });
+ // The sub is untouched.
+ expect(await listPeerSubscriptions()).toHaveLength(1);
+ });
+
+ it('drops the tombstone cursor when the peer’s last sub was an orphan', async () => {
+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u-gone' });
+ let cursors = await listCursors();
+ expect(cursors['peer-a']).toBeDefined();
+ await pruneOrphanedPeerSubscriptions(async () => false); // everything orphaned
+ cursors = await listCursors();
+ expect(cursors['peer-a']).toBeUndefined();
+ });
+ });
+
describe('autoSubscribeRecordToAllPeers', () => {
beforeEach(() => {
// Default these so the push triggered by subscribePeer doesn't 500
diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.js
index 7e3d56bb1c..1b75fd46c9 100644
--- a/server/services/sharing/tombstoneGc.js
+++ b/server/services/sharing/tombstoneGc.js
@@ -31,7 +31,7 @@ import { pruneTombstonedSeries, listSeries } from '../pipeline/series.js';
import { pruneTombstonedIssues, listIssueIds } from '../pipeline/issues.js';
import { pruneTombstonedCollections, listCollections } from '../mediaCollections.js';
import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';
-import { listPeerSubscriptions } from './peerSync.js';
+import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';
import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';
import { getPeers } from '../instances.js';
@@ -68,6 +68,37 @@ function makeBaseHashKeyResolver() {
};
}
+// Each peer-subscribable kind's UNCAPPED id source INCLUDING tombstones —
+// used by the orphan peer-subscription sweep. A tombstoned record still owns
+// its subscription (the sub pushes the delete to peers), so the sweep must
+// treat a tombstone as "still resolves" and strip a sub only once the record
+// directory is actually gone (hard-deleted by the tombstone prune above).
+// Issues are absent — they're never directly subscribed (issue tombstones
+// ride their parent series's push, so PEER_SUBSCRIBABLE_KINDS has no 'issue').
+const ALL_ID_LISTERS = Object.freeze({
+ universe: async () => (await listUniverses({ includeDeleted: true })).map((r) => r.id),
+ series: async () => (await listSeries({ includeDeleted: true })).map((r) => r.id),
+ mediaCollection: async () => (await listCollections({ includeDeleted: true })).map((r) => r.id),
+});
+
+// Build the orphan-subscription resolver for ONE sweep: lazily list each kind's
+// all-ids Set (including tombstones) on first use and check membership in
+// memory — at most one listing per kind per sweep. Unknown kinds resolve to
+// `true` (never strip a sub for a kind this version doesn't recognize); a
+// listing that throws also keeps the kind's subs (`pruneOrphanedPeerSubscriptions`
+// catches the rejection and treats it as "still resolves").
+function makeSubscriptionRecordResolver() {
+ const idSets = new Map(); // kind → Set<recordId>
+ return async (kind, id) => {
+ const lister = ALL_ID_LISTERS[kind];
+ if (!lister) return true; // unknown kind → never strip
+ if (!idSets.has(kind)) {
+ idSets.set(kind, new Set(await lister()));
+ }
+ return idSets.get(kind).has(id);
+ };
+}
+
const GRACE_MS = 24 * 60 * 60 * 1000;
// `peer_subscriptions.json` rows outlive peer removal (no cleanup hook on
@@ -237,12 +268,20 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
// every kind regardless of which were refused — orphan keys aren't gated on
// snapshot coverage.
const orphan = await pruneOrphanedBaseHashes(makeBaseHashKeyResolver());
+ // Orphan peer-subscription sweep — same backstop logic as the base-hash
+ // sweep, AFTER the tombstone prunes so a record whose dir was just rm'd
+ // (no longer resolves even with includeDeleted) gets its dead subscription
+ // rows dropped. Runs every kind regardless of refusals: an orphaned sub
+ // points at a record that no longer exists, so it's safe to strip no matter
+ // what the snapshot-coverage gate decided for live tombstones.
+ const orphanSubs = await pruneOrphanedPeerSubscriptions(makeSubscriptionRecordResolver());
return {
universes: u.pruned,
series: s.pruned,
issues: i.pruned,
collections: c.pruned,
orphanBaseHashes: orphan.pruned,
+ orphanSubscriptions: orphanSubs.pruned,
refused: refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff),
};
}
diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.js
index 64b7690fb3..040c2b14a4 100644
--- a/server/services/sharing/tombstoneGc.test.js
+++ b/server/services/sharing/tombstoneGc.test.js
@@ -25,6 +25,7 @@ vi.mock('../../lib/conflictJournal.js', () => ({
}));
vi.mock('./peerSync.js', () => ({
listPeerSubscriptions: vi.fn(),
+ pruneOrphanedPeerSubscriptions: vi.fn().mockResolvedValue({ pruned: 0, removed: [] }),
}));
vi.mock('./peerTombstoneCursors.js', () => ({
getMinAckAcrossPeers: vi.fn(),
@@ -43,7 +44,7 @@ import { pruneTombstonedSeries, listSeries } from '../pipeline/series.js';
import { pruneTombstonedIssues, listIssueIds } from '../pipeline/issues.js';
import { pruneTombstonedCollections, listCollections } from '../mediaCollections.js';
import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';
-import { listPeerSubscriptions } from './peerSync.js';
+import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';
import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';
import { getPeers } from '../instances.js';
@@ -76,6 +77,7 @@ const mockSubs = (subsByKind) => {
beforeEach(() => {
vi.clearAllMocks();
listPeerSubscriptions.mockResolvedValue([]);
+ pruneOrphanedPeerSubscriptions.mockResolvedValue({ pruned: 0, removed: [] });
getMinAckAcrossPeers.mockResolvedValue(Infinity);
getPeers.mockResolvedValue([]);
});
@@ -145,6 +147,66 @@ describe('sweepTombstones — orphaned base-hash sweep', () => {
});
});
+describe('sweepTombstones — orphaned peer-subscription sweep', () => {
+ it('runs the orphan-subscription sweep AFTER the base-hash sweep and surfaces its count', async () => {
+ pruneOrphanedPeerSubscriptions.mockResolvedValueOnce({ pruned: 2, removed: ['peer-universe-u-gone-a', 'peer-series-s-gone-b'] });
+ const res = await sweepTombstones({ now: NOW });
+ expect(pruneOrphanedPeerSubscriptions).toHaveBeenCalledTimes(1);
+ // A function resolver is handed in (the kind-aware include-tombstones predicate).
+ expect(typeof pruneOrphanedPeerSubscriptions.mock.calls[0][0]).toBe('function');
+ expect(res.orphanSubscriptions).toBe(2);
+ // Ordering: the base-hash sweep must run before the subscription sweep so a
+ // record hard-deleted in this same sweep is gone for both resolvers.
+ expect(pruneOrphanedBaseHashes.mock.invocationCallOrder[0])
+ .toBeLessThan(pruneOrphanedPeerSubscriptions.mock.invocationCallOrder[0]);
+ });
+
+ it('runs the orphan-subscription sweep regardless of refusals (orphans aren’t gated on snapshot coverage)', async () => {
+ // Snapshot-mode peer with no per-record sub refuses every tombstone kind,
+ // but a subscription whose record is gone is still safe to strip.
+ getPeers.mockResolvedValue([
+ { instanceId: 'peer-a', enabled: true, syncEnabled: true, syncCategories: { universe: true, pipeline: true, mediaCollections: true } },
+ ]);
+ listPeerSubscriptions.mockResolvedValue([]);
+ pruneOrphanedPeerSubscriptions.mockResolvedValueOnce({ pruned: 1, removed: ['x'] });
+ const res = await sweepTombstones({ now: NOW });
+ expect(pruneOrphanedPeerSubscriptions).toHaveBeenCalledTimes(1);
+ expect(res.orphanSubscriptions).toBe(1);
+ expect(res.refused).toEqual(expect.arrayContaining(['universe', 'series', 'issue', 'mediaCollection']));
+ });
+
+ it('reports orphanSubscriptions:0 when nothing is orphaned', async () => {
+ const res = await sweepTombstones({ now: NOW });
+ expect(res.orphanSubscriptions).toBe(0);
+ });
+
+ it('passes a tombstone-inclusive resolver: keeps live + tombstoned records, drops dir-gone ones, keeps unknown kinds, lists once', async () => {
+ // includeDeleted:true listers — a tombstoned record (u-tomb) is STILL in the
+ // list, so its sub must survive (it pushes the delete to peers). Only a
+ // record whose dir is truly gone (u-gone) resolves false.
+ listUniverses.mockResolvedValue([{ id: 'u-live' }, { id: 'u-tomb', deleted: true }]);
+ listSeries.mockResolvedValue([{ id: 's-live' }]);
+ listCollections.mockResolvedValue([{ id: 'c-live' }]);
+ let resolver;
+ pruneOrphanedPeerSubscriptions.mockImplementationOnce(async (fn) => { resolver = fn; return { pruned: 0, removed: [] }; });
+ await sweepTombstones({ now: NOW });
+
+ expect(await resolver('universe', 'u-live')).toBe(true);
+ expect(await resolver('universe', 'u-tomb')).toBe(true); // tombstoned → kept
+ expect(await resolver('universe', 'u-gone')).toBe(false); // dir gone → orphan
+ expect(await resolver('series', 's-live')).toBe(true);
+ expect(await resolver('mediaCollection', 'c-gone')).toBe(false);
+ // Unknown kind (issues are never directly subscribed) is always kept and
+ // never triggers a listing.
+ expect(await resolver('issue', 'i-whatever')).toBe(true);
+ expect(await resolver('brain', 'whatever')).toBe(true);
+ // The resolver lists with includeDeleted so tombstones are visible.
+ expect(listUniverses).toHaveBeenCalledWith({ includeDeleted: true });
+ // Cached id-set — a second universe probe reuses the listing.
+ expect(listUniverses).toHaveBeenCalledTimes(1);
+ });
+});
+
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,
@@ -276,7 +338,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, orphanBaseHashes: 0, refused: [] });
+ expect(result).toEqual({ universes: 2, series: 0, issues: 5, collections: 3, orphanBaseHashes: 0, orphanSubscriptions: 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 8a884497e1..b0320713c8 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -793,6 +793,9 @@ async function runTombstoneSweep() {
if (result && result.orphanBaseHashes > 0) {
console.log(`🧹 Tombstone GC: swept ${result.orphanBaseHashes} orphaned base-hash entr${result.orphanBaseHashes === 1 ? 'y' : 'ies'}`);
}
+ if (result && result.orphanSubscriptions > 0) {
+ console.log(`🧹 Tombstone GC: swept ${result.orphanSubscriptions} orphaned peer subscription${result.orphanSubscriptions === 1 ? '' : 's'}`);
+ }
}
/**