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

fix: stop peer sync from skipping late-committing memory and catalog rows (#8315)

[._.]/ Adam Eivy0fe57e33d6cf
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index e78fd67734..2f3cb97a5b 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -41,6 +41,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `cos_pending_agent_feedback` — a bounded, machine-local index of completed manual CoS runs that still need a human rating. It stores only `agent_id` plus the archive date locator; the agent archive remains the source-owned record and the rating is removed from this index only after that archive carries the durable rating. PostgreSQL is authoritative in normal installs (with the documented file backend only for dev/test), the input-gated migration 008 derives existing refs from live state without a seed or provider call, and future completion events enroll new refs. **Intentionally machine-local — never federated**; the DB dump backs it up alongside the agent archive under the filesystem snapshot. Adapter: `server/services/cosAgentFeedbackStore.js`.
- `creative_director_projects` — Creative Director project/treatment/scene/run state, one row per project (`id`/`status`/timestamps as columns, the full record in `data` JSONB). Migrated from the monolithic `data/creative-director-projects.json` in Phase 3 (#997); CD is local-only, so the row carries no sync cursor/tombstone. Adapter: `server/services/creativeDirector/projectsDB.js`.
- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.
+- `sync_feed` — the commit-ordered federation change feed (#8315) behind the `memories` and catalog-table peer pulls: one row per live row version, `(stream = table name, row_sequence = that row's sync_sequence) → position`. A position is drawn at COMMIT by deferred constraint triggers serialized on one transaction-scoped advisory lock, so a transaction that commits late can never land below a cursor a peer already advanced past (the write-time `sync_sequence` could). Peers page by position; positions start at 1e15, so a pre-feed cursor replays each stream once after an upgrade (apply is LWW / ON CONFLICT, so nothing is duplicated). Machine-local bookkeeping — only the rows it points at federate. DDL: `server/lib/db/schema/syncFeed.js` + `init-db.sql`; existing rows are backfilled by db-migration `009-commit-ordered-sync-feed.js`.
- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences, and portable character production packages) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Character production packages carry only versioned voice direction and approved managed-image roles; local profiles, recordings, provider ids, and training artifacts are excluded from the federated wire. Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. **`universe_runs` is intentionally never federated** — a regenerable render cache under a 200-row *global* cap that two producers would mutually evict, while the durable universe record already syncs (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724). Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`. **One universe ships with the product:** `universe-reality` ("Reality"), seeded by `scripts/migrations/395-reality-universe-seed.js` — not by `data.reference/`, because universes are PG rows and `setup-data.js` only copies files. It carries the federated `factual: true` flag (#7616), which marks a world whose people and places are real so the catalog extractor reads captured text as lived record rather than invented story; `factual` is persisted ONLY when true, so every fiction universe keeps its exact on-disk shape and wire checksum, and `PORTOS_SCHEMA_VERSIONS.universes` is 12 so a `factual`-unaware peer cannot strip-then-LWW the flag away. The migration gates on the ABSENCE of any row with that id — tombstone included — so a Reality the user deleted is never resurrected by an upgrade.
- `voice_profiles` / `voice_profile_renders` — machine-local DB-primary records for approved `(universeId, characterId)` bindings and the latest rendered dialogue line per `(issueId, lineId)`. They store the promoted Kokoro/Piper preset, profile revision, route availability, benchmark provenance, and reproducible dialogue delivery details (engine/model revision, timing, controls, and mastering). The portable Universe character and federated pipeline issue keep only portable voice data and audio filenames; they never store a local profile id. Rendered benchmark WAVs, safe-basename source-asset metadata, and future local engine artifacts live under `data/voice-profiles/<profileId>/`. Both the PostgreSQL dump and that managed directory are included in normal backup, while peer sync intentionally carries neither. Adapter: `server/services/voice/profiles.js`.
- `tribe_people` / `tribe_touchpoints` / `tribe_memory_links` — the Tribe relationship/CRM graph (people + their care cadence, contact touchpoints, and cross-links into brain `memories`). **Intentionally machine-local — never federated** (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724): it is relationship-graph data, mirroring the deliberate "memory_links are instance-local" boundary in `memorySync.js` (memory *nodes* federate, the link graph does not), and is coupled to machine-local domains — `tribe_memory_links` extends the non-federated `memory_links` layer and `tribe_touchpoints` carry per-machine calendar-account refs. NO `sync_sequence`, no peer-sync record kind, no `dataSync` category. Adapter: `server/services/tribe.js`.
diff --git a/server/lib/db.ddlParity.test.js b/server/lib/db.ddlParity.test.js
index b30f273108..4cddee04f7 100644
--- a/server/lib/db.ddlParity.test.js
+++ b/server/lib/db.ddlParity.test.js
@@ -25,6 +25,7 @@
import { describe, it, expect } from 'vitest';
import { FTS_PAYLOAD_FIELDS } from './catalogTypes.js';
+import { syncFeedDdl, syncFeedTables, buildSyncFeedTriggers } from './db/schema/syncFeed.js';
import { readFileSync, readdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
@@ -357,6 +358,25 @@ describe('DDL parity (init-db.sql ↔ db/schema ensureSchema)', () => {
for (const table of jsAuditTables) expect(shared, `audited table ${table} is not declared in both sources`).toContain(table);
});
+ // Commit-ordered sync feed (#8315). The constraint triggers carry
+ // DEFERRABLE/WHEN clauses the generic trigger extractor above does not
+ // parse, and syncFeed.js generates its statements from `syncFeedTables`, so
+ // compare the composed JS statements against init-db.sql directly. A feed
+ // trigger missing from init-db.sql would leave a fresh install's peers
+ // pulling an empty feed for that stream.
+ it('sync feed DDL and deferred capture triggers match in both files', () => {
+ const flat = (s) => s.replace(/\s+/g, ' ').trim();
+ const sql = flat(INIT_SQL.replace(/--[^\n]*\n/g, '\n'));
+ const jsStatements = [...syncFeedDdl, ...buildSyncFeedTriggers()];
+ for (const stmt of jsStatements) {
+ expect(sql, `init-db.sql is missing: ${flat(stmt).slice(0, 120)}`).toContain(flat(stmt));
+ }
+ const sqlConstraintTriggers = [...INIT_SQL.matchAll(/CREATE CONSTRAINT TRIGGER\s+(\w+)/gi)].map((m) => m[1]).sort();
+ const jsConstraintTriggers = jsStatements.flatMap((s) => [...s.matchAll(/CREATE CONSTRAINT TRIGGER\s+(\w+)/gi)].map((m) => m[1])).sort();
+ expect(sqlConstraintTriggers).toEqual(jsConstraintTriggers);
+ expect(jsConstraintTriggers).toHaveLength(syncFeedTables.length * 2);
+ });
+
it('catalog_ingredients type is app-layer-gated (no hardcoded CHECK in either file)', () => {
// The legacy `CHECK (type IN (...))` was dropped — valid types are gated at
// the app layer via the INGREDIENT_TYPES registry + Zod enum, so a new type
diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.md
index 5771517ddb..8da2305f85 100644
--- a/server/lib/db/schema/README.md
+++ b/server/lib/db/schema/README.md
@@ -44,13 +44,14 @@ init-db.sql, each with a one-line reason.
| `x.js` | `xDdl` | X account diagnostics, public post metrics, and review-gated drafts |
| `beeper.js` | `beeperDdl` | Beeper conversation mirror — accounts, the vault-encrypted access credential, conversations, messages, participants, attachment metadata, sync cursors, and the outbound send outbox (machine-local, never federated) |
| `audit.js` | `auditDdl`, `auditedTables`, `buildAuditTriggers()` | `record_audit` table/function + per-table audit triggers |
+| `syncFeed.js` | `syncFeedDdl`, `syncFeedTables`, `buildSyncFeedTriggers()` | Commit-ordered federation change feed (`sync_feed`) + deferred capture triggers on memories and the catalog tables (#8315) |
### Composer (`index.js`)
- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions` → `userActions` → `reviewQueueTriage` → `cosAgentFeedback` → `aiGraph`).
- `buildCatalogDdl()` → phase-2 list (`catalog` → `media` → `catalogUserTypes` →
`universes` → `library` → `pipeline` → `writersRoom` → `lora` → `privacy` → `stackerNews` → `x` →
- `beeper` → `audit` DDL → audit triggers).
+ `beeper` → `audit` DDL → audit triggers → `syncFeed` DDL → sync-feed triggers).
`ensureSchemaImpl()` calls these two builders and runs each list through
`pool.query` in order.
diff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.js
index dba171fb96..2c1f795cc1 100644
--- a/server/lib/db/schema/index.js
+++ b/server/lib/db/schema/index.js
@@ -36,6 +36,7 @@ import { mindToolRecipesDdl } from './mindToolRecipes.js';
import { decksDdl } from './decks.js';
import { beeperDdl } from './beeper.js';
import { auditDdl, auditedTables, buildAuditTriggers } from './audit.js';
+import { syncFeedDdl, syncFeedTables, buildSyncFeedTriggers } from './syncFeed.js';
export {
coreDdl,
@@ -64,6 +65,9 @@ export {
auditDdl,
auditedTables,
buildAuditTriggers,
+ syncFeedDdl,
+ syncFeedTables,
+ buildSyncFeedTriggers,
};
// Phase 1 — the `upgrades` list: memory-sync columns + migration tracker, then
@@ -87,7 +91,9 @@ export function buildUpgradeDdl() {
// record_audit table/function, then the per-table audit triggers. catalog_user_types
// is threaded in AFTER the media block to match its original position (see catalog.js).
// `beeperDdl` is appended after `xDdl` (#27) — same external-mirror shape as
-// stackerNews/x, added last of that group, before the audit block.
+// stackerNews/x, added last of that group, before the audit block. The
+// commit-ordered sync feed (#8315) comes last: its triggers attach to memories
+// and the catalog tables, which must already exist.
export function buildCatalogDdl() {
return [
...catalogDdl,
@@ -106,5 +112,7 @@ export function buildCatalogDdl() {
...decksDdl,
...auditDdl,
...buildAuditTriggers(),
+ ...syncFeedDdl,
+ ...buildSyncFeedTriggers(),
];
}
diff --git a/server/lib/db/schema/schema.test.js b/server/lib/db/schema/schema.test.js
index f7eaf2ce93..9c83e44cc7 100644
--- a/server/lib/db/schema/schema.test.js
+++ b/server/lib/db/schema/schema.test.js
@@ -29,7 +29,7 @@ const DOMAIN_ARRAYS = [
'catalogDdl', 'catalogUserTypesDdl', 'mediaDdl', 'universesDdl',
'libraryDdl', 'pipelineDdl', 'writersRoomDdl', 'loraDdl', 'privacyDdl', 'stackerNewsDdl', 'xDdl',
'beeperDdl', 'mindToolRecipesDdl',
- 'auditDdl',
+ 'auditDdl', 'syncFeedDdl',
];
describe('db/schema barrel + composer (#2832)', () => {
@@ -73,6 +73,8 @@ describe('db/schema barrel + composer (#2832)', () => {
...schema.decksDdl,
...schema.auditDdl,
...buildAuditTriggers(),
+ ...schema.syncFeedDdl,
+ ...schema.buildSyncFeedTriggers(),
];
expect(buildCatalogDdl()).toEqual(expected);
});
diff --git a/server/lib/db/schema/syncFeed.db.test.js b/server/lib/db/schema/syncFeed.db.test.js
new file mode 100644
index 0000000000..a91bd4a5c4
--- /dev/null
+++ b/server/lib/db/schema/syncFeed.db.test.js
@@ -0,0 +1,239 @@
+/**
+ * Postgres-backed contract for the commit-ordered federation change feed (#8315).
+ *
+ * The bug this pins is a visibility interleaving that only a real database can
+ * produce: transaction T1 writes a row (drawing a LOWER write-time
+ * sync_sequence) and stays open, T2 writes and commits, a peer pulls and
+ * advances its cursor past T2, then T1 commits. Paging by sync_sequence skipped
+ * T1's row forever. Each test here holds real transactions open across real
+ * pulls through the public sync readers.
+ *
+ * `*.db.test.js` → runs ONLY via `npm run test:db` against `portos_test`
+ * (registered in DB_TEST_INCLUDE). Every row uses a per-run id prefix and is
+ * removed in afterAll, so the shared test database stays usable by concurrent
+ * worktrees.
+ */
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { randomUUID } from 'node:crypto';
+import { checkHealth, close, ensureSchema, query, withTransaction } from '../../db.js';
+import { requireDbOrSkip } from '../../dbTestGate.js';
+import { SYNC_FEED_POSITION_BASE } from './syncFeed.js';
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ const recheck = await checkHealth().catch(() => ({ hasSchema: false, hasCatalogSchema: false }));
+ if (recheck.hasSchema && recheck.hasCatalogSchema) dbReady = true;
+ else skipReason = 'memory/catalog schema not present';
+ }
+}
+const runDb = requireDbOrSkip('lib/db/schema/syncFeed.db.test', dbReady, skipReason);
+
+const nonce = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+const TAG_PREFIX = `cat-tag-feedtest-${nonce}`;
+const memoryIds = [];
+
+const insertMemory = async (client, content) => {
+ const id = randomUUID();
+ memoryIds.push(id);
+ const { rows: [row] } = await client.query(
+ `INSERT INTO memories (id, type, content) VALUES ($1, 'fact', $2) RETURNING id, sync_sequence::text AS seq`,
+ [id, content],
+ );
+ return row;
+};
+
+const insertTag = async (client, suffix) => {
+ const { rows: [row] } = await client.query(
+ `INSERT INTO catalog_tags (id, label) VALUES ($1, $2) RETURNING id, sync_sequence::text AS seq`,
+ [`${TAG_PREFIX}-${suffix}`, `Feed test ${suffix}`],
+ );
+ return row;
+};
+
+// Run `write` inside a transaction that stays OPEN until commit() is called.
+// `written` resolves once the write has executed (its sync_sequence is drawn),
+// or rejects if the write fails, so a broken fixture fails instead of hanging.
+function holdOpen(write) {
+ let release;
+ const gate = new Promise((resolve) => { release = resolve; });
+ let signalWritten;
+ const writtenSignal = new Promise((resolve) => { signalWritten = resolve; });
+ const done = withTransaction(async (client) => {
+ const out = await write(client);
+ signalWritten(out);
+ await gate;
+ return out;
+ });
+ return { written: Promise.race([writtenSignal, done]), commit: () => { release(); return done; } };
+}
+
+// Drain a reader from `cursor` to the end of its feed, returning every item
+// and the final cursor, the way syncOrchestrator pages a peer.
+async function drain(read, cursor) {
+ const items = [];
+ let next = cursor;
+ let more = true;
+ while (more) {
+ const page = await read(next);
+ items.push(...page.items);
+ if (page.items.length === 0) break;
+ next = page.items[page.items.length - 1].syncSequence;
+ more = page.hasMore;
+ }
+ return { items, cursor: next };
+}
+
+describe.skipIf(!runDb)('commit-ordered sync feed (#8315)', () => {
+ let memorySync;
+ let catalogDB;
+ let backfillSyncFeed;
+ const readMemories = (since) => memorySync.getChangesSince(since, 1000)
+ .then(({ memories, hasMore }) => ({ items: memories, hasMore }));
+ const readTags = (since) => catalogDB.getTagChangesSince(since, 1000);
+
+ beforeAll(async () => {
+ memorySync = await import('../../../services/memorySync.js');
+ catalogDB = await import('../../../services/catalogDB.js');
+ ({ up: backfillSyncFeed } = await import('../../../scripts/db-migrations/009-commit-ordered-sync-feed.js'));
+ });
+
+ afterAll(async () => {
+ if (memoryIds.length) await query('DELETE FROM memories WHERE id = ANY($1::uuid[])', [memoryIds]).catch(() => {});
+ await query('DELETE FROM catalog_tags WHERE id LIKE $1', [`${TAG_PREFIX}%`]).catch(() => {});
+ await close();
+ });
+
+ it('still delivers a memory whose transaction commits after a peer advanced past a later one', async () => {
+ const start = await memorySync.getMaxSequence();
+ const t1 = holdOpen((client) => insertMemory(client, 'late committer'));
+ const late = await t1.written;
+ const early = await withTransaction((client) => insertMemory(client, 'early committer'));
+ // The legacy hazard: the late row holds the LOWER write-time sequence, so a
+ // `sync_sequence > cursor` pull that already saw the early row skips it.
+ expect(BigInt(late.seq)).toBeLessThan(BigInt(early.seq));
+
+ const firstPull = await drain(readMemories, start);
+ expect(firstPull.items.map((m) => m.id)).toContain(early.id);
+ expect(firstPull.items.map((m) => m.id)).not.toContain(late.id);
+
+ await t1.commit();
+ const secondPull = await drain(readMemories, firstPull.cursor);
+ expect(secondPull.items.map((m) => m.id)).toContain(late.id);
+ });
+
+ it('still delivers a catalog row whose transaction commits after a peer advanced past a later one', async () => {
+ const { tags: start } = await catalogDB.getMaxSequences();
+ const t1 = holdOpen((client) => insertTag(client, 'late'));
+ const late = await t1.written;
+ const early = await withTransaction((client) => insertTag(client, 'early'));
+ expect(BigInt(late.seq)).toBeLessThan(BigInt(early.seq));
+
+ const firstPull = await drain(readTags, start);
+ expect(firstPull.items.map((t) => t.id)).toEqual([early.id]);
+
+ await t1.commit();
+ const secondPull = await drain(readTags, firstPull.cursor);
+ expect(secondPull.items.map((t) => t.id)).toEqual([late.id]);
+ });
+
+ it('orders feed positions by commit, not by write, under concurrent writers', async () => {
+ const writers = ['a', 'b', 'c', 'd', 'e'].map((suffix) => holdOpen((client) => insertTag(client, `concurrent-${suffix}`)));
+ const rows = await Promise.all(writers.map((w) => w.written));
+ // Commit in an order unrelated to write order (write order is a..e).
+ const commitOrder = [3, 0, 4, 1, 2];
+ for (const i of commitOrder) await writers[i].commit();
+
+ const { rows: feed } = await query(
+ `SELECT t.id FROM sync_feed f JOIN catalog_tags t ON t.sync_sequence = f.row_sequence
+ WHERE f.stream = 'catalog_tags' AND t.id = ANY($1::text[]) ORDER BY f.position`,
+ [rows.map((r) => r.id)],
+ );
+ expect(feed.map((r) => r.id)).toEqual(commitOrder.map((i) => rows[i].id));
+ });
+
+ it('keeps one feed entry per live row version', async () => {
+ const row = await withTransaction((client) => insertMemory(client, 'versioned'));
+ const positionsFor = async (seq) => (await query(
+ `SELECT position::text AS position FROM sync_feed WHERE stream = 'memories' AND row_sequence = $1`,
+ [seq],
+ )).rows.map((r) => r.position);
+ const currentSeq = async () => (await query('SELECT sync_sequence::text AS seq FROM memories WHERE id = $1', [row.id])).rows[0].seq;
+ const [created] = await positionsFor(row.seq);
+ expect(created).toBeDefined();
+
+ // An access-stat update does not move sync_sequence, so the feed is untouched.
+ await query('UPDATE memories SET access_count = access_count + 1 WHERE id = $1', [row.id]);
+ expect(await currentSeq()).toBe(row.seq);
+ expect(await positionsFor(row.seq)).toEqual([created]);
+
+ // A content edit re-queues the row at a later position and retires the old entry.
+ await query(`UPDATE memories SET content = 'versioned, edited' WHERE id = $1`, [row.id]);
+ const editedSeq = await currentSeq();
+ expect(await positionsFor(row.seq)).toEqual([]);
+ const [edited] = await positionsFor(editedSeq);
+ expect(BigInt(edited)).toBeGreaterThan(BigInt(created));
+
+ await query('DELETE FROM memories WHERE id = $1', [row.id]);
+ expect(await positionsFor(editedSeq)).toEqual([]);
+ });
+
+ it('upgrade backfill replays rows below a legacy cursor without duplicating applied rows', async () => {
+ // An install upgrading into the feed: rows that predate it carry no feed
+ // entry, and a peer holds a legacy cursor at the newest row's sync_sequence
+ // — past the row its old pulls skipped.
+ const legacyRows = [];
+ for (const label of ['legacy one', 'legacy skipped', 'legacy three']) {
+ legacyRows.push(await withTransaction((client) => insertMemory(client, label)));
+ }
+ const ids = legacyRows.map((r) => r.id);
+ await query(
+ `DELETE FROM sync_feed WHERE stream = 'memories'
+ AND row_sequence IN (SELECT sync_sequence FROM memories WHERE id = ANY($1::uuid[]))`,
+ [ids],
+ );
+ const legacyCursor = legacyRows.at(-1).seq;
+ expect(BigInt(legacyCursor)).toBeLessThan(BigInt(SYNC_FEED_POSITION_BASE));
+
+ // Before the backfill those rows are invisible to the feed at any cursor.
+ expect((await drain(readMemories, '0')).items.map((m) => m.id)).not.toContain(ids[1]);
+
+ // A restored pre-feed dump can leave feed entries that match no row; and a
+ // peer may already hold a POSITION cursor at the current feed maximum.
+ const STALE_SEQUENCE = '-8315';
+ await query(
+ `INSERT INTO sync_feed (stream, row_sequence, position) VALUES ('memories', $1, nextval('memories_sync_feed_seq'))
+ ON CONFLICT (stream, row_sequence) DO NOTHING`,
+ [STALE_SEQUENCE],
+ );
+ const positionCursor = await memorySync.getMaxSequence();
+
+ await withTransaction((client) => backfillSyncFeed(client));
+
+ const { rows: stale } = await query(
+ `SELECT 1 FROM sync_feed WHERE stream = 'memories' AND row_sequence = $1`,
+ [STALE_SEQUENCE],
+ );
+ expect(stale).toEqual([]);
+ // Every row is queued past cursors peers already hold, legacy or position.
+ const pastPositionCursor = (await drain(readMemories, positionCursor)).items.map((m) => m.id);
+ expect(pastPositionCursor).toEqual(expect.arrayContaining(ids));
+
+ // The peer's legacy cursor now replays every row, including the skipped one…
+ const replay = await drain(readMemories, legacyCursor);
+ const replayed = replay.items.filter((m) => ids.includes(m.id));
+ expect(replayed.map((m) => m.id).sort()).toEqual([...ids].sort());
+ expect(BigInt(replay.cursor)).toBeGreaterThanOrEqual(BigInt(SYNC_FEED_POSITION_BASE));
+
+ // …and re-applying the replay where the rows already exist is a pure LWW skip.
+ const applied = await memorySync.applyRemoteChanges(replayed);
+ expect(applied).toEqual({ inserted: 0, updated: 0, skipped: ids.length });
+ const { rows: [{ count }] } = await query('SELECT COUNT(*)::int AS count FROM memories WHERE id = ANY($1::uuid[])', [ids]);
+ expect(count).toBe(ids.length);
+ });
+});
diff --git a/server/lib/db/schema/syncFeed.js b/server/lib/db/schema/syncFeed.js
new file mode 100644
index 0000000000..87bac7896d
--- /dev/null
+++ b/server/lib/db/schema/syncFeed.js
@@ -0,0 +1,104 @@
+// Commit-ordered federation change feed (#8315).
+//
+// Every federated PostgreSQL stream (memories + the seven catalog tables) used
+// to hand peers its `sync_sequence` BIGSERIAL as the pull cursor. A sequence
+// value is allocated when a row is WRITTEN, not when its transaction COMMITS,
+// so a transaction that took 100 and committed after one that took 101 was
+// invisible to a pull that already advanced the peer's cursor to 101 — and
+// every later `> 101` pull skipped it for good.
+//
+// The feed fixes that without touching the row tables' write paths. Each row
+// change queues a DEFERRED constraint trigger; at commit the trigger takes one
+// transaction-scoped advisory lock (held until the transaction ends) and only
+// then draws the stream's feed position. Two committers therefore draw their
+// positions one after the other, and whoever holds the lower position has
+// already committed by the time a higher one exists — so a reader that sees
+// position N can never later discover a committed position below N. The lock
+// is held only for the commit instant, and a lock holder touches nothing but
+// `sync_feed`, so it cannot close a deadlock cycle with row locks.
+//
+// `sync_feed` holds one row per live row version: (stream = table name,
+// row_sequence = that row's current `sync_sequence`) → position. An update that
+// moves `sync_sequence` replaces the entry; a delete removes it. Readers join
+// the feed to the table on `sync_sequence` and page by `position`.
+//
+// Positions start at SYNC_FEED_POSITION_BASE, far above any legacy
+// `sync_sequence` an install could have allocated. That keeps the wire shape
+// (one numeric-string cursor per stream) while making an old cursor
+// self-identifying: a peer holding a legacy cursor pulls `position > legacy`,
+// which is the whole feed, so the upgrade replays every row once and recovers
+// anything the old cursors skipped. Apply paths are LWW / ON CONFLICT upserts,
+// so the replay rewrites nothing a peer already holds. The reverse (a peer
+// that downgrades) is caught by the existing reset detection: a saved cursor
+// above the peer's reported maximum rewinds to 0.
+//
+// The db-migration `009-commit-ordered-sync-feed.js` backfills rows that
+// predate the feed. Mirrored in server/scripts/init-db.sql (parity-locked by
+// db.ddlParity.test.js).
+
+export const SYNC_FEED_POSITION_BASE = '1000000000000000';
+
+// Transaction-scoped advisory lock key that serializes feed position draws
+// with commit. Distinct from SCHEMA_DDL_ADVISORY_LOCK_KEY (5977001) in db.js.
+export const SYNC_FEED_LOCK_KEY = 8315001;
+
+// Every table whose rows federate through a `sync_sequence` pull cursor. The
+// feed stream name IS the table name.
+export const syncFeedTables = [
+ 'memories',
+ 'catalog_scraps',
+ 'catalog_ingredients',
+ 'catalog_ingredient_sources',
+ 'catalog_ingredient_refs',
+ 'catalog_ingredient_relations',
+ 'catalog_tags',
+ 'catalog_ingredient_media',
+];
+
+export const syncFeedSequenceName = (table) => `${table}_sync_feed_seq`;
+
+export const syncFeedDdl = [
+ `CREATE TABLE IF NOT EXISTS sync_feed (
+ stream TEXT NOT NULL,
+ row_sequence BIGINT NOT NULL,
+ position BIGINT NOT NULL,
+ PRIMARY KEY (stream, row_sequence)
+ )`,
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_sync_feed_position ON sync_feed (stream, position)`,
+ ...syncFeedTables.map((t) =>
+ `CREATE SEQUENCE IF NOT EXISTS ${syncFeedSequenceName(t)} START WITH ${SYNC_FEED_POSITION_BASE} MINVALUE ${SYNC_FEED_POSITION_BASE}`),
+ `CREATE OR REPLACE FUNCTION sync_feed_capture()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ PERFORM pg_advisory_xact_lock(${SYNC_FEED_LOCK_KEY});
+ IF TG_OP <> 'INSERT' THEN
+ DELETE FROM sync_feed WHERE stream = TG_TABLE_NAME AND row_sequence = OLD.sync_sequence;
+ END IF;
+ IF TG_OP <> 'DELETE' THEN
+ INSERT INTO sync_feed (stream, row_sequence, position)
+ VALUES (TG_TABLE_NAME, NEW.sync_sequence, nextval(format('%I', TG_TABLE_NAME || '_sync_feed_seq')::regclass))
+ ON CONFLICT (stream, row_sequence) DO UPDATE SET position = EXCLUDED.position;
+ END IF;
+ RETURN NULL;
+ END;
+ $$ LANGUAGE plpgsql`,
+];
+
+// Two deferred constraint triggers per table: INSERT/DELETE unconditionally,
+// UPDATE only when the row's `sync_sequence` moved (the BEFORE UPDATE triggers
+// skip the bump for access-stat and no-op writes, and so does the feed).
+// Constraint triggers have no CREATE OR REPLACE, hence DROP + CREATE.
+export function buildSyncFeedTriggers() {
+ const stmts = [];
+ for (const t of syncFeedTables) {
+ stmts.push(`DROP TRIGGER IF EXISTS trg_${t}_sync_feed ON ${t}`);
+ stmts.push(
+ `CREATE CONSTRAINT TRIGGER trg_${t}_sync_feed AFTER INSERT OR DELETE ON ${t} DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION sync_feed_capture()`,
+ );
+ stmts.push(`DROP TRIGGER IF EXISTS trg_${t}_sync_feed_update ON ${t}`);
+ stmts.push(
+ `CREATE CONSTRAINT TRIGGER trg_${t}_sync_feed_update AFTER UPDATE ON ${t} DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (OLD.sync_sequence IS DISTINCT FROM NEW.sync_sequence) EXECUTE FUNCTION sync_feed_capture()`,
+ );
+ }
+ return stmts;
+}
diff --git a/server/scripts/db-migrations/009-commit-ordered-sync-feed.js b/server/scripts/db-migrations/009-commit-ordered-sync-feed.js
new file mode 100644
index 0000000000..4f1a620216
--- /dev/null
+++ b/server/scripts/db-migrations/009-commit-ordered-sync-feed.js
@@ -0,0 +1,51 @@
+/**
+ * Backfill the commit-ordered federation change feed (#8315).
+ *
+ * ensureSchema() installs `sync_feed` and its deferred capture triggers, so
+ * every row written from this boot on gets a feed position at commit. Rows
+ * that predate the feed have none, and the readers only serve rows that do —
+ * this (re)queues every row of every federated stream, in legacy
+ * `sync_sequence` order, and drops entries that no longer match a row.
+ *
+ * Every row is queued, not just the ones without an entry: an install that
+ * restores a pre-feed database dump keeps the feed rows written since the
+ * upgrade, and those can point at a `sync_sequence` the restored table reuses
+ * for a different row. Re-queueing everything above the current positions
+ * costs nothing extra — the first pull after the upgrade replays each stream
+ * anyway — and guarantees no row sits below a cursor a peer already holds.
+ *
+ * Every position is above SYNC_FEED_POSITION_BASE, above any legacy cursor a
+ * peer holds, so a peer's next pull replays the whole stream once. That replay
+ * is the recovery for rows the old write-time cursors skipped; the apply side
+ * is LWW / ON CONFLICT upserts, so rows a peer already holds are skipped rather
+ * than duplicated.
+ *
+ * The feed's advisory lock is taken in its own statement FIRST, so the
+ * statements below run on snapshots taken after any in-flight feed commit
+ * finished, and no live commit can draw a position until this transaction's
+ * positions are committed. Derived from the install's own rows — no seed.
+ */
+
+import { SYNC_FEED_LOCK_KEY, syncFeedTables, syncFeedSequenceName } from '../../lib/db/schema/syncFeed.js';
+
+export async function up(client) {
+ await client.query('SELECT pg_advisory_xact_lock($1)', [SYNC_FEED_LOCK_KEY]);
+ let total = 0;
+ for (const table of syncFeedTables) {
+ await client.query(
+ `DELETE FROM sync_feed f
+ WHERE f.stream = $1
+ AND NOT EXISTS (SELECT 1 FROM ${table} t WHERE t.sync_sequence = f.row_sequence)`,
+ [table],
+ );
+ const { rowCount } = await client.query(
+ `INSERT INTO sync_feed (stream, row_sequence, position)
+ SELECT $1, legacy.sync_sequence, nextval($2::regclass)
+ FROM (SELECT sync_sequence FROM ${table} ORDER BY sync_sequence) legacy
+ ON CONFLICT (stream, row_sequence) DO UPDATE SET position = EXCLUDED.position`,
+ [table, syncFeedSequenceName(table)],
+ );
+ total += rowCount ?? 0;
+ }
+ console.log(`🔁 Sync feed: queued ${total} row${total === 1 ? '' : 's'} across ${syncFeedTables.length} streams`);
+}
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 0a52e036aa..6cc3cb1ad1 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -2148,3 +2148,76 @@ CREATE TABLE IF NOT EXISTS deck_cards (
);
CREATE INDEX IF NOT EXISTS idx_deck_cards_deck ON deck_cards (deck_id, position);
CREATE INDEX IF NOT EXISTS idx_decks_deleted ON decks (deleted, updated_at DESC);
+
+-- ============================================================================
+-- Commit-ordered federation change feed (#8315)
+-- ============================================================================
+-- Peers page memories and the catalog tables by a feed POSITION drawn at
+-- COMMIT (deferred constraint triggers serialized by a transaction-scoped
+-- advisory lock), not by the row-write-time sync_sequence, so a transaction
+-- that commits late can never land below a cursor a peer already advanced
+-- past. Positions start at 1e15 so a legacy sync_sequence cursor replays the
+-- whole feed once. Rationale: server/lib/db/schema/syncFeed.js (mirrored there
+-- for existing installs; parity-locked by db.ddlParity.test.js).
+CREATE TABLE IF NOT EXISTS sync_feed (
+ stream TEXT NOT NULL,
+ row_sequence BIGINT NOT NULL,
+ position BIGINT NOT NULL,
+ PRIMARY KEY (stream, row_sequence)
+);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_sync_feed_position ON sync_feed (stream, position);
+CREATE SEQUENCE IF NOT EXISTS memories_sync_feed_seq START WITH 1000000000000000 MINVALUE 1000000000000000;
+CREATE SEQUENCE IF NOT EXISTS catalog_scraps_sync_feed_seq START WITH 1000000000000000 MINVALUE 1000000000000000;
+CREATE SEQUENCE IF NOT EXISTS catalog_ingredients_sync_feed_seq START WITH 1000000000000000 MINVALUE 1000000000000000;
+CREATE SEQUENCE IF NOT EXISTS catalog_ingredient_sources_sync_feed_seq START WITH 1000000000000000 MINVALUE 1000000000000000;
+CREATE SEQUENCE IF NOT EXISTS catalog_ingredient_refs_sync_feed_seq START WITH 1000000000000000 MINVALUE 1000000000000000;
+CREATE SEQUENCE IF NOT EXISTS catalog_ingredient_relations_sync_feed_seq START WITH 1000000000000000 MINVALUE 1000000000000000;
+CREATE SEQUENCE IF NOT EXISTS catalog_tags_sync_feed_seq START WITH 1000000000000000 MINVALUE 1000000000000000;
+CREATE SEQUENCE IF NOT EXISTS catalog_ingredient_media_sync_feed_seq START WITH 1000000000000000 MINVALUE 1000000000000000;
+CREATE OR REPLACE FUNCTION sync_feed_capture()
+RETURNS TRIGGER AS $$
+BEGIN
+ PERFORM pg_advisory_xact_lock(8315001);
+ IF TG_OP <> 'INSERT' THEN
+ DELETE FROM sync_feed WHERE stream = TG_TABLE_NAME AND row_sequence = OLD.sync_sequence;
+ END IF;
+ IF TG_OP <> 'DELETE' THEN
+ INSERT INTO sync_feed (stream, row_sequence, position)
+ VALUES (TG_TABLE_NAME, NEW.sync_sequence, nextval(format('%I', TG_TABLE_NAME || '_sync_feed_seq')::regclass))
+ ON CONFLICT (stream, row_sequence) DO UPDATE SET position = EXCLUDED.position;
+ END IF;
+ RETURN NULL;
+END;
+$$ LANGUAGE plpgsql;
+DROP TRIGGER IF EXISTS trg_memories_sync_feed ON memories;
+CREATE CONSTRAINT TRIGGER trg_memories_sync_feed AFTER INSERT OR DELETE ON memories DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_memories_sync_feed_update ON memories;
+CREATE CONSTRAINT TRIGGER trg_memories_sync_feed_update AFTER UPDATE ON memories DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (OLD.sync_sequence IS DISTINCT FROM NEW.sync_sequence) EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_catalog_scraps_sync_feed ON catalog_scraps;
+CREATE CONSTRAINT TRIGGER trg_catalog_scraps_sync_feed AFTER INSERT OR DELETE ON catalog_scraps DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_catalog_scraps_sync_feed_update ON catalog_scraps;
+CREATE CONSTRAINT TRIGGER trg_catalog_scraps_sync_feed_update AFTER UPDATE ON catalog_scraps DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (OLD.sync_sequence IS DISTINCT FROM NEW.sync_sequence) EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_catalog_ingredients_sync_feed ON catalog_ingredients;
+CREATE CONSTRAINT TRIGGER trg_catalog_ingredients_sync_feed AFTER INSERT OR DELETE ON catalog_ingredients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_catalog_ingredients_sync_feed_update ON catalog_ingredients;
+CREATE CONSTRAINT TRIGGER trg_catalog_ingredients_sync_feed_update AFTER UPDATE ON catalog_ingredients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (OLD.sync_sequence IS DISTINCT FROM NEW.sync_sequence) EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_catalog_ingredient_sources_sync_feed ON catalog_ingredient_sources;
+CREATE CONSTRAINT TRIGGER trg_catalog_ingredient_sources_sync_feed AFTER INSERT OR DELETE ON catalog_ingredient_sources DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_catalog_ingredient_sources_sync_feed_update ON catalog_ingredient_sources;
+CREATE CONSTRAINT TRIGGER trg_catalog_ingredient_sources_sync_feed_update AFTER UPDATE ON catalog_ingredient_sources DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (OLD.sync_sequence IS DISTINCT FROM NEW.sync_sequence) EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_catalog_ingredient_refs_sync_feed ON catalog_ingredient_refs;
+CREATE CONSTRAINT TRIGGER trg_catalog_ingredient_refs_sync_feed AFTER INSERT OR DELETE ON catalog_ingredient_refs DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_catalog_ingredient_refs_sync_feed_update ON catalog_ingredient_refs;
+CREATE CONSTRAINT TRIGGER trg_catalog_ingredient_refs_sync_feed_update AFTER UPDATE ON catalog_ingredient_refs DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (OLD.sync_sequence IS DISTINCT FROM NEW.sync_sequence) EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_catalog_ingredient_relations_sync_feed ON catalog_ingredient_relations;
+CREATE CONSTRAINT TRIGGER trg_catalog_ingredient_relations_sync_feed AFTER INSERT OR DELETE ON catalog_ingredient_relations DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_catalog_ingredient_relations_sync_feed_update ON catalog_ingredient_relations;
+CREATE CONSTRAINT TRIGGER trg_catalog_ingredient_relations_sync_feed_update AFTER UPDATE ON catalog_ingredient_relations DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (OLD.sync_sequence IS DISTINCT FROM NEW.sync_sequence) EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_catalog_tags_sync_feed ON catalog_tags;
+CREATE CONSTRAINT TRIGGER trg_catalog_tags_sync_feed AFTER INSERT OR DELETE ON catalog_tags DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_catalog_tags_sync_feed_update ON catalog_tags;
+CREATE CONSTRAINT TRIGGER trg_catalog_tags_sync_feed_update AFTER UPDATE ON catalog_tags DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (OLD.sync_sequence IS DISTINCT FROM NEW.sync_sequence) EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_catalog_ingredient_media_sync_feed ON catalog_ingredient_media;
+CREATE CONSTRAINT TRIGGER trg_catalog_ingredient_media_sync_feed AFTER INSERT OR DELETE ON catalog_ingredient_media DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION sync_feed_capture();
+DROP TRIGGER IF EXISTS trg_catalog_ingredient_media_sync_feed_update ON catalog_ingredient_media;
+CREATE CONSTRAINT TRIGGER trg_catalog_ingredient_media_sync_feed_update AFTER UPDATE ON catalog_ingredient_media DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (OLD.sync_sequence IS DISTINCT FROM NEW.sync_sequence) EXECUTE FUNCTION sync_feed_capture();
diff --git a/server/services/catalogDB/sync.js b/server/services/catalogDB/sync.js
index 0db2bdc232..311cbcf9d8 100644
--- a/server/services/catalogDB/sync.js
+++ b/server/services/catalogDB/sync.js
@@ -1,8 +1,9 @@
/**
* Creative Ingredients Catalog — peer-sync change feeds & upserts.
*
- * The `get*ChangesSince` readers page rows by `sync_sequence` for outbound
- * pulls; the `upsert*FromPeer` writers apply an inbound peer's rows. Mixed-
+ * The `get*ChangesSince` readers page rows by their commit-ordered feed
+ * position (`sync_feed`, #8315 — see server/lib/db/schema/syncFeed.js) for
+ * outbound pulls; the `upsert*FromPeer` writers apply an inbound peer's rows. Mixed-
* version federation is handled per-table: "tombstone keys absent" is treated
* as "peer has no opinion" so a pre-tombstone peer can't revive a local delete,
* and FK-lagged child/parent rows retry parent-less then re-link on a later page.
@@ -19,16 +20,30 @@ import {
rowToTag,
} from './shared.js';
-export async function getRelationChangesSince(since = '0', limit = 100) {
+// One page of a table's feed: rows whose committed feed position is past the
+// peer's cursor, in position order. `syncSequence` on each item carries the
+// FEED POSITION — the cursor unit peers store — not the row's write-time
+// `sync_sequence`, which a late-committing transaction can land below a
+// cursor a peer already advanced past. `stream` is one of the table-name
+// literals the exported readers below pass, never caller input.
+async function getFeedChangesSince(stream, mapRow, since, limit) {
const result = await query(
- `SELECT * FROM catalog_ingredient_relations WHERE sync_sequence > $1 ORDER BY sync_sequence ASC LIMIT $2`,
- [since, limit + 1],
+ `SELECT t.*, f.position::text AS feed_position
+ FROM sync_feed f
+ JOIN ${stream} t ON t.sync_sequence = f.row_sequence
+ WHERE f.stream = $1 AND f.position > $2
+ ORDER BY f.position ASC
+ LIMIT $3`,
+ [stream, since, limit + 1],
);
const hasMore = result.rows.length > limit;
const rows = hasMore ? result.rows.slice(0, limit) : result.rows;
- return { items: rows.map(rowToRelation), hasMore };
+ return { items: rows.map((row) => ({ ...mapRow(row), syncSequence: row.feed_position })), hasMore };
}
+export const getRelationChangesSince = (since = '0', limit = 100) =>
+ getFeedChangesSince('catalog_ingredient_relations', rowToRelation, since, limit);
+
export async function upsertRelationFromPeer(rel) {
// Mirrors upsertRefFromPeer's mixed-version handling: a peer that predates
// the relations feature never emits these rows, so there's no v1-without-
@@ -58,15 +73,8 @@ export async function upsertRelationFromPeer(rel) {
}
}
-export async function getMediaChangesSince(since = '0', limit = 100) {
- const result = await query(
- `SELECT * FROM catalog_ingredient_media WHERE sync_sequence > $1 ORDER BY sync_sequence ASC LIMIT $2`,
- [since, limit + 1],
- );
- const hasMore = result.rows.length > limit;
- const rows = hasMore ? result.rows.slice(0, limit) : result.rows;
- return { items: rows.map(rowToMedia), hasMore };
-}
+export const getMediaChangesSince = (since = '0', limit = 100) =>
+ getFeedChangesSince('catalog_ingredient_media', rowToMedia, since, limit);
export async function upsertMediaFromPeer(media) {
// Mirrors upsertRefFromPeer's mixed-version handling: a peer that predates
@@ -120,15 +128,8 @@ export async function upsertMediaFromPeer(media) {
}
}
-export async function getTagChangesSince(since = '0', limit = 100) {
- const result = await query(
- `SELECT * FROM catalog_tags WHERE sync_sequence > $1 ORDER BY sync_sequence ASC LIMIT $2`,
- [since, limit + 1],
- );
- const hasMore = result.rows.length > limit;
- const rows = hasMore ? result.rows.slice(0, limit) : result.rows;
- return { items: rows.map(rowToTag), hasMore };
-}
+export const getTagChangesSince = (since = '0', limit = 100) =>
+ getFeedChangesSince('catalog_tags', rowToTag, since, limit);
export async function upsertTagFromPeer(tag) {
// LWW on updated_at for the mutable fields (description/color/parent_id) +
@@ -173,59 +174,35 @@ export async function upsertTagFromPeer(tag) {
return { applied: result.rows.length > 0, isInsert: result.rows[0]?.is_insert ?? false };
}
+// Per-stream maximum feed position. Each subquery is a backward scan of the
+// (stream, position) index.
export async function getMaxSequences() {
+ const maxOf = (stream) =>
+ `COALESCE((SELECT MAX(position) FROM sync_feed WHERE stream = '${stream}'), 0)::text`;
const result = await query(`
SELECT
- COALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredients), 0)::text AS ingredients,
- COALESCE((SELECT MAX(sync_sequence) FROM catalog_scraps), 0)::text AS scraps,
- COALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredient_sources), 0)::text AS sources,
- COALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredient_refs), 0)::text AS refs,
- COALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredient_relations), 0)::text AS relations,
- COALESCE((SELECT MAX(sync_sequence) FROM catalog_tags), 0)::text AS tags,
- COALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredient_media), 0)::text AS media
+ ${maxOf('catalog_ingredients')} AS ingredients,
+ ${maxOf('catalog_scraps')} AS scraps,
+ ${maxOf('catalog_ingredient_sources')} AS sources,
+ ${maxOf('catalog_ingredient_refs')} AS refs,
+ ${maxOf('catalog_ingredient_relations')} AS relations,
+ ${maxOf('catalog_tags')} AS tags,
+ ${maxOf('catalog_ingredient_media')} AS media
`);
return result.rows[0];
}
-export async function getScrapChangesSince(since = '0', limit = 100) {
- const result = await query(
- `SELECT * FROM catalog_scraps WHERE sync_sequence > $1 ORDER BY sync_sequence ASC LIMIT $2`,
- [since, limit + 1],
- );
- const hasMore = result.rows.length > limit;
- const rows = hasMore ? result.rows.slice(0, limit) : result.rows;
- return { items: rows.map(rowToScrap), hasMore };
-}
+export const getScrapChangesSince = (since = '0', limit = 100) =>
+ getFeedChangesSince('catalog_scraps', rowToScrap, since, limit);
-export async function getIngredientChangesSince(since = '0', limit = 100) {
- const result = await query(
- `SELECT * FROM catalog_ingredients WHERE sync_sequence > $1 ORDER BY sync_sequence ASC LIMIT $2`,
- [since, limit + 1],
- );
- const hasMore = result.rows.length > limit;
- const rows = hasMore ? result.rows.slice(0, limit) : result.rows;
- return { items: rows.map(rowToIngredient), hasMore };
-}
+export const getIngredientChangesSince = (since = '0', limit = 100) =>
+ getFeedChangesSince('catalog_ingredients', rowToIngredient, since, limit);
-export async function getSourceChangesSince(since = '0', limit = 100) {
- const result = await query(
- `SELECT * FROM catalog_ingredient_sources WHERE sync_sequence > $1 ORDER BY sync_sequence ASC LIMIT $2`,
- [since, limit + 1],
- );
- const hasMore = result.rows.length > limit;
- const rows = hasMore ? result.rows.slice(0, limit) : result.rows;
- return { items: rows.map(rowToSource), hasMore };
-}
+export const getSourceChangesSince = (since = '0', limit = 100) =>
+ getFeedChangesSince('catalog_ingredient_sources', rowToSource, since, limit);
-export async function getRefChangesSince(since = '0', limit = 100) {
- const result = await query(
- `SELECT * FROM catalog_ingredient_refs WHERE sync_sequence > $1 ORDER BY sync_sequence ASC LIMIT $2`,
- [since, limit + 1],
- );
- const hasMore = result.rows.length > limit;
- const rows = hasMore ? result.rows.slice(0, limit) : result.rows;
- return { items: rows.map(rowToRef), hasMore };
-}
+export const getRefChangesSince = (since = '0', limit = 100) =>
+ getFeedChangesSince('catalog_ingredient_refs', rowToRef, since, limit);
export async function upsertScrapFromPeer(scrap) {
// A child scrap (parent_scrap_id set) may arrive in the envelope BEFORE its
diff --git a/server/services/catalogDBMedia.test.js b/server/services/catalogDBMedia.test.js
index da18d9a05f..cbfa159179 100644
--- a/server/services/catalogDBMedia.test.js
+++ b/server/services/catalogDBMedia.test.js
@@ -204,11 +204,11 @@ describe('listIngredients card thumbnail', () => {
});
describe('getMaxSequences includes the media cursor', () => {
- it('selects MAX(sync_sequence) from catalog_ingredient_media AS media', async () => {
+ it('reads the catalog_ingredient_media feed stream AS media', async () => {
const db = await import('../lib/db.js');
db.query.mockResolvedValueOnce({ rows: [{ media: '0' }] });
await catalogDB.getMaxSequences();
const sql = db.query.mock.calls.at(-1)[0].replace(/\s+/g, ' ');
- expect(sql).toMatch(/catalog_ingredient_media\), 0\)::text AS media/i);
+ expect(sql).toMatch(/stream = 'catalog_ingredient_media'\), 0\)::text AS media/i);
});
});
diff --git a/server/services/catalogSync.js b/server/services/catalogSync.js
index 86ce7978e3..0cffff291f 100644
--- a/server/services/catalogSync.js
+++ b/server/services/catalogSync.js
@@ -13,10 +13,12 @@
* GET /api/catalog/sync?since[scraps]=A&since[ingredients]=B&...&since[media]=G&limit=100
* → { scraps[], ingredients[], sources[], refs[], relations[], tags[], media[], maxSequences, hasMore }
*
- * The BIGSERIAL `sync_sequence` columns are INDEPENDENT — a row at
- * sources.sync_sequence=50 isn't comparable to ingredients.sync_sequence=50.
- * The receiver therefore tracks one cursor per kind and `since` is `{ scraps,
- * ingredients, sources, refs, relations }`. A scalar `?since=N` is still accepted for
+ * Each kind is its own feed stream with its own commit-ordered positions
+ * (`sync_feed`, #8315 — drawn at COMMIT, so a late-committing transaction can
+ * never land below a cursor a peer already advanced past). Positions of
+ * different kinds are INDEPENDENT — sources position P isn't comparable to
+ * ingredients position P. The receiver therefore tracks one cursor per kind
+ * and `since` is `{ scraps, ingredients, sources, refs, relations }`. A scalar `?since=N` is still accepted for
* back-compat / one-shot pulls and is applied uniformly to all four kinds.
* `hasMore` is true when ANY of the four tables had more than `limit` rows
* past its respective cursor — drain by re-pulling with the maxSequences from
@@ -93,8 +95,8 @@ export async function getChangesSince(since = '0', limit = 100) {
// True per-table maxima, INDEPENDENT of the inbound cursor. `maxSequences`
// (below) falls back to the inbound cursor on a quiet kind, so it can't be
// used to detect a peer rebuild/restore — it would just echo the caller's
- // cursor. `tableMaxSequences` reports the real MAX(sync_sequence) so the
- // receiver can spot `savedCursor > tableMax` and rewind. One cheap MAX query.
+ // cursor. `tableMaxSequences` reports each stream's real max feed position so
+ // the receiver can spot `savedCursor > tableMax` and rewind. One cheap MAX query.
const tableMaxSequences = await getMaxSequences();
// User-defined type definitions ride EVERY envelope (not sequence-tracked —
@@ -425,6 +427,6 @@ export function countAppliedFromStats(stats = {}) {
}
// Per-kind cursor view for the federation orchestrator. The previous scalar
-// `getMaxSequence` collapsed the four BIGSERIALs into one max — that lied
-// about the protocol (one cursor can't represent four independent sequences).
+// `getMaxSequence` collapsed the independent per-kind cursors into one max —
+// that lied about the protocol (one cursor can't represent four independent sequences).
export { getMaxSequences };
diff --git a/server/services/memorySync.js b/server/services/memorySync.js
index 29d5bd1e78..b17fcd46b3 100644
--- a/server/services/memorySync.js
+++ b/server/services/memorySync.js
@@ -2,14 +2,18 @@
* Memory Federation Sync Service
*
* Enables memory synchronization between PortOS instances via the
- * sync_sequence column in PostgreSQL. Peers pull changes since their
- * last known sequence number.
+ * commit-ordered federation change feed (`sync_feed`, #8315). Peers pull
+ * changes since their last known feed position.
*
* Sync Protocol:
- * 1. Each memory row has an auto-incrementing sync_sequence (BIGSERIAL)
- * 2. Peers request GET /api/memory/sync?since={lastSequence}&limit=100
- * 3. Response includes memories changed since that sequence + the max sequence
- * 4. Peer stores the max sequence and uses it for the next poll
+ * 1. Every committed memory change gets a feed position, drawn AT COMMIT
+ * (server/lib/db/schema/syncFeed.js) — never the write-time
+ * sync_sequence, which a late-committing transaction could land below a
+ * cursor a peer already advanced past
+ * 2. Peers request GET /api/memory/sync?since={lastPosition}&limit=100
+ * 3. Response includes memories changed since that position + the max position
+ * 4. Peer stores the max position and uses it for the next poll. A legacy
+ * sync_sequence cursor is below every position, so it replays the stream
* 5. Conflict resolution: last-writer-wins by updated_at timestamp
*
* Note: memory_links (relationships) are not synced — only the memories table
@@ -22,26 +26,28 @@ import { PERSISTENT_MIND_CHOSEN_NAME_TAG } from '../lib/persistentMindChosenName
import { dedupeByKey } from '../lib/arrayUtils.js';
/**
- * Get memories changed since a given sync sequence.
+ * Get memories changed since a given feed position.
* Used by peers to pull incremental updates.
*
- * @param {string} sinceSequence - Return changes after this sequence (string to avoid BigInt precision loss)
+ * @param {string} sinceSequence - Return changes after this feed position (string to avoid BigInt precision loss)
* @param {number} limit - Max records to return per batch
* @returns {Promise<{memories: Array, maxSequence: string, hasMore: boolean}>}
*/
export async function getChangesSince(sinceSequence = '0', limit = 100) {
// Fetch limit+1 rows to detect whether more records exist beyond this batch
const result = await query(
- `SELECT id, type, content, summary, category, tags,
- embedding, embedding_model, confidence, importance,
- status, source_task_id, source_agent_id, source_app_id,
- expires_at, created_at, updated_at, sync_sequence,
- origin_instance_id
- FROM memories
- WHERE sync_sequence > $1
- AND source_agent_id IS DISTINCT FROM $3
- AND NOT ($4 = ANY(COALESCE(tags, '{}'::text[])))
- ORDER BY sync_sequence ASC
+ `SELECT m.id, m.type, m.content, m.summary, m.category, m.tags,
+ m.embedding, m.embedding_model, m.confidence, m.importance,
+ m.status, m.source_task_id, m.source_agent_id, m.source_app_id,
+ m.expires_at, m.created_at, m.updated_at, m.origin_instance_id,
+ f.position::text AS feed_position
+ FROM sync_feed f
+ JOIN memories m ON m.sync_sequence = f.row_sequence
+ WHERE f.stream = 'memories'
+ AND f.position > $1
+ AND m.source_agent_id IS DISTINCT FROM $3
+ AND NOT ($4 = ANY(COALESCE(m.tags, '{}'::text[])))
+ ORDER BY f.position ASC
LIMIT $2`,
[sinceSequence, limit + 1, PERSISTENT_MIND_ID, PERSISTENT_MIND_CHOSEN_NAME_TAG]
);
@@ -69,7 +75,7 @@ export async function getChangesSince(sinceSequence = '0', limit = 100) {
expiresAt: row.expires_at?.toISOString() ?? null,
createdAt: row.created_at.toISOString(),
updatedAt: row.updated_at.toISOString(),
- syncSequence: String(row.sync_sequence),
+ syncSequence: row.feed_position,
originInstanceId: row.origin_instance_id
}));
@@ -186,12 +192,13 @@ export async function applyRemoteChanges(incomingMemories) {
}
/**
- * Get the current maximum sync sequence.
- * Used by peers to determine if they're up-to-date.
+ * Get the current maximum feed position.
+ * Used by peers to determine if they're up-to-date, and to detect a reset
+ * (a saved cursor above this maximum rewinds to 0).
*
- * @returns {Promise<string>} Sequence as string to avoid BigInt precision loss
+ * @returns {Promise<string>} Position as string to avoid BigInt precision loss
*/
export async function getMaxSequence() {
- const result = await query('SELECT COALESCE(MAX(sync_sequence), 0)::text AS max_seq FROM memories');
+ const result = await query("SELECT COALESCE(MAX(position), 0)::text AS max_seq FROM sync_feed WHERE stream = 'memories'");
return result.rows?.[0]?.max_seq ?? '0';
}
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index b17aefb64a..5eece0f487 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -297,9 +297,12 @@ async function syncMemoryFromPeer(peer, cursor) {
return { memorySeq, totalApplied };
}
-// The seven INDEPENDENT BIGSERIAL cursors the catalog sync envelope tracks.
-// Each table advances its own sequence, so the receiver carries seven cursors
-// (not one) — see catalogSync.js for the protocol rationale.
+// The seven INDEPENDENT feed-position cursors the catalog sync envelope tracks.
+// Each table is its own commit-ordered feed stream (#8315), so the receiver
+// carries seven cursors (not one) — see catalogSync.js for the protocol
+// rationale. A pre-#8315 cursor (a write-time sync_sequence) is below every
+// feed position, so the first pull after a peer upgrades replays each stream
+// once; a cursor above a downgraded peer's maximum rewinds via the reset check.
const CATALOG_CURSOR_KINDS = ['scraps', 'ingredients', 'sources', 'refs', 'relations', 'tags', 'media'];
// Build the `?since[scraps]=A&since[ingredients]=B&...` query string the
@@ -427,7 +430,7 @@ async function syncCatalogFromPeer(peer, peerId, cursor) {
}
/**
- * Safely parse a value to BigInt for BIGSERIAL comparison.
+ * Safely parse a value to BigInt for feed-position comparison.
* Returns 0n for invalid/empty/negative inputs.
*/
function safeBigInt(value) {
@@ -468,7 +471,7 @@ function detectCursorReset(cursor, peer) {
}
}
- // Memory: BigInt comparison (BIGSERIAL can exceed Number.MAX_SAFE_INTEGER)
+ // Memory: BigInt comparison (BIGINT positions can exceed Number.MAX_SAFE_INTEGER)
// Only check when peer reports a numeric memorySeq (null means non-Postgres peer)
const remoteMemRaw = remote.memorySeq;
const hasNumericRemoteMem = remoteMemRaw != null && (
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index 75da3491f2..25b36d1fa9 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -49,6 +49,7 @@ export const DB_TEST_INCLUDE = [
'services/modelPinRecords.db.test.js',
'scripts/run-db-migrations.test.js',
'lib/db/schema/audit.db.test.js',
+ 'lib/db/schema/syncFeed.db.test.js',
];
/**