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: prevent duplicate Catalog ingredients when retrying commits (#8684)

[._.]/ Adam Eivyfeccbd2f4c2e
diff --git a/client/src/pages/CatalogIngest.jsx b/client/src/pages/CatalogIngest.jsx
index 53e6810073..be9799fe60 100644
--- a/client/src/pages/CatalogIngest.jsx
+++ b/client/src/pages/CatalogIngest.jsx
@@ -5,6 +5,7 @@
* name + description). Full-width page; owns its own scroll.
*/
+import { uuidv4 } from '../lib/uuid.js';
import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import { useNavigate, useLocation } from 'react-router';
import { Sparkles, Loader2, CheckCircle2, AlertCircle, ArrowLeft, RotateCcw, Circle, Upload, Link2, FileText, Mic, Square } from 'lucide-react';
@@ -183,6 +184,7 @@ export default function CatalogIngest() {
// current stage list (server fans these to all sockets — single-user trust
// model still applies, but tab refresh + a slow extract overlap is real).
const activeRunIdRef = useRef(null);
+ const commitOperationRef = useRef(null);
useEffect(() => {
if (babble) return;
const onProgress = (ev) => {
@@ -210,6 +212,7 @@ export default function CatalogIngest() {
}, [babble]);
const reset = () => {
+ commitOperationRef.current = null;
activeRunIdRef.current = null;
// Abandoning the review (Start Over / Cancel) discards the Brain hand-off —
// a later commit of unrelated text must NOT mark the original notes consumed.
@@ -243,6 +246,7 @@ export default function CatalogIngest() {
// through here to populate the review phase.
const enterReviewFromResult = (result, sourceKind) => {
if (!result?.draft) { setPhase('paste'); return false; }
+ commitOperationRef.current = null;
if (result.scrap?.id) setScrapId(result.scrap.id);
setUniverseRef(defaultUniverseForSource(sourceKind));
const d = Object.fromEntries(KIND_SECTIONS.map((s) => [
@@ -504,7 +508,7 @@ export default function CatalogIngest() {
};
const handleCommit = async () => {
- if (!scrapId) return;
+ if (!scrapId || committing) return;
const totalSelected = KIND_SECTIONS.reduce((sum, s) => sum + (selected[s.key]?.size || 0), 0);
const activeRelCount = isStructuredDraft
@@ -564,15 +568,24 @@ export default function CatalogIngest() {
}));
}
- const result = await commitCatalogScrapDraft(scrapId, accepted, {
+ const commitOptions = {
universeRef: universeRef === UNASSIGNED_UNIVERSE ? undefined : universeRef,
relationships: relsToCommit,
+ };
+ const submission = JSON.stringify({ scrapId, accepted, ...commitOptions });
+ if (commitOperationRef.current?.submission !== submission) {
+ commitOperationRef.current = { submission, key: uuidv4() };
+ }
+ const result = await commitCatalogScrapDraft(scrapId, accepted, {
+ ...commitOptions,
+ operationKey: commitOperationRef.current.key,
silent: true,
}).catch((err) => {
toast.error(err?.message || 'Commit failed');
return null;
});
if (!result) { setCommitting(false); return; }
+ commitOperationRef.current = null;
// Keep `committing` true through the mark request + navigate: re-enabling the
// Commit button before the awaited follow-up finishes would open a
// double-submit window that re-commits the same scrap and duplicates
diff --git a/client/src/pages/CatalogIngest.test.jsx b/client/src/pages/CatalogIngest.test.jsx
index 8d9025e5d2..05a29b1f83 100644
--- a/client/src/pages/CatalogIngest.test.jsx
+++ b/client/src/pages/CatalogIngest.test.jsx
@@ -355,3 +355,25 @@ it('renders retry button on partial failures which re-extracts without silent au
expect(commitCatalogScrapDraft).not.toHaveBeenCalled();
});
+
+it('retains the operation key after a lost response and rotates it for edited reviewed content', async () => {
+ createCatalogScrap.mockResolvedValue({ scrap: { id: 'example-retry-scrap' } });
+ pruneCatalogScrap.mockResolvedValue({ scrap: { id: 'example-retry-scrap' }, draft: { ideas: [{ name: 'Example retry idea' }] } });
+ commitCatalogScrapDraft.mockRejectedValue(new Error('Response lost'));
+ render(<MemoryRouter initialEntries={['/catalog/ingest?mode=babble']}><CatalogIngest /></MemoryRouter>);
+ fireEvent.change(screen.getByLabelText(/Babble freely/), { target: { value: 'Example retry source.' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Prune into suggestions' }));
+ await screen.findByDisplayValue('Example retry idea');
+ const commit = () => screen.getByRole('button', { name: /Commit/ });
+ fireEvent.click(commit());
+ await waitFor(() => expect(commit()).not.toBeDisabled());
+ const firstKey = commitCatalogScrapDraft.mock.lastCall[2].operationKey;
+ expect(firstKey).toMatch(/^[0-9a-f-]{36}$/);
+ fireEvent.click(commit());
+ await waitFor(() => expect(commit()).not.toBeDisabled());
+ expect(commitCatalogScrapDraft.mock.lastCall[2].operationKey).toBe(firstKey);
+ fireEvent.change(screen.getByDisplayValue('Example retry idea'), { target: { value: 'Example changed idea' } });
+ fireEvent.click(commit());
+ await waitFor(() => expect(commit()).not.toBeDisabled());
+ expect(commitCatalogScrapDraft.mock.lastCall[2].operationKey).not.toBe(firstKey);
+});
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index 950c32a3fa..361cee4286 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -33,12 +33,13 @@ export const pruneCatalogScrap = (id, body, options) =>
// when the caller passes 'unassigned' (the "no universe" choice), reproducing
// prior behavior exactly (source link only, no homing ref).
// `relationships` forwards explicit grounded graph relationships (including [] for structured drafts).
-export const commitCatalogScrapDraft = (id, accepted, { universeRef, role, relationships, ...options } = {}, maybeRelationships) => {
+export const commitCatalogScrapDraft = (id, accepted, { universeRef, role, relationships, operationKey, ...options } = {}, maybeRelationships) => {
const rels = maybeRelationships !== undefined ? maybeRelationships : relationships;
return request(`/catalog/scraps/${enc(id)}/commit`, {
method: 'POST',
body: JSON.stringify({
accepted,
+ ...(operationKey ? { operationKey } : {}),
...(universeRef ? { universeRef, ...(role ? { role } : {}) } : {}),
...(rels !== undefined ? { relationships: rels } : {}),
}),
diff --git a/client/src/services/apiCatalog.test.js b/client/src/services/apiCatalog.test.js
index 4f5a15a419..06f670adf3 100644
--- a/client/src/services/apiCatalog.test.js
+++ b/client/src/services/apiCatalog.test.js
@@ -101,3 +101,14 @@ describe('getCatalogFacets (#1762)', () => {
});
});
// @vitest-environment node
+
+it('serializes the commit operation key into the HTTP body while retaining request options', async () => {
+ const { commitCatalogScrapDraft } = await import('./apiCatalog.js');
+ const operationKey = '11111111-1111-4111-8111-111111111111';
+ await commitCatalogScrapDraft('example-scrap', [], { operationKey, relationships: [], silent: true });
+ const [path, options] = request.mock.lastCall;
+ expect(path).toBe('/catalog/scraps/example-scrap/commit');
+ expect(JSON.parse(options.body)).toEqual({ accepted: [], operationKey, relationships: [] });
+ expect(options.silent).toBe(true);
+ expect(options).not.toHaveProperty('operationKey');
+});
diff --git a/docs/API.md b/docs/API.md
index 2d2ce10ff3..37369bb31e 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -999,6 +999,8 @@ Common error codes:
### Catalog scrap graph commits
+An optional UUID `operationKey` makes a reviewed submission retry-safe. Reuse it for retries with the same accepted content, relationships, scrap, universe and role: the server returns the original ingredient response without creating another batch, including after restart or concurrent requests. Reusing it with different input returns HTTP 409. Embedding output is excluded from request identity. Mint a new key for an intentional new submission; callers omitting it keep legacy behavior. Receipts remain local to the accepting instance and persist with its database.
+
`POST /api/catalog/scraps/:id/commit` accepts up to 200 `accepted` entries and an optional `relationships` array (at most 1,000 edges). Each explicit edge has `fromDraftId`, `toDraftId`, `kind`, and nonempty `evidence` (at most 400 characters). When the array is present, every accepted entry needs a unique nonempty `draftId` (at most 120 characters); both endpoints must be accepted IDs and self-edges are rejected. Draft IDs stay outside persisted payloads. Renaming or reordering entries does not change endpoint identity.
The server validates the graph before embedding or writing. Duplicate directed tuples create one edge, retaining every distinct evidence passage in the source ingredient's existing `payload.evidence` field with the kind and target name. Bible entries keep their evidence arrays (20 passages, 500 characters each including the contextual prefix); light entries keep string evidence, or arrays when supplied. Overflow is rejected explicitly, never truncated. The existing 200KB payload limit still applies after evidence enrichment.
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 8b9e5fccd4..9e963cc07c 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -36,6 +36,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `catalog_pending_applies` — receiver-local, db-primary inbox for Catalog tags/scraps arriving before their parents. Full wire rows and source timestamps survive restart; duplicate delivery coalesces by kind/id, and ready rows drain under normal LWW. Not exported to peers or user lists; no binary assets or TTL (unresolved data must not expire). Covered by PostgreSQL backup. Boot DDL and DB migration 011 install the empty store without a seed.
- `catalog_ingredients` — typed creative records with JSONB payload, tags, embeddings, generated `search_tsv`, soft delete, sync sequence.
- `catalog_ingredient_refs` — homing links from an ingredient to the universe/series/creative-director/issue/work that consumes it. Since #7615, `POST /scraps/:id/commit` (the paste→extract→review ingest flow, plus bulk-import's long-standing `defaults.universeRef`) writes one `ref_kind='universe'` row per committed ingredient in the same transaction as the ingredient insert — the role is derived from the ingredient's type (`universeRefRoleForType` in `server/services/catalogDB/refs.js`) unless the caller overrides it. Omitting `universeRef` at commit time leaves the ingredient unlinked (the catalog's "Raw" bucket), exactly as before #7615.
+- `catalog_commit_receipts` — machine-local, `db-primary` extraction retry receipts. A unique operation UUID, canonical request fingerprint and original ingredient response commit atomically with the batch. Retained indefinitely to preserve retry identity, included in PostgreSQL backups, and never federated. Additive schema plus DB migration 012 supports existing installs; no seed or binary assets.
- `catalog_ingredient_relations` — directed ingredient→ingredient graph edges. Scrap commits with explicit `relationships` write only the reviewed edges (including none for `[]`), atomically with ingredients, source links, and universe refs. Legacy callers omitting the field still receive one `related-to` edge per unordered pair in batches of 2–25. The additive graph API is documented in [API.md](API.md#catalog-scrap-graph-commits).
- `catalog_scraps` / `catalog_ingredient_sources` — the catalog's SECOND grouping seam alongside refs (universe/series/work): a scrap is the raw pasted/imported text an ingredient was extracted from, and `catalog_ingredient_sources` links `(ingredient_id, scrap_id)` with an optional `span`. The ingredient detail page's `GET /ingredients/:id/details` joins the scrap's `title` onto each source link and batches every sibling ingredient extracted from the SAME scrap (`listSiblingIngredientsBySource`) in the one round-trip, so "what else came out of this piece?" is a rendered list, never a second fetch. `GET /ingredients?scrapId=<id>` (and `/catalog?scrap=<id>` client-side) filters the catalog to one scrap's whole extraction set — a provenance dimension orthogonal to the universe/series ref filters, so it composes with them rather than joining their mutual-exclusivity rule (#7617).
- `memories` / `memory_links` — long-term memory + pgvector similarity.
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index 78b03b5cb9..20a245a69e 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -418,6 +418,7 @@ export const catalogDraftRelationshipSchema = z.object({
// scrap-commit) cannot drift (#7615). Omitting `universeRef` reproduces
// today's behavior exactly: source link only, no homing ref.
export const catalogScrapCommitSchema = z.object({
+ operationKey: z.string().uuid().optional(),
accepted: z.array(catalogIngredientCreateSchema.extend({
// Extraction-local identity, never an ingredient ID or payload field.
draftId: z.string().trim().min(1).max(120).optional(),
diff --git a/server/lib/db/schema/catalog.js b/server/lib/db/schema/catalog.js
index ec51a878ca..620a836f26 100644
--- a/server/lib/db/schema/catalog.js
+++ b/server/lib/db/schema/catalog.js
@@ -17,7 +17,18 @@ export const catalogPendingAppliesDdl = [
)`,
];
+// Machine-local retry receipts: retained with the database backup, never federated.
+export const catalogCommitReceiptsDdl = [
+ `CREATE TABLE IF NOT EXISTS catalog_commit_receipts (
+ operation_key UUID PRIMARY KEY,
+ fingerprint TEXT NOT NULL,
+ ingredients JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+)`,
+];
+
export const catalogDdl = [
+ ...catalogCommitReceiptsDdl,
...catalogPendingAppliesDdl,
`CREATE TABLE IF NOT EXISTS catalog_scraps (
id TEXT PRIMARY KEY,
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 600ce06d56..98fc0ffec2 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -176,6 +176,7 @@ router.post('/scraps/:id/commit', asyncHandler(async (req, res) => {
const created = await catalogDB.commitScrap({
scrapId: scrap.id,
+ operationKey: body.operationKey,
accepted: body.accepted,
...(body.relationships !== undefined ? { relationships: body.relationships } : {}),
embeds,
diff --git a/server/routes/catalog.test.js b/server/routes/catalog.test.js
index 7dc79d530a..3d1f630b1a 100644
--- a/server/routes/catalog.test.js
+++ b/server/routes/catalog.test.js
@@ -18,6 +18,9 @@
import { describe, it, expect, afterAll, vi } from 'vitest';
import express from 'express';
import pg from 'pg';
+import { randomUUID } from 'node:crypto';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import { checkHealth, ensureSchema, close, query, withTransaction } from '../lib/db.js';
@@ -66,9 +69,11 @@ const NONCE = Date.now();
const createdIngredientIds = new Set();
const createdScrapIds = new Set();
+const receiptKeys = new Set();
afterAll(async () => {
if (!dbReady) return;
+ await query('DELETE FROM catalog_commit_receipts WHERE operation_key = ANY($1::uuid[])', [[...receiptKeys]]);
for (const id of createdIngredientIds) {
await catalogDB.deleteIngredient(id, { hard: true }).catch(() => {});
}
@@ -454,6 +459,70 @@ describe.skipIf(!runDb)('POST /api/catalog/scraps/:id/commit — universe bindin
await query('DELETE FROM universes WHERE id = $1', [UNI]).catch(() => {});
});
+ it('replays a lost response and concurrent commits without duplicating the batch, and rejects changed input', async () => {
+ const scrap = await catalogDB.createScrap({ rawText: 'Example receipt source' });
+ createdScrapIds.add(scrap.id);
+ await query('INSERT INTO universes (id, name) VALUES ($1, $2) ON CONFLICT DO NOTHING', [UNI, 'Example Universe']);
+ const operationKey = randomUUID();
+ receiptKeys.add(operationKey);
+ const body = {
+ operationKey, universeRef: UNI,
+ accepted: [
+ { type: 'idea', name: 'Example receipt A', payload: { a: 1, b: 2 } },
+ { type: 'idea', name: 'Example receipt B' },
+ ],
+ };
+ const post = (input) => request(makeApp()).post(`/api/catalog/scraps/${scrap.id}/commit`).send(input);
+ const [first, concurrent] = await Promise.all([post(body), post(body)]);
+ expect(first.status).toBe(201);
+ expect(concurrent.status).toBe(201);
+ expect(concurrent.body.ingredients).toEqual(first.body.ingredients);
+ const ids = first.body.ingredients.map(row => row.id);
+ ids.forEach(id => createdIngredientIds.add(id));
+ const counts = async () => {
+ const { rows: [row] } = await query(`SELECT
+ (SELECT count(*) FROM catalog_ingredient_sources WHERE scrap_id = $1) AS sources,
+ (SELECT count(*) FROM catalog_ingredients WHERE id = ANY($2::text[])) AS ingredients,
+ (SELECT count(*) FROM catalog_ingredient_revisions WHERE ingredient_id = ANY($2::text[])) AS revisions,
+ (SELECT count(*) FROM catalog_ingredient_refs WHERE ingredient_id = ANY($2::text[])) AS refs,
+ (SELECT count(*) FROM catalog_ingredient_relations WHERE from_id = ANY($2::text[])) AS edges`, [scrap.id, ids]);
+ return row;
+ };
+ const originalCounts = await counts();
+ expect(originalCounts).toEqual({ sources: '2', ingredients: '2', revisions: '2', refs: '2', edges: '1' });
+ // A fresh process has no request cache: it must replay the durable receipt.
+ const { stdout } = await promisify(execFile)(process.execPath, ['--input-type=module', '-e', `
+ import { commitScrap } from './services/catalogDB/commit.js';
+ import { catalogScrapCommitSchema } from './lib/catalogValidation.js';
+ import { close } from './lib/db.js';
+ const input = JSON.parse(process.argv[1]);
+ const result = await commitScrap({ scrapId: input.scrapId, ...catalogScrapCommitSchema.parse(input.body) });
+ await close();
+ console.log('RECEIPT:' + JSON.stringify(result));
+ `, JSON.stringify({ scrapId: scrap.id, body })], {
+ cwd: new URL('../', import.meta.url),
+ env: { ...process.env, NODE_ENV: 'test', PGDATABASE: 'portos_test' },
+ });
+ const restartedResult = JSON.parse(stdout.split('\n').find(line => line.startsWith('RECEIPT:')).slice(8));
+ expect(restartedResult).toEqual(first.body.ingredients);
+ const replay = await post({ ...body, accepted: [
+ { ...body.accepted[0], payload: { b: 2, a: 1 } }, body.accepted[1],
+ ] });
+ expect(replay.status).toBe(201);
+ expect(replay.body.ingredients).toEqual(first.body.ingredients);
+ expect(await counts()).toEqual(originalCounts);
+ expect((await post({ ...body, accepted: [{ type: 'idea', name: 'Changed' }] })).status).toBe(409);
+ expect(await counts()).toEqual(originalCounts);
+ const nextKey = randomUUID();
+ receiptKeys.add(nextKey);
+ const intentional = await post({ ...body, operationKey: nextKey });
+ expect(intentional.status).toBe(201);
+ intentional.body.ingredients.forEach(row => {
+ createdIngredientIds.add(row.id);
+ expect(ids).not.toContain(row.id);
+ });
+ });
+
it('links every committed ingredient to the universe with the type-derived role, and clusters the batch with related-to edges', async () => {
await query('INSERT INTO universes (id, name) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING', [UNI, `Commit Universe ${NONCE}`]);
const scrap = await catalogDB.createScrap({ rawText: `Commit binding source ${NONCE}` });
@@ -570,6 +639,8 @@ describe.skipIf(!runDb)('POST /api/catalog/scraps/:id/commit — universe bindin
it('rolls back source links, universe refs, ingredients and earlier edges on a relation failure', async () => {
const scrap = await catalogDB.createScrap({ rawText: 'Example relation rollback source' });
createdScrapIds.add(scrap.id);
+ const operationKey = randomUUID();
+ receiptKeys.add(operationKey);
const refs = await import('../services/catalogDB/refs.js');
const realLink = refs.linkIngredientRelation;
const linkedIds = new Set();
@@ -582,7 +653,7 @@ describe.skipIf(!runDb)('POST /api/catalog/scraps/:id/commit — universe bindin
});
try {
await expect(catalogDB.commitScrap({
- scrapId: scrap.id, universeRef: UNI,
+ scrapId: scrap.id, universeRef: UNI, operationKey,
accepted: ['a', 'b', 'c'].map(draftId => ({ draftId, type: 'idea', name: 'Example ' + draftId })),
relationships: [
{ fromDraftId: 'a', toDraftId: 'b', kind: 'references', evidence: 'A references B.' },
@@ -593,6 +664,13 @@ describe.skipIf(!runDb)('POST /api/catalog/scraps/:id/commit — universe bindin
spy.mockRestore();
}
expect(calls).toBe(2);
+ expect((await query('SELECT * FROM catalog_commit_receipts WHERE operation_key = $1', [operationKey])).rows).toEqual([]);
+ const retry = await catalogDB.commitScrap({
+ scrapId: scrap.id, operationKey,
+ accepted: [{ type: 'idea', name: 'Example successful retry after rollback' }],
+ });
+ retry.forEach(row => createdIngredientIds.add(row.id));
+ expect(retry).toHaveLength(1);
for (const id of linkedIds) {
expect(await catalogDB.getIngredient(id)).toBeNull();
expect(await catalogDB.listSourcesForIngredient(id)).toEqual([]);
diff --git a/server/scripts/db-migrations/012-catalog-commit-receipts.js b/server/scripts/db-migrations/012-catalog-commit-receipts.js
new file mode 100644
index 0000000000..3384cac009
--- /dev/null
+++ b/server/scripts/db-migrations/012-catalog-commit-receipts.js
@@ -0,0 +1,7 @@
+// Durable retry identity for Catalog scrap commits (#8684); additive and
+// machine-local — receipts are never federated.
+import { catalogCommitReceiptsDdl } from '../../lib/db/schema/catalog.js';
+
+export async function up(client) {
+ for (const statement of catalogCommitReceiptsDdl) await client.query(statement);
+}
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index ed3f3d99cd..f9cd763a6d 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -323,6 +323,14 @@ CREATE TRIGGER trg_memory_updated_at
-- Federates via sync_sequence BIGSERIAL + LWW on updated_at (same pattern as
-- the memories table above).
+-- Machine-local retry receipts: retained with the database backup, never federated.
+CREATE TABLE IF NOT EXISTS catalog_commit_receipts (
+ operation_key UUID PRIMARY KEY,
+ fingerprint TEXT NOT NULL,
+ ingredients JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
-- Raw user input preserved verbatim. One scrap can spawn many ingredients.
CREATE TABLE IF NOT EXISTS catalog_scraps (
id TEXT PRIMARY KEY, -- 'cat-scrap-<uuid>'
diff --git a/server/services/catalogDB/commit.js b/server/services/catalogDB/commit.js
index 510bfb01b0..4705b9692f 100644
--- a/server/services/catalogDB/commit.js
+++ b/server/services/catalogDB/commit.js
@@ -5,6 +5,9 @@
* cannot accidentally persist only part of a scrap's accepted extraction.
*/
+import { createHash } from 'node:crypto';
+import { canonicalStringify } from '../../lib/objects.js';
+import { ServerError } from '../../lib/errorHandler.js';
import { catalogScrapCommitSchema } from '../../lib/catalogValidation.js';
import { withTransaction } from '../../lib/db.js';
import { createIngredient } from './ingredients.js';
@@ -25,12 +28,34 @@ const RELATION_BATCH_LIMIT = 25;
* mid-batch failure rolls back ingredients, refs, and relations together.
* Omitting it reproduces prior behavior exactly (source link only).
*/
-export async function commitScrap({ scrapId, accepted = [], embeds = [], universeRef = null, role = null, relationships } = {}) {
+export async function commitScrap({ scrapId, accepted = [], embeds = [], universeRef = null, role = null, relationships, operationKey } = {}) {
// Service callers receive the same pre-write guarantees as HTTP callers.
if (relationships !== undefined) {
({ accepted, relationships } = catalogScrapCommitSchema.parse({ accepted, relationships }));
}
+ // Embeddings are derived provider output, not reviewed submission identity.
+ const fingerprint = operationKey
+ ? createHash('sha256').update(canonicalStringify({ scrapId, accepted, universeRef, role, relationships })).digest('hex')
+ : null;
return withTransaction(async (client) => {
+ if (operationKey) {
+ // A competing INSERT waits for the owner to commit or roll back. The
+ // following SELECT gets a fresh READ COMMITTED snapshot of its receipt.
+ const claim = await client.query(
+ `INSERT INTO catalog_commit_receipts (operation_key, fingerprint)
+ VALUES ($1, $2) ON CONFLICT (operation_key) DO NOTHING RETURNING operation_key`,
+ [operationKey, fingerprint],
+ );
+ if (!claim.rowCount) {
+ const { rows: [receipt] } = await client.query(
+ 'SELECT fingerprint, ingredients FROM catalog_commit_receipts WHERE operation_key = $1', [operationKey],
+ );
+ if (receipt.fingerprint !== fingerprint) {
+ throw new ServerError('Commit operation key was already used for a different submission', { status: 409 });
+ }
+ return receipt.ingredients;
+ }
+ }
const created = [];
const ids = new Map();
for (let i = 0; i < accepted.length; i++) {
@@ -78,6 +103,12 @@ export async function commitScrap({ scrapId, accepted = [], embeds = [], univers
}
}
+ if (operationKey) {
+ await client.query(
+ 'UPDATE catalog_commit_receipts SET ingredients = $2::jsonb WHERE operation_key = $1',
+ [operationKey, JSON.stringify(created)],
+ );
+ }
return created;
});
}