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

perf: sync federated usage per instance slot, not the whole digest map (#5759)

Adam Eivy9daa3a12837e
diff --git a/docs/decisions/2026-09-01-federated-usage-metrics.md b/docs/decisions/2026-09-01-federated-usage-metrics.md
index b6471f7025..e354ff9239 100644
--- a/docs/decisions/2026-09-01-federated-usage-metrics.md
+++ b/docs/decisions/2026-09-01-federated-usage-metrics.md
@@ -121,11 +121,20 @@ excluded on both privacy and payload grounds.
- Peer rows are as fresh as the last 60s sync cycle, so each row states when its
digest was captured rather than implying it is live.
- `usage` is the first snapshot category that is **always dirty** — `saveUsage`
- rewrites `usage.json` on every AI run — so it transfers the whole digest map
- where every other category rests on a rarely-moving checksum. The payload is
- bounded here (120-day wire rollup, all-time `byProvider`/`byModel` dropped,
- no per-provider rows on fleet output); replacing the whole-payload transfer
- with a `capturedAt` manifest + per-slot fetch is filed as **#5759**.
+ rewrites `usage.json` on every AI run — where every other category rests on a
+ rarely-moving checksum. The payload is bounded (120-day wire rollup, all-time
+ `byProvider`/`byModel` dropped, no per-provider rows on fleet output), and
+ since **#5759** the transfer is per-slot rather than whole-map: the category
+ serves a **manifest** at `/api/sync/usage/manifest` — `{ instances: {
+ <instanceId>: capturedAt }, tombstones }` — and that manifest, not the
+ payload, is what the category's checksum hashes. A puller diffs the remote
+ manifest against what it already holds and fetches only the advanced slots
+ via `/api/sync/usage/snapshot?slots=…`, so one machine burning tokens moves
+ one digest instead of N. Both legs degrade: a source peer too old to serve a
+ manifest 404s it and the puller falls back to the whole snapshot, and a
+ snapshot request with no `slots` serves everything — receivers merge per slot
+ under LWW either way, so a full payload is always applied idempotently. See
+ `server/lib/syncManifest.js` for the wire contract.
- **The per-peer toggle governs the INBOUND direction.** Snapshot sync is
pull-only, and `/api/sync/:category/snapshot` carries no per-peer category
authorization for *any* category — the receiver-side gap that per-record pulls
diff --git a/server/lib/README.md b/server/lib/README.md
index f2cbb3f35e..e3cb0c4c1f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -466,6 +466,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `isoWeek.js` | ISO-8601 week identity — the single source of the `YYYY-Www` week id. `getWeekId(date)` keys on the ISO week-numbering **year** (the calendar year of that week's Thursday), not `date.getFullYear()`, so one ISO week is never split across two ids and two weeks never collide on one (#3465). Also `isoWeekParts`, `getIsoWeekNumber`, `getIsoWeekYear`, `parseWeekId` (null on garbage), and `isoWeeksInYear(year)` (52, or 53 in a leap-week year). Shared by productivity week aggregates and weekly digest filenames. |
| `snapshotChecksum.js` | The two snapshot-checksum flavours a sync category can want. `snapshotChecksum(data)` hashes `JSON.stringify` — insertion-order SENSITIVE, correct only where the getter already canonicalizes its own ordering (`dataSync.js`, `digital-twin-sync.js`). `canonicalSnapshotChecksum(data)` hashes `canonicalStringify`, so two converged machines hash identically regardless of the order they learned the data (`peerUsage.js`, whose payload is a map keyed by wire-supplied instance ids). Picking the wrong one is not a crash — it is two synced peers whose checksums never match, which the sync UI reads as "behind" forever. |
| `lwwTimestamp.js` | Last-writer-wins timestamp comparison for cross-instance sync merges. `parseTsMs(s)` (Date.parse → epoch ms or null), `compareNewerWins(candidate, incumbent)` (true iff candidate strictly newer; unparseable-loses, tie → incumbent — used to decide remote-overwrites-local), `compareEarlierWins(a, b)` (−1/0/1 earliest-wins tiebreak; unparseable-loses). Single source of the LWW polarity shared by `mergeMediaCollectionsFromSync` / `mergeAuthorsFromSync` etc. |
+| `syncManifest.js` | Wire contract for the snapshot-sync MANIFEST leg — the fix for a category that is always dirty AND a map of per-instance slots (`usage`), where one instance advancing dragged every other instance's digest across the wire. `isManifestEnvelope(value)` validates a `{ data: { instances }, checksum }` response (a legacy peer that 404s the endpoint fails it, and the puller falls back to the whole snapshot); `diffManifestSlots(remoteInstances, localInstances)` returns the sorted slot ids whose REMOTE LWW stamp is strictly newer than ours — exactly the slots worth fetching. Comparison goes through `lwwTimestamp.js`, so a tie breaks to what we already hold. Consumed by `syncOrchestrator.syncDataCategoryFromPeer`; served by `dataSync.getManifest`. |
| `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. |
| `markedSection.js` | Marker-delimited section replacement (pure). `buildMarkers(id)` → `{ start, end }` HTML-comment marker pair; `replaceMarkedSection(content, body, markers)` splices/replaces/removes an auto-generated region without touching surrounding user content (idempotent); `extractMarkedSection` / `hasMarkedSection` read it back. Powers the daily-log activity-digest auto-drafts (#2155) via `brainJournal.upsertAutoSection()`. |
| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 14a07b9dc9..549ffc41ee 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -15189,6 +15189,14 @@
"server/routes/dataSync.js"
]
},
+ {
+ "method": "GET",
+ "path": "/api/sync/:category/manifest",
+ "mountPath": "/api/sync",
+ "sources": [
+ "server/routes/dataSync.js"
+ ]
+ },
{
"method": "GET",
"path": "/api/sync/:category/snapshot",
@@ -17424,8 +17432,8 @@
],
"stats": {
"mounts": 146,
- "operations": 2158,
- "declarations": 2166,
+ "operations": 2159,
+ "declarations": 2167,
"sourceFiles": 229
}
}
diff --git a/server/lib/index.js b/server/lib/index.js
index 33359dbfa2..37d73bebfc 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -443,6 +443,7 @@ export * from './fetchErrorChain.js';
export * from './isoWeek.js';
export * from './lwwTimestamp.js';
export * from './snapshotChecksum.js';
+export * from './syncManifest.js';
export * from './mapWithConcurrency.js';
export * from './markedSection.js';
export * from './mirrorParity.js';
diff --git a/server/lib/syncManifest.js b/server/lib/syncManifest.js
new file mode 100644
index 0000000000..7e9925b99e
--- /dev/null
+++ b/server/lib/syncManifest.js
@@ -0,0 +1,69 @@
+/**
+ * Snapshot-sync MANIFEST wire contract.
+ *
+ * Most snapshot categories are effectively static, so the checksum
+ * short-circuit in `syncOrchestrator` is enough: nothing moved → nothing
+ * transfers. `usage` broke that assumption — it is always dirty (every recorded
+ * AI run rewrites `usage.json`) and it is a MAP of per-instance slots, so a
+ * single instance advancing its counters dragged every other instance's digest
+ * across the wire on the next 60s cycle.
+ *
+ * A manifest fixes the granularity: the category serves
+ * `{ instances: { <slotId>: <lww timestamp> }, tombstones }` — a few hundred
+ * bytes — and the puller fetches only the slots whose timestamp actually moved.
+ *
+ * Two rules make it safe across independently-upgrading installs:
+ *
+ * - **The manifest is the category's checksum.** A category that serves one
+ * hashes the manifest (not the payload) for BOTH `/checksum` and
+ * `/snapshot`, so an older peer that only knows those two endpoints still
+ * sees a checksum that changes exactly when a slot advances.
+ * - **Every leg degrades to the whole snapshot.** A puller that gets no usable
+ * manifest (older source peer → 404) falls back to the full snapshot, and a
+ * source peer that gets no `slots` filter serves everything. Receivers merge
+ * per slot under LWW either way, so a full payload is always applied
+ * idempotently.
+ *
+ * Timestamp comparison goes through `lwwTimestamp.js` so the polarity matches
+ * every other sync merge: a tie breaks to what we already hold, and an
+ * unparseable remote stamp never drags a slot across.
+ */
+
+import { isPlainObject } from './objects.js';
+import { compareNewerWins } from './lwwTimestamp.js';
+
+/**
+ * Hard cap on the slot ids one `?slots=` request may carry — a bound on the URL
+ * and on the Set the server builds from it, not a tuning knob. Comfortably
+ * above any real fleet (`peerUsage` stores at most 64 instances), but a puller
+ * that DOES diff more stale slots than this must truncate AND leave its cached
+ * checksum unadvanced, or the slots it dropped are never fetched again.
+ */
+export const MAX_MANIFEST_SLOTS = 128;
+
+/** True when `value` is a usable `{ data: { instances }, checksum }` envelope. */
+export function isManifestEnvelope(value) {
+ return typeof value?.checksum === 'string'
+ && value.checksum.length > 0
+ && isPlainObject(value?.data)
+ && isPlainObject(value.data.instances);
+}
+
+/**
+ * Slot ids whose REMOTE timestamp is strictly newer than the local one — i.e.
+ * exactly the slots worth fetching. A slot we have never seen is always newer
+ * (local `undefined` is unparseable, so `compareNewerWins` takes the remote).
+ * Returned sorted so the request URL — and therefore any test asserting it — is
+ * deterministic regardless of map ordering.
+ */
+export function diffManifestSlots(remoteInstances, localInstances) {
+ if (!isPlainObject(remoteInstances)) return [];
+ const local = isPlainObject(localInstances) ? localInstances : {};
+ const stale = [];
+ for (const [slotId, capturedAt] of Object.entries(remoteInstances)) {
+ if (typeof slotId !== 'string' || slotId.length === 0) continue;
+ if (!compareNewerWins(capturedAt, local[slotId])) continue;
+ stale.push(slotId);
+ }
+ return stale.sort();
+}
diff --git a/server/lib/syncManifest.test.js b/server/lib/syncManifest.test.js
new file mode 100644
index 0000000000..6d90769526
--- /dev/null
+++ b/server/lib/syncManifest.test.js
@@ -0,0 +1,65 @@
+import { describe, it, expect } from 'vitest';
+import { isManifestEnvelope, diffManifestSlots } from './syncManifest.js';
+
+describe('isManifestEnvelope', () => {
+ it('accepts a well-formed manifest response', () => {
+ expect(isManifestEnvelope({ checksum: 'abc', data: { instances: {} } })).toBe(true);
+ });
+
+ // `fetchPeer` returns null for a 404 — which is exactly what a source peer
+ // running the pre-manifest code does with this endpoint. Every non-envelope
+ // must read as "no manifest" so the puller falls back to the whole snapshot
+ // instead of silently syncing nothing.
+ it.each([
+ ['a legacy peer 404 (null)', null],
+ ['a checksum-only response', { checksum: 'abc' }],
+ ['a snapshot response (data, no instances map)', { checksum: 'abc', data: { sessions: [] } }],
+ ['an instances array rather than a map', { checksum: 'abc', data: { instances: [] } }],
+ ['a manifest with no checksum', { data: { instances: {} } }],
+ ])('rejects %s', (_label, value) => {
+ expect(isManifestEnvelope(value)).toBe(false);
+ });
+});
+
+describe('diffManifestSlots', () => {
+ const local = {
+ 'inst-a': '2026-09-01T10:00:00.000Z',
+ 'inst-b': '2026-09-01T10:00:00.000Z',
+ };
+
+ it('returns only the slots whose remote stamp advanced', () => {
+ expect(diffManifestSlots({
+ 'inst-a': '2026-09-01T11:00:00.000Z',
+ 'inst-b': '2026-09-01T10:00:00.000Z',
+ }, local)).toEqual(['inst-a']);
+ });
+
+ it('returns nothing when every slot matches', () => {
+ expect(diffManifestSlots({ ...local }, local)).toEqual([]);
+ });
+
+ it('takes a slot we have never seen', () => {
+ expect(diffManifestSlots({ 'inst-c': '2026-09-01T09:00:00.000Z' }, local)).toEqual(['inst-c']);
+ });
+
+ it('leaves a slot where our copy is newer', () => {
+ expect(diffManifestSlots({ 'inst-a': '2026-08-30T00:00:00.000Z' }, local)).toEqual([]);
+ });
+
+ it('ignores an unparseable remote stamp rather than fetching on it forever', () => {
+ expect(diffManifestSlots({ 'inst-a': 'not-a-date', 'inst-z': null }, local)).toEqual([]);
+ });
+
+ it('sorts the result so the request URL is deterministic', () => {
+ expect(diffManifestSlots({ 'inst-z': '2026-10-01T00:00:00.000Z', 'inst-c': '2026-10-01T00:00:00.000Z' }, local))
+ .toEqual(['inst-c', 'inst-z']);
+ });
+
+ it('treats a missing local manifest as "we hold nothing"', () => {
+ expect(diffManifestSlots({ 'inst-a': '2026-09-01T10:00:00.000Z' }, undefined)).toEqual(['inst-a']);
+ });
+
+ it('returns nothing for a non-map remote', () => {
+ expect(diffManifestSlots(null, local)).toEqual([]);
+ });
+});
diff --git a/server/routes/dataSync.js b/server/routes/dataSync.js
index e9bfe0eee7..0d67491237 100644
--- a/server/routes/dataSync.js
+++ b/server/routes/dataSync.js
@@ -40,6 +40,7 @@ import { z } from 'zod';
import * as dataSync from '../services/dataSync.js';
import { sweepTombstones, getSweepStatus, TOMBSTONE_GRACE_MS } from '../services/sharing/tombstoneGc.js';
import { authorizePeerPull } from '../services/sharing/peerPullAuthorization.js';
+import { MAX_MANIFEST_SLOTS } from '../lib/syncManifest.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
const router = Router();
@@ -107,6 +108,37 @@ const forPeerOf = (req) => {
return trimmed.length > 0 ? trimmed : undefined;
};
+// Optional `?slots=<id>,<id>` on the snapshot read — the per-instance slots a
+// manifest-aware puller diffed as stale. Only a manifest-serving category
+// (`usage`) honours it; everything else ignores it and serves the whole
+// payload, and so does a manifest category given no slots (an older peer, or a
+// puller whose manifest fetch failed). Bounded the same way `forPeer` is: a
+// single scalar, trimmed, per-id length-capped, and capped in COUNT so a
+// hostile query string can't turn into an unbounded Set. Repeated keys arrive
+// as an array from Express and are dropped.
+const slotsOf = (req) => {
+ if (typeof req.query.slots !== 'string') return undefined;
+ const ids = req.query.slots.split(',')
+ .map((id) => id.trim().slice(0, 128))
+ .filter((id) => id.length > 0)
+ .slice(0, MAX_MANIFEST_SLOTS);
+ return ids.length > 0 ? ids : undefined;
+};
+
+// GET /api/sync/:category/manifest — the category's per-slot version map.
+// 404 for a category that doesn't serve one; a puller treats that (and the
+// 404 an older peer returns for the whole route) as "no manifest" and falls
+// back to the whole snapshot.
+router.get('/:category/manifest', asyncHandler(async (req, res) => {
+ const category = categoryParam.parse(req.params.category);
+ // Same gate as the other two reads — a manifest is a fingerprint of the same
+ // payload, so it must never become the weaker door.
+ await authorizeSyncPull(req, category);
+ const manifest = await dataSync.getManifest(category);
+ if (!manifest) throw new ServerError('Category has no sync manifest', { status: 404 });
+ res.json(manifest);
+}));
+
// GET /api/sync/:category/checksum — return checksum only (lightweight)
router.get('/:category/checksum', asyncHandler(async (req, res) => {
const category = categoryParam.parse(req.params.category);
@@ -120,7 +152,7 @@ router.get('/:category/checksum', asyncHandler(async (req, res) => {
router.get('/:category/snapshot', asyncHandler(async (req, res) => {
const category = categoryParam.parse(req.params.category);
await authorizeSyncPull(req, category);
- const snapshot = await dataSync.getSnapshot(category, { forPeerId: forPeerOf(req) });
+ const snapshot = await dataSync.getSnapshot(category, { forPeerId: forPeerOf(req), slots: slotsOf(req) });
if (!snapshot) throw new ServerError('Category not found', { status: 404 });
res.json(snapshot);
}));
diff --git a/server/routes/dataSync.test.js b/server/routes/dataSync.test.js
index ff36aa7810..8a111bc53f 100644
--- a/server/routes/dataSync.test.js
+++ b/server/routes/dataSync.test.js
@@ -19,6 +19,7 @@ vi.mock('../services/sharing/tombstoneGc.js', () => ({
vi.mock('../services/dataSync.js', async () => ({
getChecksum: vi.fn(),
getSnapshot: vi.fn(),
+ getManifest: vi.fn(),
applyRemote: vi.fn(),
getSupportedCategories: (await vi.importActual('../services/dataSync.js')).getSupportedCategories,
}));
@@ -46,8 +47,9 @@ vi.mock('../services/settings.js', async () => ({
}));
import { sweepTombstones, getSweepStatus } from '../services/sharing/tombstoneGc.js';
-import { getChecksum, getSnapshot, applyRemote, getSupportedCategories } from '../services/dataSync.js';
+import { getChecksum, getSnapshot, getManifest, applyRemote, getSupportedCategories } from '../services/dataSync.js';
import { PEER_INSTANCE_ID_HEADER, __resetPullWarnThrottleForTests } from '../services/sharing/peerPullAuthorization.js';
+import { MAX_MANIFEST_SLOTS } from '../lib/syncManifest.js';
import dataSyncRoutes, { categoryParam } from './dataSync.js';
const PEER_ID = 'peer-a-instance-id';
@@ -201,6 +203,83 @@ describe('/api/sync/:category — enum parity with getSupportedCategories()', ()
});
});
+// #5759 — the manifest leg that lets a puller fetch only the per-instance slots
+// that moved, instead of the whole digest map every 60s cycle.
+describe('GET /api/sync/:category/manifest', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ settings = {};
+ setPeers(allowedPeer());
+ __resetPullWarnThrottleForTests();
+ getSnapshot.mockResolvedValue({ data: {}, checksum: 'abc' });
+ getManifest.mockResolvedValue({ data: { instances: { 'inst-a': '2026-09-01T10:00:00.000Z' }, tombstones: [] }, checksum: 'abc' });
+ });
+
+ it('serves the version map for a manifest category', async () => {
+ const res = await request(buildApp())
+ .get('/api/sync/usage/manifest')
+ .set(PEER_INSTANCE_ID_HEADER, PEER_ID);
+ expect(res.status).toBe(200);
+ expect(res.body.data.instances).toEqual({ 'inst-a': '2026-09-01T10:00:00.000Z' });
+ });
+
+ // The puller reads a 404 as "no manifest here" and falls back to the whole
+ // snapshot — the same signal a pre-manifest peer gives by not having the route.
+ it('404s a category that serves no manifest', async () => {
+ getManifest.mockResolvedValue(null);
+ const res = await request(buildApp())
+ .get('/api/sync/goals/manifest')
+ .set(PEER_INSTANCE_ID_HEADER, PEER_ID);
+ expect(res.status).toBe(404);
+ });
+
+ it('runs the same peer-pull gate as the other two reads', async () => {
+ // A manifest is a fingerprint of the same payload, so it must not become
+ // the weaker door (#5663).
+ const res = await request(buildApp()).get('/api/sync/digitalTwin/manifest');
+ expect(res.status).toBe(403);
+ expect(getManifest).not.toHaveBeenCalled();
+ });
+});
+
+describe('GET /api/sync/:category/snapshot — slots scoping', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ settings = {};
+ setPeers(allowedPeer());
+ __resetPullWarnThrottleForTests();
+ getSnapshot.mockResolvedValue({ data: {}, checksum: 'abc' });
+ });
+
+ const getSlots = async (qs) => {
+ const res = await request(buildApp())
+ .get(`/api/sync/usage/snapshot${qs}`)
+ .set(PEER_INSTANCE_ID_HEADER, PEER_ID);
+ expect(res.status).toBe(200);
+ return getSnapshot.mock.calls.at(-1)[1].slots;
+ };
+
+ it('threads trimmed, comma-separated slot ids through to the service', async () => {
+ expect(await getSlots('?slots=inst-a%2C%20inst-b')).toEqual(['inst-a', 'inst-b']);
+ });
+
+ it('serves the whole payload when slots is absent, blank, or repeated', async () => {
+ expect(await getSlots('')).toBeUndefined();
+ expect(await getSlots('?slots=%20%2C%20')).toBeUndefined();
+ expect(await getSlots('?slots=a&slots=b')).toBeUndefined();
+ });
+
+ it('caps the slot count so a hostile query string cannot become an unbounded set', async () => {
+ const many = Array.from({ length: MAX_MANIFEST_SLOTS * 2 }, (_, i) => `inst-${i}`).join(',');
+ expect(await getSlots(`?slots=${many}`)).toHaveLength(MAX_MANIFEST_SLOTS);
+ });
+
+ it('caps each id length', async () => {
+ const slots = await getSlots(`?slots=${'x'.repeat(500)}`);
+ expect(slots[0]).toHaveLength(128);
+ });
+});
+
// #5663 — the snapshot transport predates the peer-pull gate #3659 added to
// `/api/peer-sync/*`, so it served the user's identity record to anything that
// could reach the port.
@@ -289,7 +368,7 @@ describe('GET /api/sync/:category — peer-pull authorization', () => {
.get('/api/sync/digitalTwin/snapshot')
.set(PEER_INSTANCE_ID_HEADER, PEER_ID);
expect(res.status).toBe(200);
- expect(getSnapshot).toHaveBeenCalledWith('digitalTwin', { forPeerId: undefined });
+ expect(getSnapshot).toHaveBeenCalledWith('digitalTwin', { forPeerId: undefined, slots: undefined });
});
it('still serves a non-PII snapshot to an unidentified caller, warning once', async () => {
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index 81d6253a0c..b55893136d 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -36,6 +36,7 @@ import {
} from './digital-twin-sync.js';
import {
getUsageSnapshot,
+ getUsageManifest,
applyUsageRemote,
USAGE_CHECKSUM_PATHS,
} from './peerUsage.js';
@@ -770,7 +771,11 @@ const CATEGORIES = {
mediaCollections: { getSnapshot: getMediaCollectionsSnapshot, applyRemote: applyMediaCollectionsRemote },
videoHistory: { getSnapshot: getVideoHistorySnapshot, applyRemote: applyVideoHistoryRemote },
storyBuilder: { getSnapshot: getStoryBuilderSnapshot, applyRemote: applyStoryBuilderRemote },
- usage: { getSnapshot: getUsageSnapshot, applyRemote: applyUsageRemote }
+ // `getManifest` is optional and only `usage` has one: it is the only category
+ // that is BOTH always dirty (every recorded AI run rewrites usage.json) and a
+ // map of independently-advancing per-instance slots, so it is the only one
+ // where "one slot moved" was costing a whole-payload transfer (#5759).
+ usage: { getSnapshot: getUsageSnapshot, getManifest: getUsageManifest, applyRemote: applyUsageRemote }
};
// Map a snapshot CATEGORY to the `PORTOS_SCHEMA_VERSIONS` keys whose storage
@@ -951,13 +956,32 @@ export async function getChecksum(category, { forPeerId } = {}) {
// cache-hit path above never uses `exclude`, so deferring it here saves
// that I/O on every poll that hits the cache.
const exclude = await resolveExcludeSet(category, forPeerId);
- const snapshot = await cat.getSnapshot({ exclude });
- setChecksumCache(cacheKey, { fingerprints, checksum: snapshot.checksum });
- return { checksum: snapshot.checksum };
+ const { checksum } = await checksumSource(cat, exclude);
+ setChecksumCache(cacheKey, { fingerprints, checksum });
+ return { checksum };
}
const exclude = await resolveExcludeSet(category, forPeerId);
- const snapshot = await cat.getSnapshot({ exclude });
- return { checksum: snapshot.checksum };
+ return { checksum: (await checksumSource(cat, exclude)).checksum };
+}
+
+// A manifest-serving category hashes its MANIFEST, not its payload, so the
+// cheap map is enough to answer a checksum probe — no need to materialize every
+// digest just to throw them away.
+const checksumSource = (cat, exclude) => (cat.getManifest ? cat.getManifest() : cat.getSnapshot({ exclude }));
+
+/**
+ * The category's per-slot version map (`{ data: { instances: { <slotId>:
+ * <lwwTimestamp> }, ... }, checksum }`), or `null` for a category that doesn't
+ * serve one. Served at `/api/sync/:category/manifest` and read locally by the
+ * orchestrator as "what do we already hold?" — see `lib/syncManifest.js`.
+ */
+export async function getManifest(category) {
+ const cat = CATEGORIES[category];
+ if (!cat?.getManifest) return null;
+ // Same envelope a snapshot carries, so the receiver's schema-version gate
+ // still fires on the path where a manifest with no stale slots stands in for
+ // a snapshot fetch (a tombstone-only cycle).
+ return { ...(await cat.getManifest()), portosMeta: await buildPortosMeta() };
}
/**
@@ -970,12 +994,19 @@ export async function getChecksum(category, { forPeerId } = {}) {
* category (legacy behavior), which the receiver applies idempotently. This
* additive, ignore-if-unknown query param is what keeps the change
* forward/backward compatible across independently-upgrading installs.
+ *
+ * `options.slots` (from `?slots=`) narrows a manifest-serving category to the
+ * per-instance slots the caller diffed as stale. Absent — every non-manifest
+ * category, and any older peer — serves the whole payload.
*/
-export async function getSnapshot(category, { forPeerId } = {}) {
+export async function getSnapshot(category, { forPeerId, slots } = {}) {
const cat = CATEGORIES[category];
if (!cat) return null;
const exclude = await resolveExcludeSet(category, forPeerId);
- const snap = await cat.getSnapshot({ exclude });
+ // `slots` narrows a manifest-serving category to the entries the caller says
+ // it is missing. Every other category ignores the option and serves the whole
+ // payload, exactly as before.
+ const snap = await cat.getSnapshot({ exclude, slots });
// Stamp the sender's PortOS version + schema versions on every outbound
// snapshot. Receivers compare against their own PORTOS_SCHEMA_VERSIONS in
// `applyRemote` and reject ahead-mismatches before any data is merged.
diff --git a/server/services/peerUsage.js b/server/services/peerUsage.js
index d554a375fc..6bf06da253 100644
--- a/server/services/peerUsage.js
+++ b/server/services/peerUsage.js
@@ -220,23 +220,66 @@ async function entriesWithSelf() {
};
}
+/**
+ * The category's version map: `{ <instanceId>: capturedAt }` plus the tombstone
+ * list. A few hundred bytes, and the ONLY thing this category's checksum is
+ * computed over (see `usageChecksum`).
+ */
+function manifestOf(self, peers, tombstones) {
+ const instances = Object.fromEntries(peers.map((e) => [e.instanceId, e.capturedAt]));
+ if (self) instances[self.instanceId] = self.capturedAt;
+ return { instances, tombstones };
+}
+
+/**
+ * CANONICAL: the payload is a map keyed by instance ids arriving over the wire,
+ * so two converged peers would otherwise hash differently purely from the order
+ * they happened to learn each other — which the sync UI reads as "behind"
+ * forever.
+ *
+ * Hashed over the MANIFEST rather than the digests themselves. The digests are
+ * a pure function of the (instanceId, capturedAt) pairs — a slot is replaced
+ * whole under that stamp and never edited in place — so the manifest is a
+ * faithful fingerprint of the payload, and it is what `getUsageSnapshot`
+ * reports too. A peer that only knows `/checksum` + `/snapshot` therefore still
+ * sees the checksum change exactly when a slot advances.
+ */
+const usageChecksum = (manifest) => canonicalSnapshotChecksum(manifest);
+
+/**
+ * dataSync `getManifest` for the `usage` category. Served at
+ * `/api/sync/usage/manifest` so a puller can fetch only the slots that moved,
+ * and read locally (same function, no arguments) as "what do we already hold?"
+ * for that diff.
+ */
+export async function getUsageManifest() {
+ const { self, peers, tombstones } = await entriesWithSelf();
+ const data = manifestOf(self, peers, tombstones);
+ return { data, checksum: usageChecksum(data) };
+}
+
/**
* dataSync `getSnapshot` for the `usage` category: our own live digest plus
* every peer digest we hold, so a third instance reachable only through us
* still propagates.
+ *
+ * `slots` (a `Set`/array of instance ids, from `?slots=` on the wire) narrows
+ * the payload to the digests a manifest-aware puller actually needs. Absent —
+ * an older peer, or any caller that skipped the manifest — serves everything,
+ * which the receiver merges idempotently. The checksum is the FULL manifest's
+ * either way: it describes the category's state, not the slice we happened to
+ * serve, so the two endpoints can never disagree.
*/
-export async function getUsageSnapshot() {
+export async function getUsageSnapshot({ slots = null } = {}) {
const { self, peers, tombstones } = await entriesWithSelf();
- const instances = Object.fromEntries(peers.map((e) => [e.instanceId, e]));
- if (self) instances[self.instanceId] = self;
- // Tombstones ride the snapshot so a retirement propagates: an add-only merge
- // alone would let any peer that still holds the digest hand it straight back.
- const data = { instances, tombstones };
- // CANONICAL: the payload is a map keyed by instance ids arriving over the
- // wire, so two converged peers would otherwise hash differently purely from
- // the order they happened to learn each other — which the sync UI reads as
- // "behind" forever.
- return { data, checksum: canonicalSnapshotChecksum(data) };
+ const wanted = slots instanceof Set ? slots : (Array.isArray(slots) && slots.length > 0 ? new Set(slots) : null);
+ const keep = (id) => !wanted || wanted.has(id);
+ const instances = Object.fromEntries(peers.filter((e) => keep(e.instanceId)).map((e) => [e.instanceId, e]));
+ if (self && keep(self.instanceId)) instances[self.instanceId] = self;
+ // Tombstones ride EVERY response (slot-scoped included) so a retirement
+ // propagates: an add-only merge alone would let any peer that still holds the
+ // digest hand it straight back, and a retirement moves no slot's capturedAt.
+ return { data: { instances, tombstones }, checksum: usageChecksum(manifestOf(self, peers, tombstones)) };
}
/**
@@ -423,9 +466,8 @@ export async function forgetInstanceUsage(instanceId) {
}
// Files whose fingerprint invalidates the category's checksum cache. The
-// instances file is in the set because the snapshot embeds this instance's NAME
-// — without it a rename never reaches peers and their fleet table keeps showing
-// the old one until an AI run happens to move usage.json.
+// instances file is in the set because the manifest is keyed by this instance's
+// ID — a re-identified machine must re-checksum even when no counter moved.
export const USAGE_CHECKSUM_PATHS = [USAGE_FILE, PEER_USAGE_FILE, dataPath('instances.json')];
export { PEER_USAGE_FILE };
diff --git a/server/services/peerUsage.test.js b/server/services/peerUsage.test.js
index d40292ea87..ccc4efd7be 100644
--- a/server/services/peerUsage.test.js
+++ b/server/services/peerUsage.test.js
@@ -28,6 +28,7 @@ vi.mock('./usage.js', async () => {
const { buildUsageDigest, getUsage } = await import('./usage.js');
const {
getUsageSnapshot,
+ getUsageManifest,
applyUsageRemote,
getFleetUsage,
forgetInstanceUsage,
@@ -195,6 +196,98 @@ describe('usage sync category', () => {
});
});
+describe('usage sync manifest (#5759)', () => {
+ const otherEntry = (overrides = {}) => peerEntry({
+ instanceId: 'inst-other',
+ name: 'Render Box',
+ capturedAt: '2026-08-30T08:00:00.000Z',
+ ...overrides,
+ });
+
+ it('publishes one capturedAt per instance instead of the digests', async () => {
+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry(), 'inst-other': otherEntry() } });
+
+ const { data } = await getUsageManifest();
+ expect(data.instances).toEqual({
+ 'inst-self': '2026-08-30T12:00:00.000Z',
+ 'inst-peer': '2026-08-30T09:00:00.000Z',
+ 'inst-other': '2026-08-30T08:00:00.000Z',
+ });
+ });
+
+ // The two endpoints must agree or the puller caches a checksum for state it
+ // never fetched. A pre-manifest peer only ever sees the snapshot's, so this
+ // is also what keeps ITS short-circuit honest.
+ it('reports the same checksum as the snapshot, whole or slot-scoped', async () => {
+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry(), 'inst-other': otherEntry() } });
+
+ const manifest = await getUsageManifest();
+ expect((await getUsageSnapshot()).checksum).toBe(manifest.checksum);
+ expect((await getUsageSnapshot({ slots: ['inst-peer'] })).checksum).toBe(manifest.checksum);
+ });
+
+ it('changes only when an instance digest actually advances', async () => {
+ const before = (await getUsageManifest()).checksum;
+ // A digest that loses the LWW race moves no capturedAt, so nothing to fetch.
+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry() } });
+ const withPeer = (await getUsageManifest()).checksum;
+ expect(withPeer).not.toBe(before);
+
+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry({ capturedAt: '2026-08-29T00:00:00.000Z' }) } });
+ expect((await getUsageManifest()).checksum).toBe(withPeer);
+ });
+
+ it('serves only the requested slots, so one instance advancing moves one digest', async () => {
+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry(), 'inst-other': otherEntry() } });
+
+ const { data } = await getUsageSnapshot({ slots: ['inst-peer'] });
+ expect(Object.keys(data.instances)).toEqual(['inst-peer']);
+ expect(data.instances['inst-peer'].usage.totalTokens.output).toBe(4000);
+ });
+
+ it('still serves everything when no slots are named (a pre-manifest peer)', async () => {
+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry(), 'inst-other': otherEntry() } });
+
+ for (const slots of [undefined, [], null]) {
+ const { data } = await getUsageSnapshot({ slots });
+ expect(Object.keys(data.instances).sort()).toEqual(['inst-other', 'inst-peer', 'inst-self']);
+ }
+ });
+
+ // A retirement advances no slot's capturedAt, so it can only reach a peer by
+ // riding every response — the slot-scoped one included.
+ it('rides tombstones on the manifest and on a slot-scoped snapshot', async () => {
+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry(), 'inst-other': otherEntry() } });
+ await forgetInstanceUsage('inst-peer');
+
+ expect((await getUsageManifest()).data.tombstones).toEqual([
+ { instanceId: 'inst-peer', deletedAt: expect.any(String) },
+ ]);
+ expect((await getUsageSnapshot({ slots: ['inst-other'] })).data.tombstones).toHaveLength(1);
+ });
+
+ // The whole round trip, both directions, against the shipped merge: a puller
+ // that fetches ONLY the diffed slot converges exactly as a whole-payload one.
+ it('converges a receiver that fetches only the advanced slot', async () => {
+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry(), 'inst-other': otherEntry() } });
+ const held = (await getUsageManifest()).data.instances;
+
+ // A source peer whose `inst-other` digest moved on; everything else is level.
+ const advanced = otherEntry({ capturedAt: '2026-09-02T00:00:00.000Z', usage: buildUsageDigest(usageFixture({ tokensOut: 7777 })) });
+ const remoteManifest = { ...held, 'inst-other': advanced.capturedAt };
+ const { diffManifestSlots } = await import('../lib/syncManifest.js');
+ const stale = diffManifestSlots(remoteManifest, held);
+ expect(stale).toEqual(['inst-other']);
+
+ const partial = { instances: Object.fromEntries(stale.map((id) => [id, advanced])) };
+ expect(await applyUsageRemote(partial)).toEqual({ applied: true, count: 1 });
+ const store = await readStoreFile();
+ expect(store.instances['inst-other'].usage.totalTokens.output).toBe(7777);
+ // The slot we did NOT fetch is untouched, not dropped.
+ expect(store.instances['inst-peer'].usage.totalTokens.output).toBe(4000);
+ });
+});
+
describe('untrusted digest handling', () => {
// canonicalStringify (this category's checksum) recurses in JS, with a far
// smaller depth budget than native JSON.stringify — so a digest that survives
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index a4ee47c2e3..e14b5b74bb 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -23,6 +23,7 @@ import * as catalogSync from './catalogSync.js';
import * as dataSync from './dataSync.js';
import { getBackendName } from './memoryBackend.js';
import { withAbortTimeout } from '../lib/abortTimeout.js';
+import { isManifestEnvelope, diffManifestSlots, MAX_MANIFEST_SLOTS } from '../lib/syncManifest.js';
const CURSORS_FILE = dataPath('instances_sync_cursors.json');
const SYNC_INTERVAL_MS = 60000;
@@ -484,9 +485,22 @@ async function syncDataCategoryFromPeer(peer, peerId, category, cachedChecksums,
return { totalApplied: 0, checksum: checksumRes.checksum };
}
- // Checksum changed — fetch full snapshot (same forPeer scoping as checksum
- // so the snapshot we apply matches the checksum we just cached).
- const snapshot = await fetchPeer(peer, `/api/sync/${category}/snapshot${forPeerQs}`);
+ // Checksum changed — fetch the snapshot (same forPeer scoping as checksum so
+ // the snapshot we apply matches the checksum we just cached).
+ //
+ // A manifest-serving category (`usage`) narrows that to the per-instance
+ // slots that actually moved. `resolveStaleSlots` returns null when the source
+ // peer serves no usable manifest (an older install 404s the endpoint), and
+ // the whole-snapshot fetch below is then exactly the legacy path.
+ const manifest = await resolveStaleSlots(peer, category, forPeerQs);
+ // No slot moved, yet the checksum did — a retirement (tombstones ride every
+ // response and advance no slot's `capturedAt`), or our own digest coming back
+ // at us, which the receiver skips anyway. Synthesize the empty payload rather
+ // than spending a round trip on it; the tombstones still have to be applied
+ // or the retirement never propagates.
+ const snapshot = manifest?.slots.length === 0
+ ? { data: { instances: {}, tombstones: manifest.tombstones }, portosMeta: manifest.portosMeta, checksum: manifest.checksum }
+ : await fetchPeer(peer, `/api/sync/${category}/snapshot${forPeerQs}${slotsQsOf(manifest, forPeerQs)}`);
if (!snapshot?.data) return { totalApplied: 0, checksum: null };
// Forward the sender's portosMeta envelope so applyRemote can run the
@@ -519,9 +533,51 @@ async function syncDataCategoryFromPeer(peer, peerId, category, cachedChecksums,
await clearPeerSchemaGap(peerId, category)
.catch((err) => console.log(`⚠️ syncOrchestrator: clear schema gap failed: ${err.message}`));
- return { totalApplied: result.applied ? result.count : 0, checksum: snapshot.checksum };
+ // Cache the MANIFEST's checksum when we took the per-slot path: it is the
+ // state we actually diffed against and converged to. The snapshot's own
+ // checksum could already describe a newer manifest (a digest landing between
+ // the two fetches), and caching that would skip the slot we never pulled.
+ // It is deliberately null on a truncated diff — same reason.
+ return { totalApplied: result.applied ? result.count : 0, checksum: manifest ? manifest.checksum : snapshot.checksum };
+}
+
+/**
+ * Ask a peer for a manifest-serving category's per-slot version map and diff it
+ * against ours, so the snapshot fetch carries only the slots that moved.
+ *
+ * Returns `null` — meaning "fetch the whole snapshot" — for a category with no
+ * manifest, for a source peer too old to serve one (404 → `fetchPeer` null),
+ * for a malformed response, and if our own local read fails. Every one of those
+ * degrades to the pre-manifest transfer, which receivers merge idempotently.
+ */
+async function resolveStaleSlots(peer, category, forPeerQs) {
+ const local = await dataSync.getManifest(category).catch(() => null);
+ if (!local) return null;
+ const remote = await fetchPeer(peer, `/api/sync/${category}/manifest${forPeerQs}`);
+ if (!isManifestEnvelope(remote)) return null;
+ const stale = diffManifestSlots(remote.data.instances, local.data?.instances);
+ return {
+ // A truncated request converges only if we DON'T cache the checksum: the
+ // dropped slots would otherwise sit behind a checksum that now matches. The
+ // next cycle re-diffs and takes the next batch. (Unreachable with today's
+ // 64-instance store cap; the guard is what makes raising that cap safe.)
+ checksum: stale.length > MAX_MANIFEST_SLOTS ? null : remote.checksum,
+ slots: stale.slice(0, MAX_MANIFEST_SLOTS),
+ // Tombstones ride the manifest, so a retirement propagates even on a cycle
+ // where no slot advanced.
+ tombstones: Array.isArray(remote.data.tombstones) ? remote.data.tombstones : [],
+ // Carried so the empty-payload shortcut above still runs the same
+ // schema-version gate a fetched snapshot would.
+ portosMeta: remote.portosMeta,
+ };
}
+// `?slots=` for the narrowed snapshot fetch — empty (whole payload) whenever no
+// manifest resolved. Joined with `&` when `?forPeer=` already opened the query.
+const slotsQsOf = (manifest, forPeerQs) => (manifest
+ ? `${forPeerQs ? '&' : '?'}slots=${manifest.slots.map(encodeURIComponent).join(',')}`
+ : '');
+
/**
* Persist a per-(peer, category) schema-version gap on the peer record.
* Stored under `peer.schemaGaps[category]` as `{ detectedAt, ahead, behind,
diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.js
index 8994fff273..fb431b3b6e 100644
--- a/server/services/syncOrchestrator.test.js
+++ b/server/services/syncOrchestrator.test.js
@@ -61,6 +61,9 @@ vi.mock('./memoryBackend.js', () => ({
vi.mock('./dataSync.js', () => ({
getSnapshot: vi.fn().mockResolvedValue({ data: {}, checksum: 'abc' }),
getChecksum: vi.fn().mockResolvedValue({ checksum: 'abc' }),
+ // null = "this category serves no manifest" (every category but `usage`),
+ // which is the signal to fetch the whole snapshot.
+ getManifest: vi.fn().mockResolvedValue(null),
applyRemote: vi.fn().mockResolvedValue({ applied: false, count: 0 }),
getSupportedCategories: vi.fn(() => ['goals', 'character', 'digitalTwin', 'meatspace'])
}));
@@ -870,6 +873,128 @@ describe('syncOrchestrator', () => {
});
});
+ // #5759: `usage` is always dirty AND a map of per-instance slots, so the
+ // checksum short-circuit alone dragged every instance's digest across the
+ // wire whenever any one of them advanced.
+ describe('manifest-scoped snapshot pull (#5759)', () => {
+ const syncUrls = () => mockFetch.mock.calls.map((c) => c[0]).filter((url) => url.includes('/api/sync/'));
+ const urlFor = (leg) => syncUrls().find((url) => url.includes(`/usage/${leg}`));
+
+ // We already hold two instances; the source peer's own digest advanced.
+ const localManifest = {
+ data: { instances: { 'inst-a': '2026-09-01T10:00:00.000Z', 'inst-b': '2026-09-01T10:00:00.000Z' }, tombstones: [] },
+ checksum: 'local-manifest',
+ };
+ const remoteManifest = {
+ data: { instances: { 'inst-a': '2026-09-01T10:00:00.000Z', 'inst-b': '2026-09-01T12:00:00.000Z' }, tombstones: [] },
+ checksum: 'remote-manifest',
+ portosMeta: { portosVersion: '2.56.0', schemaVersions: {} },
+ };
+
+ let dataSync;
+ beforeEach(async () => {
+ dataSync = await import('./dataSync.js');
+ dataSync.getSupportedCategories.mockReturnValue(['usage']);
+ dataSync.getManifest.mockResolvedValue(localManifest);
+ dataSync.applyRemote.mockResolvedValue({ applied: true, count: 1 });
+ mockFetch.mockImplementation(async (url) => {
+ if (url.includes('/usage/checksum')) return { ok: true, json: async () => ({ checksum: 'remote-manifest' }) };
+ if (url.includes('/usage/manifest')) return { ok: true, json: async () => remoteManifest };
+ if (url.includes('/usage/snapshot')) return { ok: true, json: async () => ({ data: { instances: { 'inst-b': {} } }, checksum: 'remote-manifest' }) };
+ return { ok: true, json: async () => ({}) };
+ });
+ });
+
+ it('fetches only the slot whose capturedAt advanced', async () => {
+ await syncWithPeer({ ...mockPeer, syncCategories: { usage: true } });
+ expect(urlFor('manifest')).toBeTruthy();
+ // `inst-a` is level on both sides, so it must not ride the wire.
+ expect(urlFor('snapshot')).toContain('slots=inst-b');
+ expect(urlFor('snapshot')).not.toContain('inst-a');
+ // `?forPeer=` already opened the query string.
+ expect(urlFor('snapshot')).toContain('forPeer=our-inst-id&slots=');
+ });
+
+ it('caches the manifest checksum, not the snapshot response checksum', async () => {
+ // A digest landing between the two fetches would make the snapshot
+ // describe state we did not pull; caching that would skip it forever.
+ mockFetch.mockImplementation(async (url) => {
+ if (url.includes('/usage/checksum')) return { ok: true, json: async () => ({ checksum: 'remote-manifest' }) };
+ if (url.includes('/usage/manifest')) return { ok: true, json: async () => remoteManifest };
+ if (url.includes('/usage/snapshot')) return { ok: true, json: async () => ({ data: { instances: {} }, checksum: 'even-newer' }) };
+ return { ok: true, json: async () => ({}) };
+ });
+ const result = await syncWithPeer({ ...mockPeer, syncCategories: { usage: true } });
+ expect(result.usage.checksum).toBe('remote-manifest');
+ });
+
+ it('applies the tombstones without a snapshot fetch when no slot moved', async () => {
+ // A retirement advances no capturedAt, so the checksum moves and the
+ // manifest diff comes back empty — the tombstones still have to land.
+ const tombstones = [{ instanceId: 'inst-a', deletedAt: '2026-09-02T00:00:00.000Z' }];
+ mockFetch.mockImplementation(async (url) => {
+ if (url.includes('/usage/checksum')) return { ok: true, json: async () => ({ checksum: 'retired' }) };
+ if (url.includes('/usage/manifest')) return { ok: true, json: async () => ({ data: { instances: localManifest.data.instances, tombstones }, checksum: 'retired' }) };
+ return { ok: true, json: async () => ({}) };
+ });
+ await syncWithPeer({ ...mockPeer, syncCategories: { usage: true } });
+
+ expect(urlFor('snapshot')).toBeUndefined();
+ expect(dataSync.applyRemote).toHaveBeenCalledWith('usage', { instances: {}, tombstones }, expect.anything());
+ });
+
+ // Backward compatibility: the source peer runs the pre-manifest code and
+ // 404s the endpoint. The whole-snapshot leg is then exactly the old path.
+ it('falls back to the whole snapshot against a pre-manifest peer', async () => {
+ mockFetch.mockImplementation(async (url) => {
+ if (url.includes('/usage/checksum')) return { ok: true, json: async () => ({ checksum: 'remote-full' }) };
+ if (url.includes('/usage/manifest')) return { ok: false, status: 404, json: async () => ({}) };
+ if (url.includes('/usage/snapshot')) return { ok: true, json: async () => ({ data: { instances: { 'inst-a': {}, 'inst-b': {} } }, checksum: 'remote-full' }) };
+ return { ok: true, json: async () => ({}) };
+ });
+ const result = await syncWithPeer({ ...mockPeer, syncCategories: { usage: true } });
+
+ expect(urlFor('snapshot')).not.toContain('slots=');
+ expect(result.usage.checksum).toBe('remote-full');
+ expect(dataSync.applyRemote).toHaveBeenCalledWith('usage', { instances: { 'inst-a': {}, 'inst-b': {} } }, expect.anything());
+ });
+
+ // The slot cap bounds the request URL; without leaving the checksum
+ // unadvanced, the slots it dropped would sit behind a checksum that now
+ // matches and would never be fetched again.
+ it('leaves the checksum unadvanced when the diff exceeds the slot cap', async () => {
+ const { MAX_MANIFEST_SLOTS } = await import('../lib/syncManifest.js');
+ const instances = Object.fromEntries(
+ Array.from({ length: MAX_MANIFEST_SLOTS + 5 }, (_, i) => [`inst-${i}`, '2026-09-01T12:00:00.000Z']),
+ );
+ dataSync.getManifest.mockResolvedValue({ data: { instances: {}, tombstones: [] }, checksum: 'local' });
+ mockFetch.mockImplementation(async (url) => {
+ if (url.includes('/usage/checksum')) return { ok: true, json: async () => ({ checksum: 'wide' }) };
+ if (url.includes('/usage/manifest')) return { ok: true, json: async () => ({ data: { instances, tombstones: [] }, checksum: 'wide' }) };
+ if (url.includes('/usage/snapshot')) return { ok: true, json: async () => ({ data: { instances: {} }, checksum: 'wide' }) };
+ return { ok: true, json: async () => ({}) };
+ });
+ const result = await syncWithPeer({ ...mockPeer, syncCategories: { usage: true } });
+
+ expect(urlFor('snapshot').match(/inst-\d+/g)).toHaveLength(MAX_MANIFEST_SLOTS);
+ expect(result.usage.checksum).toBeNull();
+ });
+
+ // The other direction of the same compatibility rule: a category with no
+ // manifest must not pay for a manifest probe at all.
+ it('never probes for a manifest on a category that serves none', async () => {
+ dataSync.getSupportedCategories.mockReturnValue(['goals']);
+ dataSync.getManifest.mockResolvedValue(null);
+ mockFetch.mockImplementation(async (url) => {
+ if (url.includes('/goals/checksum')) return { ok: true, json: async () => ({ checksum: 'remote' }) };
+ if (url.includes('/goals/snapshot')) return { ok: true, json: async () => ({ data: { goals: [] }, checksum: 'remote' }) };
+ return { ok: true, json: async () => ({}) };
+ });
+ await syncWithPeer({ ...mockPeer, syncCategories: { goals: true } });
+ expect(syncUrls().some((url) => url.includes('/manifest'))).toBe(false);
+ });
+ });
+
describe('syncAllPeers', () => {
it('iterates online peers with instanceId', async () => {
const onlinePeer = { ...mockPeer };