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.

feat: an export skips unrestorable rows instead of refusing the whole backup

aashu38d196d5166a
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
new file mode 100644
index 0000000000..d76cf09c8a
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.compatibility.test.ts
@@ -0,0 +1,229 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ BACKUP_KIND,
+ BACKUP_VERSION,
+ type Catalog,
+ type ColumnInfo,
+ type Manifest,
+ reportBackupCompatibility,
+ type TableInfo
+} from "./company-backup";
+
+vi.mock("./company-backup.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");
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.exportable.test.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.exportable.test.ts
new file mode 100644
index 0000000000..9d8e70cef2
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.exportable.test.ts
@@ -0,0 +1,136 @@
+import { describe, expect, it } from "vitest";
+import type { Catalog, ColumnInfo, TableInfo } from "./company-backup";
+import {
+ exportableColumns,
+ SECRET_TABLES,
+ selectExportableTables
+} from "./company-backup";
+
+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/inngest/functions/tasks/company-backup.renames.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.renames.ts
new file mode 100644
index 0000000000..67a0b88ddf
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.renames.ts
@@ -0,0 +1,24 @@
+/**
+ * Tenant-scoped tables that have been RENAMED or DROPPED, so an older backup
+ * naming them can still be read.
+ *
+ * THE CONTRACT: a migration that renames or drops a tenant-scoped table MUST add
+ * an entry here. A missing entry is a deliberate hard refusal, not an oversight to
+ * paper over.
+ *
+ * Why this file has to exist: "the table is not in the current schema" means two
+ * completely different things, and the schema cannot tell them apart.
+ *
+ * - Dropped with its feature → the rows are meaningless now, skipping is correct.
+ * - RENAMED → skipping silently discards real data AND orphans everything that
+ * references it, while the restore reports success. That is strictly worse than
+ * refusing, because nobody finds out.
+ *
+ * Guessing between those two is how a restore quietly loses a customer's data, so
+ * an unmapped missing table blocks the restore and names itself.
+ *
+ * Deliberately starts EMPTY. No historical entries have been invented — a wrong
+ * mapping is worse than no mapping, since it would redirect rows into a table that
+ * was never their home.
+ */
+export const TABLE_RENAMES: Record<string, string | null> = {};
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
index 1fda4d49cc..9288f4420f 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
@@ -8,6 +8,7 @@ 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";
const log = getLogger("jobs", "company-backup");
@@ -291,6 +292,35 @@ export type Catalog = {
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;
@@ -305,6 +335,12 @@ 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 = {
@@ -796,6 +832,141 @@ export function assertBackupImportable(
return { ok: true };
}
+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]));
+ 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;
+ }
+ 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),
@@ -939,66 +1110,152 @@ export function buildScopeFilter(
* (restore nulls a missing nullable ref) and refs to retained/global/secret
* tables (`user`, `company`, …, and anything not exported).
*/
-export async function findExportScopeViolations(
+export 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.
+ *
+ * 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
+ * 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.
+ */
+export 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. Shared by the guard and the exclusion pass for
+ * the same reason `outOfScopeRefPredicate` is.
+ */
+export 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.
+ */
+export async function findExportScopeViolationDetails(
db: Kysely<KyselyDatabase>,
exportable: TableInfo[],
byName: Map<string, TableInfo>,
companyId: string,
companyGroupId: string | null
-): Promise<string[]> {
+): Promise<ScopeViolation[]> {
const exportableNames = new Set(exportable.map((t) => t.name));
- const checks: Array<{ desc: string; query: RawBuilder<{ n: string }> }> = [];
+ const checks: Array<{
+ violation: Omit<ScopeViolation, "rows">;
+ query: RawBuilder<{ n: string }>;
+ }> = [];
for (const t of exportable) {
- 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
+ for (const fk of closureCheckedForeignKeys(t, exportableNames)) {
const parent = byName.get(fk.refTable)!;
const childScope = buildScopeFilter(t, byName, companyId, companyGroupId);
- const parentScope = buildScopeFilter(
- parent,
- byName,
- companyId,
- companyGroupId
- );
- // 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 — widen the
- // existence set to include it. A ref to a row owned by a different company
- // (scopeCol = some other value) is still NOT matched, so it still surfaces.
- // This is the one cross-tenant rule, no per-table allow-list.
- const parentExistence =
- parent.scope.kind === "direct"
- ? sql`${parentScope} OR ${sql.id(parent.scope.column)} IS NULL`
- : parentScope;
checks.push({
- desc: `${t.name}.${fk.column} → ${fk.refTable}`,
+ violation: { table: t.name, column: fk.column, refTable: fk.refTable },
query: sql<{ n: string }>`
SELECT count(*)::text AS n
FROM ${sql.id(t.name)}
WHERE ${childScope}
- 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}
- )`
+ AND ${outOfScopeRefPredicate(
+ fk,
+ parent,
+ byName,
+ companyId,
+ companyGroupId
+ )}`
});
}
}
- const violations: string[] = [];
+ const violations: ScopeViolation[] = [];
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.desc} (${n} row${n === 1 ? "" : "s"})`);
+ if (n > 0) violations.push({ ...c.violation, rows: n });
});
return violations;
}
+/** Human-readable form of one violation, e.g. `pickMethod.itemId → item (1 row)`. */
+export 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 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-compatibility.test.ts b/packages/jobs/src/inngest/functions/tasks/company-compatibility.test.ts
new file mode 100644
index 0000000000..b0de96f699
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/company-compatibility.test.ts
@@ -0,0 +1,190 @@
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { describe, expect, it, vi } from "vitest";
+import {
+ BACKUP_KIND,
+ BACKUP_VERSION,
+ type Catalog,
+ type ColumnInfo,
+ type Manifest,
+ type TableInfo
+} from "./company-backup";
+import {
+ backupCompatibilityPath,
+ compatibilityStatus,
+ writeBackupCompatibility
+} from "./company-compatibility";
+
+vi.mock("./company-backup.renames", () => ({ TABLE_RENAMES: {} }));
+
+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: "20260825075035",
+ tables
+});
+
+function manifest(tables: Manifest["tables"]): Manifest {
+ return {
+ kind: BACKUP_KIND,
+ version: BACKUP_VERSION,
+ schemaVersion: "20260101000000",
+ 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: []
+ };
+}
+
+/** Records what was uploaded, so a test can read the stored JSON back. */
+function fakeClient(uploadError?: string) {
+ const uploads: Array<{ path: string; body: string }> = [];
+ const client = {
+ storage: {
+ from: () => ({
+ upload: async (path: string, body: Buffer) => {
+ uploads.push({ path, body: body.toString("utf8") });
+ return uploadError
+ ? { error: { message: uploadError } }
+ : { error: null };
+ }
+ })
+ }
+ } as unknown as SupabaseClient;
+ return { client, uploads };
+}
+
+describe("compatibilityStatus", () => {
+ it("is ready when nothing differs", () => {
+ expect(compatibilityStatus({ findings: [], blocked: false })).toBe("ready");
+ });
+
+ it("is restorable-with-changes when there are findings but none block", () => {
+ expect(
+ compatibilityStatus({
+ findings: [
+ { kind: "defaulted", table: "item", column: "x", reason: "r" }
+ ],
+ blocked: false
+ })
+ ).toBe("restorable-with-changes");
+ });
+
+ it("is not-restorable as soon as one finding blocks", () => {
+ expect(
+ compatibilityStatus({
+ findings: [
+ { kind: "defaulted", table: "item", column: "x", reason: "r" },
+ { kind: "blocked", table: "item", column: "y", reason: "r" }
+ ],
+ blocked: true
+ })
+ ).toBe("not-restorable");
+ });
+});
+
+describe("backupCompatibilityPath", () => {
+ it("sits beside the manifest in the backup's own folder", () => {
+ expect(backupCompatibilityPath("2026-02-01_backup")).toBe(
+ "exports/2026-02-01_backup/compatibility.json"
+ );
+ });
+});
+
+describe("writeBackupCompatibility", () => {
+ it("stores a ready verdict against the schema it was checked on", async () => {
+ const { client, uploads } = fakeClient();
+
+ const stored = await writeBackupCompatibility(
+ client,
+ "company-a",
+ "b1",
+ catalog([table("item", [col("id"), col("name")])]),
+ manifest([{ name: "item", rows: 3, columns: ["id", "name"] }]),
+ "2026-02-01T00:00:00.000Z"
+ );
+
+ expect(stored.status).toBe("ready");
+ expect(stored.findings).toEqual([]);
+ // The catalog's version, not the backup's — a verdict is only true of the
+ // schema it was compared against.
+ expect(stored.schemaVersion).toBe("20260825075035");
+ expect(uploads).toHaveLength(1);
+ expect(uploads[0]?.path).toBe("exports/b1/compatibility.json");
+ expect(JSON.parse(uploads[0]?.body ?? "{}")).toEqual(stored);
+ });
+
+ it("stores the findings that make a backup restorable-with-changes", async () => {
+ const { client, uploads } = fakeClient();
+
+ const stored = await writeBackupCompatibility(
+ client,
+ "company-a",
+ "b2",
+ catalog([table("item", [col("id"), col("uom", { hasDefault: true })])]),
+ manifest([{ name: "item", rows: 1, columns: ["id"] }]),
+ "2026-02-01T00:00:00.000Z"
+ );
+
+ expect(stored.status).toBe("restorable-with-changes");
+ expect(stored.findings).toHaveLength(1);
+ expect(JSON.parse(uploads[0]?.body ?? "{}").findings[0]).toMatchObject({
+ kind: "defaulted",
+ column: "uom"
+ });
+ });
+
+ it("stores not-restorable rather than omitting a verdict it cannot honour", async () => {
+ const { client } = fakeClient();
+
+ const stored = await writeBackupCompatibility(
+ client,
+ "company-a",
+ "b3",
+ catalog([table("item", [col("id"), col("uom")])]),
+ manifest([{ name: "item", rows: 1, columns: ["id"] }]),
+ "2026-02-01T00:00:00.000Z"
+ );
+
+ expect(stored.status).toBe("not-restorable");
+ });
+
+ it("throws when the upload fails, so the caller decides whether it matters", async () => {
+ const { client } = fakeClient("bucket unavailable");
+
+ await expect(
+ writeBackupCompatibility(
+ client,
+ "company-a",
+ "b4",
+ catalog([table("item", [col("id")])]),
+ manifest([{ name: "item", rows: 1, columns: ["id"] }]),
+ "2026-02-01T00:00:00.000Z"
+ )
+ ).rejects.toThrow("bucket unavailable");
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/tasks/company-compatibility.ts b/packages/jobs/src/inngest/functions/tasks/company-compatibility.ts
new file mode 100644
index 0000000000..4b721d2a8c
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/company-compatibility.ts
@@ -0,0 +1,98 @@
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { Catalog, CompatibilityFinding, Manifest } from "./company-backup";
+import { EXPORTS_PREFIX, reportBackupCompatibility } from "./company-backup";
+
+/**
+ * The precomputed "can this still be restored?" verdict, stored beside the
+ * backup it describes.
+ *
+ * WHY A FILE. The comparison needs `reportBackupCompatibility` and a live schema
+ * read, both of which live on the jobs side — and `@carbon/jobs` deliberately
+ * exposes only `.`, `./events`, `./inngest` and `./worker`, with its AGENTS.md
+ * forbidding app code from importing job internals. Rather than widen that
+ * contract, the jobs side computes the verdict once and writes it where the app
+ * already reads: storage. The app then treats it like any other stored fact, and
+ * the Backups page costs no `information_schema` query per render.
+ *
+ * Written ONCE, by the export job, so a fresh backup has a verdict immediately.
+ * It is never refreshed, and `checkedAt` is therefore always the export date —
+ * the verdict is a dated fact about the schema of that day, not a claim about
+ * today's. A nightly re-check existed and was removed (2026-08-25): rot is
+ * prevented at commit time by `pnpm db:check:backups`, and re-deciding it after
+ * the breaking change is already in production repaired nothing and alerted
+ * nobody. The live gate is `assertBackupImportable` inside the restore itself.
+ */
+/**
+ * Not exported: nothing outside this file can use it. `backupCompatibilityPath`
+ * below is the only way to build the path, and the ERP reader cannot import from
+ * here at all — `listCompanyBackups` in `apps/erp/app/modules/settings/
+ * backups.service.ts` repeats this string and the status union by hand, because app
+ * code may not import job internals. Change either one and that reader silently
+ * finds nothing, which the UI reports as "not yet checked". Update both together.
+ */
+const COMPATIBILITY_FILE = "compatibility.json";
+
+export type BackupCompatibilityStatus =
+ | "ready"
+ | "restorable-with-changes"
+ | "not-restorable";
+
+export type StoredCompatibility = {
+ /** When this verdict was computed — a verdict is only true of one schema. */
+ checkedAt: string;
+ /** The schema it was checked against, so a stale verdict is recognisable. */
+ schemaVersion: string;
+ status: BackupCompatibilityStatus;
+ findings: CompatibilityFinding[];
+};
+
+export function backupCompatibilityPath(name: string): string {
+ return `${EXPORTS_PREFIX}/${name}/${COMPATIBILITY_FILE}`;
+}
+
+/** Map a compatibility report onto the shared five-word 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";
+}
+
+/**
+ * Compute the verdict for one backup and store it next to its manifest.
+ *
+ * MUST be called after `writeBackupManifest`, never before: `manifest.json` is the
+ * completion flag for the whole folder, and a verdict appearing first would
+ * describe a backup the UI still considers unfinished.
+ */
+export async function writeBackupCompatibility(
+ client: SupabaseClient,
+ companyId: string,
+ name: string,
+ catalog: Catalog,
+ manifest: Manifest,
+ checkedAt: string
+): Promise<StoredCompatibility> {
+ const report = reportBackupCompatibility(catalog, manifest);
+ const stored: StoredCompatibility = {
+ checkedAt,
+ schemaVersion: catalog.schemaVersion,
+ status: compatibilityStatus(report),
+ findings: report.findings
+ };
+
+ const up = await client.storage
+ .from(companyId)
+ .upload(
+ backupCompatibilityPath(name),
+ Buffer.from(JSON.stringify(stored)),
+ {
+ contentType: "application/json",
+ upsert: true
+ }
+ );
+ if (up.error) throw new Error(`compatibility: ${up.error.message}`);
+
+ return stored;
+}
diff --git a/packages/jobs/src/inngest/functions/tasks/company-export.exclusions.test.ts b/packages/jobs/src/inngest/functions/tasks/company-export.exclusions.test.ts
new file mode 100644
index 0000000000..1f70eeb499
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/company-export.exclusions.test.ts
@@ -0,0 +1,153 @@
+import {
+ DummyDriver,
+ Kysely,
+ PostgresAdapter,
+ PostgresIntrospector,
+ PostgresQueryCompiler,
+ sql
+} from "kysely";
+import { describe, expect, it } from "vitest";
+import type { ColumnInfo, ForeignKey, TableInfo } from "./company-backup";
+import {
+ closureCheckedForeignKeys,
+ formatScopeViolation,
+ outOfScopeRefPredicate
+} from "./company-backup";
+
+/** Compiles SQL without a connection. */
+const db = new Kysely<never>({
+ dialect: {
+ createAdapter: () => new PostgresAdapter(),
+ createDriver: () => new DummyDriver(),
+ createIntrospector: (i) => new PostgresIntrospector(i),
+ createQueryCompiler: () => new PostgresQueryCompiler()
+ }
+});
+
+const col = (name: string, isNullable = false): ColumnInfo => ({
+ name,
+ dataType: "text",
+ udtName: "text",
+ isNullable,
+ isGenerated: false,
+ hasDefault: false
+});
+
+const table = (
+ name: string,
+ columns: ColumnInfo[],
+ foreignKeys: ForeignKey[] = []
+): TableInfo => ({
+ name,
+ columns,
+ scope: { kind: "direct", column: "companyId" },
+ scopeColumn: "companyId",
+ pkColumns: ["id", "companyId"],
+ uniqueColumns: [],
+ hasId: false,
+ foreignKeys
+});
+
+const job = table("job", [col("id"), col("companyId")]);
+const byName = new Map([["job", job]]);
+const exportableNames = new Set(["job", "jobOperationDependency"]);
+
+describe("closureCheckedForeignKeys", () => {
+ it("keeps a NOT-NULL id reference to another exportable scoped table", () => {
+ const t = table(
+ "jobOperationDependency",
+ [col("jobId"), col("companyId")],
+ [{ column: "jobId", refTable: "job", refColumn: "id" }]
+ );
+ expect(
+ closureCheckedForeignKeys(t, exportableNames).map((f) => f.column)
+ ).toEqual(["jobId"]);
+ });
+
+ it("skips a nullable reference — a restore nulls it rather than dangling", () => {
+ const t = table(
+ "jobOperationDependency",
+ [col("jobId", true), col("companyId")],
+ [{ column: "jobId", refTable: "job", refColumn: "id" }]
+ );
+ expect(closureCheckedForeignKeys(t, exportableNames)).toEqual([]);
+ });
+
+ it("skips a reference to a retained global table", () => {
+ const t = table(
+ "jobOperationDependency",
+ [col("createdBy"), col("companyId")],
+ [{ column: "createdBy", refTable: "user", refColumn: "id" }]
+ );
+ expect(closureCheckedForeignKeys(t, exportableNames)).toEqual([]);
+ });
+
+ it("skips a reference to a table that is not exported at all", () => {
+ const t = table(
+ "apiKeyRateLimit",
+ [col("apiKeyId"), col("companyId")],
+ [{ column: "apiKeyId", refTable: "apiKey", refColumn: "id" }]
+ );
+ expect(closureCheckedForeignKeys(t, exportableNames)).toEqual([]);
+ });
+});
+
+describe("outOfScopeRefPredicate", () => {
+ const fk: ForeignKey = { column: "jobId", refTable: "job", refColumn: "id" };
+ const compiled = () =>
+ outOfScopeRefPredicate(fk, job, byName, "company-a", "group-a").compile(db)
+ .sql;
+
+ it("matches only rows whose reference is set and resolves nowhere in scope", () => {
+ const s = compiled();
+ expect(s).toContain(`"jobId" IS NOT NULL`);
+ expect(s).toContain(`"jobId" NOT IN`);
+ expect(s).toContain(`FROM "job"`);
+ });
+
+ it("widens the parent set to companyId IS NULL — shared seeded substrate", () => {
+ // Global material/currency rows live in every target, so a reference to one
+ // is never a closure gap. A reference to ANOTHER company's row still is.
+ expect(compiled()).toContain(`"companyId" IS NULL`);
+ });
+
+ it("is the exact expression the dump negates, so guard and exclusion cannot drift", () => {
+ // The whole point of exporting this predicate: the guard counts rows it
+ // matches and the dump drops those same rows with NOT (...). If these two
+ // ever came from separate expressions, a backup could claim to have excluded
+ // unrestorable rows while still carrying some.
+ const predicate = outOfScopeRefPredicate(
+ fk,
+ job,
+ byName,
+ "company-a",
+ "group-a"
+ );
+ const inner = predicate.compile(db).sql;
+ const negated = sql`true AND NOT (${predicate})`.compile(db).sql;
+
+ expect(negated).toContain(`NOT (${inner})`);
+ });
+});
+
+describe("formatScopeViolation", () => {
+ it("reads like the message operators already know, and gets plurals right", () => {
+ expect(
+ formatScopeViolation({
+ table: "pickMethod",
+ column: "itemId",
+ refTable: "item",
+ rows: 1
+ })
+ ).toBe("pickMethod.itemId → item (1 row)");
+
+ expect(
+ formatScopeViolation({
+ table: "jobOperationDependency",
+ column: "jobId",
+ refTable: "job",
+ rows: 3
+ })
+ ).toBe("jobOperationDependency.jobId → job (3 rows)");
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/tasks/company-export.ts b/packages/jobs/src/inngest/functions/tasks/company-export.ts
index 788ec2f86c..c44af65575 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-export.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-export.ts
@@ -2,7 +2,12 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { sql } from "kysely";
import { getJobDatabaseClient, type JobDatabase } from "../../../db";
import { inngest } from "../../client";
-import type { Manifest } from "./company-backup";
+import type {
+ Catalog,
+ ForeignKey,
+ Manifest,
+ ScopeViolation
+} from "./company-backup";
import {
BACKUP_INTEGRATION,
BACKUP_KIND,
@@ -10,16 +15,21 @@ import {
backupAssetsDir,
backupTablePath,
buildScopeFilter,
+ closureCheckedForeignKeys,
copyAssetsToBackup,
encodeValue,
- findExportScopeViolations,
+ exportableColumns,
+ findExportScopeViolationDetails,
+ formatScopeViolation,
getCompanyTableCatalog,
mapWithConcurrency,
- SECRET_TABLES,
+ outOfScopeRefPredicate,
STORAGE_BUCKET,
+ selectExportableTables,
serializeTable,
writeBackupManifest
} from "./company-backup";
+import { writeBackupCompatibility } from "./company-compatibility";
// Assets are copied server-side into the backup's `assets/` folder (no bytes pass
// through this process), so there's no memory reason to cap a single file — the
@@ -61,9 +71,13 @@ export async function buildCompanyBackup(
): Promise<{
name: string;
manifest: Manifest;
+ /** The schema this backup was taken against — the compatibility verdict's baseline. */
+ catalog: Catalog;
rows: number;
/** `private`-bucket paths to copy into the backup's `assets/` folder. */
assetSourcePaths: string[];
+ /** Rows omitted because a NOT-NULL reference escaped company scope. */
+ excludedRows: ScopeViolation[];
}> {
const { companyId, userId, includeStorage } = opts;
const label = opts.label ?? null;
@@ -100,50 +114,73 @@ export async function buildCompanyBackup(
// Secrets (credentials/tokens) never travel — they belong to the source
// company, not a copy. (Billing identity like companyPlan never enters the
// catalog: it's a company-singleton deliberately left out of the scoped set.)
- const secretTables = new Set<string>(SECRET_TABLES);
- const excludedTables = catalog.tables
- .filter((t) => secretTables.has(t.name))
- .map((t) => t.name);
- const exportable = catalog.tables.filter((t) => !secretTables.has(t.name));
+ const { exportable, excludedTables } = selectExportableTables(catalog);
const byName = new Map(catalog.tables.map((t) => [t.name, t]));
// Closure guard — never write a backup that couldn't be restored. A NOT-NULL FK
// pointing outside the company's scope (cross-company / out-of-scope) would dump
- // the child but not its parent, dangling on restore. Fail BEFORE writing any
- // table file, listing every offending FK.
- const scopeViolations = await findExportScopeViolations(
+ // the child but not its parent, dangling on restore.
+ //
+ // These rows are EXCLUDED rather than fatal. Refusing the whole export left a
+ // company with no backup at all over a handful of rows that are meaningless
+ // without the parent they point at — and reported it as "the system created an
+ // invalid backup", blaming the product for a data-integrity finding. The
+ // exclusion is recorded in the manifest and surfaced in the UI so it is a
+ // disclosed omission, not a silent one.
+ const scopeViolations = await findExportScopeViolationDetails(
db,
exportable,
byName,
companyId,
companyGroupId
);
- if (scopeViolations.length > 0) {
- throw new Error(
- `Refusing to export ${companyId}: ${scopeViolations.length} NOT-NULL reference(s) ` +
- `escape company scope, so the backup could never be restored:\n ${scopeViolations.join(
- "\n "
- )}`
+ // table → the FK edges whose out-of-scope rows must be excluded from its dump.
+ const exclusionsByTable = new Map<string, ForeignKey[]>();
+ const exportableNames = new Set(exportable.map((t) => t.name));
+ for (const v of scopeViolations) {
+ const table = byName.get(v.table)!;
+ const fk = closureCheckedForeignKeys(table, exportableNames).find(
+ (f) => f.column === v.column && f.refTable === v.refTable
);
+ if (!fk) continue;
+ exclusionsByTable.set(v.table, [
+ ...(exclusionsByTable.get(v.table) ?? []),
+ fk
+ ]);
}
// Dump each non-empty table to its own `tables/<table>.ndjson.gz`, in parallel.
const tableManifest: Manifest["tables"] = [];
let dumped = 0; // incremented as each table completes (single-threaded → safe)
await mapWithConcurrency(exportable, TABLE_CONCURRENCY, async (table) => {
- const columns = table.columns.filter((c) => !c.isGenerated);
+ const columns = exportableColumns(table);
// a prior import's revert ledger must never travel in an artifact
const ledgerFilter =
table.name === "externalIntegrationMapping"
? sql` AND ${sql.id("integration")} != ${BACKUP_INTEGRATION}`
: sql``;
+ // Rows whose NOT-NULL reference escapes company scope are dropped here, using
+ // the SAME predicate the guard above counted them with, negated. One
+ // expression, two uses — the guard's count and the dump's omission cannot
+ // drift apart.
+ const exclusionFilter = (exclusionsByTable.get(table.name) ?? []).reduce(
+ (acc, fk) =>
+ sql`${acc} AND NOT (${outOfScopeRefPredicate(
+ fk,
+ byName.get(fk.refTable)!,
+ byName,
+ companyId,
+ companyGroupId
+ )})`,
+ sql``
+ );
// Direct-scoped tables filter by their companyId/companyGroupId column;
// transitively-scoped child tables (contacts, line prices, …) filter through
// their parent FK — see buildScopeFilter.
const result = await sql<Record<string, unknown>>`
SELECT ${sql.join(columns.map((c) => sql.id(c.name)))}
FROM ${sql.id(table.name)}
- WHERE ${buildScopeFilter(table, byName, companyId, companyGroupId)}${ledgerFilter}
+ WHERE ${buildScopeFilter(table, byName, companyId, companyGroupId)}${ledgerFilter}${exclusionFilter}
`.execute(db);
if (result.rows.length === 0) {
@@ -223,13 +260,21 @@ export async function buildCompanyBackup(
includeStorage,
tables: tableManifest,
storage: storageManifest,
- excludedTables
+ excludedTables,
+ excludedRows: scopeViolations
};
// The manifest is NOT written here — the caller writes it LAST (after assets)
// via writeBackupManifest, so its presence marks the backup as complete.
const rows = tableManifest.reduce((sum, t) => sum + t.rows, 0);
- return { name, manifest, rows, assetSourcePaths };
+ return {
+ name,
+ manifest,
+ catalog,
+ rows,
+ assetSourcePaths,
+ excludedRows: scopeViolations
+ };
}
// One company-scoped progress marker (exports run one-at-a-time, so no run id).
@@ -326,14 +371,36 @@ export const companyExportFunction = inngest.createFunction(
};
try {
- const { name, manifest, rows, assetSourcePaths } =
- await buildCompanyBackup(client, db, {
+ const {
+ name,
+ manifest,
+ catalog,
+ rows,
+ assetSourcePaths,
+ excludedRows
+ } = await buildCompanyBackup(client, db, {
+ companyId,
+ userId,
+ label,
+ includeStorage,
+ onProgress: report
+ });
+
+ // One line per excluded edge. A cross-tenant reference is an engineering
+ // escalation even though the export now succeeds — the nightly
+ // tenant-integrity monitor is the systematic detector, this is the
+ // in-context record of what this particular backup left out.
+ for (const v of excludedRows) {
+ logger.warn("Company export excluded out-of-scope rows", {
companyId,
- userId,
- label,
- includeStorage,
- onProgress: report
+ name,
+ table: v.table,
+ column: v.column,
+ refTable: v.refTable,
+ rows: v.rows,
+ detail: formatScopeViolation(v)
});
+ }
// Copy the in-scope assets server-side into the backup's `assets/` folder.
// Best-effort (matches restore/import): the table files are already
@@ -357,6 +424,31 @@ export const companyExportFunction = inngest.createFunction(
// never shows a half-written backup as ready.
await writeBackupManifest(client, companyId, name, manifest);
+ // The compatibility verdict, written AFTER the manifest so it can never
+ // make an unfinished backup look complete. This is the ONLY place it is
+ // written. Best-effort: a backup whose verdict failed to write reads as
+ // "not yet checked", and an absent answer is not a bad one — losing a
+ // committed backup over a missing advisory badge would be.
+ try {
+ await writeBackupCompatibility(
+ client,
+ companyId,
+ name,
+ catalog,
+ manifest,
+ manifest.exportedAt
+ );
+ } catch (err) {
+ logger.warn(
+ "Company export could not record a compatibility verdict",
+ {
+ companyId,
+ name,
+ error: err instanceof Error ? err.message : String(err)
+ }
+ );
+ }
+
logger.info("Company export complete", {
companyId,
name,