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: a renamed table's rows actually restore, instead of only looking restorable

aashu232a97ab85d9
diff --git a/.claude/rules/company-backup-restore.md b/.claude/rules/company-backup-restore.md
index f89f91add8..dd481abf2d 100644
--- a/.claude/rules/company-backup-restore.md
+++ b/.claude/rules/company-backup-restore.md
@@ -129,16 +129,20 @@ postings simply has no `journalLine`/`costLedger` rows; that is data-absence, no
coverage gap. With `includeStorage: "all"`, `buildCompanyBackup` records the
in-scope asset paths in `manifest.storage` and returns them; the job then
`copyAssetsToBackup` them server-side into the backup's `assets/` folder.
-- **Out-of-scope rows are EXCLUDED, not fatal** (`manifest.excludedRows`, a
- `ScopeViolation[]`). `findExportScopeViolationDetails` counts rows whose NOT-NULL
- FK points outside the company's scope; the dump then appends the SAME predicate,
- negated (`outOfScopeRefPredicate`), so the guard's count and the dump's omission
- cannot drift. One `logger.warn` per edge, `excludedRowCount` on the list row.
- Such a row is meaningless without the parent it points at, and the previous
- behaviour — refusing the whole export — left the company with no backup at all
- and reported it as `The system created an invalid backup`, blaming the product for
- a data-integrity finding. Absent on manifests predating the field; read it as `[]`.
- The only remaining hard export failure is a company with no `companyGroupId`.
+- **Out-of-scope rows are FATAL, deliberately.** `findExportScopeViolations` counts
+ rows whose NOT-NULL FK points outside the company's scope, and a non-zero count
+ throws before any table file is written, listing every offending edge.
+
+ **This refusal is a tenant-leak detector, not a backup bug.** RLS hides another
+ tenant's rows from every ordinary read; an export runs without RLS, so it is the
+ first thing in the system with a wide enough view to see a cross-tenant reference
+ at all. An implementation that excluded those rows and finished the backup was
+ built and REVERTED on 2026-08-26 for exactly that reason — it made the only
+ detector we have go quiet, in exchange for a nicer error on a company whose data
+ was already wrong. Do not rebuild it. If the customer cost of a blocked export
+ needs addressing, address it by finding the write path, not by lowering the guard.
+
+ The other hard export failure is a company with no `companyGroupId`.
- **`compatibility.json`**, written by `writeBackupCompatibility`
(`company-compatibility.ts`) immediately AFTER the manifest — never before, since
the manifest is the completion flag. Holds `{ checkedAt, schemaVersion, status,
@@ -278,6 +282,34 @@ 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`
+
+`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. A migration that renames or drops such a table
+must add an entry in the same commit; `db:check:backups` fails the commit until it does,
+and `.claude/rules/workflow-database-migration.md` step 3b is where the author is told.
+
+The map exists because "this table is not in the schema" is ambiguous and the schema cannot
+disambiguate it. Dropped → skipping the rows is correct. Renamed → skipping silently
+discards real data, orphans everything referencing it, and still reports success. So an
+UNMAPPED missing table refuses the restore and names itself, rather than guessing.
+
+`applyTableRenames(catalog, backup)` is what makes a mapping actually do something. It runs
+ONCE, immediately after `readBackup` and before `assertBackupImportable`, in all four load
+paths (restore, restore-revert, template-revert, import), rewriting the manifest table names
+and the `data` keys. Everything downstream — the gate, the closure preflight,
+`wipeAndLoad` — keys off table name, so normalising once is what keeps them from disagreeing;
+before it existed the mapping reached only `reportBackupCompatibility`, so the pre-restore
+screen said "restorable" and the gate then refused with
+`table "X" no longer exists in the current schema`.
+
+Two rules that make cycles safe. The map is consulted **only** for a name the live schema no
+longer has, so after A→B→A the stale `A: "B"` entry is never read and cannot redirect rows
+away from the table they belong to. And resolution is a **single hop**, never a chain — it
+reads one entry and resolves it once against the catalog, so it cannot spin. Anything it
+can't resolve confidently (unmapped, mapped at a name also missing, or mapped at a name this
+same backup already carries) is left untouched for the gate to refuse.
+
## No nightly housekeeping — deliberately
A backup exists because a person took one, and stays until a person deletes it.
@@ -436,27 +468,52 @@ snapshot through exactly this path. See `onboarding-company-templates.md`.
can make. The badge answers the real question, for today.
- UI: `modules/settings/ui/Backups/` — `BackupChoices` (Data only / Data + files),
`BackupSourcePicker`, `BackupProgressModal`, `RestoreReviewRow` (Keep/Revert),
- `RestoreDisclosure` (the pre-restore screen — the ONLY path to a restore now;
- it groups the stored verdict's findings by `tableArea` from `backups.areas.ts`,
- always states delete-and-replace / snapshot / Revert / Keep in that order,
- requires a typed confirmation only when something will be DISCARDED, and offers
- no confirm button at all when a finding blocks). It renders TWO kinds of loss,
- excluded rows FIRST and schema findings after, because they have different
- causes: `ExcludedRows` reports rows the export never wrote (`manifest.excludedRows`,
- a `ScopeViolation[]` of `{table, column, refTable, rows}`, carried through
- `CompanyBackupSummary.excludedRows` in full rather than as the list row's bare
- count) while a finding reports the schema drifting since. **Both gate the typed
- confirmation** — an excluded row exists in the company TODAY and a restore
- deletes today's data, so confirming loses it for good; that it was unrestorable
- junk is not a reason to learn about it afterwards. Both group by `tableArea`, so
- the real case reads "Items, Production" rather than `pickMethod` /
- `jobOperationDependency`,
+ `RestoreDisclosure` (the pre-restore screen — the ONLY path to a restore now),
`BackupContentsInfo` (lazy popover), `format.ts`. `JobProgressModal` tracks real
completion, not a timer: restore/revert poll the status marker; **export** has no
marker, so the route component revalidates the list and passes `completed` once
the new backup actually appears (`exportBaseline` diff) — the dialog never claims
success before the artifact exists.
+### `RestoreDisclosure` — five states, one base sentence
+
+The pre-restore screen. It renders the verdict stored beside the backup, so it costs no
+schema read and cannot disagree with the badge on the list. It is DISCLOSURE, not
+authorization: `assertBackupImportable` runs against the LIVE schema inside the restore, so
+a stale verdict can leave this screen under-informed but can never let through a restore the
+gate would refuse.
+
+Every state opens with the same two sentences — *This company's data is replaced with the
+contents of this backup. Today's data is saved first, so you can revert.* Keep and Revert are
+NOT explained here; they are explained on `RestoreReviewRow`, where they are the actual
+decision. The four-line version that spelled out delete / snapshot / Revert / Keep upfront
+read as a warning label and was cut.
+
+| State | Added copy | Confirm |
+|---|---|---|
+| clean | none | button, no typing |
+| unchecked (uploaded backup, no stored verdict) | "This backup hasn't been checked yet…" | button, no typing |
+| defaults only | `Filled with a default` group | button, no typing |
+| discards | `Discarded` group + "Some records won't come back. Type restore to continue." | typed `restore` |
+| blocked | `Can't be restored` group | **no button at all** |
+
+Findings group by `tableArea` (`backups.areas.ts`) — "Production" means something to the
+person deciding, `jobOperationDependency` does not — with table names in a `Details`
+expander and `Checked <date>` beneath.
+
+The state decision lives in `disclosure-state.ts` (`disclosureState(backup, typed)` →
+`{ unchecked, blocked, discards, canConfirm }`), NOT in the component, and is unit-tested in
+`disclosure-state.test.ts`. That split exists because the states worth seeing are the ones
+nobody can produce by hand; the app has no browser-rendering test setup, so the branching is
+what gets pinned.
+
+There is one state with **no purpose-written copy**: a backup that is not referentially
+closed. `assertReferentiallyClosed` throws inside the restore job with
+`This backup can't be restored: the backup is not self-contained — …`, which surfaces after
+the user clicks Restore, not on this screen — the stored verdict compares table and column
+NAMES, and this is a row-level fact it cannot see. The refusal happens before the wipe, so
+nothing is lost. Known gap.
+
## Onboarding seed
`routes/onboarding+/industry.tsx` → `dataChoice: "template" | "import" | "none"`
diff --git a/.claude/rules/workflow-database-migration.md b/.claude/rules/workflow-database-migration.md
index 8271b0a4c1..2d34cc0658 100644
--- a/.claude/rules/workflow-database-migration.md
+++ b/.claude/rules/workflow-database-migration.md
@@ -84,6 +84,19 @@ newest migrations, e.g. `20260609143732_document-template.sql`):
- **Never**: an `itemReadableId` column, or a precision spec on `NUMERIC`.
- **Views** use `WITH(SECURITY_INVOKER=true)`.
+### 3b. Renaming or dropping a table? Record it for backups
+
+If the migration **renames or drops a table that has a `companyId` or `companyGroupId`
+column**, add an entry to `TABLE_RENAMES` in
+`packages/jobs/src/inngest/functions/tasks/company-backup.renames.ts` in the SAME commit:
+the new name for a rename, `null` for a table dropped along with its feature.
+
+Only you know which of the two it was. A customer's existing backup still names the old
+table, and to a restore "this table is gone" is ambiguous — guessing "dropped" when it was
+really a rename silently discards their rows and still reports success. So an unmapped
+missing table refuses the restore outright, and `pnpm db:check:backups` fails your commit
+until the entry exists.
+
### 4. Update the Zod validators
Update the module's `apps/erp/app/modules/{module}/{module}.models.ts` to match
@@ -111,5 +124,7 @@ alone, `pnpm db:types`. **Do NOT run `npm run db:build` — it does not exist.**
- [ ] RLS enabled with the four standardized policy names (SELECT via
`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
- [ ] Zod validators updated in `{module}.models.ts`
- [ ] Applied locally with `pnpm db:migrate` (regenerates types) — never `db:build`
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.compatibility.test.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.compatibility.test.ts
index d76cf09c8a..8729729acb 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.compatibility.test.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.compatibility.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import {
+ assertBackupImportable,
BACKUP_KIND,
BACKUP_VERSION,
type Catalog,
@@ -227,3 +228,107 @@ describe("reportBackupCompatibility — TABLE_RENAMES", () => {
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("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/inngest/functions/tasks/company-backup.renames.test.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.renames.test.ts
new file mode 100644
index 0000000000..d95542aa67
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.renames.test.ts
@@ -0,0 +1,119 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { applyTableRenames, TABLE_RENAMES } from "./company-backup.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/inngest/functions/tasks/company-backup.renames.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.renames.ts
index 67a0b88ddf..5bfc01b4c1 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.renames.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.renames.ts
@@ -22,3 +22,50 @@
* was never their home.
*/
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 without any of them knowing this file exists.
+ */
+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 rather
+ // than dropping rows, or merging two tables, in silence.
+ 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/inngest/functions/tasks/company-backup.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
index 9288f4420f..875ebbc9e2 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
@@ -335,12 +335,6 @@ export type Manifest = {
tables: Array<{ name: string; rows: number; columns: string[] }>;
storage: Array<{ path: string; size: number; included: boolean }>;
excludedTables: string[];
- /**
- * Rows left OUT of this backup because a NOT-NULL reference escaped company
- * scope, so including them would produce a backup that could never be restored.
- * Absent on manifests written before this field existed — read it as `[]`.
- */
- excludedRows?: ScopeViolation[];
};
export type CompanyBackup = {
@@ -767,69 +761,38 @@ export async function getCompanyTableCatalog(
}
/**
- * Decide whether a backup can be imported into the *current* schema. A backup
- * is a point-in-time snapshot; a breaking migration since then would make the
- * insert fail. Incompatible when, for a table the backup populates, the live
- * schema either no longer has the table, or has gained a required column (NOT
- * NULL, no default, not generated) the backup can't supply. Additive migrations
- * (new nullable/defaulted columns, new tables) stay compatible automatically —
- * so there's no version to bump by hand.
+ * 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
+ * question `reportBackupCompatibility` answers in detail.
+ *
+ * It DELEGATES to that function rather than restating its rules. The two were
+ * separate implementations kept in step by hand, and they drifted: table renames
+ * reached the report but not the gate, so the pre-restore screen said "restorable"
+ * and the restore then refused. A finding is `blocked` or it is not; that decision
+ * now exists in one place.
+ *
+ * Reads only the manifest, so the verdict never depends on which table files a
+ * caller happens to have loaded.
*/
export function assertBackupImportable(
catalog: Catalog,
backup: CompanyBackup
): { ok: true } | { ok: false; reason: string } {
- const { manifest } = backup;
-
- if (manifest.version !== BACKUP_VERSION) {
- return {
- ok: false,
- 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 came from a groupless company and would
- // leave a dangling FK (the export-side guard now prevents producing these).
- if (
- (backup.data.accountDefault?.length ?? 0) > 0 &&
- (backup.data.account?.length ?? 0) === 0
- ) {
- return {
- ok: false,
- reason:
- "it has account defaults but no chart of accounts (exported from a company with no group)"
- };
- }
+ const { findings } = reportBackupCompatibility(catalog, backup.manifest);
+ const blocking = findings.find((f) => f.kind === "blocked");
+ if (!blocking) return { ok: true };
+ return { ok: false, reason: blockingReason(blocking) };
+}
- 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 {
- ok: false,
- reason: `table "${backupTable.name}" no longer exists in the current schema`
- };
- }
- const backupCols = new Set(backupTable.columns);
- const missing = live.columns.find(
- (c) =>
- !c.isNullable &&
- !c.hasDefault &&
- !c.isGenerated &&
- !backupCols.has(c.name)
- );
- if (missing) {
- return {
- ok: false,
- reason: `"${backupTable.name}" now requires column "${missing.name}", which this backup predates`
- };
- }
+/**
+ * A `blocked` finding as one sentence, for a caller with nowhere to render the
+ * `table`/`column` fields the UI shows beside `reason`.
+ */
+function blockingReason(f: CompatibilityFinding): string {
+ if (f.column) {
+ return `"${f.table}" now requires column "${f.column}", which this backup predates`;
}
- return { ok: true };
+ return f.reason;
}
export type CompatibilityFinding = {
@@ -1110,7 +1073,7 @@ export function buildScopeFilter(
* (restore nulls a missing nullable ref) and refs to retained/global/secret
* tables (`user`, `company`, …, and anything not exported).
*/
-export type ScopeViolation = {
+type ScopeViolation = {
table: string;
column: string;
refTable: string;
@@ -1121,12 +1084,6 @@ export type ScopeViolation = {
* The predicate identifying a row whose NOT-NULL FK escapes the referenced
* table's export scope.
*
- * Exported because TWO callers need it and they must never disagree: the guard
- * below counts rows it matches, and `buildCompanyBackup` excludes those same rows
- * from the dump with `NOT (…)`. Two hand-written copies of this expression would
- * eventually diverge, and the failure mode is silent — a backup that claims to
- * have excluded the unrestorable rows while still carrying some.
- *
* 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
@@ -1134,7 +1091,7 @@ export type ScopeViolation = {
* so it still surfaces. This is the one cross-tenant rule, no per-table
* allow-list.
*/
-export function outOfScopeRefPredicate(
+function outOfScopeRefPredicate(
fk: ForeignKey,
parent: TableInfo,
byName: Map<string, TableInfo>,
@@ -1161,10 +1118,9 @@ export function outOfScopeRefPredicate(
/**
* The FK edges this guard considers: NOT-NULL, `id`-targeting, and pointing at
- * another exportable scoped table. Shared by the guard and the exclusion pass for
- * the same reason `outOfScopeRefPredicate` is.
+ * another exportable scoped table.
*/
-export function closureCheckedForeignKeys(
+function closureCheckedForeignKeys(
table: TableInfo,
exportableNames: Set<string>
): ForeignKey[] {
@@ -1186,7 +1142,7 @@ export function closureCheckedForeignKeys(
* 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.
*/
-export async function findExportScopeViolationDetails(
+async function findExportScopeViolationDetails(
db: Kysely<KyselyDatabase>,
exportable: TableInfo[],
byName: Map<string, TableInfo>,
@@ -1229,16 +1185,13 @@ export async function findExportScopeViolationDetails(
}
/** Human-readable form of one violation, e.g. `pickMethod.itemId → item (1 row)`. */
-export function formatScopeViolation(v: ScopeViolation): string {
+function formatScopeViolation(v: ScopeViolation): string {
return `${v.table}.${v.column} → ${v.refTable} (${v.rows} row${
v.rows === 1 ? "" : "s"
})`;
}
-/**
- * Export-time closure guard, string form — kept for the monitor and for log
- * messages. A thin formatter over `findExportScopeViolationDetails`.
- */
+/** Export-time closure guard: one readable line per offending FK edge. */
export async function findExportScopeViolations(
db: Kysely<KyselyDatabase>,
exportable: TableInfo[],
diff --git a/packages/jobs/src/inngest/functions/tasks/company-import.ts b/packages/jobs/src/inngest/functions/tasks/company-import.ts
index 651958c118..a0ac78a243 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-import.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-import.ts
@@ -19,6 +19,7 @@ import {
restoreAssetsFromBackup,
SECRET_TABLES
} from "./company-backup";
+import { applyTableRenames } from "./company-backup.renames";
import {
buildRowTransforms,
loadSubstrateIds
@@ -75,15 +76,12 @@ export const companyImportFunction = inngest.createFunction(
}
const name = backupNameFromSource(filePath);
- const backup = await readBackup(client, companyId, name);
+ const raw = await readBackup(client, companyId, name);
- if (
- mode === "preserve" &&
- backup.manifest.sourceCompanyId !== companyId
- ) {
+ if (mode === "preserve" && raw.manifest.sourceCompanyId !== companyId) {
throw new Error(
"Preserve mode requires importing into the same company the artifact " +
- `was exported from (${backup.manifest.sourceCompanyId}). ` +
+ `was exported from (${raw.manifest.sourceCompanyId}). ` +
"Use reseed mode to import into a different company."
);
}
@@ -115,6 +113,8 @@ export const companyImportFunction = inngest.createFunction(
const targetGroupId = targetCompany.data?.companyGroupId ?? null;
const catalog = await getCompanyTableCatalog(db);
+ // Renamed tables move onto their current names before the gate sees them.
+ const backup = applyTableRenames(catalog, raw);
const compatibility = assertBackupImportable(catalog, backup);
if (!compatibility.ok) {
throw new Error(
diff --git a/packages/jobs/src/inngest/functions/tasks/company-restore.ts b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
index b1ce4e1f6a..1b8515f0ce 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-restore.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
@@ -24,6 +24,7 @@ import {
wipeScopedData,
writeBackupManifest
} from "./company-backup";
+import { applyTableRenames } from "./company-backup.renames";
import {
assertReferentiallyClosed,
buildRowTransforms,
@@ -415,7 +416,7 @@ export const companyRestoreFunction = inngest.createFunction(
try {
const name = backupNameFromSource(filePath);
- const backup = await readBackup(client, companyId, name);
+ const raw = await readBackup(client, companyId, name);
const { targetGroupId, includeGroup } = await resolveRestoreScope(
client,
companyId
@@ -423,7 +424,7 @@ export const companyRestoreFunction = inngest.createFunction(
// A backup from ANOTHER company must re-stamp the chart of accounts onto
// this group, so it's only allowed when the group is this company's alone.
- const foreign = backup.manifest.sourceCompanyId !== companyId;
+ const foreign = raw.manifest.sourceCompanyId !== companyId;
if (foreign && !includeGroup) {
throw new Error(
!targetGroupId
@@ -437,6 +438,10 @@ export const companyRestoreFunction = inngest.createFunction(
}
const catalog = await getCompanyTableCatalog(db);
+ // Move renamed tables onto their current names BEFORE the gate, so the
+ // gate, the closure preflight and the load all agree on what this backup
+ // contains. An unmapped missing table survives this and the gate refuses it.
+ const backup = applyTableRenames(catalog, raw);
const compatibility = assertBackupImportable(catalog, backup);
if (!compatibility.ok) {
throw new Error(
@@ -656,9 +661,11 @@ export const companyRestoreRevertFunction = inngest.createFunction(
// check). Wipe + reload the SAME scope the forward restore touched so the
// undo is exact — including group data (chart of accounts) when the
// forward run covered it.
- const snapshot = await readBackup(client, companyId, snapshotPath);
+ const rawSnapshot = await readBackup(client, companyId, snapshotPath);
const targetGroupId = await getCompanyGroupId(client, companyId);
const catalog = await getCompanyTableCatalog(db);
+ // A snapshot predates any migration deployed since the restore it undoes.
+ const snapshot = applyTableRenames(catalog, rawSnapshot);
const { rows, idRewrite } = await wipeAndLoad(db, catalog, snapshot, {
companyId,
userId: "",
diff --git a/packages/jobs/src/inngest/functions/tasks/company-template.ts b/packages/jobs/src/inngest/functions/tasks/company-template.ts
index 80a9608401..b5df4e527e 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-template.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-template.ts
@@ -17,6 +17,7 @@ import {
throttleProgress,
writeBackupManifest
} from "./company-backup";
+import { applyTableRenames } from "./company-backup.renames";
import { buildCompanyBackup } from "./company-export";
import { resolveRestoreScope, wipeAndLoad } from "./company-restore";
@@ -435,9 +436,11 @@ export const companyTemplateRevertFunction = inngest.createFunction(
// SAME scope the forward apply covered so the undo is exact. Note this is
// the restore engine's tabula-rasa wipe, not the dataset wipe the forward
// apply used: the snapshot carries the config back, so nothing is kept.
- const snapshot = await readBackup(client, companyId, snapshotPath);
+ const rawSnapshot = await readBackup(client, companyId, snapshotPath);
const { targetGroupId } = await resolveRestoreScope(client, companyId);
const catalog = await getCompanyTableCatalog(db);
+ // A snapshot predates any migration deployed since the apply it undoes.
+ const snapshot = applyTableRenames(catalog, rawSnapshot);
const { rows, idRewrite } = await wipeAndLoad(db, catalog, snapshot, {
companyId,
userId: "",