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: compute the backup compatibility verdict against today's schema

Sidwebworks6e4417a31d24
diff --git a/apps/erp/app/modules/settings/backups.server.ts b/apps/erp/app/modules/settings/backups.server.ts
index d2db3aac67..2a56f05fbf 100644
--- a/apps/erp/app/modules/settings/backups.server.ts
+++ b/apps/erp/app/modules/settings/backups.server.ts
@@ -1,10 +1,58 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Database } from "@carbon/database";
import { trigger } from "@carbon/jobs";
+import {
+ compatibilityStatus,
+ getCompanyTableCatalog,
+ reportBackupCompatibility
+} from "@carbon/jobs/backups";
+import type { SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
+import { getDatabaseClient } from "~/services/database.server";
+import {
+ type CompanyBackupSummary,
+ listCompanyBackupFolders
+} from "./backups.service";
-// Server-only: enqueues the in-place restore inngest jobs. Kept out of the
-// route module so `@carbon/jobs` (which pulls Node `Buffer` via the Inngest
-// client) never lands in the browser bundle.
+// Server-only: enqueues the in-place restore inngest jobs and computes the
+// live compatibility verdict. Kept out of the route module so `@carbon/jobs`
+// (which pulls Node `Buffer` via the Inngest client) never lands in the
+// browser bundle.
+
+/**
+ * The Backups loader's list: each ready backup's manifest diffed against
+ * TODAY's schema, so the badge and the restore disclosure describe what a
+ * restore would actually do right now. Computed on every load rather than
+ * stored — a verdict written at export time compares the manifest against the
+ * very schema it was projected from and can only ever say "ready".
+ */
+export async function getCompanyBackups(
+ client: SupabaseClient<Database>,
+ companyId: string
+): Promise<{ data: CompanyBackupSummary[] | null; error: Error | null }> {
+ const { data, error } = await listCompanyBackupFolders(client, companyId);
+ if (error || !data) return { data: null, error };
+
+ // One schema read per page load, shared by every row.
+ const catalog = data.some((b) => b.manifest)
+ ? await getCompanyTableCatalog(getDatabaseClient())
+ : null;
+
+ return {
+ data: data.map(({ manifest, ...summary }) => {
+ if (!catalog || !manifest) return summary;
+ const report = reportBackupCompatibility(catalog, manifest);
+ return {
+ ...summary,
+ compatibility: {
+ status: compatibilityStatus(report),
+ findings: report.findings
+ }
+ };
+ }),
+ error: null
+ };
+}
/**
* Kick off an in-place restore of `filePath` (one of this company's own
diff --git a/apps/erp/app/modules/settings/backups.service.ts b/apps/erp/app/modules/settings/backups.service.ts
index e9952ff3f5..2f29db2813 100644
--- a/apps/erp/app/modules/settings/backups.service.ts
+++ b/apps/erp/app/modules/settings/backups.service.ts
@@ -1,4 +1,9 @@
import type { Database } from "@carbon/database";
+import type {
+ BackupCompatibilityStatus,
+ CompatibilityFinding,
+ Manifest
+} from "@carbon/jobs/backups";
import type { SupabaseClient } from "@supabase/supabase-js";
// Company backup data access. The export edge function is a thin auth boundary;
@@ -14,6 +19,7 @@ const SNAPSHOT_PREFIX = "_pre-restore-";
/** Supabase storage caps a `list` call; page until a short page comes back. */
const BACKUP_LIST_PAGE_SIZE = 100;
+const BACKUP_LIST_MAX_PAGES = 50;
/**
* Remove every object under a prefix (recursing into folders) so a deleted
@@ -66,51 +72,45 @@ export type CompanyBackupSummary = {
/** Total bundled asset bytes (the bulk of a backup's footprint). */
sizeBytes: number;
/**
- * The verdict from `compatibility.json`, written beside the manifest by the
- * export job and never refreshed — so `checkedAt` is the export date, and the
- * row's own exported-at line already dates it. Read as a plain file rather than
- * recomputed here: the comparison needs the live schema and lives in
- * `@carbon/jobs`, which app code may not import.
- *
- * A badge is therefore a dated fact, not a live promise. That is deliberate:
- * the hard refusal runs against the live schema inside the restore
- * (`assertBackupImportable`), and `RestoreDisclosure` prints `checkedAt` at the
- * one moment the answer changes a decision. Do not add a job to keep this fresh
- * — one existed and was removed for finding problems nobody was told about.
- *
- * `checkedAt: null` means no verdict has been written yet — the row says "not yet
- * checked", never "not restorable". An absent answer is not a bad one.
+ * "Would this backup restore into TODAY's schema?" — computed live against
+ * the current schema by `getCompanyBackups` (backups.server.ts) on every
+ * load, never stored. The hard refusal is still `assertBackupImportable`
+ * inside the restore job; this is the same diff, disclosed upfront.
*/
compatibility: {
- checkedAt: string | null;
- status: "ready" | "restorable-with-changes" | "not-restorable";
- findings: Array<{
- kind: "defaulted" | "discarded" | "blocked";
- table: string;
- column?: string;
- reason: string;
- }>;
+ status: BackupCompatibilityStatus;
+ findings: CompatibilityFinding[];
};
};
/**
- * List a company's backups (the `exports/<name>/` folders, snapshots excluded),
- * reading each manifest for its metadata. Manifests are tiny, so the per-backup
- * reads run in parallel.
+ * List a company's backup folders (`exports/<name>/`, snapshots excluded),
+ * reading each manifest for its metadata. Storage layer only: `compatibility`
+ * is a placeholder here — `getCompanyBackups` in backups.server.ts computes
+ * the real verdict from the returned `manifest` (server-only, since it needs
+ * `@carbon/jobs/backups` and a schema read) and strips it before the loader
+ * returns.
*/
-export async function listCompanyBackups(
+export async function listCompanyBackupFolders(
client: SupabaseClient<Database>,
companyId: string
-): Promise<{ data: CompanyBackupSummary[] | null; error: Error | null }> {
- // Paged: storage caps a list call, and the un-listed page is invisible in the
- // UI — a backup you can neither restore nor delete.
+): Promise<{
+ data: (CompanyBackupSummary & { manifest: Manifest | null })[] | null;
+ error: Error | null;
+}> {
+ // Paged: storage caps a list call, and an un-listed backup can be neither
+ // restored nor deleted. The page cap only guards a misbehaving storage
+ // response from looping forever.
const entries: Awaited<
ReturnType<ReturnType<typeof client.storage.from>["list"]>
>["data"] = [];
- for (let offset = 0; ; offset += BACKUP_LIST_PAGE_SIZE) {
+ for (let page = 0; page < BACKUP_LIST_MAX_PAGES; page++) {
const { data, error } = await client.storage
.from(companyId)
- .list("exports", { limit: BACKUP_LIST_PAGE_SIZE, offset });
+ .list("exports", {
+ limit: BACKUP_LIST_PAGE_SIZE,
+ offset: page * BACKUP_LIST_PAGE_SIZE
+ });
if (error) return { data: null, error };
entries.push(...(data ?? []));
if ((data?.length ?? 0) < BACKUP_LIST_PAGE_SIZE) break;
@@ -121,65 +121,45 @@ export async function listCompanyBackups(
);
const backups = await Promise.all(
- folders.map(async (folder): Promise<CompanyBackupSummary> => {
- const summary: CompanyBackupSummary = {
- name: folder.name,
- status: "pending",
- exportedAt: null,
- label: null,
- rows: 0,
- sizeBytes: 0,
- compatibility: { checkedAt: null, status: "ready", findings: [] }
- };
- // Both objects are tiny and independent — fetch them together so adding the
- // verdict costs a parallel request, not a second serial round trip per row.
- const [mf, cf] = await Promise.all([
- client.storage
+ folders.map(
+ async (
+ folder
+ ): Promise<CompanyBackupSummary & { manifest: Manifest | null }> => {
+ const summary: CompanyBackupSummary & { manifest: Manifest | null } = {
+ name: folder.name,
+ status: "pending",
+ exportedAt: null,
+ label: null,
+ rows: 0,
+ sizeBytes: 0,
+ compatibility: { status: "ready", findings: [] },
+ manifest: null
+ };
+ const mf = await client.storage
.from(companyId)
- .download(`exports/${folder.name}/manifest.json`),
- client.storage
- .from(companyId)
- .download(`exports/${folder.name}/compatibility.json`)
- ]);
- if (cf.data) {
- try {
- const c = JSON.parse(
- await cf.data.text()
- ) as CompanyBackupSummary["compatibility"];
- summary.compatibility = {
- checkedAt: c.checkedAt ?? null,
- status: c.status ?? "ready",
- findings: c.findings ?? []
- };
- } catch {
- // Unreadable verdict is the same as an absent one: not yet checked.
- }
- }
- if (mf.data) {
- try {
- const m = JSON.parse(await mf.data.text()) as {
- exportedAt?: string;
- label?: string | null;
- tables?: Array<{ rows?: number }>;
- storage?: Array<{ size?: number; included?: boolean }>;
- };
- summary.status = "ready";
- summary.exportedAt = m.exportedAt ?? null;
- summary.label = m.label ?? null;
- summary.rows = (m.tables ?? []).reduce(
- (sum, t) => sum + (t.rows ?? 0),
- 0
- );
- summary.sizeBytes = (m.storage ?? [])
- .filter((x) => x.included)
- .reduce((sum, x) => sum + (x.size ?? 0), 0);
- } catch {
- // Manifest present but unreadable — treat as a partial/aborted export
- // (stays "pending"); still listed by name so the user can delete it.
+ .download(`exports/${folder.name}/manifest.json`);
+ if (mf.data) {
+ try {
+ const m = JSON.parse(await mf.data.text()) as Manifest;
+ summary.status = "ready";
+ summary.exportedAt = m.exportedAt ?? null;
+ summary.label = m.label ?? null;
+ summary.rows = (m.tables ?? []).reduce(
+ (sum, t) => sum + (t.rows ?? 0),
+ 0
+ );
+ summary.sizeBytes = (m.storage ?? [])
+ .filter((x) => x.included)
+ .reduce((sum, x) => sum + (x.size ?? 0), 0);
+ summary.manifest = { ...m, tables: m.tables ?? [] };
+ } catch {
+ // Manifest present but unreadable — treat as a partial/aborted
+ // export (stays "pending"); still listed so the user can delete it.
+ }
}
+ return summary;
}
- return summary;
- })
+ )
);
backups.sort((a, b) =>
diff --git a/apps/erp/app/modules/settings/ui/Backups/RestoreDisclosure.tsx b/apps/erp/app/modules/settings/ui/Backups/RestoreDisclosure.tsx
index 224f2754c4..d99fded045 100644
--- a/apps/erp/app/modules/settings/ui/Backups/RestoreDisclosure.tsx
+++ b/apps/erp/app/modules/settings/ui/Backups/RestoreDisclosure.tsx
@@ -23,11 +23,11 @@ type Finding = CompanyBackupSummary["compatibility"]["findings"][number];
/**
* What the person is told before their company's data is replaced.
*
- * The verdict rendered here is the one stored beside the backup, so this screen
- * costs no schema read and can never disagree with the badge on the list. It is
- * DISCLOSURE, not authorization: the restore job runs the real gate itself, so a
- * verdict that has gone stale since it was written can leave this screen
- * under-informed but can never let through a restore the gate would refuse.
+ * The verdict rendered here was computed in the loader against the LIVE schema
+ * (`getCompanyBackups`), so it describes what a restore would do right now. It
+ * is DISCLOSURE, not authorization: the restore job runs the real gate itself
+ * (`assertBackupImportable`), so this screen can never let through a restore
+ * the gate would refuse.
*/
export function RestoreDisclosure({
backups,
@@ -47,11 +47,10 @@ export function RestoreDisclosure({
[backups, source]
);
- // No stored verdict — an uploaded backup, or one whose check never landed. The
- // consequences below still apply and are still shown; only the findings are
- // unknown, which the screen says rather than implying a clean bill of health.
+ // No verdict — an upload-sourced restore. The consequences below still
+ // apply and are shown; only the findings are unknown, which the screen says
+ // rather than implying a clean bill of health.
const findings = backup?.compatibility.findings ?? [];
- const checkedAt = backup?.compatibility.checkedAt ?? null;
const { unchecked, blocked, discards, canConfirm } = disclosureState(
backup,
typed
@@ -111,7 +110,7 @@ export function RestoreDisclosure({
) : null}
{findings.length > 0 ? (
- <FindingGroups findings={findings} checkedAt={checkedAt} />
+ <FindingGroups findings={findings} />
) : null}
{discards ? (
@@ -173,13 +172,7 @@ const KIND_ICON = {
} as const;
/** Findings by kind, then by product area. Table names live in the expander. */
-function FindingGroups({
- findings,
- checkedAt
-}: {
- findings: Finding[];
- checkedAt: string | null;
-}) {
+function FindingGroups({ findings }: { findings: Finding[] }) {
const { t } = useLingui();
const kindLabel: Record<Finding["kind"], string> = {
blocked: t`Can't be restored`,
@@ -226,11 +219,6 @@ function FindingGroups({
);
}
)}
- {checkedAt ? (
- <span className="text-xs text-muted-foreground">
- <Trans>Checked</Trans> {formatBackupDate(checkedAt)}
- </span>
- ) : null}
</VStack>
);
}
diff --git a/apps/erp/app/modules/settings/ui/Backups/disclosure-state.test.ts b/apps/erp/app/modules/settings/ui/Backups/disclosure-state.test.ts
index ae6d1d98f2..d7f47d3350 100644
--- a/apps/erp/app/modules/settings/ui/Backups/disclosure-state.test.ts
+++ b/apps/erp/app/modules/settings/ui/Backups/disclosure-state.test.ts
@@ -7,18 +7,15 @@ type Finding = CompanyBackupSummary["compatibility"]["findings"][number];
const finding = (kind: Finding["kind"], table = "job"): Finding =>
({ kind, table, column: "startDate", reason: "a reason" }) as Finding;
-const backup = (
- findings: Finding[] = [],
- checkedAt: string | null = "2026-08-25T20:06:00.000Z"
-): CompanyBackupSummary =>
+const backup = (findings: Finding[] = []): CompanyBackupSummary =>
({
name: "minimal",
label: "minimal",
exportedAt: "2026-08-25T20:06:00.000Z",
- compatibility: { checkedAt, findings }
+ compatibility: { findings }
}) as unknown as CompanyBackupSummary;
-// The five states the disclosure screen can be in. Named here the way they are
+// The states the disclosure screen can be in. Named here the way they are
// described to a reader, so a future change that collapses two of them fails.
describe("disclosureState", () => {
it("a clean backup asks for nothing", () => {
@@ -39,16 +36,6 @@ describe("disclosureState", () => {
});
});
- it("a LISTED backup with no verdict is unchecked, not clean", () => {
- // compatibility.json absent or unreadable — no findings, but nobody looked.
- expect(disclosureState(backup([], null), "")).toEqual({
- unchecked: true,
- blocked: false,
- discards: false,
- canConfirm: true
- });
- });
-
it("a default-only finding is information, not a gate", () => {
const state = disclosureState(backup([finding("defaulted")]), "");
expect(state.discards).toBe(false);
diff --git a/apps/erp/app/modules/settings/ui/Backups/disclosure-state.ts b/apps/erp/app/modules/settings/ui/Backups/disclosure-state.ts
index cbec454851..cc9a85ae32 100644
--- a/apps/erp/app/modules/settings/ui/Backups/disclosure-state.ts
+++ b/apps/erp/app/modules/settings/ui/Backups/disclosure-state.ts
@@ -4,7 +4,7 @@ import type { CompanyBackupSummary } from "../../backups.service";
export const CONFIRM_WORD = "restore";
export type DisclosureState = {
- /** No stored verdict — an uploaded backup. Say so rather than imply it is clean. */
+ /** No verdict — an upload-sourced restore. Say so rather than imply it is clean. */
unchecked: boolean;
/** A finding refuses the restore outright. No confirm button is offered. */
blocked: boolean;
@@ -29,10 +29,9 @@ export function disclosureState(
const discards = findings.some((f) => f.kind === "discarded");
return {
- // A listed backup with no verdict reads as "no findings", which is
- // indistinguishable from clean. `checkedAt` is the only thing that separates
- // "we looked and found nothing" from "nobody looked".
- unchecked: !backup || backup.compatibility.checkedAt === null,
+ // Every LISTED backup carries a live verdict (computed in the loader), so
+ // only a restore from outside the list — an uploaded file — is unchecked.
+ unchecked: !backup,
blocked,
discards,
canConfirm:
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index 348db4bb91..46459b822e 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-08-26T14:48:57.221Z",
+ "generated": "2026-08-28T12:16:54.521Z",
"totalTools": 1447,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/x+/settings+/backups.tsx b/apps/erp/app/routes/x+/settings+/backups.tsx
index 3a47e28e03..8d0b7a85a6 100644
--- a/apps/erp/app/routes/x+/settings+/backups.tsx
+++ b/apps/erp/app/routes/x+/settings+/backups.tsx
@@ -48,12 +48,12 @@ import {
deleteCompanyBackup,
exportCompanyBackup,
getCompanyExportRun,
- getCompanyRestoreRuns,
- listCompanyBackups
+ getCompanyRestoreRuns
} from "~/modules/settings";
import {
dismissCompanyExportFailure,
finalizeCompanyRestore,
+ getCompanyBackups,
revertCompanyRestore,
startCompanyRestore
} from "~/modules/settings/backups.server";
@@ -111,7 +111,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
requireBackupAccess(email);
const [backupsList, restoreRuns, exportRun] = await Promise.all([
- listCompanyBackups(client, companyId),
+ getCompanyBackups(client, companyId),
getCompanyRestoreRuns(client, companyId),
getCompanyExportRun(client, companyId)
]);
diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.md
index a402f91c58..76dcca34d5 100644
--- a/packages/jobs/AGENTS.md
+++ b/packages/jobs/AGENTS.md
@@ -21,7 +21,7 @@ Background job system built on Inngest. Handles event system processing (webhook
## Never
-- Import Inngest internals or server-only job code in app bundles — use only the public exports from `@carbon/jobs` (`.` subpath: `trigger`, `batchTrigger`, schemas).
+- Import Inngest internals or server-only job code in app bundles — use only the public exports from `@carbon/jobs` (`.` subpath: `trigger`, `batchTrigger`, schemas; `./backups`: the pure catalog/compatibility layer, server-side only).
- Use the event system for real-time / data-integrity needs — it is async (typically ~3–5s, up to ~1 min if a push wake is lost). Use sync interceptors instead.
- Bypass the PGMQ queue by writing directly to handler tables — always go through `dispatch_event_batch()` triggers.
- Give a workflow action anything but the owner-scoped client it was handed. A privileged or
@@ -59,6 +59,7 @@ field for one script. That is exactly why the catalog/compatibility logic lives
| Subpath | Provides |
|---------|----------|
| `.` (index) | `trigger()`, `batchTrigger()`, `Events` type, Jira/Linear webhook schemas |
+| `./backups` | `src/backups/schema.ts` — catalog introspection + backup-compatibility diff (`getCompanyTableCatalog`, `reportBackupCompatibility`, `compatibilityStatus`, types). No Inngest, no logger; the ERP Backups loader computes the live restore verdict through it. Server-side only (runs `information_schema` SQL) |
| `./events` | `Events` type (re-export from `@carbon/lib`) |
| `./inngest` | Inngest client + function registrations, plus `setWorkflowDispatch` and its `WorkflowDispatch` / `DispatchContext` / `DispatchResult` types (server-only) |
| `./worker` | Worker entry point for Inngest serve |
diff --git a/packages/jobs/package.json b/packages/jobs/package.json
index b3cfbe6cf9..51cd52448d 100644
--- a/packages/jobs/package.json
+++ b/packages/jobs/package.json
@@ -50,6 +50,7 @@
},
"exports": {
".": "./src/index.ts",
+ "./backups": "./src/backups/schema.ts",
"./events": "./src/events.ts",
"./inngest": "./src/inngest/index.ts",
"./worker": "./src/inngest/worker.ts"
diff --git a/packages/jobs/src/backups/schema.test.ts b/packages/jobs/src/backups/schema.test.ts
index 7dc86f38ff..3566e19d0a 100644
--- a/packages/jobs/src/backups/schema.test.ts
+++ b/packages/jobs/src/backups/schema.test.ts
@@ -5,6 +5,7 @@ import {
BACKUP_VERSION,
type Catalog,
type ColumnInfo,
+ compatibilityStatus,
type Manifest,
reportBackupCompatibility,
type TableInfo
@@ -348,3 +349,32 @@ describe("assertBackupImportable", () => {
);
});
});
+
+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");
+ });
+});
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
deleted file mode 100644
index 018ddd87dc..0000000000
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.compatibility.test.ts
+++ /dev/null
@@ -1,350 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-import {
- assertBackupImportable,
- 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");
- });
-});
-
-// 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/inngest/functions/tasks/company-backup.exportable.test.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.exportable.test.ts
deleted file mode 100644
index 9d8e70cef2..0000000000
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.exportable.test.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-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.test.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.renames.test.ts
deleted file mode 100644
index d95542aa67..0000000000
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.renames.test.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-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
deleted file mode 100644
index 5bfc01b4c1..0000000000
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.renames.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * 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> = {};
-
-/**
- * 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-compatibility.test.ts b/packages/jobs/src/inngest/functions/tasks/company-compatibility.test.ts
deleted file mode 100644
index b0de96f699..0000000000
--- a/packages/jobs/src/inngest/functions/tasks/company-compatibility.test.ts
+++ /dev/null
@@ -1,190 +0,0 @@
-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
deleted file mode 100644
index 4b721d2a8c..0000000000
--- a/packages/jobs/src/inngest/functions/tasks/company-compatibility.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-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.ts b/packages/jobs/src/inngest/functions/tasks/company-export.ts
index f0f13b04a3..bc8f4c4009 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-export.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-export.ts
@@ -2,7 +2,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { sql } from "kysely";
import { getJobDatabaseClient, type JobDatabase } from "../../../db";
import { inngest } from "../../client";
-import type { Catalog, Manifest } from "./company-backup";
+import type { Manifest } from "./company-backup";
import {
BACKUP_INTEGRATION,
BACKUP_KIND,
@@ -21,7 +21,6 @@ import {
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
@@ -63,8 +62,6 @@ 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[];
@@ -235,7 +232,7 @@ export async function buildCompanyBackup(
// 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, catalog, rows, assetSourcePaths };
+ return { name, manifest, rows, assetSourcePaths };
}
// One company-scoped progress marker (exports run one-at-a-time, so no run id).
@@ -332,7 +329,7 @@ export const companyExportFunction = inngest.createFunction(
};
try {
- const { name, manifest, catalog, rows, assetSourcePaths } =
+ const { name, manifest, rows, assetSourcePaths } =
await buildCompanyBackup(client, db, {
companyId,
userId,
@@ -363,31 +360,6 @@ 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,
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index e9ff517e97..e63fe499ed 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -3031,9 +3031,6 @@ msgstr "Überprüfen Sie das Artikelhauptbuch auf Artikel mit negativem Bestand
msgid "Check your email"
msgstr "Überprüfen Sie Ihre E-Mail"
-msgid "Checked"
-msgstr "Geprüft"
-
msgid "Checking Stripe for this customer…"
msgstr "Stripe wird für diesen Kunden geprüft…"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 45fabf261e..0da64c6c55 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -3031,9 +3031,6 @@ msgstr "Check the item ledger for any items with a negative on-hand quantity as
msgid "Check your email"
msgstr "Check your email"
-msgid "Checked"
-msgstr "Checked"
-
msgid "Checking Stripe for this customer…"
msgstr "Checking Stripe for this customer…"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 6b7b229e3f..2a7bab56a9 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -3031,9 +3031,6 @@ msgstr "Revise el libro mayor de artículos para buscar artículos con cantidad
msgid "Check your email"
msgstr "Revisa tu correo electrónico"
-msgid "Checked"
-msgstr "Verificado"
-
msgid "Checking Stripe for this customer…"
msgstr "Verificando Stripe para este cliente…"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 5cf2d9bd4a..3d08022108 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -3031,9 +3031,6 @@ msgstr "Vérifiez le registre des articles pour tous les articles ayant une quan
msgid "Check your email"
msgstr "Vérifiez votre email"
-msgid "Checked"
-msgstr "Vérifié"
-
msgid "Checking Stripe for this customer…"
msgstr "Vérification de Stripe pour ce client…"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 4a69840f20..0ddf348c23 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -3031,9 +3031,6 @@ msgstr "अवधि के अंत तक नकारात्मक मौ
msgid "Check your email"
msgstr "अपना ईमेल जांचें"
-msgid "Checked"
-msgstr "जांचा गया"
-
msgid "Checking Stripe for this customer…"
msgstr "इस ग्राहक के लिए Stripe की जांच कर रहे हैं…"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index e69a3262d1..b71328daf5 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -3031,9 +3031,6 @@ msgstr "Controlla il registro degli articoli per eventuali articoli con una quan
msgid "Check your email"
msgstr "Controlla la tua email"
-msgid "Checked"
-msgstr "Verificato"
-
msgid "Checking Stripe for this customer…"
msgstr "Controllo di Stripe per questo cliente…"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 0d7c61fead..ae134fc33d 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -3031,9 +3031,6 @@ msgstr "期末時点で保有数量がマイナスの品目がないか品目台
msgid "Check your email"
msgstr "メールを確認してください"
-msgid "Checked"
-msgstr "チェック済み"
-
msgid "Checking Stripe for this customer…"
msgstr "このカスタマーのStripeを確認しています…"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 5610d775e2..3536170e13 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -3031,9 +3031,6 @@ msgstr "기간 종료 시점의 음수 수량 보유 항목에 대해 항목 원
msgid "Check your email"
msgstr "이메일을 확인하세요"
-msgid "Checked"
-msgstr "확인됨"
-
msgid "Checking Stripe for this customer…"
msgstr "이 고객의 Stripe 확인 중…"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 4ac78519f9..dc051e23fa 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -3031,9 +3031,6 @@ msgstr "Sprawdź księgę pozycji w poszukiwaniu pozycji z ujemną ilością dos
msgid "Check your email"
msgstr "Sprawdź swoją pocztę"
-msgid "Checked"
-msgstr "Zaznaczono"
-
msgid "Checking Stripe for this customer…"
msgstr "Sprawdzanie Stripe dla tego klienta…"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index ad88bc994f..37cdb26ecb 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -3031,9 +3031,6 @@ msgstr "Verifique o razão de itens para qualquer item com quantidade em mão ne
msgid "Check your email"
msgstr "Verifique seu email"
-msgid "Checked"
-msgstr "Verificado"
-
msgid "Checking Stripe for this customer…"
msgstr "Verificando Stripe para este cliente…"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index ca1b2cdef5..edb3d1993a 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -3031,9 +3031,6 @@ msgstr "Проверьте реестр товаров на наличие то
msgid "Check your email"
msgstr "Проверьте вашу почту"
-msgid "Checked"
-msgstr "Проверено"
-
msgid "Checking Stripe for this customer…"
msgstr "Проверка Stripe для этого клиента…"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index c33ee4a9d1..92edcb39d7 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -3031,9 +3031,6 @@ msgstr "Dönem sonunda negatif el altında miktarı olan herhangi bir madde içi
msgid "Check your email"
msgstr "E-postanızı kontrol edin"
-msgid "Checked"
-msgstr "İşaretlendi"
-
msgid "Checking Stripe for this customer…"
msgstr "Bu müşteri için Stripe kontrol ediliyor…"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 842d790791..44858981b4 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -3031,9 +3031,6 @@ msgstr "检查物料分类账中期末库存数量为负的任何物料——通
msgid "Check your email"
msgstr "检查您的电子邮件"
-msgid "Checked"
-msgstr "已检查"
-
msgid "Checking Stripe for this customer…"
msgstr "正在检查此客户的 Stripe…"