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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(catalog): wrap scrap-commit loop in a transaction
[._.]/ Adam Eivy4ee7c2a6827e
diff --git a/server/routes/catalog.js b/server/routes/catalog.jsindex da63d6a7ff..936ac1f6a6 100644--- a/server/routes/catalog.js+++ b/server/routes/catalog.js@@ -4,6 +4,7 @@import { Router } from 'express';import * as catalogDB from '../services/catalogDB.js';import * as catalogSync from '../services/catalogSync.js';+import { withTransaction } from '../lib/db.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import {@@ -87,25 +88,35 @@ router.post('/scraps/:id/commit', asyncHandler(async (req, res) => {if (!scrap) throw new ServerError('Scrap not found', { status: 404 });// Embed all drafts in parallel (concurrency-4 inside embedBatch) before- // sequentially writing — LLM round-trips dominate, DB inserts don't.+ // sequentially writing — LLM round-trips dominate, DB inserts don't. Embeds+ // stay OUTSIDE the transaction: they're network round-trips to the provider,+ // not DB writes, and a half-embedded batch is fine (failed embeds just land+ // as null `embedding` on the row, same as today).const seeds = req.body.accepted.map((d) => ingredientEmbedSeed(d));const embeds = await embedBatch(seeds);- const created = [];- for (let i = 0; i < req.body.accepted.length; i++) {- const draft = req.body.accepted[i];- const e = embeds[i];- const ing = await catalogDB.createIngredient({- type: draft.type,- name: draft.name,- payload: draft.payload || {},- tags: draft.tags || [],- embedding: e?.embedding ?? null,- embeddingModel: e?.model ?? null,- });- await catalogDB.linkIngredientToSource(ing.id, scrap.id, draft.span || null);- created.push(ing);- }+ // Wrap the per-draft loop in a transaction so a mid-loop failure (DB+ // timeout, future unique-constraint violation, span shape error) rolls back+ // the whole batch instead of leaving some ingredients persisted without+ // their source-link rows.+ const created = await withTransaction(async (client) => {+ const out = [];+ for (let i = 0; i < req.body.accepted.length; i++) {+ const draft = req.body.accepted[i];+ const e = embeds[i];+ const ing = await catalogDB.createIngredient({+ type: draft.type,+ name: draft.name,+ payload: draft.payload || {},+ tags: draft.tags || [],+ embedding: e?.embedding ?? null,+ embeddingModel: e?.model ?? null,+ }, { client });+ await catalogDB.linkIngredientToSource(ing.id, scrap.id, draft.span || null, { client });+ out.push(ing);+ }+ return out;+ });res.status(201).json({ scrap, ingredients: created });}));diff --git a/server/services/catalogDB.js b/server/services/catalogDB.jsindex c7e31b47a7..d1f5060fab 100644--- a/server/services/catalogDB.js+++ b/server/services/catalogDB.js@@ -187,7 +187,12 @@ export async function deleteScrap(id, { hard = false } = {}) {}-export async function createIngredient({ id: explicitId, type, name, payload = {}, tags = [], embedding = null, embeddingModel = null } = {}) {+// `{ client }` is optional — when supplied, SQL runs on the caller's transaction+// client (so the write rolls back if a later step in the same `withTransaction`+// block throws). Absent, falls through to the pool-level `query` as before.+// See `POST /api/catalog/scraps/:id/commit` for the scrap-commit batch that+// needs every per-draft ingredient + source-link to commit-or-rollback together.+export async function createIngredient({ id: explicitId, type, name, payload = {}, tags = [], embedding = null, embeddingModel = null } = {}, { client } = {}) {if (!type || !TYPE_PREFIX[type]) throw new Error(`Invalid ingredient type: ${type}`);if (!name || !String(name).trim()) throw new Error('name is required');@@ -197,7 +202,8 @@ export async function createIngredient({ id: explicitId, type, name, payload = {// user-initiated creates omit it and we mint a fresh prefix:uuid.const id = explicitId || newIngredientId(type);const originInstanceId = await getInstanceId();- const result = await query(+ const exec = client ? client.query.bind(client) : query;+ const result = await exec(`INSERT INTO catalog_ingredients(id, type, name, payload, tags, embedding, embedding_model, origin_instance_id)VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8)@@ -393,8 +399,12 @@ export async function searchIngredientsByText(q, { type, limit = 20 } = {}) {}-export async function linkIngredientToSource(ingredientId, scrapId, span = null) {- await query(+// `{ client }` is optional — see the createIngredient comment above. Passing+// the same client used to insert the ingredient row keeps the source-link row+// in the same transaction so a mid-batch failure rolls back both halves.+export async function linkIngredientToSource(ingredientId, scrapId, span = null, { client } = {}) {+ const exec = client ? client.query.bind(client) : query;+ await exec(`INSERT INTO catalog_ingredient_sources (ingredient_id, scrap_id, span)VALUES ($1, $2, $3::jsonb)ON CONFLICT (ingredient_id, scrap_id) DO UPDATE SET span = EXCLUDED.span`,