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

address review (codex): send fullSync-only disable + treat stale subs as pending

[._.]/ Adam Eivyaeb7a836e8f3
diff --git a/server/services/instances.js b/server/services/instances.js
index bda413e161..6780943e84 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -918,11 +918,16 @@ export async function applyReciprocalSync(instanceId, categories, { fullSync } =
* peer that's offline or on an older version (404s the endpoint) just stays
* one-directional until the next toggle. Returns `{ ok, reason }`.
*/
-export async function requestReciprocalSync(peer, categories, { fullSync = false } = {}) {
+export async function requestReciprocalSync(peer, categories, { fullSync } = {}) {
const self = await getSelf();
if (!self?.instanceId) return { ok: false, reason: 'no-self-identity' };
const sanitized = sanitizeSyncCategories(categories);
- if (!sanitized) return { ok: false, reason: 'no-categories' };
+ // Bail only when there's genuinely nothing to say: no actionable categories
+ // AND no full-sync state to communicate. A full-sync DISABLE (fullSync:false)
+ // on a peer whose stored category map is empty must still send — otherwise the
+ // remote never learns to drop its mirror. `fullSync === undefined` means the
+ // caller didn't communicate a full-sync state at all (legacy direct callers).
+ if (!sanitized && fullSync === undefined) return { ok: false, reason: 'no-categories' };
const url = `${peerBaseUrl(peer)}/api/instances/peers/sync-categories`;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
@@ -933,12 +938,14 @@ export async function requestReciprocalSync(peer, categories, { fullSync = false
// Always carry our current full-sync state (true OR false) so a peer new
// enough to understand it adopts mirror mode on enable AND drops it on
// disable. Older peers ignore the field; on enable they still mirror via
- // the all-on syncCategories map we sent.
- body: JSON.stringify({ instanceId: self.instanceId, syncCategories: sanitized, fullSync: fullSync === true }),
+ // the all-on syncCategories map we sent. syncCategories defaults to {} so
+ // the receiver's required-object schema still parses a fullSync-only send.
+ body: JSON.stringify({ instanceId: self.instanceId, syncCategories: sanitized || {}, fullSync: fullSync === true }),
signal: controller.signal
}, peer);
if (res.ok) {
- console.log(`🔁 Requested reciprocal sync from ${peer.name}: ${Object.keys(sanitized).filter(k => sanitized[k]).join(',') || 'none'}`);
+ const enabledList = sanitized ? Object.keys(sanitized).filter(k => sanitized[k]).join(',') : '';
+ console.log(`🔁 Requested reciprocal sync from ${peer.name}: ${fullSync === false ? 'full-mirror-off' : (enabledList || 'none')}`);
return { ok: true };
}
// 404 = peer predates this endpoint; not an error worth surfacing loudly.
diff --git a/server/services/instances.test.js b/server/services/instances.test.js
index 947f89b125..6ef6423b9e 100644
--- a/server/services/instances.test.js
+++ b/server/services/instances.test.js
@@ -824,16 +824,22 @@ describe('instances.js', () => {
expect(peer.fullSync).toBe(true);
});
- it('disabling fullSync reciprocates fullSync:false to the peer', async () => {
+ it('disabling fullSync reciprocates fullSync:false even with an empty category map', async () => {
+ // The empty-map case is the one the no-categories send guard used to drop:
+ // a just-disabled mirror peer whose underlying syncCategories is empty must
+ // STILL POST fullSync:false so the remote learns to drop its mirror.
readJSONFile.mockResolvedValue({
self: { instanceId: 'me-id' },
- peers: [{ id: 'p1', instanceId: 'inst-A', name: 'A', enabled: true, fullSync: false, syncCategories: { brain: true } }],
+ peers: [{ id: 'p1', instanceId: 'inst-A', name: 'A', enabled: true, fullSync: false, syncCategories: {} }],
});
const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200 });
vi.stubGlobal('fetch', fetchMock);
- await enqueueReciprocalSync('p1');
+ const result = await enqueueReciprocalSync('p1');
+ expect(result.ok).toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
const body = JSON.parse(fetchMock.mock.calls.at(-1)[1].body);
expect(body.fullSync).toBe(false);
+ expect(body.syncCategories).toEqual({}); // valid object so the receiver schema parses
});
it('updateSelf persists the new-peer full-sync default', async () => {
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 96ffc9fb2b..f7edda5f22 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -559,11 +559,21 @@ export async function getFullSyncCoverageForPeer(peerId) {
listRecordsForKind(kind).catch(() => []),
listPeerSubscriptions({ peerId, recordKind: kind }).catch(() => []),
]);
- // A record counts as confirmed only when its subscription carries a
- // confirmed-delivery water-mark — a created-but-never-pushed sub is pending.
- const confirmedIds = new Set(subs.filter(s => s.lastConfirmedPushedAt).map(s => s.recordId));
+ // Map each subscribed record to its confirmed-delivery water-mark (ms epoch).
+ const confirmedAtById = new Map(subs.filter(s => s.lastConfirmedPushedAt).map(s => [s.recordId, s.lastConfirmedPushedAt]));
+ // A record counts as mirrored only when a confirmed push covers its CURRENT
+ // version — the confirm happened at/after the record's last edit. A record
+ // edited after its last confirmed push (peer offline / schema-blocked since)
+ // has stale content on the peer, so it's pending, not mirrored. A created-
+ // but-never-pushed sub (no water-mark) is pending too.
const kindTotal = records.length;
- const kindConfirmed = records.filter(r => confirmedIds.has(r.id)).length;
+ const kindConfirmed = records.filter((r) => {
+ const confirmedAt = confirmedAtById.get(r.id);
+ if (!confirmedAt) return false;
+ const updatedAt = Date.parse(r.updatedAt);
+ // No parseable updatedAt → can't prove staleness; trust the confirmation.
+ return !Number.isFinite(updatedAt) || confirmedAt >= updatedAt;
+ }).length;
return { kind, total: kindTotal, confirmed: kindConfirmed, pending: kindTotal - kindConfirmed };
}));
const byKind = {};
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index e1706e6cfa..5de1160eb1 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -482,6 +482,24 @@ describe('peerSync', () => {
expect(cov.fullyMirrored).toBe(true);
});
+ it('counts a record edited AFTER its last confirmed push as pending (stale content)', async () => {
+ // Record confirmed once, then edited (updatedAt in the future relative to
+ // the confirm time) — the peer has stale content, so it's not mirrored.
+ vi.mocked(getPeers).mockResolvedValue([
+ { instanceId: 'peer-a', name: 'A', enabled: true, syncEnabled: true, fullSync: true, syncCategories: {} },
+ ]);
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }]);
+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });
+ await forcePushRecord('peer-a', 'universe', 'u1'); // stamps lastConfirmedPushedAt ≈ now
+ // Now the record reports an edit far in the future relative to the confirm.
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1', updatedAt: '2999-01-01T00:00:00Z' }]);
+ const cov = await getFullSyncCoverageForPeer('peer-a');
+ expect(cov.total).toBe(1);
+ expect(cov.confirmed).toBe(0);
+ expect(cov.pending).toBe(1);
+ expect(cov.fullyMirrored).toBe(false);
+ });
+
it('a created-but-unconfirmed subscription still counts as pending', async () => {
vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }]);
// Push FAILS — the sub is created but never confirmed-delivered.