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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(peer-sync): per-record tombstone-ack clamp so a failed push can't get its tombstone GC'd
Adam Eivy34abb063b038
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 49d1fa59e5..931c69229a 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -233,6 +233,19 @@ export async function subscribePeer({ peerId, recordKind, recordId }, opts = {})updatedAt: now,lastPushedAt: null,lastPushedHash: null,+ // Per-(peer,record) confirmed-delivery water-mark (ms epoch). Set ONLY+ // when a push to this peer for THIS record lands successfully (the+ // receiver returned 2xx). Distinct from the per-peer tombstone ack+ // cursor (`peer_tombstone_cursors.json`) which advances to the MAX+ // acked deletedAt across ALL of a peer's pushes — a later record-B+ // success would otherwise advance that cursor past a failed record-A,+ // letting GC prune A's tombstone before A's delete-push was ever+ // confirmed. tombstoneGc clamps its prune cutoff to the MIN of this+ // field across a kind's subscription rows, so an unconfirmed record+ // (still `null`, or stuck at a pre-delete success time) holds the+ // line. Lives on the row → cleaned up for free when the row is+ // removed (`unsubscribePeer`), no separate storage to leak.+ lastConfirmedPushedAt: null,adoptedFromReverse: opts.adoptedFromReverse === true,};state.subscriptions.push(existing);@@ -903,7 +916,16 @@ export async function pushRecordToPeer(sub, options = {}) {// merge LWW path; only cost is one redundant POST per push cycle// until the receiver finishes pulling).const missingCount = Array.isArray(body?.missingAssets) ? body.missingAssets.length : 0;- await persistPushSuccess(sub.id, missingCount > 0 ? null : hash);+ // This push landed (receiver returned 2xx). Stamp the per-record confirmed-+ // delivery water-mark so tombstoneGc won't prune THIS record's tombstone+ // until its delete-push has been confirmed — even if a later push for a+ // DIFFERENT record advances the per-peer ack cursor past it. We stamp on+ // every confirmed push (not just deletes): a successful pre-delete push+ // establishes the floor, and the subsequent delete-push raises it above+ // the tombstone's deletedAt once it lands. The `missingAssets` case still+ // counts as confirmed delivery of the RECORD (merge ran on the receiver);+ // only the asset-stranded hash is withheld, not the confirmation mark.+ await persistPushSuccess(sub.id, missingCount > 0 ? null : hash, { confirmedAtMs: Date.now() });if (Number.isFinite(body?.ackedDeletesUpTo) && body.ackedDeletesUpTo > 0) {await ackDeletesUpTo(sub.peerId, body.ackedDeletesUpTo).catch(() => {});}@@ -915,7 +937,7 @@ export async function pushRecordToPeer(sub, options = {}) {};}-async function persistPushSuccess(subId, hash) {+async function persistPushSuccess(subId, hash, { confirmedAtMs = Date.now() } = {}) {await withStateLock(async () => {const state = await readState();const sub = state.subscriptions.find((s) => s.id === subId);@@ -924,6 +946,13 @@ async function persistPushSuccess(subId, hash) {sub.lastPushedAt = now;sub.lastPushedHash = hash;sub.updatedAt = now;+ // Advance the per-record confirmed-delivery water-mark monotonically — an+ // out-of-order retry must not retract it (mirrors ackDeletesUpTo's+ // never-move-backward guarantee). tombstoneGc reads MIN-of-this across a+ // kind's rows, so a regression here would let a stale tombstone prune.+ if (Number.isFinite(confirmedAtMs) && confirmedAtMs > (sub.lastConfirmedPushedAt ?? 0)) {+ sub.lastConfirmedPushedAt = confirmedAtMs;+ }// A successful push (or even a no-asset-stranded push) clears any prior// schema-version block — the peer can receive again.if (sub.blockedBySchema) delete sub.blockedBySchema;diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 55dfedf2df..740cd6f9d6 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -73,6 +73,7 @@ import {pullRecordFromPeer,syncNowForPeer,collectSubscriptionsForUpdate,+ peerSyncEvents,__resetForTests,__drainForTests,} from './peerSync.js';@@ -1249,6 +1250,47 @@ describe('peerSync', () => {expect(cursors['peer-a'].lastAckedDeleteAt).toBe(5000);});+ it('stamps the per-record lastConfirmedPushedAt on a confirmed push (per-record tombstone-ack clamp)', async () => {+ // The per-peer cursor advances to the MAX deletedAt across all pushes;+ // the per-record water-mark must additionally record THIS record's+ // confirmed delivery so tombstoneGc won't prune its tombstone before+ // its own (delete-)push lands. See tombstoneGc.minConfirmedPushedAtForKind.+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({ missingAssets: [] }) });+ const before = Date.now();+ const sub = await subscribePeer(+ { peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' },+ { adoptedFromReverse: true },+ );+ expect(sub.lastConfirmedPushedAt).toBeNull(); // not set until a push lands+ await pushRecordToPeer(sub);+ const refreshed = await findPeerSubscription('peer-a', 'universe', 'u1');+ expect(refreshed.lastConfirmedPushedAt).toBeGreaterThanOrEqual(before);+ });++ it('does NOT advance lastConfirmedPushedAt on a failed push (no false confirmation)', async () => {+ // A network failure must leave the per-record water-mark untouched —+ // otherwise GC would treat an undelivered record's tombstone as safe.+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({ missingAssets: [] }) });+ const sub = await subscribePeer(+ { peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' },+ { adoptedFromReverse: true },+ );+ await pushRecordToPeer(sub); // first push confirms+ const afterFirst = await findPeerSubscription('peer-a', 'universe', 'u1');+ const stamped = afterFirst.lastConfirmedPushedAt;+ expect(stamped).toBeTruthy();+ // Now a later push to the SAME sub fails at the network — content must+ // differ so the unchanged-hash short-circuit doesn't skip the wire.+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Bar' });+ vi.mocked(peerFetch).mockRejectedValue(new Error('ECONNREFUSED'));+ const result = await pushRecordToPeer({ ...afterFirst });+ expect(result.pushed).toBe(false);+ const afterFail = await findPeerSubscription('peer-a', 'universe', 'u1');+ expect(afterFail.lastConfirmedPushedAt).toBe(stamped); // unchanged+ });+it('handles a network-level failure without throwing (returns pushed:false)', async () => {vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });vi.mocked(peerFetch).mockRejectedValue(new Error('ECONNREFUSED'));@@ -1899,6 +1941,62 @@ describe('peerSync', () => {const all = await listPeerSubscriptions({ peerId: 'peer-a' });expect(all).toHaveLength(1);});++ it('emits peerSyncEvents "subscription-created" ONLY when a reverse sub is genuinely created', async () => {+ // The Instances UI listens on the relayed `peerSync:subscription:created`+ // socket event to re-fetch a peer's subs without a manual reload. It must+ // fire exactly once — on the first push that creates the reverse sub —+ // and NOT on every subsequent push to the same (already-subscribed) record.+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });+ const events = [];+ const handler = (payload) => events.push(payload);+ peerSyncEvents.on('subscription-created', handler);+ try {+ await applyIncomingPush({+ kind: 'universe',+ record: { id: 'u1' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ // Second push — sub already exists, so no new event.+ await applyIncomingPush({+ kind: 'universe',+ record: { id: 'u1', updatedAt: '2026-01-02T00:00:00Z' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ } finally {+ peerSyncEvents.off('subscription-created', handler);+ }+ expect(events).toHaveLength(1);+ expect(events[0]).toMatchObject({+ peerId: 'peer-a',+ recordKind: 'universe',+ recordId: 'u1',+ });+ expect(typeof events[0].subId).toBe('string');+ });++ it('does NOT emit "subscription-created" when the reverse-sub gate refuses (inbound-only peer)', async () => {+ // No reverse sub is created for an inbound-only peer, so the UI signal+ // must stay silent — emitting on every push would trigger needless+ // peerSubs refetches across all cards.+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });+ const events = [];+ const handler = (payload) => events.push(payload);+ peerSyncEvents.on('subscription-created', handler);+ try {+ await applyIncomingPush({+ kind: 'universe',+ record: { id: 'u1' },+ assetManifest: [],+ sourceInstanceId: 'peer-b-inbound-only',+ });+ } finally {+ peerSyncEvents.off('subscription-created', handler);+ }+ expect(events).toHaveLength(0);+ });});// -------------------------------------------------------------------------diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.jsindex b89c907d3c..b32292a99e 100644--- a/server/services/sharing/tombstoneGc.js+++ b/server/services/sharing/tombstoneGc.js@@ -59,6 +59,45 @@ function peerIdsSubscribedToKind(subs, peers, recordKind) {)];}+// Lowest per-(peer,record) confirmed-delivery water-mark across this kind's+// eligible subscription rows (ms epoch). This closes the per-peer-cursor gap:+// the per-peer tombstone ack cursor advances to the MAX deletedAt acked across+// ALL of a peer's pushes, so a later record-B success can drag it past a+// record-A whose push never landed — and GC would then prune A's tombstone+// even though A was never confirmed delivered. Clamping the prune cutoff to+// the MIN `lastConfirmedPushedAt` across the kind's rows holds the line: any+// record whose push is unconfirmed (field still `null`, or stuck at a+// pre-delete success time) pins the cutoff below its own `deletedAt`, so its+// tombstone survives until that record's (delete-)push is actually confirmed.+//+// A row with no `lastConfirmedPushedAt` yet (never had a confirmed push) floors+// to its `createdAt` rather than 0: a brand-new subscription should protect+// tombstones created AFTER it subscribed (those it still owes the peer) without+// freezing GC of tombstones that predate the subscription entirely — those+// older tombstones are already gated by the cursor's `subscribedSince` horizon+// (peerTombstoneCursors.js) and were never going to ride this row's pushes.+// An unparseable `createdAt` (hand-edited / legacy row) floors to 0 — fully+// conservative, never a false prune.+//+// Returns Infinity when there are no eligible rows for the kind (no per-record+// constraint → the snapshot-coverage + per-peer-ack checks alone govern).+function minConfirmedPushedAtForKind(subs, peers, recordKind) {+ const eligible = eligiblePeerIdSet(peers);+ let min = Infinity;+ for (const s of subs) {+ if (s.recordKind !== recordKind) continue;+ if (!s.peerId || !eligible.has(s.peerId)) continue;+ let confirmed = s.lastConfirmedPushedAt;+ if (!Number.isFinite(confirmed)) {+ // Never confirmed → floor to createdAt (0 if unparseable). See header.+ const createdMs = Date.parse(s.createdAt || '');+ confirmed = Number.isFinite(createdMs) ? createdMs : 0;+ }+ if (confirmed < min) min = confirmed;+ }+ return min;+}+function snapshotCategoryForKind(recordKind) {if (recordKind === 'universe') return 'universe';if (recordKind === 'series' || recordKind === 'issue') return 'pipeline';@@ -88,19 +127,27 @@ function snapshotPeerIdsForKind(peers, recordKind) {// Returns null when ANY snapshot-mode peer for this kind isn't covered by// a per-record subscription — without an ack horizon, an offline peer could// resurrect a pruned tombstone via its next snapshot push. Otherwise the-// cutoff is `min(now, minAck) - graceMs + 1`. The `+1` compensates for the-// strict-less-than comparison the prune helpers use (`deletedAt < beforeMs`);-// without it, a tombstone deleted at the same millisecond as `minAck`-// survives forever under `graceMs:0` (the manual-trigger path). At-// graceMs=24h the 1ms shift is invisible, so the orchestrator path is-// unchanged in practice.+// cutoff is `min(now, minAck, minConfirmedPush) - graceMs + 1`. The `+1`+// compensates for the strict-less-than comparison the prune helpers use+// (`deletedAt < beforeMs`); without it, a tombstone deleted at the same+// millisecond as the clamp survives forever under `graceMs:0` (the manual-+// trigger path). At graceMs=24h the 1ms shift is invisible, so the+// orchestrator path is unchanged in practice.+//+// `minConfirmedPush` is the per-(peer,record) clamp (see+// minConfirmedPushedAtForKind): the per-peer `minAck` cursor alone can drift+// past a record whose push never landed, so we additionally hold the cutoff+// at/below the lowest confirmed per-record delivery point. Issue tombstones+// ride their parent series's push, so the caller reuses the `series` cutoff+// for issues — the series rows' confirmed-push marks cover issues too.async function cutoffForKind(recordKind, { peers, subs, now, graceMs }) {const peerIds = peerIdsSubscribedToKind(subs, peers, recordKind);const snapshotPeerIds = snapshotPeerIdsForKind(peers, recordKind);const subbed = new Set(peerIds);if (snapshotPeerIds.some((id) => !subbed.has(id))) return null;const minAck = await getMinAckAcrossPeers(peerIds);- return Math.min(minAck, now) - graceMs + 1;+ const minConfirmedPush = minConfirmedPushedAtForKind(subs, peers, recordKind);+ return Math.min(minAck, minConfirmedPush, now) - graceMs + 1;}// Single point of disk I/O for peer registry + subscription rows. Bothdiff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.jsindex 14febaa2f2..a04ff13c5a 100644--- a/server/services/sharing/tombstoneGc.test.js+++ b/server/services/sharing/tombstoneGc.test.js@@ -45,10 +45,22 @@ const NOW = 1_700_000_000_000; // arbitrary epoch ms anchor// per-kind filter, so tests should hand the full sub list with each row// carrying its own `recordKind` tag. The previous per-kind mock shape// (`mockImplementation(({ recordKind }) => ...)`) is replaced by this.+//+// `lastConfirmedPushedAt` defaults to NOW so the per-record clamp+// (minConfirmedPushedAtForKind) is a no-op for the per-peer-ack policy tests —+// they model "pushes are landing, only the tombstone ACK cursor lags." Tests+// that exercise the per-record clamp (a record whose push never confirmed)+// override it per row with a lower value (or `null`).const mockSubs = (subsByKind) => {const rows = [];for (const [recordKind, peers] of Object.entries(subsByKind)) {- for (const p of peers) rows.push({ ...p, recordKind });+ for (const p of peers) {+ rows.push({+ lastConfirmedPushedAt: NOW,+ ...p,+ recordKind,+ });+ }}listPeerSubscriptions.mockResolvedValue(rows);};@@ -285,6 +297,101 @@ describe('sweepTombstones — graceMs override (manual trigger / CLI path)', ()});});+describe('sweepTombstones — per-record confirmed-push clamp (peer-sync-per-record-tombstone-ack-cursor)', () => {+ // Regression for the per-peer cursor gap: the per-peer tombstone ack cursor+ // (getMinAckAcrossPeers) advances to the MAX deletedAt acked across ALL of a+ // peer's pushes. If push for record-A FAILS and a later push for record-B+ // SUCCEEDS, the receiver returns ackedDeletesUpTo = B.deletedAt > A.deletedAt+ // and the per-peer cursor jumps past A — even though A's delete-push was+ // never confirmed. Without the per-record clamp, GC prunes A's tombstone and+ // A's stale live copy on the receiver resurrects on the next snapshot sync.+ //+ // The fix clamps the cutoff to MIN(lastConfirmedPushedAt) across the kind's+ // rows. Record-A's row is stuck at a pre-delete confirm time below A's+ // deletedAt, so the cutoff stays below A and A's tombstone survives.+ const A_DELETED_AT = NOW - 10 * 60 * 1000; // A deleted 10m ago+ const A_LAST_CONFIRMED = NOW - 20 * 60 * 1000; // A's last *confirmed* push (pre-delete), 20m ago+ const B_DELETED_AT = NOW - 5 * 60 * 1000; // B deleted 5m ago (more recent than A)++ it('does NOT prune record-A tombstone when A push failed but a later record-B push advanced the per-peer cursor', async () => {+ // Per-peer cursor reflects B's ack (the bug: it jumped past A).+ getMinAckAcrossPeers.mockResolvedValue(B_DELETED_AT);+ getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);+ // Two universe subs to the same peer. A's push never confirmed since+ // before its delete (stuck low); B's push confirmed recently (at NOW).+ mockSubs({+ universe: [+ { peerId: 'peer-a', recordId: 'u-A', createdAt: new Date(NOW - 60 * 60 * 1000).toISOString(), lastConfirmedPushedAt: A_LAST_CONFIRMED },+ { peerId: 'peer-a', recordId: 'u-B', createdAt: new Date(NOW - 60 * 60 * 1000).toISOString(), lastConfirmedPushedAt: NOW },+ ],+ });+ await sweepTombstones({ now: NOW, graceMs: 0 });+ const cutoff = pruneTombstonedUniverses.mock.calls[0][0];+ // Cutoff must be clamped to A's stuck confirm point (+1), NOT the per-peer+ // ack of B. So A's tombstone (deletedAt = A_DELETED_AT) does NOT satisfy+ // `A_DELETED_AT < cutoff` and survives; B's (deletedAt = B_DELETED_AT)+ // also survives, which is fine — correctness over GC aggressiveness.+ expect(cutoff).toBe(A_LAST_CONFIRMED + 1);+ expect(A_DELETED_AT).toBeGreaterThanOrEqual(cutoff); // A NOT pruned+ });++ it('prunes record-A tombstone once A push is confirmed past its deletedAt', async () => {+ // After A's delete-push finally lands, A's row confirm advances above its+ // deletedAt and the clamp no longer holds the line — A is prunable.+ getMinAckAcrossPeers.mockResolvedValue(B_DELETED_AT);+ getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);+ mockSubs({+ universe: [+ { peerId: 'peer-a', recordId: 'u-A', createdAt: new Date(NOW - 60 * 60 * 1000).toISOString(), lastConfirmedPushedAt: NOW },+ { peerId: 'peer-a', recordId: 'u-B', createdAt: new Date(NOW - 60 * 60 * 1000).toISOString(), lastConfirmedPushedAt: NOW },+ ],+ });+ await sweepTombstones({ now: NOW, graceMs: 0 });+ const cutoff = pruneTombstonedUniverses.mock.calls[0][0];+ // Both rows confirmed at NOW; the per-peer ack (B) is the binding clamp now.+ expect(cutoff).toBe(B_DELETED_AT + 1);+ expect(A_DELETED_AT).toBeLessThan(cutoff); // A NOW pruned+ });++ it('floors a never-confirmed row to its createdAt (protects post-subscribe tombstones, GC of pre-subscribe ones unaffected)', async () => {+ // A brand-new sub (lastConfirmedPushedAt absent) shouldn't permanently+ // freeze GC at 0 — it floors to createdAt, protecting only tombstones it+ // still owes the peer (those created after it subscribed).+ const createdAt = NOW - 30 * 60 * 1000;+ getMinAckAcrossPeers.mockResolvedValue(NOW);+ getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);+ mockSubs({+ universe: [+ // lastConfirmedPushedAt: null overrides the mockSubs NOW default to+ // model a row whose push has never been confirmed.+ { peerId: 'peer-a', recordId: 'u-new', createdAt: new Date(createdAt).toISOString(), lastConfirmedPushedAt: null },+ ],+ });+ await sweepTombstones({ now: NOW, graceMs: 0 });+ const cutoff = pruneTombstonedUniverses.mock.calls[0][0];+ expect(cutoff).toBe(createdAt + 1);+ });++ it('issues inherit the series rows confirmed-push clamp (issue tombstones ride series pushes)', async () => {+ // An issue tombstone is bundled into its parent series push, so its+ // protection comes from the series row's confirmed-push mark — not a+ // (nonexistent) issue subscription.+ const seriesStuckConfirm = NOW - 25 * 60 * 1000;+ getMinAckAcrossPeers.mockResolvedValue(NOW);+ getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);+ mockSubs({+ series: [+ { peerId: 'peer-a', recordId: 's-A', createdAt: new Date(NOW - 60 * 60 * 1000).toISOString(), lastConfirmedPushedAt: seriesStuckConfirm },+ ],+ });+ await sweepTombstones({ now: NOW, graceMs: 0 });+ const seriesCutoff = pruneTombstonedSeries.mock.calls[0][0];+ const issueCutoff = pruneTombstonedIssues.mock.calls[0][0];+ expect(seriesCutoff).toBe(seriesStuckConfirm + 1);+ expect(issueCutoff).toBe(seriesCutoff); // issues clamp identically to series+ });+});+describe('getSweepStatus — dry-run for UI button gating', () => {it('returns refused kinds without invoking any prune helper', async () => {listPeerSubscriptions.mockResolvedValue([]);