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): don't advance a catalog kind cursor past apply failures; rewind a stale cursor on peer DB rebuild

[._.]/ Adam Eivy21a39df1389f
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index 160a1f2946..6b73d3e978 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -204,10 +204,39 @@ async function syncCatalogFromPeer(peer, peerId, cursor) {
let blockedBySchema = null;
let hasMore = true;
+ // Only the FIRST fetch can carry a stale saved cursor from a prior session;
+ // once we start draining, each cursor came from this peer's own maxSequences
+ // and can't exceed them. So the rebuild/reset check runs on the first fetch
+ // only (a mid-drain quiet kind legitimately reports a per-page max at/under
+ // our just-advanced cursor, which must NOT be read as a reset).
+ let firstFetch = true;
while (hasMore) {
const data = await fetchPeer(peer, `/api/catalog/sync?${catalogSinceQuery(catalogSeqs)}&limit=100`);
if (!data) break;
+ // Detect a peer catalog rebuild/restore: if our saved cursor for a kind
+ // exceeds the peer's reported maximum, that table's sequence was reset, so
+ // our `since[kind]=<high>` would skip every row forever. Rewind the
+ // affected kinds to 0 and re-fetch from scratch before applying — safe
+ // because catalog apply is idempotent (LWW / ON CONFLICT dedup). Mirrors
+ // the brain/memory `detectCursorReset` path, but uses the sync response's
+ // own maxSequences so it needs no separate peer probe.
+ if (firstFetch && isPlainObjectShallow(data.maxSequences)) {
+ let rewound = false;
+ for (const kind of CATALOG_CURSOR_KINDS) {
+ const ours = catalogSeqs[kind];
+ const peerMax = data.maxSequences[kind];
+ if (typeof ours === 'string' && /^\d+$/.test(ours)
+ && typeof peerMax === 'string' && /^\d+$/.test(peerMax)
+ && BigInt(ours) > BigInt(peerMax)) {
+ console.log(`🔄 Catalog cursor reset for ${peer.name} (${kind}): cursor ${ours} > peer max ${peerMax}`);
+ catalogSeqs[kind] = '0';
+ rewound = true;
+ }
+ } if (rewound) continue; // re-fetch with the rewound cursors before applying
+ }
+ firstFetch = false;
+
// Forward the sender's portosMeta so applyRemoteChanges runs the schema
// gate BEFORE merging — a sender ahead on `catalog` throws and we persist
// the gap rather than corrupting local state.
@@ -235,6 +264,13 @@ async function syncCatalogFromPeer(peer, peerId, cursor) {
const before = catalogSinceQuery(catalogSeqs);
if (isPlainObjectShallow(data.maxSequences)) {
for (const kind of CATALOG_CURSOR_KINDS) {
+ // Don't advance a kind's cursor past a page that had apply failures: a
+ // child row (relation/media/ref to an ingredient on a LATER page) fails
+ // when its parent isn't applied yet. Leaving the cursor makes the next
+ // pull re-request and re-apply it once the parent lands (re-applying the
+ // page's already-succeeded rows is idempotent). A quiet/clean kind has
+ // failed===0 and still advances normally.
+ if ((stats?.[kind]?.failed || 0) > 0) continue;
const v = data.maxSequences[kind];
if (typeof v === 'string' && /^\d+$/.test(v)) catalogSeqs[kind] = v;
}
diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.js
index 63c70f4806..e134066fe4 100644
--- a/server/services/syncOrchestrator.test.js
+++ b/server/services/syncOrchestrator.test.js
@@ -60,7 +60,11 @@ vi.mock('./instanceEvents.js', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
- readJSONFile: vi.fn().mockResolvedValue({}),
+ // Fresh object per call: `mockResolvedValue({})` would hand every
+ // loadCursors() the SAME object, so one test's saveCursors mutation leaks
+ // into the next (a prior test's high catalog cursor then trips the
+ // rebuild/reset detection). A fresh {} isolates each test's cursor state.
+ readJSONFile: vi.fn(async () => ({})),
ensureDir: vi.fn().mockResolvedValue(),
atomicWrite: vi.fn().mockResolvedValue(),
PATHS: { data: '/mock/data' },
@@ -74,6 +78,7 @@ vi.mock('fs/promises', () => ({
rename: vi.fn().mockResolvedValue()
}));
+import { readJSONFile } from '../lib/fileUtils.js';
import { getPeers } from './instances.js';
import { applyRemoteChanges as applyBrainChanges } from './brainSync.js';
import { applyRemoteChanges as applyMemoryChanges } from './memorySync.js';
@@ -95,6 +100,12 @@ describe('syncOrchestrator', () => {
beforeEach(() => {
vi.clearAllMocks();
+ // Reset the cursor-store read to a FRESH empty object each test. The
+ // brain/memory reset tests below override it with `mockResolvedValue(
+ // cursorData)`, and that implementation survives `clearAllMocks` — without
+ // this reset a later test inherits a prior test's (mutated) cursor and the
+ // catalog rebuild/reset detection fires on it.
+ readJSONFile.mockImplementation(async () => ({}));
vi.useFakeTimers();
mockFetch.mockReset();
vi.stubGlobal('fetch', mockFetch);
@@ -380,6 +391,75 @@ describe('syncOrchestrator', () => {
expect(result.catalog.catalogSeqs.ingredients).toBe('9');
});
+ it('rewinds a stale catalog cursor that exceeds the peer max (peer DB rebuild) and re-pulls from 0', async () => {
+ // Saved cursor is far ahead of the peer's rebuilt table maxima.
+ readJSONFile.mockResolvedValue({
+ [catalogPeer.instanceId]: {
+ catalogSeqs: { scraps: '0', ingredients: '999', sources: '0', refs: '0', relations: '0', tags: '0', media: '0' },
+ },
+ });
+ mockFetch
+ .mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ ingredients: [],
+ maxSequences: { scraps: '0', ingredients: '5', sources: '0', refs: '0', relations: '0', tags: '0', media: '0' },
+ hasMore: true,
+ portosMeta: { schemaVersions: { catalog: 1 } },
+ }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ ingredients: [{ id: 'a' }],
+ maxSequences: { scraps: '0', ingredients: '5', sources: '0', refs: '0', relations: '0', tags: '0', media: '0' },
+ hasMore: false,
+ portosMeta: { schemaVersions: { catalog: 1 } },
+ }),
+ });
+ applyCatalogChanges.mockResolvedValue({
+ scraps: { inserted: 0, updated: 0 }, ingredients: { inserted: 1, updated: 0 },
+ sources: { applied: 0 }, refs: { applied: 0 }, relations: { applied: 0 },
+ tags: { inserted: 0, updated: 0 }, media: { applied: 0 }, errors: [],
+ });
+
+ await syncWithPeer(catalogPeer);
+
+ // First fetch carries the stale cursor; detecting cursor(999) > peerMax(5)
+ // rewinds ingredients to 0 and re-fetches BEFORE applying, so the stale
+ // page isn't applied and the rewound page is.
+ expect(mockFetch.mock.calls[0][0]).toContain('since[ingredients]=999');
+ expect(mockFetch.mock.calls[1][0]).toContain('since[ingredients]=0');
+ expect(applyCatalogChanges).toHaveBeenCalledTimes(1);
+ });
+
+ it('holds a kind cursor when that kind had apply failures (parent on a later page)', async () => {
+ // A ref fails because its parent ingredient is on a later page; the
+ // ingredient itself applies cleanly in the same batch.
+ mockFetch.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ ingredients: [{ id: 'a' }], refs: [{ id: 'r' }],
+ maxSequences: { scraps: '0', ingredients: '5', sources: '0', refs: '5', relations: '0', tags: '0', media: '0' },
+ hasMore: false,
+ portosMeta: { schemaVersions: { catalog: 1 } },
+ }),
+ });
+ applyCatalogChanges.mockResolvedValue({
+ scraps: { inserted: 0, updated: 0 }, ingredients: { inserted: 1, updated: 0 },
+ sources: { applied: 0 }, refs: { applied: 0, failed: 1 }, relations: { applied: 0 },
+ tags: { inserted: 0, updated: 0 }, media: { applied: 0 }, errors: [{ kind: 'refs', id: 'r' }],
+ });
+
+ const result = await syncWithPeer(catalogPeer);
+
+ // ingredients applied cleanly → its cursor advances; refs failed → its
+ // cursor is HELD (unset/0) so the next sync re-requests it once the parent
+ // ingredient has landed.
+ expect(result.catalog.catalogSeqs.ingredients).toBe('5');
+ expect(result.catalog.catalogSeqs.refs ?? '0').toBe('0');
+ });
+
it('records a schema gap and stops draining when the sender is ahead on catalog', async () => {
mockFetch.mockResolvedValue({
ok: true,