Skip to content

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.

fix: backup exclude transient mrp tables (#954)

Sidc5d04e77e261
diff --git a/.claude/rules/company-backup-restore.md b/.claude/rules/company-backup-restore.md
index 2dae2021dd..efed262c05 100644
--- a/.claude/rules/company-backup-restore.md
+++ b/.claude/rules/company-backup-restore.md
@@ -47,12 +47,26 @@ The catalog is **schema-introspected**, not a hand-maintained list:
- `scopeColumn: "companyId" | "companyGroupId"`. `companyId` = the company's own
data; `companyGroupId` = config shared across a company group (chart of
accounts, currencies, dimensions).
-- Skip/scope sets: `SECRET_TABLES` (`apiKey`, `companyIntegration`, `webhook`,
- `oauthClient`, `oauthToken` — never travel), `STRUCTURAL_TABLES` (`company` —
- excluded from catalog), `RESEED_SKIPPED_TABLES` (memberships/invites/employee/
- externalIntegrationMapping — skipped on onboarding reseed),
- `IN_PLACE_SKIPPED_TABLES` (access/identity tables a restore must keep so the
- user isn't locked out).
+- Skip/scope sets: `SECRET_TABLES` (`apiKey`, `apiKeyRateLimit`,
+ `companyIntegration`, `webhook`, `oauthClient`, `oauthToken` — never travel;
+ `apiKeyRateLimit` is here because its NOT-NULL `apiKeyId` references the stripped
+ secret `apiKey`, so exporting it alone would dangle every row on restore — and
+ it's UNLOGGED operational counters, not user data), `STRUCTURAL_TABLES` (`company` —
+ excluded from catalog), `TRANSIENT_TABLES` (`demandForecastSource`,
+ `demandActual`, `supplyForecast`, `supplyActual` — MRP planning output the
+ `mrp` edge fn regenerates wholesale every run; excluded from the catalog
+ entirely alongside `STRUCTURAL_TABLES`, so they're never exported/wiped/loaded
+ and the next MRP run rebuilds them. `demandForecastSource`'s discriminator
+ CHECK (`sourceType` ↔ which of `jobId`/`salesOrderLineId`/`demandProjectionId`
+ is non-null) made a remapped restore crash — the FK-nulling dangling-ref policy
+ in `buildRowTransforms` nulls a set FK and violates the CHECK. `demandForecast`
+ is deliberately kept: it has a user-forecast write path and no such CHECK. The
+ two excluded sets are unioned into `CATALOG_EXCLUDED_TABLES`, which
+ `assertBackupImportable` also skips — an OLDER backup that still carries an
+ excluded table is not schema drift, its rows are just ignored on load),
+ `RESEED_SKIPPED_TABLES` (memberships/invites/employee/externalIntegrationMapping
+ — skipped on onboarding reseed), `IN_PLACE_SKIPPED_TABLES` (access/identity
+ tables a restore must keep so the user isn't locked out).
- Format: the gz is **NDJSON** — line 1 is `{ manifest }`, every later line is one
`{ t, r }` table row. Written/read a line at a time (`serializeBackup` /
`deserializeBackup` in `company-backup.ts`) so a large backup never materializes
@@ -130,6 +144,13 @@ Forward flow:
`targetGroupId`; on a foreign/remap load it mints new ids (text/uuid only) and
remaps FKs, with a dangling-ref guard (nullable FK → null, non-nullable →
throw).
+ - Closure preflight (`assertReferentiallyClosed` → `findDanglingReferences`)
+ runs before the wipe and refuses a backup whose NOT-NULL FK points at a row
+ it doesn't include. It tracks a parent's ids for **any table with an `id`
+ column**, not only `hasId` (sole-`id` PK) tables — the ~25 composite
+ `("id","companyId")`-PK tables (`stockTransfer`, `supplierPart`, …) are
+ referenced by their `id` too, and gating on `hasId` falsely flagged every
+ child of them and refused otherwise-valid restores.
5. `restoreAssetsFromBackup` (outside the txn, non-transactional) copies the files
from the backup's `.assets/` folder back to `private/<rewritten path>`,
server-side. It runs **before** the `ready` marker (step below) so the progress
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
index 4d5c62eb0f..ce30026e7b 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
@@ -138,6 +138,37 @@ describe("findDanglingReferences", () => {
expect(findDanglingReferences(cat, data, substrate)).toEqual([]);
});
+ it("resolves a FK into a composite-PK parent (`(id, companyId)`, hasId=false)", () => {
+ // ~25 Carbon tables key on a composite ("id", "companyId") PK (stockTransfer,
+ // supplierPart, …) so `hasId` is false. Their `id` is still the referenced
+ // column, so their rows MUST be tracked — gating on `hasId` left them
+ // untracked and falsely flagged every child as dangling, refusing the
+ // restore of an otherwise self-contained backup.
+ const stockTransfer = table(
+ "stockTransfer",
+ [col("id"), col("companyId")],
+ [],
+ { pkColumns: ["id", "companyId"] }
+ );
+ const stockTransferLine = table(
+ "stockTransferLine",
+ [col("id"), col("stockTransferId"), col("companyId")],
+ [fk("stockTransferId", "stockTransfer")],
+ { pkColumns: ["id", "companyId"] }
+ );
+ expect(stockTransfer.hasId).toBe(false);
+ const result = findDanglingReferences(
+ catalog([stockTransfer, stockTransferLine]),
+ {
+ stockTransfer: [{ id: "st1", companyId: "c1" }],
+ stockTransferLine: [
+ { id: "stl1", stockTransferId: "st1", companyId: "c1" }
+ ]
+ }
+ );
+ expect(result).toEqual([]);
+ });
+
it("still flags a missing NOT-NULL FK into an ordinary company table (revert did not loosen general closure)", () => {
// A non-reference company table (item) is NOT in the deferral set, so a
// dangling NOT-NULL ref to it is a fatal closure gap, as before.
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts
index 8e94f298c2..0f28dffa1a 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts
@@ -52,7 +52,13 @@ export function findDanglingReferences(
const catalogNames = new Set(catalog.tables.map((t) => t.name));
const idsByTable = new Map<string, Set<unknown>>();
for (const t of catalog.tables) {
- if (!t.hasId) continue;
+ // FKs are only ever checked against `refColumn === "id"` below, so any table
+ // with an `id` column can be a referenced parent — NOT only those whose PK is
+ // exactly `id` (`hasId`). Most Carbon tables key on `id` alone, but ~25 use a
+ // composite `("id", "companyId")` PK (stockTransfer, supplierPart, …); gating
+ // on `hasId` left those untracked, so every child row pointing at them was
+ // falsely reported as dangling and refused the restore.
+ if (!t.columns.some((c) => c.name === "id")) continue;
const ids = new Set<unknown>();
for (const row of dataByTable[t.name] ?? []) ids.add(row.id);
idsByTable.set(t.name, ids);
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
index 2f4193d61f..644a6b389e 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
@@ -122,6 +122,10 @@ export function rewriteStoragePath(
*/
export const SECRET_TABLES = [
"apiKey",
+ // Worthless without its (secret, stripped) apiKey, which it references via a
+ // NOT-NULL FK — exporting it alone dangles every row on restore. It's also an
+ // UNLOGGED operational rate-limit counter, never user data.
+ "apiKeyRateLimit",
"companyIntegration",
"webhook",
"oauthClient",
@@ -150,6 +154,36 @@ export const COMPANY_SINGLETON_TABLES = [
*/
export const STRUCTURAL_TABLES = ["company"];
+/**
+ * MRP planning output — the `mrp` edge function deletes then re-inserts these
+ * wholesale per company on every run, and nothing else writes them. They hold
+ * no user-authored data, so a backup must not carry them: restoring stale
+ * projections is pure bloat (the next MRP run rebuilds them), and
+ * `demandForecastSource`'s discriminator CHECK (`sourceType` ↔ which FK is
+ * non-null) makes a remapped restore brittle — the FK-nulling dangling-ref
+ * policy silently violates it. Excluded from the catalog entirely, so they are
+ * never exported, wiped, or loaded. (`demandForecast` is deliberately NOT here:
+ * it also has a user-forecast write path and carries no such CHECK.)
+ */
+export const TRANSIENT_TABLES = [
+ "demandForecastSource",
+ "demandActual",
+ "supplyForecast",
+ "supplyActual"
+] as const satisfies readonly TableName[];
+
+/**
+ * Tables deliberately kept out of the catalog: the company shell + MRP planning
+ * output. The catalog skips them so they're never exported/wiped/loaded, and
+ * `assertBackupImportable` skips them too — an older backup that still carries
+ * one of these (made before it was excluded) is NOT schema drift; its rows are
+ * simply ignored on load (the next MRP run rebuilds the data).
+ */
+export const CATALOG_EXCLUDED_TABLES = new Set<string>([
+ ...STRUCTURAL_TABLES,
+ ...TRANSIENT_TABLES
+]);
+
/**
* Additional tables skipped in `reseed` mode — memberships, invites and
* integration state belong to the source company's users, not to a copy.
@@ -465,7 +499,9 @@ export async function getCompanyTableCatalog(
`.execute(db);
// companyId wins when a table carries both columns.
- const structural = new Set(STRUCTURAL_TABLES);
+ // Excluded from the catalog entirely: the company shell + MRP planning output
+ // (regenerated every run, never user data — see CATALOG_EXCLUDED_TABLES).
+ const structural = CATALOG_EXCLUDED_TABLES;
const scopeByTable = new Map<string, "companyId" | "companyGroupId">();
for (const r of scopeRows.rows) {
if (structural.has(r.name)) continue;
@@ -700,6 +736,9 @@ export function assertBackupImportable(
const liveByName = new Map(catalog.tables.map((t) => [t.name, t]));
for (const backupTable of manifest.tables) {
+ // A backup table the catalog now excludes by design (MRP output, the company
+ // shell) is not schema drift — skip it; its rows are ignored on load.
+ if (CATALOG_EXCLUDED_TABLES.has(backupTable.name)) continue;
const live = liveByName.get(backupTable.name);
if (!live) {
return {