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: guard catalog ref/relation/media sync against reviving newer tombstones (#8347)

[._.]/ Adam Eivyedb19dbf3aa5
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index 0233e51794..78b03b5cb9 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -614,20 +614,29 @@ export const catalogSyncSourceSchema = z.object({
syncSequence: z.string().optional(),
}).passthrough();
+// Ref rows carry tombstone fields (soft-delete from day one) plus, since
+// #8347, an `updatedAt` tombstone/revival change-clock — see
+// `upsertRefFromPeer` in catalogDB/sync.js for the LWW revival-guard
+// rationale. Both are optional on the wire (absent = "peer has no opinion" /
+// pre-#8347 sender) and preserved regardless via `.passthrough()`.
export const catalogSyncRefSchema = z.object({
ingredientId: z.string().max(80),
refKind: z.string().max(32),
refId: z.string().max(120),
role: z.string().max(64),
createdAt: isoDate,
+ deleted: z.boolean().optional(),
+ deletedAt: z.string().nullable().optional(),
+ updatedAt: isoDate.optional(),
syncSequence: z.string().optional(),
}).passthrough();
-// Relation rows carry tombstone fields (soft-delete from day one). `kind` is a
-// freeform string on the wire (not the strict enum) so a peer running a newer
-// PortOS with an additional relation kind doesn't get its whole envelope
-// rejected by an older receiver — the version gate already covers true
-// shape skew, and an unknown-kind row stores harmlessly.
+// Relation rows carry tombstone fields (soft-delete from day one) + the same
+// #8347 `updatedAt` revival-guard clock as refs. `kind` is a freeform string
+// on the wire (not the strict enum) so a peer running a newer PortOS with an
+// additional relation kind doesn't get its whole envelope rejected by an
+// older receiver — the version gate already covers true shape skew, and an
+// unknown-kind row stores harmlessly.
export const catalogSyncRelationSchema = z.object({
fromId: z.string().max(80),
toId: z.string().max(80),
@@ -635,6 +644,7 @@ export const catalogSyncRelationSchema = z.object({
createdAt: isoDate,
deleted: z.boolean().optional(),
deletedAt: z.string().nullable().optional(),
+ updatedAt: isoDate.optional(),
syncSequence: z.string().optional(),
}).passthrough();
@@ -699,6 +709,8 @@ export const catalogSyncMediaSchema = z.object({
createdAt: isoDate,
deleted: z.boolean().optional(),
deletedAt: z.string().nullable().optional(),
+ // #8347 revival-guard clock — see catalogSyncRefSchema above.
+ updatedAt: isoDate.optional(),
syncSequence: z.string().optional(),
}).passthrough();
diff --git a/server/lib/db/schema/catalog.js b/server/lib/db/schema/catalog.js
index e915fb9474..fd53caa5d9 100644
--- a/server/lib/db/schema/catalog.js
+++ b/server/lib/db/schema/catalog.js
@@ -149,6 +149,7 @@ export const catalogDdl = [
created_at TIMESTAMPTZ DEFAULT NOW(),
deleted BOOLEAN DEFAULT FALSE,
deleted_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
sync_sequence BIGSERIAL,
PRIMARY KEY (ingredient_id, ref_kind, ref_id, role)
)`,
@@ -158,6 +159,15 @@ export const catalogDdl = [
// never learn the ref was removed.
`ALTER TABLE catalog_ingredient_refs ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
`ALTER TABLE catalog_ingredient_refs ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
+ // #8347: a tombstone/revival change-clock, independent of `deleted_at`
+ // (which is NULL again on a revival, so it can't order two conflicting
+ // apply attempts). Backfilled for existing rows to `deleted_at` when the
+ // row is already tombstoned (the most accurate change-time we have for
+ // it) or `created_at` otherwise, so a pre-upgrade row's clock isn't
+ // misdated younger than its own last known change.
+ `ALTER TABLE catalog_ingredient_refs ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ`,
+ `UPDATE catalog_ingredient_refs SET updated_at = COALESCE(deleted_at, created_at) WHERE updated_at IS NULL`,
+ `ALTER TABLE catalog_ingredient_refs ALTER COLUMN updated_at SET DEFAULT NOW()`,
`CREATE INDEX IF NOT EXISTS idx_catalog_ing_refs_target ON catalog_ingredient_refs (ref_kind, ref_id)`,
`CREATE INDEX IF NOT EXISTS idx_catalog_ing_refs_sync_seq ON catalog_ingredient_refs (sync_sequence)`,
@@ -172,9 +182,15 @@ export const catalogDdl = [
created_at TIMESTAMPTZ DEFAULT NOW(),
deleted BOOLEAN DEFAULT FALSE,
deleted_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
sync_sequence BIGSERIAL,
PRIMARY KEY (from_id, to_id, kind)
)`,
+ // #8347: same tombstone/revival change-clock as catalog_ingredient_refs —
+ // see that block's comment for the backfill rationale.
+ `ALTER TABLE catalog_ingredient_relations ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ`,
+ `UPDATE catalog_ingredient_relations SET updated_at = COALESCE(deleted_at, created_at) WHERE updated_at IS NULL`,
+ `ALTER TABLE catalog_ingredient_relations ALTER COLUMN updated_at SET DEFAULT NOW()`,
`CREATE INDEX IF NOT EXISTS idx_catalog_ing_relations_to ON catalog_ingredient_relations (to_id)`,
`CREATE INDEX IF NOT EXISTS idx_catalog_ing_relations_sync_seq ON catalog_ingredient_relations (sync_sequence)`,
@@ -238,12 +254,18 @@ export const catalogDdl = [
created_at TIMESTAMPTZ DEFAULT NOW(),
deleted BOOLEAN DEFAULT FALSE,
deleted_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
sync_sequence BIGSERIAL,
PRIMARY KEY (ingredient_id, media_key, kind)
)`,
// CREATE IF NOT EXISTS does not add columns to existing installs, so keep
// the provenance upgrade idempotent for rows created before this field.
`ALTER TABLE catalog_ingredient_media ADD COLUMN IF NOT EXISTS metadata JSONB NOT NULL DEFAULT '{}'::jsonb`,
+ // #8347: same tombstone/revival change-clock as catalog_ingredient_refs —
+ // see that block's comment for the backfill rationale.
+ `ALTER TABLE catalog_ingredient_media ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ`,
+ `UPDATE catalog_ingredient_media SET updated_at = COALESCE(deleted_at, created_at) WHERE updated_at IS NULL`,
+ `ALTER TABLE catalog_ingredient_media ALTER COLUMN updated_at SET DEFAULT NOW()`,
`CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_ingredient ON catalog_ingredient_media (ingredient_id)`,
`CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_key ON catalog_ingredient_media (media_key)`,
`CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_sync_seq ON catalog_ingredient_media (sync_sequence)`,
@@ -329,11 +351,18 @@ export const catalogDdl = [
// path would update `deleted`/`deleted_at` but leave sync_sequence at
// the original INSERT value — peers past that cursor would never see
// the tombstone and their "Appears in" panels would stay stale.
+ // #8347: also stamps `updated_at` (unless the caller already set an
+ // explicit value — a peer apply carrying the sender's own clock) so the
+ // revival guard in `upsertRefFromPeer` has a change-clock that moves on
+ // BOTH a delete and a revival, unlike `deleted_at` which resets to NULL.
`CREATE OR REPLACE FUNCTION update_catalog_ref_sync_seq()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.deleted IS DISTINCT FROM OLD.deleted
OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at THEN
+ IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
+ NEW.updated_at := NOW();
+ END IF;
NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_refs', 'sync_sequence'));
END IF;
RETURN NEW;
@@ -347,12 +376,15 @@ export const catalogDdl = [
// Relation UPDATE bumps sync_sequence on soft-delete / revival so a peer
// sees the tombstone (or un-delete) on its next pull — mirrors the ref
- // trigger above.
+ // trigger above, including the #8347 `updated_at` change-clock stamp.
`CREATE OR REPLACE FUNCTION update_catalog_relation_sync_seq()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.deleted IS DISTINCT FROM OLD.deleted
OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at THEN
+ IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
+ NEW.updated_at := NOW();
+ END IF;
NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_relations', 'sync_sequence'));
END IF;
RETURN NEW;
@@ -367,7 +399,7 @@ export const catalogDdl = [
// Media UPDATE bumps sync_sequence on soft-delete/revival OR a mutable
// field (role/caption/metadata) change so a peer sees the edit/tombstone
// next pull. Mirrors the relation trigger but also watches the editable
- // metadata.
+ // metadata, and stamps the same #8347 `updated_at` change-clock.
`CREATE OR REPLACE FUNCTION update_catalog_media_sync_seq()
RETURNS TRIGGER AS $$
BEGIN
@@ -376,6 +408,9 @@ export const catalogDdl = [
OR NEW.role IS DISTINCT FROM OLD.role
OR NEW.caption IS DISTINCT FROM OLD.caption
OR NEW.metadata IS DISTINCT FROM OLD.metadata THEN
+ IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
+ NEW.updated_at := NOW();
+ END IF;
NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_media', 'sync_sequence'));
END IF;
RETURN NEW;
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index f450e2cf8b..d070ad08d1 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -373,7 +373,20 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// directions, including legacy senders with no version. Whole-row LWW from
// an older peer can erase fields after an unrelated edit. Tombstone-only
// transfers remain version-independent; no local storage migration is needed.
- catalog: 10,
+ // v11 = `catalog_ingredient_refs`/`_relations`/`_media` gained `updated_at`
+ // (#8347) and their `upsertXFromPeer` apply guards now require it to be
+ // strictly newer than the local row's before applying a peer's tombstone
+ // OR revival — a ≤v10 sender's unguarded whole-row apply can revive a
+ // newer local tombstone (soft-delete R at t2, then apply B's still-live
+ // copy of R before B pulls the tombstone) whenever B re-sends R: a
+ // role/caption edit, a reset rewind, or the #8315 upgrade replay that
+ // resends every catalog row once. Same execution-semantics rationale as
+ // v10: this is a receiver-side conflict-resolution change, not just an
+ // additive field, so an equal-version requirement is the only way to know
+ // BOTH sides apply the guard. Tombstone-only transfers already skip the
+ // live-row equality check; a v11 receiver's guard still degrades safely
+ // for a ≤v10 sender's tombstone-less payload (unchanged "no opinion" path).
+ catalog: 11,
// v1 = cross-machine resumable Story Builder sessions (#730). Sessions are
// local-only by default and excluded from sync; only `sync: true` sessions
// ride the `storyBuilder` snapshot category. This is a brand-NEW synced
diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.js
index ba49500bb2..bcf4fd757f 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -45,7 +45,8 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
});
it('version-gates catalog object attachments and media generation provenance', () => {
- expect(PORTOS_SCHEMA_VERSIONS.catalog).toBe(10);
+ // v11 adds the ref/relation/media tombstone-revival guard (#8347).
+ expect(PORTOS_SCHEMA_VERSIONS.catalog).toBe(11);
});
it('version-gates the persisted FableLoom shot and reference shape', () => {
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 3ecd8e2198..92e619809c 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -463,6 +463,7 @@ CREATE TABLE IF NOT EXISTS catalog_ingredient_refs (
created_at TIMESTAMPTZ DEFAULT NOW(),
deleted BOOLEAN DEFAULT FALSE, -- soft-delete tombstone so unlinks propagate to peers
deleted_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ DEFAULT NOW(), -- #8347: tombstone/revival change-clock (deleted_at resets to NULL on revival)
sync_sequence BIGSERIAL,
PRIMARY KEY (ingredient_id, ref_kind, ref_id, role)
);
@@ -485,6 +486,7 @@ CREATE TABLE IF NOT EXISTS catalog_ingredient_relations (
created_at TIMESTAMPTZ DEFAULT NOW(),
deleted BOOLEAN DEFAULT FALSE, -- soft-delete tombstone so unlinks propagate to peers
deleted_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ DEFAULT NOW(), -- #8347: tombstone/revival change-clock (deleted_at resets to NULL on revival)
sync_sequence BIGSERIAL,
PRIMARY KEY (from_id, to_id, kind)
);
@@ -568,6 +570,7 @@ CREATE TABLE IF NOT EXISTS catalog_ingredient_media (
created_at TIMESTAMPTZ DEFAULT NOW(),
deleted BOOLEAN DEFAULT FALSE, -- soft-delete tombstone so detaches propagate to peers
deleted_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ DEFAULT NOW(), -- #8347: tombstone/revival change-clock (deleted_at resets to NULL on revival)
sync_sequence BIGSERIAL,
PRIMARY KEY (ingredient_id, media_key, kind)
);
@@ -671,11 +674,18 @@ CREATE TRIGGER trg_catalog_source_sync_seq
-- path would update `deleted`/`deleted_at` but leave sync_sequence at the
-- original INSERT value — peers past that cursor would never see the change
-- and their "Appears in" panels would stay stale forever.
+-- #8347: also stamps `updated_at` (unless the caller already set an explicit
+-- value — a peer apply carrying the sender's own clock) so the revival guard
+-- in `upsertRefFromPeer` has a change-clock that moves on BOTH a delete and a
+-- revival, unlike `deleted_at` which resets to NULL.
CREATE OR REPLACE FUNCTION update_catalog_ref_sync_seq()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.deleted IS DISTINCT FROM OLD.deleted
OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at THEN
+ IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
+ NEW.updated_at := NOW();
+ END IF;
NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_refs', 'sync_sequence'));
END IF;
RETURN NEW;
@@ -691,11 +701,15 @@ CREATE TRIGGER trg_catalog_ref_sync_seq
-- Relation UPDATE bumps sync_sequence on soft-delete or revival so peers pick
-- up the tombstone (or the un-delete) on their next pull — same rationale as
-- the ref trigger above.
+-- #8347: same `updated_at` change-clock stamp as the ref trigger above.
CREATE OR REPLACE FUNCTION update_catalog_relation_sync_seq()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.deleted IS DISTINCT FROM OLD.deleted
OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at THEN
+ IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
+ NEW.updated_at := NOW();
+ END IF;
NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_relations', 'sync_sequence'));
END IF;
RETURN NEW;
@@ -712,6 +726,7 @@ CREATE TRIGGER trg_catalog_relation_sync_seq
-- field (role/caption) changes, so peers receive the edit (or the tombstone)
-- on their next pull. Unlike refs/relations, media rows carry editable
-- metadata, so the change-detector also watches role + caption + provenance.
+-- #8347: same `updated_at` change-clock stamp as the ref/relation triggers.
CREATE OR REPLACE FUNCTION update_catalog_media_sync_seq()
RETURNS TRIGGER AS $$
BEGIN
@@ -720,6 +735,9 @@ BEGIN
OR NEW.role IS DISTINCT FROM OLD.role
OR NEW.caption IS DISTINCT FROM OLD.caption
OR NEW.metadata IS DISTINCT FROM OLD.metadata THEN
+ IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
+ NEW.updated_at := NOW();
+ END IF;
NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_ingredient_media', 'sync_sequence'));
END IF;
RETURN NEW;
diff --git a/server/services/catalogDB/shared.js b/server/services/catalogDB/shared.js
index 2a3b5dca87..7dcf57c1c3 100644
--- a/server/services/catalogDB/shared.js
+++ b/server/services/catalogDB/shared.js
@@ -127,6 +127,11 @@ export function rowToIngredient(row) {
};
}
+// #8347: `updatedAt` is the tombstone/revival change-clock (see
+// catalog.js's ref/relation/media trigger comments) — falls back to
+// `created_at` for a row whose `updated_at` column predates the backfill
+// migration having run (should not happen post-boot, but keeps the mapper
+// total rather than emitting an invalid date string).
export function rowToRef(row) {
if (!row) return null;
return {
@@ -137,6 +142,7 @@ export function rowToRef(row) {
createdAt: row.created_at.toISOString(),
deleted: !!row.deleted,
deletedAt: row.deleted_at?.toISOString() ?? null,
+ updatedAt: (row.updated_at ?? row.created_at).toISOString(),
syncSequence: String(row.sync_sequence),
};
}
@@ -150,6 +156,7 @@ export function rowToRelation(row) {
createdAt: row.created_at.toISOString(),
deleted: !!row.deleted,
deletedAt: row.deleted_at?.toISOString() ?? null,
+ updatedAt: (row.updated_at ?? row.created_at).toISOString(),
syncSequence: String(row.sync_sequence),
};
}
@@ -166,6 +173,7 @@ export function rowToMedia(row) {
createdAt: row.created_at.toISOString(),
deleted: !!row.deleted,
deletedAt: row.deleted_at?.toISOString() ?? null,
+ updatedAt: (row.updated_at ?? row.created_at).toISOString(),
syncSequence: String(row.sync_sequence),
};
}
diff --git a/server/services/catalogDB/sync.js b/server/services/catalogDB/sync.js
index 311cbcf9d8..289cdc68e9 100644
--- a/server/services/catalogDB/sync.js
+++ b/server/services/catalogDB/sync.js
@@ -7,6 +7,14 @@
* 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.
+ *
+ * The three tuple-unique kinds (refs, relations, media) additionally gate
+ * their tombstone/revival apply on an `updated_at` change-clock (#8347): a
+ * peer's `deleted`/`deleted_at` only lands when its `updated_at` is strictly
+ * newer than the local row's, so a stale re-send of a still-live row (a
+ * reset rewind, a role/data resend, or the #8315 upgrade replay that resends
+ * every catalog row once) can't revive a tombstone that happened after the
+ * peer's own clock. See `upsertRefFromPeer` for the full rationale.
*/
import { query, arrayToPgvector } from '../../lib/db.js';
@@ -54,14 +62,26 @@ export async function upsertRelationFromPeer(rel) {
Object.prototype.hasOwnProperty.call(rel, 'deleted') ||
Object.prototype.hasOwnProperty.call(rel, 'deletedAt');
if (hasTombstoneFields) {
+ // #8347 revival guard: `updated_at` is the tombstone/revival change-clock
+ // (bumped by the trg_catalog_relation_sync_seq trigger on every
+ // deleted/deleted_at flip — see catalog.js). Gate the apply on it being
+ // strictly newer than the local row's, the same LWW shape as
+ // upsertTagFromPeer, so a stale re-send of a still-live edge (a reset
+ // rewind, a role/data resend, or the #8315 upgrade replay) can't revive a
+ // local unlink that already happened. A peer that predates this field
+ // (`rel.updatedAt` absent) falls back to its `deletedAt`/`createdAt`,
+ // which is always older than a genuine later local tombstone.
+ const updatedAtClock = rel.updatedAt || rel.deletedAt || rel.createdAt;
await query(
`INSERT INTO catalog_ingredient_relations
- (from_id, to_id, kind, created_at, deleted, deleted_at)
- VALUES ($1, $2, $3, $4, $5, $6)
+ (from_id, to_id, kind, created_at, deleted, deleted_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (from_id, to_id, kind) DO UPDATE
SET deleted = EXCLUDED.deleted,
- deleted_at = EXCLUDED.deleted_at`,
- [rel.fromId, rel.toId, rel.kind, rel.createdAt, !!rel.deleted, rel.deletedAt || null],
+ deleted_at = EXCLUDED.deleted_at,
+ updated_at = EXCLUDED.updated_at
+ WHERE EXCLUDED.updated_at > catalog_ingredient_relations.updated_at`,
+ [rel.fromId, rel.toId, rel.kind, rel.createdAt, !!rel.deleted, rel.deletedAt || null, updatedAtClock],
);
} else {
await query(
@@ -96,23 +116,30 @@ export async function upsertMediaFromPeer(media) {
&& media.metadata && typeof media.metadata === 'object'
&& !Array.isArray(media.metadata) && Object.keys(media.metadata).length > 0;
const metadataColumn = hasMetadata ? ', metadata' : '';
- const metadataPlaceholder = hasMetadata ? `, $${hasTombstoneFields ? 9 : 7}` : '';
+ const metadataPlaceholder = hasMetadata ? `, $${hasTombstoneFields ? 10 : 7}` : '';
const metadataUpdate = hasMetadata ? ', metadata = EXCLUDED.metadata' : '';
const metadataParam = hasMetadata ? [JSON.stringify(media.metadata || {})] : [];
if (hasTombstoneFields) {
+ // #8347 revival guard — see upsertRelationFromPeer for the rationale.
+ // `updated_at` also moves on a role/caption/metadata-only edit (the
+ // media trigger watches those too), so the same guard additionally
+ // protects a live edit from a stale peer resend, not just a tombstone.
+ const updatedAtClock = media.updatedAt || media.deletedAt || media.createdAt;
await query(
`INSERT INTO catalog_ingredient_media
- (ingredient_id, media_key, kind, role, caption, created_at, deleted, deleted_at${metadataColumn})
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8${metadataPlaceholder})
+ (ingredient_id, media_key, kind, role, caption, created_at, deleted, deleted_at, updated_at${metadataColumn})
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9${metadataPlaceholder})
ON CONFLICT (ingredient_id, media_key, kind) DO UPDATE
SET role = EXCLUDED.role,
caption = EXCLUDED.caption,
deleted = EXCLUDED.deleted,
- deleted_at = EXCLUDED.deleted_at${metadataUpdate}`,
+ deleted_at = EXCLUDED.deleted_at,
+ updated_at = EXCLUDED.updated_at${metadataUpdate}
+ WHERE EXCLUDED.updated_at > catalog_ingredient_media.updated_at`,
[
media.ingredientId, media.mediaKey, media.kind,
media.role ?? null, media.caption ?? null, media.createdAt,
- !!media.deleted, media.deletedAt || null,
+ !!media.deleted, media.deletedAt || null, updatedAtClock,
...metadataParam,
],
);
@@ -310,11 +337,16 @@ export async function upsertSourceFromPeer(src) {
export async function upsertRefFromPeer(ref) {
// ON CONFLICT DO UPDATE so a peer's soft-delete (or revival) of a ref row
- // is mirrored locally. Refs don't carry an `updated_at` column — they're
- // tuple-unique — so a strict LWW window doesn't apply; the receiver simply
- // adopts the peer's `deleted` / `deleted_at` state. The trigger only bumps
- // sync_sequence when those columns change, so a no-op replay (peer already
- // matches local) stays silent on the next outbound pull.
+ // is mirrored locally. Refs are tuple-unique (no editable content fields),
+ // so `updated_at` exists ONLY as a tombstone/revival change-clock (#8347),
+ // bumped by trg_catalog_ref_sync_seq whenever deleted/deleted_at flips —
+ // never by a content edit, since there is no other mutable field. The
+ // WHERE guard below rejects a stale apply whose clock isn't strictly newer
+ // than the local row's, so a stale re-send of a still-live ref (a reset
+ // rewind or the #8315 upgrade replay resending every row once) can't
+ // silently revive a tombstone that happened after the peer's clock. A
+ // no-op replay (peer already matches local) still bumps nothing new, so
+ // it stays silent on the next outbound pull.
//
// Mixed-version federation: a v1 peer (pre-tombstone) emits ref rows with
// NO `deleted`/`deletedAt` keys. Treat "key absent" as "peer has no opinion"
@@ -323,18 +355,25 @@ export async function upsertRefFromPeer(ref) {
// a locally tombstoned ref. The `hasTombstoneFields` flag distinguishes this
// from an explicit v2 revival (`deleted: false` present). On INSERT a v1
// peer's row defaults to `deleted=false`, which is correct — the row is
- // brand-new locally and the peer believes it's active.
+ // brand-new locally and the peer believes it's active. A peer that carries
+ // tombstone fields but predates the `updatedAt` wire field (a v2-but-not-v3
+ // sender, which cannot occur once every peer ships this fix) falls back to
+ // its `deletedAt`/`createdAt`, which is always older than a genuine later
+ // local tombstone.
const hasTombstoneFields =
Object.prototype.hasOwnProperty.call(ref, 'deleted') ||
Object.prototype.hasOwnProperty.call(ref, 'deletedAt');
if (hasTombstoneFields) {
+ const updatedAtClock = ref.updatedAt || ref.deletedAt || ref.createdAt;
await query(
`INSERT INTO catalog_ingredient_refs
- (ingredient_id, ref_kind, ref_id, role, created_at, deleted, deleted_at)
- VALUES ($1, $2, $3, $4, $5, $6, $7)
+ (ingredient_id, ref_kind, ref_id, role, created_at, deleted, deleted_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (ingredient_id, ref_kind, ref_id, role) DO UPDATE
SET deleted = EXCLUDED.deleted,
- deleted_at = EXCLUDED.deleted_at`,
+ deleted_at = EXCLUDED.deleted_at,
+ updated_at = EXCLUDED.updated_at
+ WHERE EXCLUDED.updated_at > catalog_ingredient_refs.updated_at`,
[
ref.ingredientId,
ref.refKind,
@@ -343,6 +382,7 @@ export async function upsertRefFromPeer(ref) {
ref.createdAt,
!!ref.deleted,
ref.deletedAt || null,
+ updatedAtClock,
],
);
} else {
diff --git a/server/services/catalogDBMedia.test.js b/server/services/catalogDBMedia.test.js
index cbfa159179..08d463a71e 100644
--- a/server/services/catalogDBMedia.test.js
+++ b/server/services/catalogDBMedia.test.js
@@ -133,9 +133,12 @@ describe('upsertMediaFromPeer', () => {
role: 'r', caption: 'c', createdAt: 't', deleted: true, deletedAt: 't2',
});
const { sql, params } = calls[0];
- expect(sql).toMatch(/deleted, deleted_at/i);
+ expect(sql).toMatch(/deleted, deleted_at, updated_at/i);
expect(sql).toMatch(/SET role = EXCLUDED.role, caption = EXCLUDED.caption, deleted = EXCLUDED.deleted/i);
- expect(params).toEqual(['i1', 'a.png', 'portrait', 'r', 'c', 't', true, 't2']);
+ expect(sql).toMatch(/WHERE EXCLUDED\.updated_at > catalog_ingredient_media\.updated_at/i);
+ // #8347: the 9th param is the revival-guard change-clock — falls back to
+ // deletedAt when the peer omits updatedAt.
+ expect(params).toEqual(['i1', 'a.png', 'portrait', 'r', 'c', 't', true, 't2', 't2']);
});
it('includes generation provenance when a peer sends the additive field', async () => {
@@ -147,7 +150,8 @@ describe('upsertMediaFromPeer', () => {
const { sql, params } = calls[0];
expect(sql).toMatch(/metadata\)/i);
expect(sql).toMatch(/metadata = EXCLUDED\.metadata/i);
- expect(params).toEqual(['i1', 'a.png', 'portrait', 'r', 'c', 't', false, null, JSON.stringify(metadata)]);
+ // deletedAt is null here, so the change-clock falls back to createdAt.
+ expect(params).toEqual(['i1', 'a.png', 'portrait', 'r', 'c', 't', false, null, 't', JSON.stringify(metadata)]);
});
it('uses the tombstone-less INSERT (preserve local state) when the keys are absent', async () => {
diff --git a/server/services/catalogSync.tombstoneRevival.db.test.js b/server/services/catalogSync.tombstoneRevival.db.test.js
new file mode 100644
index 0000000000..7a85ab1260
--- /dev/null
+++ b/server/services/catalogSync.tombstoneRevival.db.test.js
@@ -0,0 +1,208 @@
+/**
+ * DB-backed regression coverage for #8347: the ref/relation/media
+ * tuple-unique upserts must not let a peer's stale live copy revive a
+ * NEWER local tombstone.
+ *
+ * `upsertRefFromPeer`, `upsertRelationFromPeer`, and `upsertMediaFromPeer`
+ * apply `deleted`/`deleted_at` unconditionally by ON CONFLICT DO UPDATE.
+ * Scenario: machine A soft-deletes ref R at t2. Before B pulls that
+ * tombstone, A pulls B's still-live copy of R (a role/data resend, a reset
+ * rewind, or the #8315 upgrade replay that resends every catalog row once).
+ * Applying it unconditionally sets `deleted = false` and revives the row —
+ * the unlink is lost. The fix adds an `updated_at` change-clock (bumped by
+ * the sync-seq triggers on every soft-delete/revival) and gates the apply
+ * on `EXCLUDED.updated_at > <table>.updated_at`.
+ *
+ * This needs a live Postgres — the trigger-maintained `updated_at` stamp and
+ * the `WHERE EXCLUDED.updated_at > …` guard are SQL-level behavior a mocked
+ * `query()` can't exercise faithfully.
+ */
+
+import { describe, it, expect, afterAll } from 'vitest';
+import { checkHealth, ensureSchema, close, query } from '../lib/db.js';
+import { requireDbOrSkip } from '../lib/dbTestGate.js';
+import * as catalogDB from './catalogDB.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(() => ({ hasCatalogSchema: false }));
+ if (recheck.hasCatalogSchema) dbReady = true;
+ else skipReason = 'catalog schema not present (ensureSchema did not create catalog tables)';
+ }
+}
+const runDb = requireDbOrSkip('services/catalogSync.tombstoneRevival.db.test', dbReady, skipReason);
+function requireDb() { return dbReady; }
+
+const createdIngredientIds = new Set();
+
+afterAll(async () => {
+ if (!dbReady) return;
+ for (const id of createdIngredientIds) {
+ await catalogDB.deleteIngredient(id, { hard: true }).catch(() => {});
+ }
+ await close();
+});
+
+async function makeIngredient(name) {
+ const ing = await catalogDB.createIngredient({ type: 'character', name, payload: {}, tags: [] });
+ createdIngredientIds.add(ing.id);
+ return ing;
+}
+
+const STALE_CLOCK = '2000-01-01T00:00:00.000Z'; // always older than any row created by this suite
+const FUTURE_CLOCK = new Date(Date.now() + 60_000).toISOString(); // always newer
+
+describe.skipIf(!runDb)('catalog tombstone/revival guard (#8347)', () => {
+ it('keeps a ref tombstone when the peer applies a stale live copy, but accepts a genuinely newer revival', async () => {
+ if (!requireDb('ref revival guard')) return;
+ const ing = await makeIngredient('Ref Revival Subject');
+ const refKind = 'universe';
+ const refId = 'u-test-8347';
+ const role = 'canon-character';
+
+ await catalogDB.linkIngredientToRef(ing.id, refKind, refId, role);
+ await catalogDB.unlinkIngredientFromRef(ing.id, refKind, refId, role); // local tombstone
+
+ const before = await query(
+ `SELECT deleted, deleted_at, updated_at, created_at FROM catalog_ingredient_refs
+ WHERE ingredient_id = $1 AND ref_kind = $2 AND ref_id = $3 AND role = $4`,
+ [ing.id, refKind, refId, role],
+ );
+ expect(before.rows[0].deleted).toBe(true);
+ expect(before.rows[0].updated_at).not.toBeNull();
+
+ // A stale peer re-sends its still-live copy of the same ref, carrying an
+ // OLDER change-clock than the local tombstone.
+ await catalogDB.upsertRefFromPeer({
+ ingredientId: ing.id, refKind, refId, role,
+ createdAt: before.rows[0].created_at.toISOString(),
+ deleted: false, deletedAt: null, updatedAt: STALE_CLOCK,
+ });
+ const afterStale = await query(
+ `SELECT deleted FROM catalog_ingredient_refs
+ WHERE ingredient_id = $1 AND ref_kind = $2 AND ref_id = $3 AND role = $4`,
+ [ing.id, refKind, refId, role],
+ );
+ expect(afterStale.rows[0].deleted).toBe(true); // tombstone survives
+
+ // A genuinely newer revival (a real re-link on the peer, later in time)
+ // still un-deletes the row.
+ await catalogDB.upsertRefFromPeer({
+ ingredientId: ing.id, refKind, refId, role,
+ createdAt: before.rows[0].created_at.toISOString(),
+ deleted: false, deletedAt: null, updatedAt: FUTURE_CLOCK,
+ });
+ const afterRevival = await query(
+ `SELECT deleted FROM catalog_ingredient_refs
+ WHERE ingredient_id = $1 AND ref_kind = $2 AND ref_id = $3 AND role = $4`,
+ [ing.id, refKind, refId, role],
+ );
+ expect(afterRevival.rows[0].deleted).toBe(false);
+ });
+
+ it('keeps a relation tombstone when the peer applies a stale live copy, but accepts a genuinely newer revival', async () => {
+ if (!requireDb('relation revival guard')) return;
+ const from = await makeIngredient('Relation Revival From');
+ const to = await makeIngredient('Relation Revival To');
+ const kind = 'related-to';
+
+ await catalogDB.linkIngredientRelation(from.id, to.id, kind);
+ await catalogDB.unlinkIngredientRelation(from.id, to.id, kind);
+
+ const before = await query(
+ `SELECT deleted, created_at FROM catalog_ingredient_relations
+ WHERE from_id = $1 AND to_id = $2 AND kind = $3`,
+ [from.id, to.id, kind],
+ );
+ expect(before.rows[0].deleted).toBe(true);
+
+ await catalogDB.upsertRelationFromPeer({
+ fromId: from.id, toId: to.id, kind,
+ createdAt: before.rows[0].created_at.toISOString(),
+ deleted: false, deletedAt: null, updatedAt: STALE_CLOCK,
+ });
+ const afterStale = await query(
+ `SELECT deleted FROM catalog_ingredient_relations WHERE from_id = $1 AND to_id = $2 AND kind = $3`,
+ [from.id, to.id, kind],
+ );
+ expect(afterStale.rows[0].deleted).toBe(true);
+
+ await catalogDB.upsertRelationFromPeer({
+ fromId: from.id, toId: to.id, kind,
+ createdAt: before.rows[0].created_at.toISOString(),
+ deleted: false, deletedAt: null, updatedAt: FUTURE_CLOCK,
+ });
+ const afterRevival = await query(
+ `SELECT deleted FROM catalog_ingredient_relations WHERE from_id = $1 AND to_id = $2 AND kind = $3`,
+ [from.id, to.id, kind],
+ );
+ expect(afterRevival.rows[0].deleted).toBe(false);
+ });
+
+ it('keeps a media tombstone when the peer applies a stale live copy, but accepts a genuinely newer revival', async () => {
+ if (!requireDb('media revival guard')) return;
+ const ing = await makeIngredient('Media Revival Subject');
+ const mediaKey = 'media-revival-8347.png';
+ const kind = 'reference';
+
+ await catalogDB.attachMedia(ing.id, mediaKey, kind);
+ await catalogDB.detachMedia(ing.id, mediaKey, kind);
+
+ const before = await query(
+ `SELECT deleted, created_at FROM catalog_ingredient_media
+ WHERE ingredient_id = $1 AND media_key = $2 AND kind = $3`,
+ [ing.id, mediaKey, kind],
+ );
+ expect(before.rows[0].deleted).toBe(true);
+
+ await catalogDB.upsertMediaFromPeer({
+ ingredientId: ing.id, mediaKey, kind,
+ createdAt: before.rows[0].created_at.toISOString(),
+ deleted: false, deletedAt: null, updatedAt: STALE_CLOCK,
+ });
+ const afterStale = await query(
+ `SELECT deleted FROM catalog_ingredient_media WHERE ingredient_id = $1 AND media_key = $2 AND kind = $3`,
+ [ing.id, mediaKey, kind],
+ );
+ expect(afterStale.rows[0].deleted).toBe(true);
+
+ await catalogDB.upsertMediaFromPeer({
+ ingredientId: ing.id, mediaKey, kind,
+ createdAt: before.rows[0].created_at.toISOString(),
+ deleted: false, deletedAt: null, updatedAt: FUTURE_CLOCK,
+ });
+ const afterRevival = await query(
+ `SELECT deleted FROM catalog_ingredient_media WHERE ingredient_id = $1 AND media_key = $2 AND kind = $3`,
+ [ing.id, mediaKey, kind],
+ );
+ expect(afterRevival.rows[0].deleted).toBe(false);
+ });
+
+ it('treats a tombstone-less (mixed-version) peer payload as no opinion, preserving a local tombstone', async () => {
+ if (!requireDb('mixed-version compatibility')) return;
+ const ing = await makeIngredient('Mixed Version Subject');
+ const refKind = 'series';
+ const refId = 's-test-8347';
+ const role = 'cast';
+
+ await catalogDB.linkIngredientToRef(ing.id, refKind, refId, role);
+ await catalogDB.unlinkIngredientFromRef(ing.id, refKind, refId, role);
+
+ // A pre-tombstone (v1-shape) peer payload carries no deleted/deletedAt keys.
+ await catalogDB.upsertRefFromPeer({
+ ingredientId: ing.id, refKind, refId, role, createdAt: new Date().toISOString(),
+ });
+ const after = await query(
+ `SELECT deleted FROM catalog_ingredient_refs
+ WHERE ingredient_id = $1 AND ref_kind = $2 AND ref_id = $3 AND role = $4`,
+ [ing.id, refKind, refId, role],
+ );
+ expect(after.rows[0].deleted).toBe(true); // untouched, "no opinion"
+ });
+});
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index 25b36d1fa9..1aa27b53dc 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -22,6 +22,7 @@ export const DB_TEST_INCLUDE = [
'services/backup.db.test.js',
'services/catalogDB.test.js',
'services/catalogDB.facets.db.test.js',
+ 'services/catalogSync.tombstoneRevival.db.test.js',
'services/humanActivity.db.test.js',
'services/postRunDb.db.test.js',
'services/userActions.db.test.js',