Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(backups): mint fresh ids for composite-PK tables on a cross-company restore
aashu2a19048deffa
diff --git a/.claude/rules/company-backup-restore.md b/.claude/rules/company-backup-restore.mdindex 36617c04f4..31b887d0ef 100644--- a/.claude/rules/company-backup-restore.md+++ b/.claude/rules/company-backup-restore.md@@ -93,8 +93,20 @@ The catalog is **schema-introspected**, not a hand-maintained list:legacy branch) in the manifest; `assertBackupImportable` rejects a file whoseversion no longer matches or that's missing a now-required column.- Id minting: `newIdForTable(table)` → `randomUUID()` for uuid id columns else- `nanoid()`. Id remap is **gated to text/uuid id columns** (serial/int ids are- left alone).+ `nanoid()`. `buildIdMaps` (`company-backup.transforms.ts`) decides WHICH rows get+ one, and both the restore and the reseed/import call it so they can't drift.+ It is **gated on having a text/uuid `id` COLUMN**, not on `hasId` (PK exactly+ `id`) — the ~25 composite-PK tables are referenced by their `id` too, and five+ of them back that with a global `UNIQUE (id)`: `changeOrderRequiredAction`,+ `balloon`, `inspectionDocument`, `inspectionFeature` (all PK+ `("id","companyId")`) and `demandProjection` (PK+ `("itemId","locationId","periodId")`). Leaving their source ids in place made a+ cross-company restore collide with the SOURCE company's still-live rows and roll+ the whole thing back. Serial/int ids are left alone. A+ 1:1 extension table whose `id` is itself an FK (`purchaseOrderDelivery.id ->+ purchaseOrder.id`) SHARES its parent's map rather than minting a second id,+ which would split the pair — and under `session_replication_role='replica'`+ the break would commit.- Storage path rewriting: `rewriteStoragePath` (swap `{sourceCompanyId}/` →`{targetCompanyId}/` + remapped id segments), `rewriteToTemplateAssetPath`(`{co}/…` → `_templates/{industryId}/…`). `STORAGE_PATH_COLUMNS` =@@ -410,9 +422,6 @@ snapshot through exactly this path. See `onboarding-company-templates.md`.assets into its `assets/` folder, so each backup costs roughly its asset size instorage. Snapshots are transient (their `assets/` is removed on keep/revert);exports persist until deleted (`deleteCompanyBackupExport` removes the folder).-- **`company-import` id-gate drift** — restore gates id remap on column type- (text/uuid); import still uses a `typeof row.id === "string"` heuristic. Share- one transform builder to fix.- Sequences: the only pg-native serials on backed-up tables are `entryNumber` on`itemLedger`/`costLedger`/`supplierLedger` (not PKs, not unique; PKs are alltext). They are **global/shared across tenants** — never `setval` them scoped todiff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.tsindex 2bd59fa1c4..75af7558a7 100644--- a/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts@@ -10,6 +10,7 @@ import {} from "./company-backup";import {assertReferentiallyClosed,+ buildIdMaps,buildRowTransforms,findDanglingReferences} from "./company-backup.transforms";@@ -503,6 +504,71 @@ describe("buildRowTransforms", () => {});});+describe("buildIdMaps", () => {+ it("remaps a composite-PK table — the cross-company id collision", () => {+ // changeOrderRequiredAction keys on ("id", "companyId") but carries a global+ // UNIQUE(id) so children can FK to it. Gating on `hasId` left its source ids+ // in place, so a cross-company restore collided with the SOURCE company's+ // still-live rows and rolled the whole restore back.+ const t = table(+ "changeOrderRequiredAction",+ [col("id"), col("companyId"), col("name")],+ [],+ { pkColumns: ["id", "companyId"], uniqueColumns: ["id"] }+ );+ expect(t.hasId).toBe(false);+ const maps = buildIdMaps([t], {+ changeOrderRequiredAction: [{ id: "cora_1", companyId: "src-co" }]+ });+ expect(maps.get("changeOrderRequiredAction")?.get("cora_1")).toBeTypeOf(+ "string"+ );+ expect(maps.get("changeOrderRequiredAction")?.get("cora_1")).not.toBe(+ "cora_1"+ );+ });++ it("gives a 1:1 extension table its PARENT's map, not a second id", () => {+ const parent = table("purchaseOrder", [col("id"), col("companyId")]);+ const child = table(+ "purchaseOrderDelivery",+ [col("id"), col("companyId")],+ [fk("id", "purchaseOrder")]+ );+ const maps = buildIdMaps([parent, child], {+ purchaseOrder: [{ id: "po1", companyId: "src-co" }],+ purchaseOrderDelivery: [{ id: "po1", companyId: "src-co" }]+ });+ expect(maps.get("purchaseOrderDelivery")?.get("po1")).toBe(+ maps.get("purchaseOrder")?.get("po1")+ );+ });++ it("leaves an id-FK table unmapped when its parent has no map", () => {+ // `terms.id -> company`: the id follows the company, via a column transform.+ const t = table(+ "terms",+ [col("id"), col("companyId")],+ [fk("id", "company")]+ );+ expect(buildIdMaps([t], { terms: [{ id: "src-co" }] }).has("terms")).toBe(+ false+ );+ });++ it("skips an int/serial id (a nanoid doesn't fit)", () => {+ const idCol: ColumnInfo = {+ ...col("id"),+ dataType: "integer",+ udtName: "int4"+ };+ const t = table("journal", [idCol, col("companyId")]);+ expect(buildIdMaps([t], { journal: [{ id: 7 }] }).has("journal")).toBe(+ false+ );+ });+});+describe("isUserScopedIdentityTable", () => {it("true when a user FK is in the PRIMARY KEY (employee shape)", () => {const t = table(diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.tsindex f06e1fb1f2..3b9bc770f0 100644--- a/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts@@ -5,6 +5,7 @@ import {type ColumnInfo,type CompanyBackup,mapWithConcurrency,+ newIdForTable,RETAINED_REF_TABLES,rewriteStoragePath,rewriteToTemplateAssetPath,@@ -213,6 +214,51 @@ export async function loadSubstrateIds(return result;}+/**+ * Assign a fresh id to every row of every id-bearing table, so a foreign load can+ * rewrite ids and the FKs pointing at them in one pass. Shared by the restore and+ * the reseed/import so the two can't drift.+ *+ * Keyed on having a text/uuid `id` COLUMN, not on `hasId` (PK exactly `id`): ~25+ * Carbon tables key on `("id", "companyId")` yet still carry a global `UNIQUE (id)`+ * so children can FK to them, and gating on `hasId` left their source ids in place —+ * which collides with the source company's own live rows on a cross-company restore.+ * Int/serial ids are still skipped (a nanoid doesn't fit, and the table is wiped+ * first so the original values are free to reuse verbatim).+ *+ * A 1:1 extension table keys itself BY its parent (`purchaseOrderDelivery.id ->+ * purchaseOrder.id`, `partner.id -> supplierLocation.id`), so it SHARES the parent's+ * map rather than minting its own — two independent ids would split the pair and+ * `session_replication_role='replica'` would let the break commit. `tables` must be+ * topologically sorted (parents first); both call sites derive from the sorted catalog.+ */+export function buildIdMaps(+ tables: TableInfo[],+ dataByTable: Record<string, Array<{ [col: string]: unknown }>>+): Map<string, Map<string, string>> {+ const idMaps = new Map<string, Map<string, string>>();+ for (const table of tables) {+ const idType = table.columns.find((c) => c.name === "id")?.udtName;+ if (idType !== "uuid" && idType !== "text") continue;+ const idFk = table.foreignKeys.find(+ (f) => f.column === "id" && f.refColumn === "id"+ );+ if (idFk) {+ // No parent map (`terms.id -> company`, `employeeJob.id -> user`) means the+ // id follows a column transform instead, so leave it unmapped.+ const parent = idMaps.get(idFk.refTable);+ if (parent) idMaps.set(table.name, parent);+ continue;+ }+ const map = new Map<string, string>();+ for (const row of dataByTable[table.name] ?? []) {+ if (typeof row.id === "string") map.set(row.id, newIdForTable(table));+ }+ idMaps.set(table.name, map);+ }+ return idMaps;+}+export type RowTransform = (value: unknown) => unknown;/**diff --git a/packages/jobs/src/inngest/functions/tasks/company-import.ts b/packages/jobs/src/inngest/functions/tasks/company-import.tsindex a0ac78a243..1ded673544 100644--- a/packages/jobs/src/inngest/functions/tasks/company-import.ts+++ b/packages/jobs/src/inngest/functions/tasks/company-import.ts@@ -13,7 +13,6 @@ import {filterUnpopulated,getCompanyTableCatalog,isUserScopedIdentityTable,- newIdForTable,RESEED_SKIPPED_TABLES,readBackup,restoreAssetsFromBackup,@@ -21,6 +20,7 @@ import {} from "./company-backup";import { applyTableRenames } from "./company-backup.renames";import {+ buildIdMaps,buildRowTransforms,loadSubstrateIds} from "./company-backup.transforms";@@ -156,24 +156,13 @@ export const companyImportFunction = inngest.createFunction(): candidateTables;- // Reseed: assign a fresh id to every row of every id-keyed table up- // front so FK references can be rewritten in a single pass.- const idMaps = new Map<string, Map<string, string>>();- if (mode === "reseed") {- for (const table of importTables) {- if (!table.hasId) continue;- // Only text/uuid ids get remapped — an int/serial id can't take a- // nanoid (same gate as the restore path, so the two don't drift).- const idType = table.columns.find((c) => c.name === "id")?.udtName;- if (idType !== "uuid" && idType !== "text") continue;- const map = new Map<string, string>();- for (const row of backup.data[table.name]!) {- if (typeof row.id === "string")- map.set(row.id, newIdForTable(table));- }- idMaps.set(table.name, map);- }- }+ // Reseed: assign a fresh id to every row of every id-bearing table up+ // front so FK references can be rewritten in a single pass. Shares+ // `buildIdMaps` with the restore path so the two can't drift.+ const idMaps =+ mode === "reseed"+ ? buildIdMaps(importTables, backup.data)+ : new Map<string, Map<string, string>>();// Flat old-id → new-id lookup across every remapped table, used to rewrite// ids embedded in storage paths (e.g. `{co}/models/{modelId}.stl`) so thediff --git a/packages/jobs/src/inngest/functions/tasks/company-restore.ts b/packages/jobs/src/inngest/functions/tasks/company-restore.tsindex 1b8515f0ce..11289659bd 100644--- a/packages/jobs/src/inngest/functions/tasks/company-restore.ts+++ b/packages/jobs/src/inngest/functions/tasks/company-restore.ts@@ -14,7 +14,6 @@ import {canSetReplicationRole,getCompanyTableCatalog,isUserScopedIdentityTable,- newIdForTable,RESTORE_INTEGRATION,readBackup,removeStoragePrefix,@@ -27,6 +26,7 @@ import {import { applyTableRenames } from "./company-backup.renames";import {assertReferentiallyClosed,+ buildIdMaps,buildRowTransforms,loadSubstrateIds} from "./company-backup.transforms";@@ -98,24 +98,14 @@ export async function wipeAndLoad(backup.manifest.tables.map((t) => [t.name, new Set(t.columns)]));- // Foreign: assign a fresh id to every id-keyed row up front so FKs (and the- // ids embedded in storage paths) can be rewritten in a single pass. Only remap- // string ids (text/uuid) — integer/serial ids (e.g. `journal`) can't take a- // nanoid, and since the table is wiped first their original ids are free to- // reuse verbatim (FKs to them stay valid by keeping the original value).- const idMaps = new Map<string, Map<string, string>>();+ // Foreign: assign a fresh id to every id-bearing row up front so FKs (and the+ // ids embedded in storage paths) can be rewritten in a single pass. See+ // `buildIdMaps` for what qualifies and why.+ const idMaps = remap+ ? buildIdMaps(loadTables, backup.data)+ : new Map<string, Map<string, string>>();const idRewrite = new Map<string, string>();if (remap) {- for (const t of loadTables) {- if (!t.hasId) continue;- const idType = t.columns.find((c) => c.name === "id")?.udtName;- if (idType !== "uuid" && idType !== "text") continue;- const map = new Map<string, string>();- for (const row of backup.data[t.name]!) {- if (typeof row.id === "string") map.set(row.id, newIdForTable(t));- }- idMaps.set(t.name, map);- }for (const map of idMaps.values()) {for (const [oldId, newId] of map) idRewrite.set(oldId, newId);}