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.

refactor: extract the schema/compat logic so the drift check needs no logger

Sidwebworks449cf93702da
diff --git a/.claude/rules/company-backup-restore.md b/.claude/rules/company-backup-restore.md
index 36617c04f4..b0d2d404fa 100644
--- a/.claude/rules/company-backup-restore.md
+++ b/.claude/rules/company-backup-restore.md
@@ -282,7 +282,7 @@ honest reading is that this pair catches the whole class of *structural* breakag
a table or column the backup has nothing to say about — and that the *value*-shaped
breakage is what `RestoreDisclosure` and the snapshot-and-revert path exist for.
-### Renamed and dropped tables — `company-backup.renames.ts`
+### Renamed and dropped tables — `src/backups/renames.ts`
`TABLE_RENAMES` maps a tenant-scoped table's OLD name to its current one, or to `null`
when it was dropped along with its feature. "Tenant-scoped" here means anything in the
diff --git a/.claude/rules/workflow-database-migration.md b/.claude/rules/workflow-database-migration.md
index 92bbb833d7..ccff90c143 100644
--- a/.claude/rules/workflow-database-migration.md
+++ b/.claude/rules/workflow-database-migration.md
@@ -88,7 +88,7 @@ newest migrations, e.g. `20260609143732_document-template.sql`):
If the migration **renames or drops any table that appears in a company backup**, add an
entry to `TABLE_RENAMES` in
-`packages/jobs/src/inngest/functions/tasks/company-backup.renames.ts` in the SAME commit:
+`packages/jobs/src/backups/renames.ts` in the SAME commit:
the new name for a rename, `null` for a table dropped along with its feature.
That is more tables than it sounds: the catalog scopes a table either DIRECTLY (its own
@@ -130,6 +130,6 @@ alone, `pnpm db:types`. **Do NOT run `npm run db:build` — it does not exist.**
`get_companies_with_employee_role()`, writes via
`get_companies_with_employee_permission('<module>_<action>')`)
- [ ] Renamed/dropped a tenant-scoped table? `TABLE_RENAMES` entry added
- (`company-backup.renames.ts`) — new name, or `null` if dropped with its feature
+ (`packages/jobs/src/backups/renames.ts`) — new name, or `null` if dropped with its feature
- [ ] Zod validators updated in `{module}.models.ts`
- [ ] Applied locally with `pnpm db:migrate` (regenerates types) — never `db:build`
diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.md
index 2a028c1d7e..a402f91c58 100644
--- a/packages/jobs/AGENTS.md
+++ b/packages/jobs/AGENTS.md
@@ -47,8 +47,12 @@ read-only. See `manifests/README.md` and `.claude/rules/company-backup-restore.m
Scripts under `src/scripts/` run through bare `tsx`, which does NOT paper over CJS/ESM interop the
way Vite and vitest do. A **named** import of a workspace package that lacks `"type": "module"`
-(`@carbon/database`, `@carbon/utils`) throws `does not provide an export named …` at run time even
-though it typechecks. Import types only from those, or use a package that has it.
+(`@carbon/database`, `@carbon/utils`, `@carbon/logger`) throws `does not provide an export named …`
+at run time even though it typechecks. The fix is to keep a script's runtime import chain free of
+those packages (type-only imports are fine — they erase) — never to flip a shared package's `type`
+field for one script. That is exactly why the catalog/compatibility logic lives in
+`src/backups/schema.ts` with no runtime `@carbon/*` imports, instead of in `company-backup.ts`
+(whose module-scope `getLogger` would drag `@carbon/logger` into the script).
## Key Exports
diff --git a/packages/jobs/src/backups/exportable.test.ts b/packages/jobs/src/backups/exportable.test.ts
new file mode 100644
index 0000000000..f306dfe925
--- /dev/null
+++ b/packages/jobs/src/backups/exportable.test.ts
@@ -0,0 +1,136 @@
+import { describe, expect, it } from "vitest";
+import type { Catalog, ColumnInfo, TableInfo } from "./schema";
+import {
+ exportableColumns,
+ SECRET_TABLES,
+ selectExportableTables
+} from "./schema";
+
+const col = (name: string, over: Partial<ColumnInfo> = {}): ColumnInfo => ({
+ name,
+ dataType: "text",
+ udtName: "text",
+ isNullable: false,
+ isGenerated: false,
+ hasDefault: false,
+ ...over
+});
+
+const table = (
+ name: string,
+ columns: ColumnInfo[] = [col("id")]
+): TableInfo => ({
+ name,
+ columns,
+ scope: { kind: "direct", column: "companyId" },
+ scopeColumn: "companyId",
+ pkColumns: ["id", "companyId"],
+ uniqueColumns: [],
+ hasId: false,
+ foreignKeys: []
+});
+
+const catalog = (tables: TableInfo[]): Catalog => ({
+ schemaVersion: "20260825075035",
+ tables
+});
+
+describe("selectExportableTables", () => {
+ it("splits the catalog into what travels and what does not", () => {
+ const { exportable, excludedTables } = selectExportableTables(
+ catalog([table("job"), table("apiKey"), table("item")])
+ );
+ expect(exportable.map((t) => t.name)).toEqual(["job", "item"]);
+ expect(excludedTables).toEqual(["apiKey"]);
+ });
+
+ it("excludes every secret table", () => {
+ const { exportable, excludedTables } = selectExportableTables(
+ catalog(SECRET_TABLES.map((name) => table(name)))
+ );
+ expect(exportable).toEqual([]);
+ expect(excludedTables).toEqual(SECRET_TABLES);
+ });
+
+ // The old duplicated copy in check-backups.ts listed the whole SECRET_TABLES
+ // constant regardless of the catalog, which would name a table the backup was
+ // never going to contain.
+ it("only reports secret tables that are actually in the catalog", () => {
+ const { excludedTables } = selectExportableTables(
+ catalog([table("job"), table("webhook")])
+ );
+ expect(excludedTables).toEqual(["webhook"]);
+ });
+
+ it("preserves catalog order, which is topological", () => {
+ const { exportable } = selectExportableTables(
+ catalog([table("company"), table("job"), table("jobOperation")])
+ );
+ expect(exportable.map((t) => t.name)).toEqual([
+ "company",
+ "job",
+ "jobOperation"
+ ]);
+ });
+
+ it("returns empty lists for an empty catalog", () => {
+ expect(selectExportableTables(catalog([]))).toEqual({
+ exportable: [],
+ excludedTables: []
+ });
+ });
+});
+
+describe("exportableColumns", () => {
+ it("drops generated columns, which the database recomputes on load", () => {
+ const t = table("job", [
+ col("id"),
+ col("total", { isGenerated: true }),
+ col("companyId")
+ ]);
+ expect(exportableColumns(t).map((c) => c.name)).toEqual([
+ "id",
+ "companyId"
+ ]);
+ });
+
+ it("keeps nullable and defaulted columns — only generated ones are dropped", () => {
+ const t = table("job", [
+ col("id"),
+ col("notes", { isNullable: true }),
+ col("status", { hasDefault: true })
+ ]);
+ expect(exportableColumns(t)).toHaveLength(3);
+ });
+});
+
+// The reason both helpers exist: the drift check's baseline must describe what a
+// real export produces. If these ever diverge, the baseline stops standing in for
+// a customer's backup while the check keeps reporting `restorable`.
+describe("the baseline and the exporter share one rule", () => {
+ it("produces the same tables and columns for the same catalog", () => {
+ const source = catalog([
+ table("job", [col("id"), col("total", { isGenerated: true })]),
+ table("apiKey", [col("id")]),
+ table("item", [col("id"), col("name")])
+ ]);
+
+ const exporterView = selectExportableTables(source).exportable.map((t) => ({
+ name: t.name,
+ columns: exportableColumns(t).map((c) => c.name)
+ }));
+ const baselineView = selectExportableTables(source).exportable.map((t) => ({
+ name: t.name,
+ rows: 0,
+ columns: exportableColumns(t).map((c) => c.name)
+ }));
+
+ expect(
+ baselineView.map(({ name, columns }) => ({ name, columns }))
+ ).toEqual(exporterView);
+ expect(baselineView).toEqual([
+ { name: "job", rows: 0, columns: ["id"] },
+ { name: "item", rows: 0, columns: ["id", "name"] }
+ ]);
+ });
+});
diff --git a/packages/jobs/src/backups/renames.test.ts b/packages/jobs/src/backups/renames.test.ts
new file mode 100644
index 0000000000..a1e54fa769
--- /dev/null
+++ b/packages/jobs/src/backups/renames.test.ts
@@ -0,0 +1,119 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { applyTableRenames, TABLE_RENAMES } from "./renames";
+
+const catalog = (...names: string[]) => ({
+ tables: names.map((name) => ({ name }))
+});
+
+const backup = (tables: Record<string, number>) => ({
+ manifest: {
+ tables: Object.entries(tables).map(([name, rows]) => ({
+ name,
+ rows,
+ columns: ["id", "companyId"]
+ }))
+ },
+ data: Object.fromEntries(
+ Object.entries(tables).map(([name, rows]) => [
+ name,
+ Array.from({ length: rows }, (_, i) => ({ id: `${name}-${i}` }))
+ ])
+ )
+});
+
+const names = (b: ReturnType<typeof applyTableRenames>) => ({
+ manifest: b.manifest.tables.map((t) => t.name).sort(),
+ data: Object.keys(b.data).sort()
+});
+
+// TABLE_RENAMES is a live constant the whole repo shares; mutate and restore.
+const withRenames = (entries: Record<string, string | null>) => {
+ Object.assign(TABLE_RENAMES, entries);
+};
+afterEach(() => {
+ for (const k of Object.keys(TABLE_RENAMES)) delete TABLE_RENAMES[k];
+});
+
+describe("applyTableRenames", () => {
+ it("leaves a backup alone when every table still exists", () => {
+ const out = applyTableRenames(
+ catalog("job", "quote"),
+ backup({ job: 2, quote: 1 })
+ );
+ expect(names(out)).toEqual({
+ manifest: ["job", "quote"],
+ data: ["job", "quote"]
+ });
+ });
+
+ it("moves a renamed table's rows onto the new name", () => {
+ withRenames({ quoteLine: "quotationLine" });
+ const out = applyTableRenames(
+ catalog("quotationLine"),
+ backup({ quoteLine: 3 })
+ );
+ expect(names(out)).toEqual({
+ manifest: ["quotationLine"],
+ data: ["quotationLine"]
+ });
+ expect(out.data.quotationLine).toHaveLength(3);
+ expect(out.manifest.tables[0]!.rows).toBe(3);
+ });
+
+ it("drops a table mapped to null, rows and all", () => {
+ withRenames({ oldFeature: null });
+ const out = applyTableRenames(
+ catalog("job"),
+ backup({ job: 1, oldFeature: 5 })
+ );
+ expect(names(out)).toEqual({ manifest: ["job"], data: ["job"] });
+ });
+
+ it("leaves an UNMAPPED missing table in place so the gate refuses it", () => {
+ const out = applyTableRenames(
+ catalog("job"),
+ backup({ job: 1, vanished: 2 })
+ );
+ expect(names(out)).toEqual({
+ manifest: ["job", "vanished"],
+ data: ["job", "vanished"]
+ });
+ });
+
+ it("leaves it in place when the mapping points at a table that is also gone", () => {
+ withRenames({ a: "b" });
+ const out = applyTableRenames(catalog("job"), backup({ a: 1 }));
+ expect(names(out)).toEqual({ manifest: ["a"], data: ["a"] });
+ });
+
+ it("ignores a stale mapping once the old name is back — the A→B→A cycle", () => {
+ // Both entries are present after renaming A→B and then B→A.
+ withRenames({ a: "b", b: "a" });
+ const out = applyTableRenames(catalog("a"), backup({ a: 4 }));
+ expect(names(out)).toEqual({ manifest: ["a"], data: ["a"] });
+ expect(out.data.a).toHaveLength(4);
+ });
+
+ it("reads a mid-cycle backup (taken while the table was B) back into A", () => {
+ withRenames({ a: "b", b: "a" });
+ const out = applyTableRenames(catalog("a"), backup({ b: 4 }));
+ expect(names(out)).toEqual({ manifest: ["a"], data: ["a"] });
+ expect(out.data.a).toHaveLength(4);
+ });
+
+ it("refuses to merge when the backup carries BOTH names", () => {
+ withRenames({ a: "b" });
+ const out = applyTableRenames(catalog("b"), backup({ a: 1, b: 2 }));
+ // `a` is left unresolved rather than folded into `b` — the gate then refuses.
+ expect(names(out)).toEqual({ manifest: ["a", "b"], data: ["a", "b"] });
+ expect(out.data.b).toHaveLength(2);
+ });
+
+ it("does not mutate the backup it was given", () => {
+ withRenames({ quoteLine: "quotationLine" });
+ const input = backup({ quoteLine: 1 });
+ applyTableRenames(catalog("quotationLine"), input);
+ expect(Object.keys(input.data)).toEqual(["quoteLine"]);
+ expect(input.manifest.tables[0]!.name).toBe("quoteLine");
+ });
+});
diff --git a/packages/jobs/src/backups/renames.ts b/packages/jobs/src/backups/renames.ts
new file mode 100644
index 0000000000..45284492b0
--- /dev/null
+++ b/packages/jobs/src/backups/renames.ts
@@ -0,0 +1,59 @@
+/**
+ * Tenant-scoped tables that have been RENAMED or DROPPED, so an older backup
+ * naming them can still be read. A migration that renames or drops a
+ * tenant-scoped table MUST add an entry here in the same commit: the new name
+ * for a rename, `null` for a table dropped with its feature.
+ *
+ * The schema alone cannot tell those two apart, and guessing "dropped" when it
+ * was a rename silently discards a customer's rows while reporting success —
+ * so an unmapped missing table refuses the restore and names itself.
+ *
+ * Starts EMPTY on purpose: a wrong historical mapping is worse than none.
+ */
+export const TABLE_RENAMES: Record<string, string | null> = {};
+
+/**
+ * Move a just-read backup's tables onto their CURRENT names. Runs once, right
+ * after `readBackup`, so the gate, the closure preflight and `wipeAndLoad` all
+ * agree on what the backup contains.
+ */
+export function applyTableRenames<
+ T extends {
+ manifest: {
+ tables: Array<{ name: string; rows: number; columns: string[] }>;
+ };
+ data: Record<string, Record<string, unknown>[]>;
+ }
+>(catalog: { tables: Array<{ name: string }> }, backup: T): T {
+ const live = new Set(catalog.tables.map((t) => t.name));
+
+ // Only consulted for a name the schema no longer has, which is what makes a
+ // rename cycle (A→B→A) safe: the stale `A: "B"` entry is never read.
+ const resolve = (name: string): string | null => {
+ if (live.has(name)) return name;
+ const mapped = TABLE_RENAMES[name];
+ if (mapped === null) return null;
+ // Can't resolve confidently — leave it for the gate to refuse by name.
+ if (mapped === undefined || !live.has(mapped) || backup.data[mapped]) {
+ return name;
+ }
+ return mapped;
+ };
+
+ const tables: typeof backup.manifest.tables = [];
+ const data: Record<string, Record<string, unknown>[]> = { ...backup.data };
+ for (const t of backup.manifest.tables) {
+ const to = resolve(t.name);
+ if (to === null) {
+ delete data[t.name];
+ continue;
+ }
+ tables.push(to === t.name ? t : { ...t, name: to });
+ if (to !== t.name && backup.data[t.name]) {
+ data[to] = backup.data[t.name]!;
+ delete data[t.name];
+ }
+ }
+
+ return { ...backup, manifest: { ...backup.manifest, tables }, data };
+}
diff --git a/packages/jobs/src/backups/schema.test.ts b/packages/jobs/src/backups/schema.test.ts
new file mode 100644
index 0000000000..7dc86f38ff
--- /dev/null
+++ b/packages/jobs/src/backups/schema.test.ts
@@ -0,0 +1,350 @@
+import { describe, expect, it, vi } from "vitest";
+import { assertBackupImportable } from "../inngest/functions/tasks/company-backup";
+import {
+ BACKUP_KIND,
+ BACKUP_VERSION,
+ type Catalog,
+ type ColumnInfo,
+ type Manifest,
+ reportBackupCompatibility,
+ type TableInfo
+} from "./schema";
+
+vi.mock("./renames", () => ({
+ // A dropped table, a renamed table, and a rename whose target is also gone.
+ TABLE_RENAMES: {
+ retiredFeature: null,
+ oldName: "newName",
+ danglingRename: "alsoMissing"
+ }
+}));
+
+const col = (name: string, opts: Partial<ColumnInfo> = {}): ColumnInfo => ({
+ name,
+ dataType: "text",
+ udtName: "text",
+ isNullable: false,
+ isGenerated: false,
+ hasDefault: false,
+ ...opts
+});
+
+const table = (name: string, columns: ColumnInfo[]): TableInfo => ({
+ name,
+ columns,
+ scope: { kind: "direct", column: "companyId" },
+ scopeColumn: "companyId",
+ pkColumns: ["id", "companyId"],
+ uniqueColumns: [],
+ hasId: false,
+ foreignKeys: []
+});
+
+const catalog = (tables: TableInfo[]): Catalog => ({
+ schemaVersion: "test",
+ tables
+});
+
+function backup(
+ tables: Manifest["tables"],
+ opts: { version?: number } = {}
+): Manifest {
+ return {
+ kind: BACKUP_KIND,
+ version: (opts.version ?? BACKUP_VERSION) as typeof BACKUP_VERSION,
+ schemaVersion: "test",
+ sourceCompanyId: "company-a",
+ sourceCompanyGroupId: "group-a",
+ sourceCompanyName: "Acme",
+ exportedAt: "2026-02-01T00:00:00.000Z",
+ exportedBy: "user-1",
+ label: null,
+ includeStorage: "none",
+ tables,
+ storage: [],
+ excludedTables: []
+ };
+}
+
+describe("reportBackupCompatibility", () => {
+ it("reports nothing when the schema has not moved", () => {
+ const result = reportBackupCompatibility(
+ catalog([table("item", [col("id"), col("name")])]),
+ backup([{ name: "item", rows: 3, columns: ["id", "name"] }])
+ );
+
+ expect(result.findings).toEqual([]);
+ expect(result.blocked).toBe(false);
+ });
+
+ it("reports a new required column WITH a default as defaulted, not blocked", () => {
+ const result = reportBackupCompatibility(
+ catalog([
+ table("item", [col("id"), col("unitOfMeasure", { hasDefault: true })])
+ ]),
+ backup([{ name: "item", rows: 1, columns: ["id"] }])
+ );
+
+ expect(result.blocked).toBe(false);
+ expect(result.findings).toHaveLength(1);
+ expect(result.findings[0]).toMatchObject({
+ kind: "defaulted",
+ table: "item",
+ column: "unitOfMeasure"
+ });
+ });
+
+ it("blocks a new required column with NO default", () => {
+ // This is the branch the D1 conformance check makes unreachable for new
+ // migrations; existing backups can still hit it.
+ const result = reportBackupCompatibility(
+ catalog([table("item", [col("id"), col("unitOfMeasure")])]),
+ backup([{ name: "item", rows: 1, columns: ["id"] }])
+ );
+
+ expect(result.blocked).toBe(true);
+ expect(result.findings[0]).toMatchObject({
+ kind: "blocked",
+ table: "item",
+ column: "unitOfMeasure"
+ });
+ });
+
+ it("ignores a new NULLABLE column — routine additive growth, not a finding", () => {
+ const result = reportBackupCompatibility(
+ catalog([table("item", [col("id"), col("notes", { isNullable: true })])]),
+ backup([{ name: "item", rows: 1, columns: ["id"] }])
+ );
+
+ expect(result.findings).toEqual([]);
+ });
+
+ it("reports a column the backup has but the schema no longer does as discarded", () => {
+ const result = reportBackupCompatibility(
+ catalog([table("item", [col("id")])]),
+ backup([{ name: "item", rows: 1, columns: ["id", "legacyCode"] }])
+ );
+
+ expect(result.blocked).toBe(false);
+ expect(result.findings[0]).toMatchObject({
+ kind: "discarded",
+ table: "item",
+ column: "legacyCode"
+ });
+ });
+
+ it("blocks an unsupported format generation", () => {
+ const result = reportBackupCompatibility(
+ catalog([table("item", [col("id")])]),
+ backup([{ name: "item", rows: 1, columns: ["id"] }], { version: 0 })
+ );
+
+ expect(result.blocked).toBe(true);
+ expect(result.findings[0]?.reason).toContain("no longer supported");
+ });
+
+ it("blocks account defaults arriving without a chart of accounts", () => {
+ // An empty table is omitted from the manifest, so "no account entry" is how a
+ // groupless export's missing chart of accounts actually presents.
+ const result = reportBackupCompatibility(
+ catalog([table("accountDefault", [col("id")])]),
+ backup([{ name: "accountDefault", rows: 1, columns: ["id"] }])
+ );
+
+ expect(result.blocked).toBe(true);
+ expect(result.findings[0]?.table).toBe("accountDefault");
+ });
+
+ it("allows account defaults when the chart of accounts travels with them", () => {
+ const result = reportBackupCompatibility(
+ catalog([
+ table("accountDefault", [col("id")]),
+ table("account", [col("id")])
+ ]),
+ backup([
+ { name: "accountDefault", rows: 1, columns: ["id"] },
+ { name: "account", rows: 40, columns: ["id"] }
+ ])
+ );
+
+ expect(result.blocked).toBe(false);
+ });
+
+ it("skips a table the catalog now excludes by design", () => {
+ // MRP output the next run regenerates — absent by design, not drift.
+ const result = reportBackupCompatibility(
+ catalog([table("item", [col("id")])]),
+ backup([
+ { name: "item", rows: 1, columns: ["id"] },
+ { name: "demandActual", rows: 5, columns: ["id"] }
+ ])
+ );
+
+ expect(result.findings).toEqual([]);
+ });
+});
+
+describe("reportBackupCompatibility — TABLE_RENAMES", () => {
+ it("blocks a missing table with no mapping, and says so", () => {
+ const result = reportBackupCompatibility(
+ catalog([table("item", [col("id")])]),
+ backup([{ name: "vanished", rows: 2, columns: ["id"] }])
+ );
+
+ expect(result.blocked).toBe(true);
+ expect(result.findings[0]?.reason).toContain("no rename mapping");
+ });
+
+ it("treats a null mapping as dropped with its feature — discarded, not blocked", () => {
+ const result = reportBackupCompatibility(
+ catalog([table("item", [col("id")])]),
+ backup([{ name: "retiredFeature", rows: 2, columns: ["id"] }])
+ );
+
+ expect(result.blocked).toBe(false);
+ expect(result.findings[0]).toMatchObject({
+ kind: "discarded",
+ table: "retiredFeature"
+ });
+ });
+
+ it("follows a rename to the new table and compares columns there", () => {
+ const result = reportBackupCompatibility(
+ catalog([table("newName", [col("id"), col("name")])]),
+ backup([{ name: "oldName", rows: 2, columns: ["id", "name"] }])
+ );
+
+ expect(result.findings).toEqual([]);
+ expect(result.blocked).toBe(false);
+ });
+
+ it("blocks when the rename target is also missing", () => {
+ const result = reportBackupCompatibility(
+ catalog([table("item", [col("id")])]),
+ backup([{ name: "danglingRename", rows: 2, columns: ["id"] }])
+ );
+
+ expect(result.blocked).toBe(true);
+ expect(result.findings[0]?.reason).toContain("alsoMissing");
+ });
+});
+
+// The gate is the boolean form of the report and delegates to it. These pin that
+// the delegation refuses exactly the `blocked` findings and nothing else — the
+// report's `discarded`/`defaulted` findings must NOT stop a restore.
+describe("assertBackupImportable", () => {
+ const gate = (cat: Catalog, mf: Manifest) =>
+ assertBackupImportable(cat, { manifest: mf, data: {} });
+
+ it("passes a backup the schema has not moved away from", () => {
+ expect(
+ gate(
+ catalog([table("item", [col("id"), col("name")])]),
+ backup([{ name: "item", rows: 3, columns: ["id", "name"] }])
+ )
+ ).toEqual({ ok: true });
+ });
+
+ it("refuses an unsupported backup format", () => {
+ const result = gate(
+ catalog([table("item", [col("id")])]),
+ backup([{ name: "item", rows: 1, columns: ["id"] }], { version: 0 })
+ );
+ expect(result.ok).toBe(false);
+ expect((result as { reason: string }).reason).toContain(
+ "is no longer supported"
+ );
+ });
+
+ it("refuses a table the schema no longer has and cannot map", () => {
+ const result = gate(
+ catalog([table("item", [col("id")])]),
+ backup([{ name: "vanished", rows: 1, columns: ["id"] }])
+ );
+ expect(result.ok).toBe(false);
+ expect((result as { reason: string }).reason).toContain("vanished");
+ });
+
+ it("refuses a new required column with no default, naming table and column", () => {
+ const result = gate(
+ catalog([table("item", [col("id"), col("mandatory")])]),
+ backup([{ name: "item", rows: 1, columns: ["id"] }])
+ );
+ expect(result).toEqual({
+ ok: false,
+ reason:
+ '"item" now requires column "mandatory", which this backup predates'
+ });
+ });
+
+ it("REFUSES a rename whose target the backup also carries", () => {
+ // Applying the rename would merge two tables; the loader keys off name, so
+ // letting it through drops oldName's rows in silence.
+ const result = gate(
+ catalog([table("newName", [col("id")])]),
+ backup([
+ { name: "oldName", rows: 2, columns: ["id"] },
+ { name: "newName", rows: 5, columns: ["id"] }
+ ])
+ );
+ expect(result.ok).toBe(false);
+ expect((result as { reason: string }).reason).toContain(
+ "which this backup also contains"
+ );
+ });
+
+ it("ACCEPTS a renamed table, the case the hand-kept copy used to refuse", () => {
+ expect(
+ gate(
+ catalog([table("newName", [col("id")])]),
+ backup([{ name: "oldName", rows: 2, columns: ["id"] }])
+ )
+ ).toEqual({ ok: true });
+ });
+
+ it("accepts a dropped-with-its-feature table — discarded is not blocking", () => {
+ expect(
+ gate(
+ catalog([table("item", [col("id")])]),
+ backup([
+ { name: "item", rows: 1, columns: ["id"] },
+ { name: "retiredFeature", rows: 9, columns: ["id"] }
+ ])
+ )
+ ).toEqual({ ok: true });
+ });
+
+ it("accepts a removed column — those values are discarded, not blocking", () => {
+ expect(
+ gate(
+ catalog([table("item", [col("id")])]),
+ backup([{ name: "item", rows: 1, columns: ["id", "goneNow"] }])
+ )
+ ).toEqual({ ok: true });
+ });
+
+ it("accepts a new required column that has a default", () => {
+ expect(
+ gate(
+ catalog([
+ table("item", [col("id"), col("added", { hasDefault: true })])
+ ]),
+ backup([{ name: "item", rows: 1, columns: ["id"] }])
+ )
+ ).toEqual({ ok: true });
+ });
+
+ it("refuses account defaults arriving without a chart of accounts", () => {
+ const result = gate(
+ catalog([
+ table("account", [col("id")]),
+ table("accountDefault", [col("id")])
+ ]),
+ backup([{ name: "accountDefault", rows: 4, columns: ["id"] }])
+ );
+ expect(result.ok).toBe(false);
+ expect((result as { reason: string }).reason).toContain(
+ "no chart of accounts"
+ );
+ });
+});
diff --git a/packages/jobs/src/backups/schema.ts b/packages/jobs/src/backups/schema.ts
new file mode 100644
index 0000000000..1a1376b7f8
--- /dev/null
+++ b/packages/jobs/src/backups/schema.ts
@@ -0,0 +1,574 @@
+import type { TableName } from "@carbon/database/audit.config";
+import type { KyselyDatabase } from "@carbon/database/client";
+import { type Kysely, sql } from "kysely";
+import { TABLE_RENAMES } from "./renames";
+
+/**
+ * Schema introspection + backup-compatibility logic, shared by the backup jobs
+ * (`../inngest/functions/tasks/company-backup.ts`), the commit-time drift check
+ * (`../scripts/check-backups.ts`) and the ERP Backups page (via the
+ * `@carbon/jobs/backups` export).
+ *
+ * Keep this module free of runtime `@carbon/*` imports (type-only is fine) —
+ * the drift check runs under bare `tsx`, which cannot named-import CJS
+ * workspace packages, and the ERP imports it into a Vite server build.
+ */
+
+export const BACKUP_KIND = "carbon-company-backup";
+export const BACKUP_VERSION = 1;
+
+/**
+ * Tables whose contents must never travel in a backup — credentials,
+ * integration tokens and webhook targets stay with the source company.
+ * (`apiKeyRateLimit` dangles without its stripped `apiKey` and is an UNLOGGED
+ * operational counter, never user data.)
+ */
+export const SECRET_TABLES = [
+ "apiKey",
+ "apiKeyRateLimit",
+ "companyIntegration",
+ "webhook",
+ "oauthClient",
+ "oauthToken"
+];
+
+/**
+ * Company-singleton config tables: one row per company, keyed by `id` (the
+ * row's `id` IS the company id via an `id -> company` FK), no `companyId`
+ * column. `companyPlan` is deliberately absent — billing identity never travels.
+ */
+export const COMPANY_SINGLETON_TABLES = [
+ "companySettings",
+ "terms",
+ "companyAccountsPayableBillingAddress",
+ "companyAccountsReceivableBillingAddress"
+] as const satisfies readonly TableName[];
+
+/** The company shell itself — created by onboarding, never imported. */
+export const STRUCTURAL_TABLES = ["company"];
+
+/**
+ * MRP planning output, regenerated wholesale every run. Restoring stale
+ * projections is bloat, and `demandForecastSource`'s discriminator CHECK breaks
+ * under the FK-nulling dangling-ref policy on a remapped restore.
+ * (`demandForecast` stays: it has a user-forecast write path and no such CHECK.)
+ */
+export const TRANSIENT_TABLES = [
+ "demandForecastSource",
+ "demandActual",
+ "supplyForecast",
+ "supplyActual"
+] as const satisfies readonly TableName[];
+
+/**
+ * Excluded from the catalog entirely — never exported, wiped, or loaded. An
+ * older backup still carrying one is not schema drift; its rows are ignored.
+ */
+export const CATALOG_EXCLUDED_TABLES = new Set<string>([
+ ...STRUCTURAL_TABLES,
+ ...TRANSIENT_TABLES
+]);
+
+export type ColumnInfo = {
+ name: string;
+ /** information_schema data_type, e.g. 'ARRAY', 'jsonb', 'USER-DEFINED' */
+ dataType: string;
+ /** information_schema udt_name, e.g. '_text', 'jsonb', 'bytea' */
+ udtName: string;
+ isNullable: boolean;
+ /** GENERATED ALWAYS / identity columns — excluded from export & insert */
+ isGenerated: boolean;
+ hasDefault: boolean;
+};
+
+export type ForeignKey = {
+ column: string;
+ refTable: string;
+ refColumn: string;
+};
+
+/**
+ * How a table's rows are scoped to a company:
+ * - `direct`: the table has a scope column (`companyId`/`companyGroupId`, or
+ * `id` for a company-singleton).
+ * - `via`: no scope column, but a FK to a scoped table (possibly transitive) —
+ * e.g. `customerContact.customerId → customer`. Resolved from the FK graph so
+ * child tables travel with their parent without a hand-maintained list.
+ */
+export type Scope =
+ | { kind: "direct"; column: "companyId" | "companyGroupId" | "id" }
+ | { kind: "via"; column: string; refColumn: string; parent: string };
+
+export type TableInfo = {
+ name: string;
+ columns: ColumnInfo[];
+ scope: Scope;
+ /**
+ * The resolved ROOT tenant column — `companyId` for most data,
+ * `companyGroupId` for shared config. For a `via` table, the root ancestor's.
+ */
+ scopeColumn: "companyId" | "companyGroupId";
+ /** primary key column names (empty when the table has no PK) */
+ pkColumns: string[];
+ /**
+ * Every column in ANY uniqueness constraint — PK, unique constraint, or bare
+ * unique index. A foreign restore that collapses a user FK in one of these
+ * would collide (`isUserScopedIdentityTable`); PK alone misses unique-index keys.
+ */
+ uniqueColumns: string[];
+ /** true when the primary key is exactly the single column "id" */
+ hasId: boolean;
+ foreignKeys: ForeignKey[];
+};
+
+export type Catalog = {
+ schemaVersion: string;
+ /** topologically sorted — referenced tables come first */
+ tables: TableInfo[];
+};
+
+export type Manifest = {
+ kind: typeof BACKUP_KIND;
+ version: typeof BACKUP_VERSION;
+ schemaVersion: string;
+ sourceCompanyId: string;
+ sourceCompanyGroupId: string | null;
+ sourceCompanyName: string | null;
+ exportedAt: string;
+ exportedBy: string;
+ label: string | null;
+ includeStorage: "none" | "all";
+ tables: Array<{ name: string; rows: number; columns: string[] }>;
+ storage: Array<{ path: string; size: number; included: boolean }>;
+ excludedTables: string[];
+};
+
+/**
+ * What a backup contains, decided in ONE place — the exporter and the drift
+ * check's baseline must be the same rule, or the baseline quietly stops
+ * describing a real backup.
+ */
+export function selectExportableTables(catalog: Catalog): {
+ exportable: TableInfo[];
+ excludedTables: string[];
+} {
+ const secret = new Set<string>(SECRET_TABLES);
+ const exportable: TableInfo[] = [];
+ const excludedTables: string[] = [];
+ for (const table of catalog.tables) {
+ if (secret.has(table.name)) excludedTables.push(table.name);
+ else exportable.push(table);
+ }
+ return { exportable, excludedTables };
+}
+
+/** The columns a backup actually carries: generated ones are recomputed on load. */
+export function exportableColumns(table: TableInfo): ColumnInfo[] {
+ return table.columns.filter((c) => !c.isGenerated);
+}
+
+/**
+ * Kahn's algorithm over in-set FK edges (referenced tables first). Cycles are
+ * broken deterministically (fewest unmet dependencies, then alphabetically).
+ * Order is best-effort: imports run with FK enforcement relaxed when possible.
+ */
+export function topologicalSort(tables: TableInfo[]): TableInfo[] {
+ const byName = new Map(tables.map((t) => [t.name, t]));
+ const remaining = new Set(byName.keys());
+ const deps = new Map<string, Set<string>>();
+
+ for (const t of tables) {
+ const set = new Set<string>();
+ for (const fk of t.foreignKeys) {
+ if (fk.refTable !== t.name && byName.has(fk.refTable)) {
+ set.add(fk.refTable);
+ }
+ }
+ deps.set(t.name, set);
+ }
+
+ const sorted: TableInfo[] = [];
+ while (remaining.size > 0) {
+ let next: string | null = null;
+ let fewest = Infinity;
+ for (const name of [...remaining].sort()) {
+ const unmet = [...(deps.get(name) ?? [])].filter((d) =>
+ remaining.has(d)
+ ).length;
+ if (unmet === 0) {
+ next = name;
+ break;
+ }
+ if (unmet < fewest) {
+ fewest = unmet;
+ next = name;
+ }
+ }
+ if (!next) break;
+ remaining.delete(next);
+ sorted.push(byName.get(next)!);
+ }
+
+ return sorted;
+}
+
+/**
+ * Build the catalog of tenant-scoped tables (public base tables with a
+ * "companyId" or "companyGroupId" column), their columns, FK edges and a
+ * topological order. A table that has both columns is companyId-scoped.
+ */
+export async function getCompanyTableCatalog(
+ db: Kysely<KyselyDatabase>
+): Promise<Catalog> {
+ const scopeRows = await sql<{ name: string; column_name: string }>`
+ SELECT c.table_name AS name, c.column_name
+ FROM information_schema.columns c
+ JOIN information_schema.tables t
+ ON t.table_schema = c.table_schema AND t.table_name = c.table_name
+ WHERE c.table_schema = 'public'
+ AND c.column_name IN ('companyId', 'companyGroupId')
+ AND t.table_type = 'BASE TABLE'
+ `.execute(db);
+
+ const structural = CATALOG_EXCLUDED_TABLES;
+ const scopeByTable = new Map<string, "companyId" | "companyGroupId">();
+ for (const r of scopeRows.rows) {
+ if (structural.has(r.name)) continue;
+ if (r.column_name === "companyId") {
+ scopeByTable.set(r.name, "companyId");
+ } else if (!scopeByTable.has(r.name)) {
+ scopeByTable.set(r.name, "companyGroupId");
+ }
+ }
+
+ const columns = await sql<{
+ table_name: string;
+ column_name: string;
+ data_type: string;
+ udt_name: string;
+ is_nullable: string;
+ is_generated: string;
+ identity_generation: string | null;
+ column_default: string | null;
+ }>`
+ SELECT table_name, column_name, data_type, udt_name, is_nullable,
+ is_generated, identity_generation, column_default
+ FROM information_schema.columns
+ WHERE table_schema = 'public'
+ `.execute(db);
+
+ const primaryKeys = await sql<{
+ table_name: string;
+ column_name: string;
+ ordinal_position: string | number;
+ }>`
+ SELECT tc.table_name, kcu.column_name, kcu.ordinal_position
+ FROM information_schema.table_constraints tc
+ JOIN information_schema.key_column_usage kcu
+ ON kcu.constraint_name = tc.constraint_name
+ AND kcu.table_schema = tc.table_schema
+ WHERE tc.table_schema = 'public' AND tc.constraint_type = 'PRIMARY KEY'
+ ORDER BY tc.table_name, kcu.ordinal_position
+ `.execute(db);
+
+ // Columns in ANY unique index (covers PKs, unique constraints, and bare
+ // CREATE UNIQUE INDEX). `attnum = ANY(indkey)` skips expression-index entries.
+ const uniqueColumns = await sql<{ table_name: string; column_name: string }>`
+ SELECT t.relname AS table_name, a.attname AS column_name
+ FROM pg_index ix
+ JOIN pg_class t ON t.oid = ix.indrelid
+ JOIN pg_namespace nsp ON nsp.oid = t.relnamespace
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY (ix.indkey)
+ WHERE ix.indisunique AND nsp.nspname = 'public'
+ `.execute(db);
+
+ const foreignKeys = await sql<{
+ table_name: string;
+ column_name: string;
+ ref_table: string;
+ ref_column: string;
+ }>`
+ SELECT src.relname AS table_name, att.attname AS column_name,
+ tgt.relname AS ref_table, tatt.attname AS ref_column
+ FROM pg_constraint con
+ JOIN pg_class src ON src.oid = con.conrelid
+ JOIN pg_namespace nsp ON nsp.oid = src.relnamespace
+ JOIN pg_class tgt ON tgt.oid = con.confrelid
+ CROSS JOIN LATERAL unnest(con.conkey, con.confkey)
+ WITH ORDINALITY AS u(attnum, fattnum, ord)
+ JOIN pg_attribute att
+ ON att.attrelid = src.oid AND att.attnum = u.attnum
+ JOIN pg_attribute tatt
+ ON tatt.attrelid = tgt.oid AND tatt.attnum = u.fattnum
+ WHERE con.contype = 'f' AND nsp.nspname = 'public'
+ `.execute(db);
+
+ // FK graph for EVERY table so scope can be resolved transitively below.
+ const allFksByTable = new Map<string, ForeignKey[]>();
+ for (const f of foreignKeys.rows) {
+ const list = allFksByTable.get(f.table_name) ?? [];
+ list.push({
+ column: f.column_name,
+ refTable: f.ref_table,
+ refColumn: f.ref_column
+ });
+ allFksByTable.set(f.table_name, list);
+ }
+
+ // A table with no scope column but a FK to an already-scoped table inherits
+ // that scope (nearest scoped parent wins — BFS by passes).
+ const scope = new Map<string, Scope>();
+ const scopeRoot = new Map<string, "companyId" | "companyGroupId">();
+ for (const [name, column] of scopeByTable) {
+ scope.set(name, { kind: "direct", column });
+ scopeRoot.set(name, column);
+ }
+ // Singletons are injected BEFORE via-resolution so a FK to a scoped table
+ // can't mis-scope them through it.
+ const existingTables = new Set(columns.rows.map((c) => c.table_name));
+ for (const name of COMPANY_SINGLETON_TABLES) {
+ if (!existingTables.has(name) || scope.has(name)) continue;
+ scope.set(name, { kind: "direct", column: "id" });
+ scopeRoot.set(name, "companyId");
+ }
+ let resolvedMore = true;
+ while (resolvedMore) {
+ resolvedMore = false;
+ for (const [name, fks] of allFksByTable) {
+ if (scope.has(name) || structural.has(name)) continue;
+ const fk = fks.find((f) => f.refTable !== name && scope.has(f.refTable));
+ if (!fk) continue;
+ scope.set(name, {
+ kind: "via",
+ column: fk.column,
+ refColumn: fk.refColumn,
+ parent: fk.refTable
+ });
+ scopeRoot.set(name, scopeRoot.get(fk.refTable)!);
+ resolvedMore = true;
+ }
+ }
+ const tableSet = new Set(scope.keys());
+
+ let schemaVersion = "unknown";
+ try {
+ const migration = await sql<{ version: string }>`
+ SELECT version FROM supabase_migrations.schema_migrations
+ ORDER BY version DESC LIMIT 1
+ `.execute(db);
+ schemaVersion = migration.rows[0]?.version ?? "unknown";
+ } catch {
+ // migrations table unavailable — leave as unknown
+ }
+
+ const columnsByTable = new Map<string, ColumnInfo[]>();
+ for (const c of columns.rows) {
+ if (!tableSet.has(c.table_name)) continue;
+ const list = columnsByTable.get(c.table_name) ?? [];
+ list.push({
+ name: c.column_name,
+ dataType: c.data_type,
+ udtName: c.udt_name,
+ isNullable: c.is_nullable === "YES",
+ isGenerated:
+ c.is_generated === "ALWAYS" || c.identity_generation !== null,
+ hasDefault: c.column_default !== null
+ });
+ columnsByTable.set(c.table_name, list);
+ }
+
+ const pkColumnsByTable = new Map<string, string[]>();
+ for (const p of primaryKeys.rows) {
+ const list = pkColumnsByTable.get(p.table_name) ?? [];
+ list.push(p.column_name);
+ pkColumnsByTable.set(p.table_name, list);
+ }
+
+ const uniqueColumnsByTable = new Map<string, Set<string>>();
+ for (const u of uniqueColumns.rows) {
+ const set = uniqueColumnsByTable.get(u.table_name) ?? new Set<string>();
+ set.add(u.column_name);
+ uniqueColumnsByTable.set(u.table_name, set);
+ }
+
+ const fksByTable = new Map<string, ForeignKey[]>();
+ for (const f of foreignKeys.rows) {
+ if (!tableSet.has(f.table_name)) continue;
+ const list = fksByTable.get(f.table_name) ?? [];
+ list.push({
+ column: f.column_name,
+ refTable: f.ref_table,
+ refColumn: f.ref_column
+ });
+ fksByTable.set(f.table_name, list);
+ }
+
+ const tables: TableInfo[] = [...tableSet].sort().map((name) => {
+ const pkColumns = pkColumnsByTable.get(name) ?? [];
+ return {
+ name,
+ columns: columnsByTable.get(name) ?? [],
+ scope: scope.get(name)!,
+ scopeColumn: scopeRoot.get(name)!,
+ pkColumns,
+ uniqueColumns: [...(uniqueColumnsByTable.get(name) ?? [])],
+ hasId: pkColumns.length === 1 && pkColumns[0] === "id",
+ foreignKeys: fksByTable.get(name) ?? []
+ };
+ });
+
+ return { schemaVersion, tables: topologicalSort(tables) };
+}
+
+export type CompatibilityFinding = {
+ /**
+ * `defaulted` — a column added since this backup, which will take its DEFAULT.
+ * `discarded` — a column removed since this backup; its values land nowhere.
+ * `blocked` — the restore cannot proceed.
+ */
+ kind: "defaulted" | "discarded" | "blocked";
+ table: string;
+ column?: string;
+ reason: string;
+};
+
+/**
+ * Diff a backup's manifest against a catalog: what a restore would fill with a
+ * default, discard, or refuse outright. Only meaningful when the two come from
+ * DIFFERENT points in time — the ERP loader computes it against the live schema,
+ * and `assertBackupImportable` is its boolean form inside the restore.
+ *
+ * A NULLABLE column added since the backup is not reported — the ordinary
+ * additive case would bury the findings that matter.
+ */
+export function reportBackupCompatibility(
+ catalog: Catalog,
+ manifest: Manifest
+): { findings: CompatibilityFinding[]; blocked: boolean } {
+ const findings: CompatibilityFinding[] = [];
+
+ if (manifest.version !== BACKUP_VERSION) {
+ // Nothing else about an unsupported generation is worth reporting.
+ findings.push({
+ kind: "blocked",
+ table: "*",
+ reason: `its format (generation ${manifest.version}) is no longer supported (current is ${BACKUP_VERSION})`
+ });
+ return { findings, blocked: true };
+ }
+
+ // Account defaults and the chart of accounts must travel together, or the
+ // restore leaves a dangling FK. Read from the manifest: an empty table is
+ // omitted entirely, so an absent entry IS a zero count.
+ const rowsIn = (table: string) =>
+ manifest.tables.find((t) => t.name === table)?.rows ?? 0;
+ if (rowsIn("accountDefault") > 0 && rowsIn("account") === 0) {
+ findings.push({
+ kind: "blocked",
+ table: "accountDefault",
+ reason:
+ "it has account defaults but no chart of accounts (exported from a company with no group)"
+ });
+ }
+
+ const liveByName = new Map(catalog.tables.map((t) => [t.name, t]));
+ const backupTableNames = new Set(manifest.tables.map((t) => t.name));
+ for (const backupTable of manifest.tables) {
+ if (CATALOG_EXCLUDED_TABLES.has(backupTable.name)) continue;
+
+ // A table missing from the catalog resolves through TABLE_RENAMES: a mapped
+ // name is the new table, an explicit null was dropped with its feature, and
+ // an UNMAPPED name blocks — see renames.ts for why guessing is unacceptable.
+ let live = liveByName.get(backupTable.name);
+ if (!live) {
+ const renamedTo = TABLE_RENAMES[backupTable.name];
+ if (renamedTo === undefined) {
+ findings.push({
+ kind: "blocked",
+ table: backupTable.name,
+ reason: `table "${backupTable.name}" is not in the current schema and has no rename mapping`
+ });
+ continue;
+ }
+ if (renamedTo === null) {
+ findings.push({
+ kind: "discarded",
+ table: backupTable.name,
+ reason:
+ "this table was removed along with its feature; its rows will not be restored"
+ });
+ continue;
+ }
+ // The backup carries BOTH names — applying the rename would merge two
+ // tables and silently drop the old one's rows. Refuse.
+ if (backupTableNames.has(renamedTo)) {
+ findings.push({
+ kind: "blocked",
+ table: backupTable.name,
+ reason: `it maps to "${renamedTo}", which this backup also contains`
+ });
+ continue;
+ }
+ live = liveByName.get(renamedTo);
+ if (!live) {
+ findings.push({
+ kind: "blocked",
+ table: backupTable.name,
+ reason: `it maps to "${renamedTo}", which is not in the current schema either`
+ });
+ continue;
+ }
+ }
+
+ const backupCols = new Set(backupTable.columns);
+ for (const c of live.columns) {
+ if (backupCols.has(c.name) || c.isGenerated || c.isNullable) continue;
+ if (c.hasDefault) {
+ findings.push({
+ kind: "defaulted",
+ table: backupTable.name,
+ column: c.name,
+ reason: "added since this backup; will take its default value"
+ });
+ } else {
+ findings.push({
+ kind: "blocked",
+ table: backupTable.name,
+ column: c.name,
+ reason:
+ "required since this backup, with no default value to fall back on"
+ });
+ }
+ }
+
+ const liveCols = new Set(live.columns.map((c) => c.name));
+ for (const name of backupTable.columns) {
+ if (liveCols.has(name)) continue;
+ findings.push({
+ kind: "discarded",
+ table: backupTable.name,
+ column: name,
+ reason: "removed since this backup; its values will not be restored"
+ });
+ }
+ }
+
+ return {
+ findings,
+ blocked: findings.some((f) => f.kind === "blocked")
+ };
+}
+
+export type BackupCompatibilityStatus =
+ | "ready"
+ | "restorable-with-changes"
+ | "not-restorable";
+
+/** Map a compatibility report onto the shared status vocabulary. */
+export function compatibilityStatus(report: {
+ findings: CompatibilityFinding[];
+ blocked: boolean;
+}): BackupCompatibilityStatus {
+ if (report.blocked) return "not-restorable";
+ return report.findings.length > 0 ? "restorable-with-changes" : "ready";
+}
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
index e5eba7c347..3f2c0453d8 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
@@ -2,32 +2,38 @@ import { randomUUID } from "node:crypto";
import { createInterface } from "node:readline";
import { Readable } from "node:stream";
import { createGunzip, createGzip } from "node:zlib";
-import type { TableName } from "@carbon/database/audit.config";
import type { KyselyDatabase } from "@carbon/database/client";
import { getLogger } from "@carbon/logger";
import type { SupabaseClient } from "@supabase/supabase-js";
import { type Kysely, type RawBuilder, sql } from "kysely";
import { nanoid } from "nanoid";
-import { TABLE_RENAMES } from "./company-backup.renames";
+import {
+ BACKUP_KIND,
+ type Catalog,
+ type ColumnInfo,
+ type CompatibilityFinding,
+ type Manifest,
+ reportBackupCompatibility,
+ SECRET_TABLES,
+ type TableInfo
+} from "../../../backups/schema";
+
+// Catalog introspection + compatibility live in src/backups/ (shared with the
+// drift check and the ERP Backups page); re-exported so the backup jobs keep
+// one import surface.
+export * from "../../../backups/renames";
+export * from "../../../backups/schema";
const log = getLogger("jobs", "company-backup");
/**
- * Shared core for company backup export/import.
- *
- * The table catalog is derived from the live database schema
- * (information_schema + pg_constraint) rather than a hand-maintained list,
- * so new company-scoped tables are picked up automatically.
+ * Shared core for company backup export/import. A backup is a folder
+ * `exports/<name>/` of small objects: `manifest.json`, one
+ * `tables/<table>.ndjson.gz` per non-empty table (dumped + loaded in
+ * parallel), and `assets/<path>` files. Per-table NDJSON is read/written a
+ * line at a time, so a huge table never materializes as one >512MB string.
*/
-export const BACKUP_KIND = "carbon-company-backup";
-// A backup is a folder `exports/<name>/` of small objects: `manifest.json`, one
-// `tables/<table>.ndjson.gz` per non-empty table (dumped + loaded in parallel),
-// and `assets/<path>` files. Each object stays under the bucket size cap; the
-// whole folder bundles into one `.carbon.tar.gz` for cross-environment transfer.
-// Per-table NDJSON is read/written a line at a time, so a huge table never
-// materializes as one >512MB string (V8's max) or one giant JSON.parse.
-export const BACKUP_VERSION = 1;
export const BACKUP_INTEGRATION = "company-backup";
export const EXPORTS_PREFIX = "exports";
/** Shared, env-agnostic bucket holding the onboarding backup templates. */
@@ -122,74 +128,6 @@ export function rewriteStoragePath(
.join("/");
}
-/**
- * Tables whose contents must never travel in a backup — credentials,
- * integration tokens and webhook targets stay with the source company.
- */
-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",
- "oauthToken"
-];
-
-/**
- * Company-singleton config tables: one row per company, keyed by `id` (the row's
- * `id` IS the company id, via an `id -> company` FK), with no `companyId` column.
- * They're a company's data, so the catalog includes them scoped by `id` directly
- * (`WHERE id = companyId`) — no redundant `companyId` column needed. `companyPlan`
- * is a singleton too but is deliberately NOT listed: it's billing/Stripe identity
- * tied to the target company and must never travel.
- */
-export const COMPANY_SINGLETON_TABLES = [
- "companySettings",
- "terms",
- "companyAccountsPayableBillingAddress",
- "companyAccountsReceivableBillingAddress"
-] as const satisfies readonly TableName[];
-
-/**
- * Tenant-root tables that carry a scope column but are NOT tenant data — the
- * company shell itself is created by onboarding, never imported. Excluded
- * from the catalog entirely.
- */
-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.
@@ -224,119 +162,6 @@ export const IN_PLACE_SKIPPED_TABLES = new Set([
/** Integration key for the in-place restore marker (holds the snapshot path). */
export const RESTORE_INTEGRATION = "company-restore";
-export type ColumnInfo = {
- name: string;
- /** information_schema data_type, e.g. 'ARRAY', 'jsonb', 'USER-DEFINED' */
- dataType: string;
- /** information_schema udt_name, e.g. '_text', 'jsonb', 'bytea' */
- udtName: string;
- isNullable: boolean;
- /** GENERATED ALWAYS / identity columns — excluded from export & insert */
- isGenerated: boolean;
- /** has a column default (so a backup that omits it can still insert) */
- hasDefault: boolean;
-};
-
-export type ForeignKey = {
- column: string;
- refTable: string;
- refColumn: string;
-};
-
-/**
- * How a table's rows are scoped to a company:
- * - `direct`: the table itself has a scope column — `companyId`/`companyGroupId`,
- * or `id` for a company-singleton (whose `id` IS the company id, see
- * {@link COMPANY_SINGLETON_TABLES}).
- * - `via`: the table has no scope column but a FK (`column` → `parent.refColumn`)
- * to a table that IS scoped (possibly transitively). It inherits that scope —
- * e.g. `customerContact.customerId → customer`. Resolved from the FK graph so
- * child tables (contacts, locations, line prices, history) travel with their
- * parent without a hand-maintained list.
- */
-export type Scope =
- | { kind: "direct"; column: "companyId" | "companyGroupId" | "id" }
- | { kind: "via"; column: string; refColumn: string; parent: string };
-
-export type TableInfo = {
- name: string;
- columns: ColumnInfo[];
- /** How the table is scoped to a company (direct column or via a parent FK). */
- scope: Scope;
- /**
- * The resolved ROOT tenant column the rows ultimately belong to — `companyId`
- * for most data, `companyGroupId` for shared config (chart of accounts,
- * currencies, …). For a `via` table it's the root ancestor's column. Used for
- * the "which tenant" decisions (wipe/reseed scope); the actual row filter is
- * built by `buildScopeFilter`.
- */
- scopeColumn: "companyId" | "companyGroupId";
- /** primary key column names (empty when the table has no PK) */
- pkColumns: string[];
- /**
- * Every column that participates in ANY uniqueness constraint — primary key,
- * unique constraint, or bare unique index (deduped). A foreign restore that
- * collapses a user FK in one of these would collide, so it's the signal for
- * `isUserScopedIdentityTable` (PK alone misses unique-index keys like
- * `trainingCompletion(trainingAssignmentId, employeeId, period)`).
- */
- uniqueColumns: string[];
- /** true when the primary key is exactly the single column "id" */
- hasId: boolean;
- foreignKeys: ForeignKey[];
-};
-
-export type Catalog = {
- schemaVersion: string;
- /** topologically sorted — referenced tables come first */
- tables: TableInfo[];
-};
-
-/**
- * What a backup contains, decided in ONE place.
- *
- * The drift check's baseline (`packages/jobs/manifests/schema.json`) exists to
- * describe what a real export produces, so the two must be the same rule rather
- * than two implementations that happen to agree. If they diverge, the baseline
- * quietly stops describing a real backup and the check keeps reporting
- * `restorable` — a drift check whose own model has drifted, which is worse than
- * none because it is trusted.
- */
-export function selectExportableTables(catalog: Catalog): {
- exportable: TableInfo[];
- excludedTables: string[];
-} {
- const secret = new Set<string>(SECRET_TABLES);
- const exportable: TableInfo[] = [];
- const excludedTables: string[] = [];
- for (const table of catalog.tables) {
- if (secret.has(table.name)) excludedTables.push(table.name);
- else exportable.push(table);
- }
- return { exportable, excludedTables };
-}
-
-/** The columns a backup actually carries: generated ones are recomputed on load. */
-export function exportableColumns(table: TableInfo): ColumnInfo[] {
- return table.columns.filter((c) => !c.isGenerated);
-}
-
-export type Manifest = {
- kind: typeof BACKUP_KIND;
- version: typeof BACKUP_VERSION;
- schemaVersion: string;
- sourceCompanyId: string;
- sourceCompanyGroupId: string | null;
- sourceCompanyName: string | null;
- exportedAt: string;
- exportedBy: string;
- label: string | null;
- includeStorage: "none" | "all";
- tables: Array<{ name: string; rows: number; columns: string[] }>;
- storage: Array<{ path: string; size: number; included: boolean }>;
- excludedTables: string[];
-};
-
export type CompanyBackup = {
manifest: Manifest;
data: Record<string, Record<string, unknown>[]>;
@@ -541,225 +366,6 @@ export async function readBackup(
return { manifest, data };
}
-/**
- * Build the catalog of tenant-scoped tables (public base tables with a
- * "companyId" or "companyGroupId" column), their columns, FK edges and a
- * topological order. A table that has both columns is treated as
- * companyId-scoped.
- */
-export async function getCompanyTableCatalog(
- db: Kysely<KyselyDatabase>
-): Promise<Catalog> {
- const scopeRows = await sql<{ name: string; column_name: string }>`
- SELECT c.table_name AS name, c.column_name
- FROM information_schema.columns c
- JOIN information_schema.tables t
- ON t.table_schema = c.table_schema AND t.table_name = c.table_name
- WHERE c.table_schema = 'public'
- AND c.column_name IN ('companyId', 'companyGroupId')
- AND t.table_type = 'BASE TABLE'
- `.execute(db);
-
- // companyId wins when a table carries both columns.
- // 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;
- if (r.column_name === "companyId") {
- scopeByTable.set(r.name, "companyId");
- } else if (!scopeByTable.has(r.name)) {
- scopeByTable.set(r.name, "companyGroupId");
- }
- }
-
- const columns = await sql<{
- table_name: string;
- column_name: string;
- data_type: string;
- udt_name: string;
- is_nullable: string;
- is_generated: string;
- identity_generation: string | null;
- column_default: string | null;
- }>`
- SELECT table_name, column_name, data_type, udt_name, is_nullable,
- is_generated, identity_generation, column_default
- FROM information_schema.columns
- WHERE table_schema = 'public'
- `.execute(db);
-
- const primaryKeys = await sql<{
- table_name: string;
- column_name: string;
- ordinal_position: string | number;
- }>`
- SELECT tc.table_name, kcu.column_name, kcu.ordinal_position
- FROM information_schema.table_constraints tc
- JOIN information_schema.key_column_usage kcu
- ON kcu.constraint_name = tc.constraint_name
- AND kcu.table_schema = tc.table_schema
- WHERE tc.table_schema = 'public' AND tc.constraint_type = 'PRIMARY KEY'
- ORDER BY tc.table_name, kcu.ordinal_position
- `.execute(db);
-
- // Columns in ANY unique index (covers PKs, unique constraints, and bare
- // CREATE UNIQUE INDEX — the last is how training tables key their employee).
- // `attnum = ANY(indkey)` skips expression-index entries (attnum 0).
- const uniqueColumns = await sql<{ table_name: string; column_name: string }>`
- SELECT t.relname AS table_name, a.attname AS column_name
- FROM pg_index ix
- JOIN pg_class t ON t.oid = ix.indrelid
- JOIN pg_namespace nsp ON nsp.oid = t.relnamespace
- JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY (ix.indkey)
- WHERE ix.indisunique AND nsp.nspname = 'public'
- `.execute(db);
-
- const foreignKeys = await sql<{
- table_name: string;
- column_name: string;
- ref_table: string;
- ref_column: string;
- }>`
- SELECT src.relname AS table_name, att.attname AS column_name,
- tgt.relname AS ref_table, tatt.attname AS ref_column
- FROM pg_constraint con
- JOIN pg_class src ON src.oid = con.conrelid
- JOIN pg_namespace nsp ON nsp.oid = src.relnamespace
- JOIN pg_class tgt ON tgt.oid = con.confrelid
- CROSS JOIN LATERAL unnest(con.conkey, con.confkey)
- WITH ORDINALITY AS u(attnum, fattnum, ord)
- JOIN pg_attribute att
- ON att.attrelid = src.oid AND att.attnum = u.attnum
- JOIN pg_attribute tatt
- ON tatt.attrelid = tgt.oid AND tatt.attnum = u.fattnum
- WHERE con.contype = 'f' AND nsp.nspname = 'public'
- `.execute(db);
-
- // FK graph for EVERY table (not just the directly-scoped ones), so scope can
- // be resolved transitively below.
- const allFksByTable = new Map<string, ForeignKey[]>();
- for (const f of foreignKeys.rows) {
- const list = allFksByTable.get(f.table_name) ?? [];
- list.push({
- column: f.column_name,
- refTable: f.ref_table,
- refColumn: f.ref_column
- });
- allFksByTable.set(f.table_name, list);
- }
-
- // Resolve scope transitively: a table with no companyId/companyGroupId column
- // but a FK to an already-scoped table inherits that scope (nearest scoped
- // parent wins — BFS by passes converges on the shortest path). This pulls in
- // child tables (contacts, locations, line prices, status history, …) without a
- // hand-maintained list.
- const scope = new Map<string, Scope>();
- const scopeRoot = new Map<string, "companyId" | "companyGroupId">();
- for (const [name, column] of scopeByTable) {
- scope.set(name, { kind: "direct", column });
- scopeRoot.set(name, column);
- }
- // Company-singletons: keyed by `id` (= the company id via an id->company FK),
- // with no companyId column. Scope them by `id` directly — a company's data
- // without a redundant column. Inject BEFORE via-resolution so a FK to a scoped
- // table (e.g. a notification-group ref) can't mis-scope them through it.
- const existingTables = new Set(columns.rows.map((c) => c.table_name));
- for (const name of COMPANY_SINGLETON_TABLES) {
- if (!existingTables.has(name) || scope.has(name)) continue;
- scope.set(name, { kind: "direct", column: "id" });
- scopeRoot.set(name, "companyId");
- }
- let resolvedMore = true;
- while (resolvedMore) {
- resolvedMore = false;
- for (const [name, fks] of allFksByTable) {
- if (scope.has(name) || structural.has(name)) continue;
- const fk = fks.find((f) => f.refTable !== name && scope.has(f.refTable));
- if (!fk) continue;
- scope.set(name, {
- kind: "via",
- column: fk.column,
- refColumn: fk.refColumn,
- parent: fk.refTable
- });
- scopeRoot.set(name, scopeRoot.get(fk.refTable)!);
- resolvedMore = true;
- }
- }
- const tableSet = new Set(scope.keys());
-
- let schemaVersion = "unknown";
- try {
- const migration = await sql<{ version: string }>`
- SELECT version FROM supabase_migrations.schema_migrations
- ORDER BY version DESC LIMIT 1
- `.execute(db);
- schemaVersion = migration.rows[0]?.version ?? "unknown";
- } catch {
- // migrations table unavailable — leave as unknown
- }
-
- const columnsByTable = new Map<string, ColumnInfo[]>();
- for (const c of columns.rows) {
- if (!tableSet.has(c.table_name)) continue;
- const list = columnsByTable.get(c.table_name) ?? [];
- list.push({
- name: c.column_name,
- dataType: c.data_type,
- udtName: c.udt_name,
- isNullable: c.is_nullable === "YES",
- isGenerated:
- c.is_generated === "ALWAYS" || c.identity_generation !== null,
- hasDefault: c.column_default !== null
- });
- columnsByTable.set(c.table_name, list);
- }
-
- const pkColumnsByTable = new Map<string, string[]>();
- for (const p of primaryKeys.rows) {
- const list = pkColumnsByTable.get(p.table_name) ?? [];
- list.push(p.column_name);
- pkColumnsByTable.set(p.table_name, list);
- }
-
- const uniqueColumnsByTable = new Map<string, Set<string>>();
- for (const u of uniqueColumns.rows) {
- const set = uniqueColumnsByTable.get(u.table_name) ?? new Set<string>();
- set.add(u.column_name);
- uniqueColumnsByTable.set(u.table_name, set);
- }
-
- const fksByTable = new Map<string, ForeignKey[]>();
- for (const f of foreignKeys.rows) {
- if (!tableSet.has(f.table_name)) continue;
- const list = fksByTable.get(f.table_name) ?? [];
- list.push({
- column: f.column_name,
- refTable: f.ref_table,
- refColumn: f.ref_column
- });
- fksByTable.set(f.table_name, list);
- }
-
- const tables: TableInfo[] = [...tableSet].sort().map((name) => {
- const pkColumns = pkColumnsByTable.get(name) ?? [];
- return {
- name,
- columns: columnsByTable.get(name) ?? [],
- scope: scope.get(name)!,
- scopeColumn: scopeRoot.get(name)!,
- pkColumns,
- uniqueColumns: [...(uniqueColumnsByTable.get(name) ?? [])],
- hasId: pkColumns.length === 1 && pkColumns[0] === "id",
- foreignKeys: fksByTable.get(name) ?? []
- };
- });
-
- return { schemaVersion, tables: topologicalSort(tables) };
-}
-
/**
* Decide whether a backup can be imported into the *current* schema — the hard
* gate the restore and import jobs call, and the boolean form of exactly the same
@@ -795,153 +401,6 @@ function blockingReason(f: CompatibilityFinding): string {
return f.reason;
}
-export type CompatibilityFinding = {
- /**
- * `defaulted` — a column added since this backup, which will take its DEFAULT.
- * `discarded` — a column removed since this backup; its values land nowhere.
- * `blocked` — the restore cannot proceed.
- */
- kind: "defaulted" | "discarded" | "blocked";
- table: string;
- column?: string;
- reason: string;
-};
-
-/**
- * Report-mode counterpart to `assertBackupImportable`.
- *
- * The gate answers yes/no; this answers "what exactly differs", so the UI can
- * disclose it and let the person decide instead of being refused. Deliberately a
- * SEPARATE function rather than a rewrite of the gate: the gate stays the boolean
- * check that CI and the loader call, and the two are kept consistent by applying
- * the same rules in the same order rather than by sharing a return type.
- *
- * A NULLABLE column added since the backup is not reported. It simply becomes
- * NULL, which is the ordinary additive case — surfacing every one of them would
- * bury the findings that matter under months of routine schema growth.
- */
-export function reportBackupCompatibility(
- catalog: Catalog,
- manifest: Manifest
-): { findings: CompatibilityFinding[]; blocked: boolean } {
- const findings: CompatibilityFinding[] = [];
-
- if (manifest.version !== BACKUP_VERSION) {
- findings.push({
- kind: "blocked",
- table: "*",
- reason: `its format (generation ${manifest.version}) is no longer supported (current is ${BACKUP_VERSION})`
- });
- }
-
- // Account defaults reference the chart of accounts, so the two must travel
- // together — defaults without accounts would leave a dangling FK. Read from the
- // manifest rather than the loaded rows: an empty table is omitted from the
- // manifest entirely, so an absent entry IS a zero count, and the verdict can be
- // reached without downloading a single table file.
- const rowsIn = (table: string) =>
- manifest.tables.find((t) => t.name === table)?.rows ?? 0;
- if (rowsIn("accountDefault") > 0 && rowsIn("account") === 0) {
- findings.push({
- kind: "blocked",
- table: "accountDefault",
- reason:
- "it has account defaults but no chart of accounts (exported from a company with no group)"
- });
- }
-
- const liveByName = new Map(catalog.tables.map((t) => [t.name, t]));
- const backupTableNames = new Set(manifest.tables.map((t) => t.name));
- for (const backupTable of manifest.tables) {
- // A table the catalog now excludes by design (MRP output, the company shell)
- // is not drift — its rows are ignored on load.
- if (CATALOG_EXCLUDED_TABLES.has(backupTable.name)) continue;
-
- // A table missing from the catalog is resolved through TABLE_RENAMES:
- // a mapped name is read as the new table, an explicit null was dropped with
- // its feature, and an UNMAPPED name blocks — see company-backup.renames.ts
- // for why guessing between those is unacceptable.
- let live = liveByName.get(backupTable.name);
- if (!live) {
- const renamedTo = TABLE_RENAMES[backupTable.name];
- if (renamedTo === undefined) {
- findings.push({
- kind: "blocked",
- table: backupTable.name,
- reason: `table "${backupTable.name}" is not in the current schema and has no rename mapping`
- });
- continue;
- }
- if (renamedTo === null) {
- findings.push({
- kind: "discarded",
- table: backupTable.name,
- reason:
- "this table was removed along with its feature; its rows will not be restored"
- });
- continue;
- }
- // The backup carries BOTH names, so the rename can't be applied without
- // merging two tables into one. Refuse: the loader keys off table name, so
- // letting this through drops the old table's rows without a word.
- if (backupTableNames.has(renamedTo)) {
- findings.push({
- kind: "blocked",
- table: backupTable.name,
- reason: `it maps to "${renamedTo}", which this backup also contains`
- });
- continue;
- }
- live = liveByName.get(renamedTo);
- if (!live) {
- findings.push({
- kind: "blocked",
- table: backupTable.name,
- reason: `it maps to "${renamedTo}", which is not in the current schema either`
- });
- continue;
- }
- }
-
- const backupCols = new Set(backupTable.columns);
- for (const c of live.columns) {
- if (backupCols.has(c.name) || c.isGenerated || c.isNullable) continue;
- if (c.hasDefault) {
- findings.push({
- kind: "defaulted",
- table: backupTable.name,
- column: c.name,
- reason: "added since this backup; will take its default value"
- });
- } else {
- findings.push({
- kind: "blocked",
- table: backupTable.name,
- column: c.name,
- reason:
- "required since this backup, with no default value to fall back on"
- });
- }
- }
-
- const liveCols = new Set(live.columns.map((c) => c.name));
- for (const name of backupTable.columns) {
- if (liveCols.has(name)) continue;
- findings.push({
- kind: "discarded",
- table: backupTable.name,
- column: name,
- reason: "removed since this backup; its values will not be restored"
- });
- }
- }
-
- return {
- findings,
- blocked: findings.some((f) => f.kind === "blocked")
- };
-}
-
/**
* FK targets a restore resolves WITHOUT the referenced row being in the backup:
* `user` (global identity table, never in the catalog) and `company` (structural),
@@ -955,52 +414,6 @@ export const RETAINED_REF_TABLES = new Set([
"companyGroup"
]);
-/**
- * Kahn's algorithm over in-set FK edges (referenced tables first). Cycles
- * are broken deterministically by picking the remaining table with the
- * fewest unmet dependencies (then alphabetically). Order is best-effort:
- * imports run with FK enforcement relaxed when possible.
- */
-export function topologicalSort(tables: TableInfo[]): TableInfo[] {
- const byName = new Map(tables.map((t) => [t.name, t]));
- const remaining = new Set(byName.keys());
- const deps = new Map<string, Set<string>>();
-
- for (const t of tables) {
- const set = new Set<string>();
- for (const fk of t.foreignKeys) {
- if (fk.refTable !== t.name && byName.has(fk.refTable)) {
- set.add(fk.refTable);
- }
- }
- deps.set(t.name, set);
- }
-
- const sorted: TableInfo[] = [];
- while (remaining.size > 0) {
- let next: string | null = null;
- let fewest = Infinity;
- for (const name of [...remaining].sort()) {
- const unmet = [...(deps.get(name) ?? [])].filter((d) =>
- remaining.has(d)
- ).length;
- if (unmet === 0) {
- next = name;
- break;
- }
- if (unmet < fewest) {
- fewest = unmet;
- next = name;
- }
- }
- if (!next) break;
- remaining.delete(next);
- sorted.push(byName.get(next)!);
- }
-
- return sorted;
-}
-
/**
* A fresh primary-key value for a table, matching its `id` column's type as the
* schema defines it — a real UUID for `uuid` columns, otherwise a nanoid (what
@@ -1078,149 +491,69 @@ export function buildScopeFilter(
* Export-time closure guard — refuse to PRODUCE a backup that could never be
* restored. For each NOT-NULL FK from an exportable scoped table to another
* exportable scoped table, count rows in this company's export scope whose
- * reference falls OUTSIDE the referenced table's export scope (a cross-company /
- * out-of-scope ref: the child row would be dumped but its parent would not).
- * DB-level and count-only, so no rows are held in memory. This is the export
- * mirror of the restore-side `assertReferentiallyClosed`. Skips nullable FKs
- * (restore nulls a missing nullable ref) and refs to retained/global/secret
- * tables (`user`, `company`, …, and anything not exported).
+ * reference falls OUTSIDE the referenced table's export scope (the child row
+ * would be dumped but its parent would not). DB-level and count-only. The
+ * export mirror of the restore-side `assertReferentiallyClosed`. Skips
+ * nullable FKs (restore nulls a missing ref) and refs to retained/global/
+ * secret tables.
*/
-type ScopeViolation = {
- table: string;
- column: string;
- refTable: string;
- rows: number;
-};
-
-/**
- * The predicate identifying a row whose NOT-NULL FK escapes the referenced
- * table's export scope.
- *
- * A NOT-NULL FK is only a real gap when it points at ANOTHER company's row. A
- * `companyId IS NULL` row is shared substrate (seeded `material*`, currencies, …)
- * present in every target, so it is never a gap — the existence set is widened to
- * include it. A ref to a row owned by a different company is still NOT matched,
- * so it still surfaces. This is the one cross-tenant rule, no per-table
- * allow-list.
- */
-function outOfScopeRefPredicate(
- fk: ForeignKey,
- parent: TableInfo,
- byName: Map<string, TableInfo>,
- companyId: string,
- companyGroupId: string | null
-): RawBuilder<unknown> {
- const parentScope = buildScopeFilter(
- parent,
- byName,
- companyId,
- companyGroupId
- );
- const parentExistence =
- parent.scope.kind === "direct"
- ? sql`${parentScope} OR ${sql.id(parent.scope.column)} IS NULL`
- : parentScope;
- return sql`${sql.id(fk.column)} IS NOT NULL
- AND ${sql.id(fk.column)} NOT IN (
- SELECT ${sql.id(fk.refColumn)}
- FROM ${sql.id(parent.name)}
- WHERE ${parentExistence}
- )`;
-}
-
-/**
- * The FK edges this guard considers: NOT-NULL, `id`-targeting, and pointing at
- * another exportable scoped table.
- */
-function closureCheckedForeignKeys(
- table: TableInfo,
- exportableNames: Set<string>
-): ForeignKey[] {
- const colByName = new Map(table.columns.map((c) => [c.name, c]));
- return table.foreignKeys.filter((fk) => {
- if (fk.refColumn !== "id") return false;
- if (RETAINED_REF_TABLES.has(fk.refTable)) return false;
- // global/secret → not in closure
- if (!exportableNames.has(fk.refTable)) return false;
- const col = colByName.get(fk.column);
- // nullable → restore nulls a missing ref
- if (!col || col.isNullable) return false;
- return true;
- });
-}
-
-/**
- * Structured form of the export-time closure guard. Counts, per FK edge, the rows
- * in this company's export scope whose reference falls outside the referenced
- * table's export scope. DB-level and count-only, so no rows are held in memory.
- */
-async function findExportScopeViolationDetails(
+export async function findExportScopeViolations(
db: Kysely<KyselyDatabase>,
exportable: TableInfo[],
byName: Map<string, TableInfo>,
companyId: string,
companyGroupId: string | null
-): Promise<ScopeViolation[]> {
+): Promise<string[]> {
const exportableNames = new Set(exportable.map((t) => t.name));
- const checks: Array<{
- violation: Omit<ScopeViolation, "rows">;
- query: RawBuilder<{ n: string }>;
- }> = [];
+ const checks: Array<{ desc: string; query: RawBuilder<{ n: string }> }> = [];
for (const t of exportable) {
- for (const fk of closureCheckedForeignKeys(t, exportableNames)) {
+ const colByName = new Map(t.columns.map((c) => [c.name, c]));
+ for (const fk of t.foreignKeys) {
+ if (fk.refColumn !== "id") continue;
+ if (RETAINED_REF_TABLES.has(fk.refTable)) continue;
+ if (!exportableNames.has(fk.refTable)) continue; // global/secret → not in closure
+ const col = colByName.get(fk.column);
+ if (!col || col.isNullable) continue; // nullable → restore nulls a missing ref
const parent = byName.get(fk.refTable)!;
const childScope = buildScopeFilter(t, byName, companyId, companyGroupId);
+ const parentScope = buildScopeFilter(
+ parent,
+ byName,
+ companyId,
+ companyGroupId
+ );
+ // A `companyId IS NULL` parent row is shared substrate (seeded
+ // `material*`, currencies, …) present in every target — never a gap. A
+ // row owned by a DIFFERENT company still surfaces.
+ const parentExistence =
+ parent.scope.kind === "direct"
+ ? sql`${parentScope} OR ${sql.id(parent.scope.column)} IS NULL`
+ : parentScope;
checks.push({
- violation: { table: t.name, column: fk.column, refTable: fk.refTable },
+ desc: `${t.name}.${fk.column} → ${fk.refTable}`,
query: sql<{ n: string }>`
SELECT count(*)::text AS n
FROM ${sql.id(t.name)}
WHERE ${childScope}
- AND ${outOfScopeRefPredicate(
- fk,
- parent,
- byName,
- companyId,
- companyGroupId
- )}`
+ AND ${sql.id(fk.column)} IS NOT NULL
+ AND ${sql.id(fk.column)} NOT IN (
+ SELECT ${sql.id(fk.refColumn)}
+ FROM ${sql.id(parent.name)}
+ WHERE ${parentExistence}
+ )`
});
}
}
- const violations: ScopeViolation[] = [];
+ const violations: string[] = [];
await mapWithConcurrency(checks, 6, async (c) => {
const r = await c.query.execute(db);
const n = Number(r.rows[0]?.n ?? 0);
- if (n > 0) violations.push({ ...c.violation, rows: n });
+ if (n > 0) violations.push(`${c.desc} (${n} row${n === 1 ? "" : "s"})`);
});
return violations;
}
-/** Human-readable form of one violation, e.g. `pickMethod.itemId → item (1 row)`. */
-function formatScopeViolation(v: ScopeViolation): string {
- return `${v.table}.${v.column} → ${v.refTable} (${v.rows} row${
- v.rows === 1 ? "" : "s"
- })`;
-}
-
-/** Export-time closure guard: one readable line per offending FK edge. */
-export async function findExportScopeViolations(
- db: Kysely<KyselyDatabase>,
- exportable: TableInfo[],
- byName: Map<string, TableInfo>,
- companyId: string,
- companyGroupId: string | null
-): Promise<string[]> {
- const details = await findExportScopeViolationDetails(
- db,
- exportable,
- byName,
- companyId,
- companyGroupId
- );
- return details.map(formatScopeViolation);
-}
-
/**
* Of the given tables, return only those the target has NOT yet populated in
* its scope (companyId or companyGroupId). Reseed import uses this so it
diff --git a/packages/jobs/src/inngest/functions/tasks/company-import.ts b/packages/jobs/src/inngest/functions/tasks/company-import.ts
index a0ac78a243..6953e8c07f 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-import.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-import.ts
@@ -1,6 +1,7 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { chunkArray } from "@carbon/utils";
import { sql } from "kysely";
+import { applyTableRenames } from "../../../backups/renames";
import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";
import {
@@ -19,7 +20,6 @@ import {
restoreAssetsFromBackup,
SECRET_TABLES
} from "./company-backup";
-import { applyTableRenames } from "./company-backup.renames";
import {
buildRowTransforms,
loadSubstrateIds
diff --git a/packages/jobs/src/inngest/functions/tasks/company-restore.ts b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
index 1b8515f0ce..738d8ba21f 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-restore.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
@@ -1,6 +1,7 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { chunkArray } from "@carbon/utils";
import { sql } from "kysely";
+import { applyTableRenames } from "../../../backups/renames";
import { getJobDatabaseClient, type JobDatabase } from "../../../db";
import { inngest } from "../../client";
import type { Catalog, CompanyBackup, JobProgress } from "./company-backup";
@@ -24,7 +25,6 @@ import {
wipeScopedData,
writeBackupManifest
} from "./company-backup";
-import { applyTableRenames } from "./company-backup.renames";
import {
assertReferentiallyClosed,
buildRowTransforms,
diff --git a/packages/jobs/src/inngest/functions/tasks/company-template.ts b/packages/jobs/src/inngest/functions/tasks/company-template.ts
index b5df4e527e..bf95498ba3 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-template.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-template.ts
@@ -4,6 +4,7 @@ import { getPostgresConnectionPool } from "@carbon/database/client";
import { applyDataset, getDataset } from "@carbon/database/datasets";
import { datetime } from "@carbon/utils";
import { NonRetriableError } from "inngest";
+import { applyTableRenames } from "../../../backups/renames";
import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";
import {
@@ -17,7 +18,6 @@ import {
throttleProgress,
writeBackupManifest
} from "./company-backup";
-import { applyTableRenames } from "./company-backup.renames";
import { buildCompanyBackup } from "./company-export";
import { resolveRestoreScope, wipeAndLoad } from "./company-restore";
diff --git a/packages/jobs/src/scripts/backup-baseline.test.ts b/packages/jobs/src/scripts/backup-baseline.test.ts
index d5ed1d9722..9d1d66bc4d 100644
--- a/packages/jobs/src/scripts/backup-baseline.test.ts
+++ b/packages/jobs/src/scripts/backup-baseline.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import type { Manifest } from "../inngest/functions/tasks/company-backup";
+import type { Manifest } from "../backups/schema";
import {
BaselineError,
type BaselineSources,
diff --git a/packages/jobs/src/scripts/backup-baseline.ts b/packages/jobs/src/scripts/backup-baseline.ts
index 23067165dc..d621784a49 100644
--- a/packages/jobs/src/scripts/backup-baseline.ts
+++ b/packages/jobs/src/scripts/backup-baseline.ts
@@ -7,7 +7,7 @@
* warnings come back as data so a test can assert on them.
*/
-import type { Manifest } from "../inngest/functions/tasks/company-backup";
+import type { Manifest } from "../backups/schema";
/** Repo-relative: the same string works for the fetch URL and for `git show`. */
export const SCHEMA_REPO_PATH = "packages/jobs/manifests/schema.json";
diff --git a/packages/jobs/src/scripts/check-backups.ts b/packages/jobs/src/scripts/check-backups.ts
index c65913cc5a..0003aaf412 100644
--- a/packages/jobs/src/scripts/check-backups.ts
+++ b/packages/jobs/src/scripts/check-backups.ts
@@ -29,10 +29,7 @@ import type { KyselyDatabase } from "@carbon/database/client";
import { now } from "@internationalized/date";
import { Kysely, PostgresDialect, sql } from "kysely";
import pg from "pg";
-import type {
- Catalog,
- Manifest
-} from "../inngest/functions/tasks/company-backup";
+import type { Catalog, Manifest } from "../backups/schema";
import {
BACKUP_KIND,
BACKUP_VERSION,
@@ -40,7 +37,7 @@ import {
getCompanyTableCatalog,
reportBackupCompatibility,
selectExportableTables
-} from "../inngest/functions/tasks/company-backup";
+} from "../backups/schema";
import {
BASELINE_BRANCH,
BaselineError,
@@ -55,7 +52,7 @@ const FETCH_TIMEOUT_MS = 3000;
const FIX_HINT =
"Fix: give the new column a DEFAULT (or make it nullable and backfill), or — " +
"if a table was renamed — add an entry to TABLE_RENAMES in " +
- "packages/jobs/src/inngest/functions/tasks/company-backup.renames.ts";
+ "packages/jobs/src/backups/renames.ts";
const RERUN_HINT =
"Re-run on its own with: pnpm db:check:backups\n" +
diff --git a/packages/logger/package.json b/packages/logger/package.json
index 12bce58925..7fd3c006c8 100644
--- a/packages/logger/package.json
+++ b/packages/logger/package.json
@@ -38,6 +38,5 @@
"typecheck": "tsgo --noEmit"
},
"sideEffects": false,
- "version": "0.0.0",
- "type": "module"
+ "version": "0.0.0"
}