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

perf: batch normalizeTags into two queries instead of one per tag (#3943)

[._.]/ Adam Eivyf7cddc1f1dda
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a9be1f2e8b..3a0ccc079c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -81,3 +81,4 @@
- Clearing a Quota Burn number box no longer discards the edit without saying so. `NumberField` held an uncommitted draft so an empty box could not commit `Number('') === 0` into a 400, but on blur it simply dropped the draft and snapped the input back to the stored value — a user who cleared "Check every (minutes)" or "Reserve (%)" and clicked away saw the old number reappear with nothing on screen explaining why. An empty, non-numeric or out-of-range draft now stays on screen next to an inline error naming what the field accepts ("Must be between 5 and 720"), wired up with `aria-invalid`/`aria-describedby`; the error clears the moment the draft is committable again, and only a committable draft is released back to the stored value. Out-of-range numbers are also no longer committed mid-typing, so a 721-minute interval is caught in the field rather than by the server.
- Applying an inbound catalog sync envelope no longer writes each legacy-tagged ingredient twice. The friendlify-on-sync repair — which rewrites an older peer's raw `from-universe` / `universe:<id>` tags to the friendly universe name — ran as a follow-up `updateIngredient` after `upsertIngredientFromPeer` had already written the row, so an envelope carrying N such ingredients cost 2N queries and left a redundant `catalog_ingredient_revisions` entry for every one of them. The rewrite now happens on the row before it is upserted, so it lands cleaned in a single write with no extra revision history. Behavior is otherwise unchanged: the universe name map is still built lazily and only once per apply, a row whose universe is not resolvable locally still lands with its machine tags intact for a later pass, an LWW skip still touches nothing, and a failure to build the map is isolated per row (reported as `ingredient-prepare`) with the raw row still applied. The friendly universe name — minted locally rather than carried by the peer — is still registered in the canonical tag taxonomy so autocomplete can suggest it, but now only for the label the rewrite adds, once per apply, instead of re-normalizing every row's whole tag array.
- Unsaved job-skill edits in the Prompt Manager are no longer thrown away when you click another skill. Selecting a skill replaced the Markdown editor's contents outright, so a half-written template vanished with no warning and no undo the moment the user reached for a neighbouring skill in the sidebar list. The editor now tracks the last server-confirmed text (a full copy, not a flag, so typing an edit and undoing it back to the original stops counting as dirty) and marks itself with an "Unsaved changes" note in the header and an "Unsaved" badge on the list row. Clicking a different skill while dirty parks that click and takes over its list slot with an inline confirm row — "Discard unsaved changes to …?" with Discard / Keep editing — so cancelling leaves the selection, the URL, and the typed text untouched, and the next skill is only fetched once the discard is confirmed. Saving snapshots exactly what was sent — and which skill it was sent for — as the new clean baseline, so a save that lands after the user has already moved on cannot mark the freshly loaded skill dirty; a preview that resolves late is dropped for the same reason rather than rendered under the wrong skill's heading.
+- Saving an ingredient no longer issues one or two database queries per tag. `normalizeTags` mapped each raw label to its canonical `catalog_tags` row inside a `for` loop — an `INSERT … ON CONFLICT DO NOTHING RETURNING label` per label, plus a follow-up `SELECT` whenever the row already existed, which is the common case — so an ingredient carrying M tags cost between M and 2M round-trips on every create, every tag-touching update, and every committed scrap. The whole list is now resolved in at most two statements: one `SELECT id, label … WHERE id = ANY($1)` to read every pre-existing row, then a single multi-row insert for whatever is missing, skipped entirely when nothing is. The canonical rules are unchanged — blank tags dropped, casing/whitespace variants collapsed to one row, order of first appearance preserved, and a stored label still beating the incoming casing (`Noir` wins over a later `NOIR`) — and passing `{ client }` still runs both statements on the caller's transaction.
diff --git a/server/services/catalogDB.tags.test.js b/server/services/catalogDB.tags.test.js
index 86117dc89e..15b8aec3bd 100644
--- a/server/services/catalogDB.tags.test.js
+++ b/server/services/catalogDB.tags.test.js
@@ -8,23 +8,29 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
// In-memory tag store keyed by id. The mock interprets the three SQL shapes
-// normalizeTags / upsertTagFromPeer issue: INSERT … ON CONFLICT DO NOTHING
-// RETURNING label, SELECT label WHERE id, and the peer LWW upsert.
+// normalizeTags / upsertTagFromPeer issue: the batched multi-row INSERT …
+// ON CONFLICT DO NOTHING RETURNING id, label, the batched SELECT id, label
+// WHERE id = ANY(...), and the peer LWW upsert.
const tagStore = new Map();
let failParentFkOnce = false;
vi.mock('../lib/db.js', () => ({
query: vi.fn(async (sql, params) => {
if (/INSERT INTO catalog_tags[\s\S]*ON CONFLICT \(id\) DO NOTHING/.test(sql)) {
- const [id, label] = params;
- if (tagStore.has(id)) return { rows: [] }; // conflict → DO NOTHING
- tagStore.set(id, { id, label });
- return { rows: [{ label }] };
+ const rows = [];
+ for (let i = 0; i < params.length; i += 2) {
+ const [id, label] = [params[i], params[i + 1]];
+ if (tagStore.has(id)) continue; // conflict → DO NOTHING
+ tagStore.set(id, { id, label });
+ rows.push({ id, label });
+ }
+ return { rows };
}
- if (/^SELECT label FROM catalog_tags WHERE id/.test(sql.trim())) {
- const [id] = params;
- const row = tagStore.get(id);
- return { rows: row ? [{ label: row.label }] : [] };
+ if (/^SELECT id, label FROM catalog_tags WHERE id = ANY/.test(sql.trim())) {
+ const [ids] = params;
+ return {
+ rows: ids.filter((id) => tagStore.has(id)).map((id) => ({ id, label: tagStore.get(id).label })),
+ };
}
if (/INSERT INTO catalog_tags[\s\S]*ON CONFLICT \(id\) DO UPDATE/.test(sql)) {
const [id, label, description, color, parentId] = params;
@@ -47,6 +53,7 @@ vi.mock('../lib/db.js', () => ({
vi.mock('./instances.js', () => ({ getInstanceId: vi.fn(async () => 'inst-test') }));
+import { query } from '../lib/db.js';
import { normalizeTags, upsertTagFromPeer } from './catalogDB.js';
beforeEach(() => {
@@ -87,6 +94,30 @@ describe('normalizeTags', () => {
const out = await normalizeTags(['beta', 'alpha', 'beta', 'gamma']);
expect(out).toEqual(['beta', 'alpha', 'gamma']);
});
+
+ it('issues at most two queries regardless of tag count (no per-label N+1)', async () => {
+ const many = Array.from({ length: 40 }, (_, i) => `tag-${i}`);
+ const out = await normalizeTags(many);
+ expect(out).toEqual(many);
+ // 1 batched SELECT + 1 batched INSERT.
+ expect(query).toHaveBeenCalledTimes(2);
+ });
+
+ it('skips the insert entirely when every tag already exists', async () => {
+ await normalizeTags(['Noir', 'Pulp']);
+ vi.clearAllMocks();
+ const out = await normalizeTags(['noir', 'PULP']);
+ expect(out).toEqual(['Noir', 'Pulp']);
+ expect(query).toHaveBeenCalledTimes(1);
+ });
+
+ it('runs the batch on the caller transaction client when one is passed', async () => {
+ const client = { query: vi.fn(async () => ({ rows: [] })) };
+ const out = await normalizeTags(['Noir', 'Pulp'], { client });
+ expect(out).toEqual(['Noir', 'Pulp']);
+ expect(client.query).toHaveBeenCalledTimes(2);
+ expect(query).not.toHaveBeenCalled();
+ });
});
describe('upsertTagFromPeer', () => {
diff --git a/server/services/catalogDB/tags.js b/server/services/catalogDB/tags.js
index 627160a9f0..c1cde8d4e8 100644
--- a/server/services/catalogDB/tags.js
+++ b/server/services/catalogDB/tags.js
@@ -22,33 +22,43 @@ import { rowToTag } from './shared.js';
export async function normalizeTags(labels = [], { client } = {}) {
if (!Array.isArray(labels) || labels.length === 0) return [];
const exec = client ? client.query.bind(client) : query;
- const out = [];
- const seen = new Set();
+
+ // De-dup by canonical key, order-preserving, first-seen casing wins.
+ const wanted = new Map();
for (const raw of labels) {
const key = canonicalTagKey(raw);
- if (!key || seen.has(key)) continue;
- seen.add(key);
- const id = tagIdForKey(key);
- const label = String(raw).trim().replace(/\s+/g, ' ');
- // First write wins on the canonical label — ON CONFLICT DO NOTHING keeps
- // the original casing rather than letting a later `NOIR` overwrite `Noir`.
- // RETURNING after a no-op conflict is empty, so re-select to read the
- // stored canonical label for the array column.
+ if (!key || wanted.has(key)) continue;
+ wanted.set(key, { id: tagIdForKey(key), label: String(raw).trim().replace(/\s+/g, ' ') });
+ }
+ if (wanted.size === 0) return [];
+
+ const entries = [...wanted.values()];
+ // Query 1 — read every pre-existing row in one round-trip. A stored label
+ // always wins over the incoming casing (`Noir` beats a later `NOIR`).
+ const existing = await exec(
+ `SELECT id, label FROM catalog_tags WHERE id = ANY($1)`,
+ [entries.map((e) => e.id)],
+ );
+ const canonical = new Map(existing.rows.map((r) => [r.id, r.label]));
+
+ // Query 2 — create every missing canonical row in one multi-row insert.
+ // ON CONFLICT DO NOTHING keeps first-write-wins; a row that conflicts here
+ // was created between the two statements, so fall back to the incoming
+ // label rather than spending another round-trip re-reading it.
+ const missing = entries.filter((e) => !canonical.has(e.id));
+ if (missing.length > 0) {
+ const values = missing.map((_, i) => `($${i * 2 + 1}, $${i * 2 + 2})`).join(', ');
const ins = await exec(
`INSERT INTO catalog_tags (id, label)
- VALUES ($1, $2)
+ VALUES ${values}
ON CONFLICT (id) DO NOTHING
- RETURNING label`,
- [id, label],
+ RETURNING id, label`,
+ missing.flatMap((e) => [e.id, e.label]),
);
- if (ins.rows[0]?.label) {
- out.push(ins.rows[0].label);
- } else {
- const existing = await exec(`SELECT label FROM catalog_tags WHERE id = $1`, [id]);
- out.push(existing.rows[0]?.label ?? label);
- }
+ for (const row of ins.rows) canonical.set(row.id, row.label);
}
- return out;
+
+ return entries.map((e) => canonical.get(e.id) ?? e.label);
}
export async function getTag(id) {