Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix: backup restore hardening and bug fixes (#950)

Sid5d734cbe20b8
diff --git a/.claude/skills/test/playbooks/backup-restore-roundtrip.md b/.claude/skills/test/playbooks/backup-restore-roundtrip.md
new file mode 100644
index 0000000000..690433f837
--- /dev/null
+++ b/.claude/skills/test/playbooks/backup-restore-roundtrip.md
@@ -0,0 +1,41 @@
+# Company Backup / Restore round-trip
+
+Last tested: 2026-06-25
+Route: `/x/settings/backups` (internal-gated — needs an `@carbon.ms` / `@carbon.us.org` user; `[email protected]` qualifies)
+
+## Prerequisites
+- Logged in (see `/login`). Dev server up.
+- `networkidle` wait times out on this app (persistent dev connections) — snapshot directly after a short `sleep` instead of `agent-browser wait --load networkidle`.
+
+## Steps (own-company round-trip — all PASS)
+
+### 1. Export
+- Navigate `/x/settings/backups`.
+- Fill the label textbox (first textbox in the panel) e.g. `loop-test-1`.
+- Leave the data-choice combobox at its default (Data only).
+- Click **Create backup**. Button goes `[disabled]` while the export job runs.
+- Wait ~20s → a modal **"Backup ready — it's in the list below"** appears. Click **Done**.
+- The backup now shows in the list with **Download** + **Delete**.
+
+### 2. Restore (own → `remap=false`)
+- Click **Choose a backup** → combobox lists `<label> <date>`; click the option.
+- **Restore** button enables. Click it.
+- ~3s → modal **"Restore complete. Loaded N rows."** (365 for the Carbon Development dev company). Click **Done**.
+- A **Keep** / **Revert** review row appears (the restore is reversible via auto-snapshot).
+
+### 3. Revert (snapshot reload)
+- Click **Revert** → toast "Reverting — your previous data is being restored", then modal **"Reverted. Your previous data is back, exactly as it was before the restore."**
+- (Or **Keep** to finalize and discard the snapshot.)
+
+## Selector Notes
+- Backups panel controls, in order: "What a backup contains" (popover), label textbox, data-choice combobox, "Create backup", "Choose a backup" (source picker), "Restore".
+- Dialog refs shift after the job completes — re-`snapshot -i` before clicking Done/Keep/Revert.
+
+## Foreign restore (the high-risk path — `remap=true`)
+- Switch company to a DIFFERENT one than the backup's source (this DB has `Carbon Development` and `Brynne Fox`), then restore the other company's backup via **Choose a backup → Upload new backup…**.
+- This is where remap runs: id remap (text/uuid only — int/serial ids kept verbatim), user/employee FK collapse to importer, user-keyed identity tables skipped, and the referential-closure preflight.
+
+## Common Failures (fixed 2026-06-25, foreign restore)
+- `Cannot read properties of undefined (reading 'get')` — int/serial-id table in id-remap; fixed by gating the transform on idMap presence.
+- `duplicate key value violates "trainingCompletion_unique_period_idx"` — user FK in a unique index collapsed to one user; fixed by widening `isUserScopedIdentityTable` to unique-index columns.
+- `Backup is inconsistent: X.col references a Y that isn't in the backup` — non-closed backup (cross-scope NOT-NULL FK); now caught up front by the restore closure preflight (fails before any wipe, lists every gap).
diff --git a/apps/erp/app/components/Layout/Panels.tsx b/apps/erp/app/components/Layout/Panels.tsx
index 3c1c22fde2..ad6ee218c6 100644
--- a/apps/erp/app/components/Layout/Panels.tsx
+++ b/apps/erp/app/components/Layout/Panels.tsx
@@ -42,15 +42,14 @@ interface PanelProviderProps {
}
export function PanelProvider({ children }: PanelProviderProps) {
- const isBrowser = typeof window !== "undefined";
const isMobile = useIsMobile();
- const [isExplorerCollapsed, setIsExplorerCollapsed] = useState(
- isBrowser ? isMobile : false
- );
- const [isPropertiesCollapsed, setIsPropertiesCollapsed] = useState(
- isBrowser ? window.innerWidth < 1024 : false
- );
+ // Seed both to `false` so the first client render matches the server (which
+ // has no `window`); collapsing based on viewport happens post-mount in the
+ // effect below. Reading `window.innerWidth` during render forks server vs
+ // client output and triggers a hydration mismatch.
+ const [isExplorerCollapsed, setIsExplorerCollapsed] = useState(false);
+ const [isPropertiesCollapsed, setIsPropertiesCollapsed] = useState(false);
const value = {
isExplorerCollapsed,
@@ -66,8 +65,10 @@ export function PanelProvider({ children }: PanelProviderProps) {
if (isMobile) {
setIsExplorerCollapsed(true);
setIsPropertiesCollapsed(true);
+ } else if (window.innerWidth < 1024) {
+ setIsPropertiesCollapsed(true);
}
- }, [isBrowser, isMobile]);
+ }, [isMobile]);
return (
<PanelContext.Provider value={value}>{children}</PanelContext.Provider>
diff --git a/apps/erp/app/components/New.tsx b/apps/erp/app/components/New.tsx
index b5588cd0fa..340c5a8fe5 100644
--- a/apps/erp/app/components/New.tsx
+++ b/apps/erp/app/components/New.tsx
@@ -32,7 +32,7 @@ const New = ({ label, to, variant = "primary" }: NewProps) => {
return (
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<Button
asChild
leftIcon={<LuCirclePlus />}
diff --git a/apps/erp/app/components/Selectors/UserSelect/components/SelectionList.tsx b/apps/erp/app/components/Selectors/UserSelect/components/SelectionList.tsx
index 3ff2aed803..1a0f926591 100644
--- a/apps/erp/app/components/Selectors/UserSelect/components/SelectionList.tsx
+++ b/apps/erp/app/components/Selectors/UserSelect/components/SelectionList.tsx
@@ -84,7 +84,7 @@ const SelectionList = () => {
{!!canExpand && (
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<IconButton
aria-label={t`Expand ${item.label}`}
icon={<LuListPlus />}
@@ -102,7 +102,7 @@ const SelectionList = () => {
{!readOnly && !alwaysSelected.includes(item.id) && (
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<IconButton
aria-label={t`Remove ${item.label}`}
icon={<LuX />}
diff --git a/apps/erp/app/components/Table/components/Columns.tsx b/apps/erp/app/components/Table/components/Columns.tsx
index 667ba0ff43..780b129786 100644
--- a/apps/erp/app/components/Table/components/Columns.tsx
+++ b/apps/erp/app/components/Table/components/Columns.tsx
@@ -43,23 +43,23 @@ const Columns = <T extends object>({
return (
<Drawer>
- <DrawerTrigger>
- <Tooltip>
- <TooltipTrigger asChild>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <DrawerTrigger asChild>
<IconButton
aria-label={t`Columns`}
title={t`Columns`}
variant="ghost"
icon={<LuColumns2 />}
/>
- </TooltipTrigger>
- <TooltipContent>
- <p>
- <Trans>Column visibility and order</Trans>
- </p>
- </TooltipContent>
- </Tooltip>
- </DrawerTrigger>
+ </DrawerTrigger>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>
+ <Trans>Column visibility and order</Trans>
+ </p>
+ </TooltipContent>
+ </Tooltip>
<DrawerContent>
<DrawerHeader>
<DrawerTitle>
diff --git a/apps/erp/app/components/Table/components/Pagination/Pagination.tsx b/apps/erp/app/components/Table/components/Pagination/Pagination.tsx
index dee0415640..2605b40a3b 100644
--- a/apps/erp/app/components/Table/components/Pagination/Pagination.tsx
+++ b/apps/erp/app/components/Table/components/Pagination/Pagination.tsx
@@ -131,7 +131,7 @@ export const PaginationButtons = ({
{condensed ? (
<>
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<IconButton
aria-label={t`Previous`}
icon={<BsChevronLeft />}
@@ -145,7 +145,7 @@ export const PaginationButtons = ({
</TooltipContent>
</Tooltip>
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<IconButton
aria-label={t`Next`}
icon={<BsChevronRight />}
@@ -166,7 +166,7 @@ export const PaginationButtons = ({
<Trans>of</Trans> {count}
</div>
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<Button
ref={previousButtonRef}
variant="secondary"
@@ -182,7 +182,7 @@ export const PaginationButtons = ({
</TooltipContent>
</Tooltip>
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<Button
ref={nextButtonRef}
variant="secondary"
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
index f1419962ac..13b936fa04 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
@@ -652,7 +652,7 @@ const InventoryTable = memo(
/>
<mrpFetcher.Form method="post" action={path.to.api.mrp(locationId)}>
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<Button
type="submit"
variant="secondary"
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferWizard.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferWizard.tsx
index 61f86422c5..4902e9644e 100644
--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferWizard.tsx
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferWizard.tsx
@@ -1177,7 +1177,7 @@ function PaginationButtons({
{count}
</div>
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<Button
variant="secondary"
isDisabled={!canPreviousPage}
@@ -1192,7 +1192,7 @@ function PaginationButtons({
</TooltipContent>
</Tooltip>
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<Button
variant="secondary"
isDisabled={!canNextPage}
diff --git a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
index c4904eb79a..f774d08fba 100644
--- a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
@@ -176,7 +176,7 @@ const BoMExplorer = ({
</InputGroup>
<DropdownMenu>
- <DropdownMenuTrigger>
+ <DropdownMenuTrigger asChild>
<IconButton
aria-label={t`Actions`}
variant="secondary"
@@ -428,7 +428,7 @@ export function BoMActions({ makeMethodId }: { makeMethodId: string }) {
const { t } = useLingui();
return (
<DropdownMenu>
- <DropdownMenuTrigger>
+ <DropdownMenuTrigger asChild>
<IconButton
aria-label={t`Actions`}
variant="secondary"
diff --git a/apps/erp/app/modules/items/ui/Item/ItemCostHistoryChart.tsx b/apps/erp/app/modules/items/ui/Item/ItemCostHistoryChart.tsx
index f7671de0ec..ea9476f510 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemCostHistoryChart.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemCostHistoryChart.tsx
@@ -314,7 +314,7 @@ export function ItemCostHistoryChart({
{h.documentId &&
h.documentType === "Purchase Invoice" && (
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<Button variant="link" size="sm" asChild>
<Link
to={path.to.purchaseInvoice(
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
index 3e6e69eb97..65540bec27 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
@@ -212,7 +212,7 @@ const JobBoMExplorer = ({ method, orderStatus }: JobBoMExplorerProps) => {
</InputGroup>
{jobId && (
<DropdownMenu>
- <DropdownMenuTrigger>
+ <DropdownMenuTrigger asChild>
<IconButton
aria-label={t`Actions`}
variant="ghost"
diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
index 4b096f5023..9df2620ff8 100644
--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
@@ -475,7 +475,7 @@ const ProductionPlanningTable = ({
/>
<mrpFetcher.Form method="post" action={path.to.api.mrp(locationId)}>
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<Button
type="submit"
variant="secondary"
diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
index 65d5067d51..7db58a920a 100644
--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
@@ -612,7 +612,7 @@ const PlanningTable = memo(
action={path.to.api.mrp(locationId)}
>
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<Button
type="submit"
variant="secondary"
diff --git a/packages/form/src/components/Combobox.tsx b/packages/form/src/components/Combobox.tsx
index 4e4ece40f6..24ec27011a 100644
--- a/packages/form/src/components/Combobox.tsx
+++ b/packages/form/src/components/Combobox.tsx
@@ -77,12 +77,12 @@ const Combobox = ({
)}
<input
{...getInputProps({
- id: name
+ id: name,
+ value: value ?? ""
})}
type="hidden"
name={name}
id={name}
- value={value}
/>
<ComboboxBase
{...props}
diff --git a/packages/form/src/components/CreatableCombobox.tsx b/packages/form/src/components/CreatableCombobox.tsx
index af73f0c78f..75b23cb7c0 100644
--- a/packages/form/src/components/CreatableCombobox.tsx
+++ b/packages/form/src/components/CreatableCombobox.tsx
@@ -107,7 +107,7 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(
<input
{...getInputProps({
id: name,
- value: value
+ value: value ?? ""
})}
type="hidden"
name={name}
diff --git a/packages/form/src/components/Select.tsx b/packages/form/src/components/Select.tsx
index 2dae6bb50a..db42ff4543 100644
--- a/packages/form/src/components/Select.tsx
+++ b/packages/form/src/components/Select.tsx
@@ -91,12 +91,12 @@ const Select = ({
<input
{...getInputProps({
- id: name
+ id: name,
+ value: value ?? ""
})}
type="hidden"
name={name}
id={name}
- value={value ?? undefined}
/>
<SelectBase
{...props}
diff --git a/packages/form/src/components/SelectControlled.tsx b/packages/form/src/components/SelectControlled.tsx
index 4b47b4d6e9..f3a304a0cf 100644
--- a/packages/form/src/components/SelectControlled.tsx
+++ b/packages/form/src/components/SelectControlled.tsx
@@ -74,12 +74,12 @@ const SelectControlled = ({
)}
<input
{...getInputProps({
- id: name
+ id: name,
+ value: controlValue ?? ""
})}
type="hidden"
name={name}
id={name}
- value={controlValue}
/>
<SelectBase
{...props}
diff --git a/packages/form/src/components/Timezone.tsx b/packages/form/src/components/Timezone.tsx
index a5bae848f4..c744615c44 100644
--- a/packages/form/src/components/Timezone.tsx
+++ b/packages/form/src/components/Timezone.tsx
@@ -50,12 +50,12 @@ const Timezone = ({
)}
<input
{...getInputProps({
- id: name
+ id: name,
+ value: value ?? ""
})}
type="hidden"
name={name}
id={name}
- value={value ?? undefined}
/>
<HStack spacing={1}>
<SelectBase
diff --git a/packages/jobs/package.json b/packages/jobs/package.json
index cf2bcf0f13..bb7908b627 100644
--- a/packages/jobs/package.json
+++ b/packages/jobs/package.json
@@ -38,7 +38,8 @@
"@types/nodemailer": "6.4.23",
"@types/react": "catalog:",
"tsx": "catalog:",
- "typescript": "catalog:"
+ "typescript": "catalog:",
+ "vitest": "catalog:"
},
"exports": {
".": "./src/index.ts",
@@ -51,6 +52,7 @@
"private": true,
"scripts": {
"dev:jobs": "pnpm dlx inngest-cli@latest dev --no-discovery -u http://localhost:3000/api/inngest",
+ "test": "vitest run",
"typecheck": "tsc --noEmit"
},
"type": "module",
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
new file mode 100644
index 0000000000..16e8fecf21
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
@@ -0,0 +1,354 @@
+import { describe, expect, it } from "vitest";
+import {
+ assertReferentiallyClosed,
+ buildRowTransforms,
+ type Catalog,
+ type ColumnInfo,
+ type CompanyBackup,
+ type ForeignKey,
+ findDanglingReferences,
+ isUserScopedIdentityTable,
+ selectWipeableTables,
+ type TableInfo
+} from "./company-backup";
+
+// ── Tiny synthetic-catalog builders ─────────────────────────────────────────
+// The closure check is a pure function of (catalog, data), so these tests need
+// no database — they pin the ONE definition of "referentially closed" that the
+// restore preflight relies on, so a schema/data shape that would dangle a
+// restore fails here in CI instead of mid-load in production.
+
+function col(name: string, opts: { nullable?: boolean } = {}): ColumnInfo {
+ return {
+ name,
+ dataType: "text",
+ udtName: "text",
+ isNullable: opts.nullable ?? false,
+ isGenerated: false,
+ hasDefault: false
+ };
+}
+
+function table(
+ name: string,
+ columns: ColumnInfo[],
+ foreignKeys: ForeignKey[] = [],
+ opts: { pkColumns?: string[]; uniqueColumns?: string[] } = {}
+): TableInfo {
+ const pkColumns =
+ opts.pkColumns ?? (columns.some((c) => c.name === "id") ? ["id"] : []);
+ return {
+ name,
+ columns,
+ scope: { kind: "direct", column: "companyId" },
+ scopeColumn: "companyId",
+ pkColumns,
+ uniqueColumns: opts.uniqueColumns ?? pkColumns,
+ hasId: pkColumns.length === 1 && pkColumns[0] === "id",
+ foreignKeys
+ };
+}
+
+function fk(column: string, refTable: string): ForeignKey {
+ return { column, refTable, refColumn: "id" };
+}
+
+function catalog(tables: TableInfo[]): Catalog {
+ return { schemaVersion: "test", tables };
+}
+
+const ITEM = table("item", [col("id"), col("companyId")]);
+const NCI = table(
+ "nonConformanceItem",
+ [col("id"), col("itemId"), col("companyId")],
+ [fk("itemId", "item")]
+);
+
+describe("findDanglingReferences", () => {
+ it("returns nothing when every FK resolves within the backup", () => {
+ const result = findDanglingReferences(catalog([ITEM, NCI]), {
+ item: [{ id: "i1", companyId: "c1" }],
+ nonConformanceItem: [{ id: "nc1", itemId: "i1", companyId: "c1" }]
+ });
+ expect(result).toEqual([]);
+ });
+
+ it("flags a NOT-NULL FK pointing at a row the backup omits, aggregating count", () => {
+ const result = findDanglingReferences(catalog([ITEM, NCI]), {
+ item: [{ id: "i1", companyId: "c1" }],
+ nonConformanceItem: [
+ { id: "nc1", itemId: "i1", companyId: "c1" },
+ { id: "nc2", itemId: "missing-x", companyId: "c1" },
+ { id: "nc3", itemId: "missing-y", companyId: "c1" }
+ ]
+ });
+ expect(result).toEqual([
+ {
+ table: "nonConformanceItem",
+ column: "itemId",
+ refTable: "item",
+ fatal: true,
+ sampleValue: "missing-x",
+ count: 2
+ }
+ ]);
+ });
+
+ it("treats a missing NULLABLE FK as a non-fatal warning (restore nulls it)", () => {
+ const nciNullable = table(
+ "nonConformanceItem",
+ [col("id"), col("itemId", { nullable: true }), col("companyId")],
+ [fk("itemId", "item")]
+ );
+ const result = findDanglingReferences(catalog([ITEM, nciNullable]), {
+ item: [],
+ nonConformanceItem: [{ id: "nc1", itemId: "missing", companyId: "c1" }]
+ });
+ expect(result).toHaveLength(1);
+ expect(result[0]?.fatal).toBe(false);
+ });
+
+ it("ignores a null FK value", () => {
+ const nciNullable = table(
+ "nonConformanceItem",
+ [col("id"), col("itemId", { nullable: true }), col("companyId")],
+ [fk("itemId", "item")]
+ );
+ const result = findDanglingReferences(catalog([ITEM, nciNullable]), {
+ item: [],
+ nonConformanceItem: [{ id: "nc1", itemId: null, companyId: "c1" }]
+ });
+ expect(result).toEqual([]);
+ });
+
+ it("ignores FKs to retained tables (user/employee/company/companyGroup)", () => {
+ const withUserFk = table(
+ "trainingCompletion",
+ [col("id"), col("employeeId"), col("companyId")],
+ [fk("employeeId", "user")]
+ );
+ const result = findDanglingReferences(catalog([withUserFk]), {
+ trainingCompletion: [
+ { id: "t1", employeeId: "some-user-not-in-backup", companyId: "c1" }
+ ]
+ });
+ expect(result).toEqual([]);
+ });
+
+ it("ignores FKs to non-scoped global tables absent from the catalog", () => {
+ const withGlobalFk = table(
+ "part",
+ [col("id"), col("unitOfMeasureCode"), col("companyId")],
+ [fk("unitOfMeasureCode", "unitOfMeasure")] // not in catalog → stable global
+ );
+ const result = findDanglingReferences(catalog([withGlobalFk]), {
+ part: [{ id: "p1", unitOfMeasureCode: "EA", companyId: "c1" }]
+ });
+ expect(result).toEqual([]);
+ });
+});
+
+describe("assertReferentiallyClosed", () => {
+ const backup = (
+ data: Record<string, Array<Record<string, unknown>>>
+ ): CompanyBackup => ({ manifest: {} as CompanyBackup["manifest"], data });
+
+ it("is ok for a self-contained backup", () => {
+ const result = assertReferentiallyClosed(
+ catalog([ITEM, NCI]),
+ backup({
+ item: [{ id: "i1", companyId: "c1" }],
+ nonConformanceItem: [{ id: "nc1", itemId: "i1", companyId: "c1" }]
+ })
+ );
+ expect(result).toEqual({ ok: true });
+ });
+
+ it("fails and names every fatal gap when the backup is not closed", () => {
+ const result = assertReferentiallyClosed(
+ catalog([ITEM, NCI]),
+ backup({
+ item: [],
+ nonConformanceItem: [{ id: "nc1", itemId: "ghost", companyId: "c1" }]
+ })
+ );
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.reason).toContain("nonConformanceItem.itemId → item");
+ expect(result.reason).toContain("ghost");
+ }
+ });
+});
+
+// Foreign-restore re-stamping — pins the bugs that crashed real restores:
+// int/serial ids dereffing an undefined idMap, and the user-collapse / dangling-FK
+// resolution rules. These only run on remap=true, which the own-restore E2E can't
+// exercise — so they live here as a regression net.
+describe("buildRowTransforms", () => {
+ type RestampCtx = Parameters<typeof buildRowTransforms>[2];
+ const ctx = (over: Partial<RestampCtx> = {}): RestampCtx => ({
+ remap: true,
+ companyId: "target-co",
+ userId: "importer",
+ targetGroupId: "target-grp",
+ sourceCompanyId: "src-co",
+ idMaps: new Map<string, Map<string, string>>(),
+ idRewrite: new Map<string, string>(),
+ ...over
+ });
+
+ function apply(
+ t: TableInfo,
+ row: Record<string, unknown>,
+ c: RestampCtx
+ ): Record<string, unknown> {
+ const transforms = buildRowTransforms(t, t.columns, c);
+ const out: Record<string, unknown> = {};
+ t.columns.forEach((c2, i) => {
+ out[c2.name] = transforms[i]!(row[c2.name]);
+ });
+ return out;
+ }
+
+ it("copies every column verbatim when remap=false (own restore)", () => {
+ const t = table("part", [col("id"), col("companyId"), col("name")]);
+ const out = apply(
+ t,
+ { id: "p1", companyId: "src-co", name: "Widget" },
+ ctx({ remap: false })
+ );
+ expect(out).toEqual({ id: "p1", companyId: "src-co", name: "Widget" });
+ });
+
+ it("does NOT crash on an int/serial-id table absent from idMaps — keeps id verbatim", () => {
+ // Regression: journal/trainingCompletion have a serial `id` and no idMap entry.
+ // The pre-fix code dereffed an undefined map here and threw at apply time.
+ const t = table("journal", [col("id"), col("companyId")]);
+ const out = apply(t, { id: 42, companyId: "src-co" }, ctx());
+ expect(out).toEqual({ id: 42, companyId: "target-co" });
+ });
+
+ it("remaps a text id present in idMaps and re-stamps companyId", () => {
+ const t = table("item", [col("id"), col("companyId")]);
+ const idMaps = new Map([["item", new Map([["old", "new"]])]]);
+ const out = apply(t, { id: "old", companyId: "src-co" }, ctx({ idMaps }));
+ expect(out).toEqual({ id: "new", companyId: "target-co" });
+ });
+
+ it("collapses a user/employee FK to the importing user", () => {
+ const t = table(
+ "salesOrder",
+ [col("id"), col("companyId"), col("assignee", { nullable: true })],
+ [fk("assignee", "user")]
+ );
+ const out = apply(
+ t,
+ { id: "s1", companyId: "src-co", assignee: "someone-else" },
+ ctx()
+ );
+ expect(out.assignee).toBe("importer");
+ });
+
+ it("nulls a nullable FK to a scoped row missing from the backup", () => {
+ const t = table(
+ "job",
+ [col("id"), col("companyId"), col("parentId", { nullable: true })],
+ [fk("parentId", "job")]
+ );
+ const idMaps = new Map([["job", new Map([["j1", "jX"]])]]);
+ const out = apply(
+ t,
+ { id: "j1", companyId: "src-co", parentId: "missing" },
+ ctx({ idMaps })
+ );
+ expect(out.parentId).toBeNull();
+ });
+
+ it("throws on a NOT-NULL FK to a scoped row missing from the backup", () => {
+ const t = table(
+ "nonConformanceItem",
+ [col("id"), col("companyId"), col("itemId")],
+ [fk("itemId", "item")]
+ );
+ const idMaps = new Map([
+ ["nonConformanceItem", new Map([["nc1", "ncX"]])],
+ ["item", new Map([["i1", "iX"]])]
+ ]);
+ expect(() =>
+ apply(
+ t,
+ { id: "nc1", companyId: "src-co", itemId: "ghost" },
+ ctx({ idMaps })
+ )
+ ).toThrow(/isn't in the backup/);
+ });
+});
+
+describe("isUserScopedIdentityTable", () => {
+ it("true when a user FK is in the PRIMARY KEY (employee shape)", () => {
+ const t = table(
+ "employee",
+ [col("id"), col("companyId")],
+ [fk("id", "user")],
+ {
+ pkColumns: ["id", "companyId"],
+ uniqueColumns: ["id", "companyId"]
+ }
+ );
+ expect(isUserScopedIdentityTable(t)).toBe(true);
+ });
+
+ it("true when a user FK is in a UNIQUE INDEX but not the PK (trainingCompletion shape)", () => {
+ const t = table(
+ "trainingCompletion",
+ [
+ col("id"),
+ col("trainingAssignmentId"),
+ col("employeeId"),
+ col("companyId")
+ ],
+ [fk("employeeId", "user")],
+ {
+ pkColumns: ["id"],
+ uniqueColumns: ["trainingAssignmentId", "employeeId", "period"]
+ }
+ );
+ expect(isUserScopedIdentityTable(t)).toBe(true);
+ });
+
+ it("false when the user FK is in no uniqueness constraint (assignee column)", () => {
+ const t = table(
+ "salesOrder",
+ [col("id"), col("companyId"), col("assignee")],
+ [fk("assignee", "user")],
+ { pkColumns: ["id"], uniqueColumns: ["id"] }
+ );
+ expect(isUserScopedIdentityTable(t)).toBe(false);
+ });
+});
+
+describe("selectWipeableTables (identity tables vs foreign restore)", () => {
+ // customerAccount is identity (NOT-NULL customerId in its PK → user-keyed); on a
+ // foreign restore its parent `customer` is remapped, and CASCADE won't clear it
+ // under replica mode, so it must be WIPED (but never reloaded) to avoid dangling.
+ const normal = table("customer", [col("id"), col("companyId")]);
+ const identity = table(
+ "customerAccount",
+ [col("id"), col("companyId")],
+ [fk("id", "user")],
+ { pkColumns: ["id"], uniqueColumns: ["id"] }
+ );
+ const cat = catalog([normal, identity]);
+
+ it("own restore keeps identity tables OUT of the wipe set", () => {
+ const names = selectWipeableTables(cat).map((t) => t.name);
+ expect(names).toContain("customer");
+ expect(names).not.toContain("customerAccount");
+ });
+
+ it("foreign restore (remap) WIPES identity tables so they can't dangle", () => {
+ const names = selectWipeableTables(cat, { remap: true }).map((t) => t.name);
+ expect(names).toContain("customer");
+ expect(names).toContain("customerAccount");
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
index ca02d068d1..1de2172d6c 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
@@ -215,6 +215,14 @@ export type TableInfo = {
scopeColumn: "companyId" | "companyGroupId";
/** primary key column names (empty when the table has no PK) */
pkColumns: string[];
+ /**
+ * Every column that participates in ANY uniqueness constraint — primary key,
+ * unique constraint, or bare unique index (deduped). A foreign restore that
+ * collapses a user FK in one of these would collide, so it's the signal for
+ * `isUserScopedIdentityTable` (PK alone misses unique-index keys like
+ * `trainingCompletion(trainingAssignmentId, employeeId, period)`).
+ */
+ uniqueColumns: string[];
/** true when the primary key is exactly the single column "id" */
hasId: boolean;
foreignKeys: ForeignKey[];
@@ -476,6 +484,18 @@ export async function getCompanyTableCatalog(
ORDER BY tc.table_name, kcu.ordinal_position
`.execute(db);
+ // Columns in ANY unique index (covers PKs, unique constraints, and bare
+ // CREATE UNIQUE INDEX — the last is how training tables key their employee).
+ // `attnum = ANY(indkey)` skips expression-index entries (attnum 0).
+ const uniqueColumns = await sql<{ table_name: string; column_name: string }>`
+ SELECT t.relname AS table_name, a.attname AS column_name
+ FROM pg_index ix
+ JOIN pg_class t ON t.oid = ix.indrelid
+ JOIN pg_namespace nsp ON nsp.oid = t.relnamespace
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY (ix.indkey)
+ WHERE ix.indisunique AND nsp.nspname = 'public'
+ `.execute(db);
+
const foreignKeys = await sql<{
table_name: string;
column_name: string;
@@ -574,6 +594,13 @@ export async function getCompanyTableCatalog(
pkColumnsByTable.set(p.table_name, list);
}
+ const uniqueColumnsByTable = new Map<string, Set<string>>();
+ for (const u of uniqueColumns.rows) {
+ const set = uniqueColumnsByTable.get(u.table_name) ?? new Set<string>();
+ set.add(u.column_name);
+ uniqueColumnsByTable.set(u.table_name, set);
+ }
+
const fksByTable = new Map<string, ForeignKey[]>();
for (const f of foreignKeys.rows) {
if (!tableSet.has(f.table_name)) continue;
@@ -594,6 +621,7 @@ export async function getCompanyTableCatalog(
scope: scope.get(name)!,
scopeColumn: scopeRoot.get(name)!,
pkColumns,
+ uniqueColumns: [...(uniqueColumnsByTable.get(name) ?? [])],
hasId: pkColumns.length === 1 && pkColumns[0] === "id",
foreignKeys: fksByTable.get(name) ?? []
};
@@ -665,6 +693,201 @@ export function assertBackupImportable(
return { ok: true };
}
+/** FKs to these collapse to the importing user when re-stamping a foreign backup. */
+export const USER_REF_TABLES = new Set(["user", "employee"]);
+
+/**
+ * FK targets a restore resolves WITHOUT the referenced row being in the backup:
+ * `user` (global identity table, never in the catalog) and `company` (structural),
+ * plus `employee` (collapsed to the importer) and `companyGroup` (re-stamped to the
+ * target group). A FK to any of these can't be a closure gap.
+ */
+export const RETAINED_REF_TABLES = new Set([
+ "user",
+ "employee",
+ "company",
+ "companyGroup"
+]);
+
+export type DanglingRef = {
+ table: string;
+ column: string;
+ refTable: string;
+ /** false → restore nulls it (warning); true → NOT NULL, restore cannot resolve. */
+ fatal: boolean;
+ sampleValue: string;
+ count: number;
+};
+
+/**
+ * Find FK values that point at a scoped row the backup does NOT contain — the exact
+ * gap that makes a restore dangle. A backup is "referentially closed" when this
+ * returns no `fatal` entries. Pure (no DB), so the SAME check runs as a unit test
+ * AND as the pre-wipe restore guard — there is one definition of closure, not two
+ * that can drift. Skips refs to `RETAINED_REF_TABLES` (resolved by collapse/identity)
+ * and to non-scoped global tables (`currency`, `country`, … — stable ids present in
+ * every target), since neither is a gap.
+ */
+export function findDanglingReferences(
+ catalog: Catalog,
+ dataByTable: Record<string, Array<{ [col: string]: unknown }>>
+): DanglingRef[] {
+ const catalogNames = new Set(catalog.tables.map((t) => t.name));
+ const idsByTable = new Map<string, Set<unknown>>();
+ for (const t of catalog.tables) {
+ if (!t.hasId) continue;
+ const ids = new Set<unknown>();
+ for (const row of dataByTable[t.name] ?? []) ids.add(row.id);
+ idsByTable.set(t.name, ids);
+ }
+
+ const found = new Map<string, DanglingRef>();
+ for (const t of catalog.tables) {
+ const rows = dataByTable[t.name];
+ if (!rows?.length) continue;
+ 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 (!catalogNames.has(fk.refTable)) continue; // non-scoped global → stable ids
+ const col = colByName.get(fk.column);
+ if (!col) continue;
+ const refIds = idsByTable.get(fk.refTable) ?? new Set();
+ for (const row of rows) {
+ const v = row[fk.column];
+ if (v == null) continue;
+ if (refIds.has(v)) continue;
+ const key = `${t.name}.${fk.column}->${fk.refTable}`;
+ const existing = found.get(key);
+ if (existing) {
+ existing.count++;
+ } else {
+ found.set(key, {
+ table: t.name,
+ column: fk.column,
+ refTable: fk.refTable,
+ fatal: !col.isNullable,
+ sampleValue: String(v),
+ count: 1
+ });
+ }
+ }
+ }
+ }
+ return [...found.values()];
+}
+
+/**
+ * Pre-wipe restore guard: refuse a backup that isn't referentially closed. A
+ * NOT-NULL FK pointing at a missing row would commit under relaxed FK checks and
+ * corrupt the restore, so this reports EVERY fatal gap at once — the whole list is
+ * surfaced before any data is touched, instead of one throw at a time mid-load.
+ */
+export function assertReferentiallyClosed(
+ catalog: Catalog,
+ backup: CompanyBackup
+): { ok: true } | { ok: false; reason: string } {
+ const fatal = findDanglingReferences(catalog, backup.data).filter(
+ (d) => d.fatal
+ );
+ if (fatal.length === 0) return { ok: true };
+ const lines = fatal
+ .map(
+ (d) =>
+ ` ${d.table}.${d.column} → ${d.refTable} (${d.count} row${
+ d.count === 1 ? "" : "s"
+ }, e.g. ${d.sampleValue})`
+ )
+ .join("\n");
+ return {
+ ok: false,
+ reason: `the backup is not self-contained — ${fatal.length} reference${
+ fatal.length === 1 ? "" : "s"
+ } point at rows it doesn't include:\n${lines}`
+ };
+}
+
+export type RowTransform = (value: unknown) => unknown;
+
+/**
+ * Per-column transforms used when re-stamping a FOREIGN backup onto this company:
+ * every id is remapped to a fresh one, companyId/companyGroupId point at the
+ * target, FKs follow the id remap, user refs collapse to the importing user, and
+ * storage paths are rewritten. For an OWN backup (remap=false) every column is
+ * identity — ids and scope already belong here. Pure (no DB), so it lives here
+ * with the other catalog helpers and is unit-tested directly.
+ */
+export function buildRowTransforms(
+ table: TableInfo,
+ columns: ColumnInfo[],
+ ctx: {
+ remap: boolean;
+ companyId: string;
+ userId: string;
+ targetGroupId: string | null;
+ sourceCompanyId: string;
+ idMaps: Map<string, Map<string, string>>;
+ idRewrite: Map<string, string>;
+ }
+): RowTransform[] {
+ const identity: RowTransform = (v) => v;
+ if (!ctx.remap) return columns.map(() => identity);
+
+ const fkByColumn = new Map(table.foreignKeys.map((fk) => [fk.column, fk]));
+ return columns.map((col) => {
+ const fk = fkByColumn.get(col.name);
+ // Only id-keyed tables with a text/uuid id get an idMap (int/serial ids reuse
+ // verbatim — see idMaps build). Gate on the map's presence, not `hasId`, or an
+ // int-id table dereferences an undefined map.
+ const idMap = ctx.idMaps.get(table.name);
+ if (col.name === "id" && idMap) {
+ return (v) => idMap.get(v as string) ?? v;
+ }
+ if (col.name === "companyId") return () => ctx.companyId;
+ if (col.name === "companyGroupId") return () => ctx.targetGroupId;
+ if (STORAGE_PATH_COLUMNS.has(col.name)) {
+ return (v) =>
+ typeof v === "string"
+ ? rewriteStoragePath(
+ v,
+ ctx.sourceCompanyId,
+ ctx.companyId,
+ ctx.idRewrite
+ )
+ : v;
+ }
+ if (fk) {
+ if (USER_REF_TABLES.has(fk.refTable)) {
+ return (v) => (v == null ? v : ctx.userId);
+ }
+ if (fk.refTable === "company") {
+ return (v) => (v === ctx.sourceCompanyId ? ctx.companyId : v);
+ }
+ if (fk.refTable === "companyGroup") {
+ return (v) => (v == null ? v : ctx.targetGroupId);
+ }
+ if (fk.refColumn === "id" && ctx.idMaps.has(fk.refTable)) {
+ const map = ctx.idMaps.get(fk.refTable)!;
+ return (v) => {
+ if (v == null) return v;
+ const mapped = map.get(v as string);
+ if (mapped) return mapped;
+ // The referenced row isn't in the backup. Keeping the stale id would
+ // dangle (FK checks are relaxed during load, so it would commit and
+ // only fail later in MRP/etc). Drop it when nullable; otherwise abort
+ // the whole restore — never commit a corrupt reference.
+ if (col.isNullable) return null;
+ throw new Error(
+ `Backup is inconsistent: ${table.name}.${col.name} references a ` +
+ `${fk.refTable} (${String(v)}) that isn't in the backup.`
+ );
+ };
+ }
+ }
+ return identity;
+ });
+}
+
/**
* Kahn's algorithm over in-set FK edges (referenced tables first). Cycles
* are broken deterministically by picking the remaining table with the
@@ -784,6 +1007,67 @@ export function buildScopeFilter(
)})`;
}
+/**
+ * Export-time closure guard — refuse to PRODUCE a backup that could never be
+ * restored. For each NOT-NULL FK from an exportable scoped table to another
+ * exportable scoped table, count rows in this company's export scope whose
+ * reference falls OUTSIDE the referenced table's export scope (a cross-company /
+ * out-of-scope ref: the child row would be dumped but its parent would not).
+ * DB-level and count-only, so no rows are held in memory. This is the export
+ * mirror of the restore-side `assertReferentiallyClosed`. Skips nullable FKs
+ * (restore nulls a missing nullable ref) and refs to retained/global/secret
+ * tables (`user`, `company`, …, and anything not exported).
+ */
+export async function findExportScopeViolations(
+ db: Kysely<KyselyDatabase>,
+ exportable: TableInfo[],
+ byName: Map<string, TableInfo>,
+ companyId: string,
+ companyGroupId: string | null
+): Promise<string[]> {
+ const exportableNames = new Set(exportable.map((t) => t.name));
+ const checks: Array<{ desc: string; 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
+ const parent = byName.get(fk.refTable)!;
+ const childScope = buildScopeFilter(t, byName, companyId, companyGroupId);
+ const parentScope = buildScopeFilter(
+ parent,
+ byName,
+ companyId,
+ companyGroupId
+ );
+ checks.push({
+ desc: `${t.name}.${fk.column} → ${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 ${parentScope}
+ )`
+ });
+ }
+ }
+
+ const violations: string[] = [];
+ await mapWithConcurrency(checks, 6, async (c) => {
+ const r = await c.query.execute(db);
+ const n = Number(r.rows[0]?.n ?? 0);
+ if (n > 0) violations.push(`${c.desc} (${n} row${n === 1 ? "" : "s"})`);
+ });
+ return violations;
+}
+
/**
* 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
@@ -844,29 +1128,41 @@ export async function canSetReplicationRole(
* A table whose primary key is keyed by a `user`/`employee` FK (e.g. `employeeJob`,
* `customerAccount`, `supplierAccount`, `userToCompany`) is per-source-user
* identity. A foreign restore / reseed collapses every user FK onto the single
- * importing user, so all such rows would land on the same `(id, companyId)` PK and
- * collide. They can never be meaningfully copied to another company — skip them on
- * both load paths (the source's belong to the source's users; the target keeps its
- * own). Derived from the catalog so a new table of this shape is covered
- * automatically rather than silently reintroducing the collision.
+ * importing user, so all such rows would collide on whatever uniqueness constraint
+ * the user column participates in — a composite PK like `(id, companyId)`, OR a
+ * unique index like `trainingCompletion(trainingAssignmentId, employeeId, period)`.
+ * They can never be meaningfully copied to another company — skip them on both load
+ * paths (the source's belong to the source's users; the target keeps its own).
+ * Keys off every unique column (not just the PK) so a table that keys its user via
+ * a unique index is covered automatically rather than silently colliding on load.
*/
export function isUserScopedIdentityTable(table: TableInfo): boolean {
+ const uniqueCols = new Set(
+ table.uniqueColumns.length > 0 ? table.uniqueColumns : table.pkColumns
+ );
return table.foreignKeys.some(
(fk) =>
- table.pkColumns.includes(fk.column) &&
+ uniqueCols.has(fk.column) &&
(fk.refTable === "user" || fk.refTable === "employee")
);
}
export function selectWipeableTables(
catalog: Catalog,
- opts: { includeGroup?: boolean } = {}
+ opts: { includeGroup?: boolean; remap?: boolean } = {}
): TableInfo[] {
const skip = new Set([...SECRET_TABLES, ...IN_PLACE_SKIPPED_TABLES]);
return catalog.tables.filter(
(t) =>
!skip.has(t.name) &&
- !isUserScopedIdentityTable(t) &&
+ // Identity tables (per-source-user rows) are normally KEPT. But a FOREIGN
+ // restore (remap) re-keys their parents' ids, and `ON DELETE CASCADE` does
+ // NOT fire under `session_replication_role='replica'` — so a kept child would
+ // be left dangling at a deleted/remapped parent. On remap we therefore WIPE
+ // them (reverse-topo wipe clears children before parents) and never reload
+ // them (the load set drops them separately). On an own restore parent ids are
+ // stable, so keeping them is safe.
+ (opts.remap === true || !isUserScopedIdentityTable(t)) &&
(t.scopeColumn === "companyId" ||
(opts.includeGroup === true && t.scopeColumn === "companyGroupId"))
);
diff --git a/packages/jobs/src/inngest/functions/tasks/company-export.ts b/packages/jobs/src/inngest/functions/tasks/company-export.ts
index b0e2cd5c14..6b263260b5 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-export.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-export.ts
@@ -11,6 +11,7 @@ import {
buildScopeFilter,
copyAssetsToBackup,
encodeValue,
+ findExportScopeViolations,
getCompanyTableCatalog,
getJobDatabaseClient,
mapWithConcurrency,
@@ -98,6 +99,26 @@ export async function buildCompanyBackup(
const exportable = catalog.tables.filter((t) => !secretTables.has(t.name));
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(
+ 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 "
+ )}`
+ );
+ }
+
// Dump each non-empty table to its own `tables/<table>.ndjson.gz`, in parallel.
const tableManifest: Manifest["tables"] = [];
await mapWithConcurrency(exportable, TABLE_CONCURRENCY, async (table) => {
diff --git a/packages/jobs/src/inngest/functions/tasks/company-import.ts b/packages/jobs/src/inngest/functions/tasks/company-import.ts
index af549672bc..d626d13740 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-import.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-import.ts
@@ -222,9 +222,9 @@ export const companyImportFunction = inngest.createFunction(
let base = identity;
const fk = fkByColumn.get(col.name);
- if (col.name === "id" && table.hasId) {
- const map = idMaps.get(table.name)!;
- base = (v) => map.get(v as string) ?? v;
+ const idMap = idMaps.get(table.name);
+ if (col.name === "id" && idMap) {
+ base = (v) => idMap.get(v as string) ?? v;
} else if (col.name === "companyId") {
base = () => companyId;
} else if (col.name === "companyGroupId") {
diff --git a/packages/jobs/src/inngest/functions/tasks/company-restore.ts b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
index d3b149a904..2ced4da1d2 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-restore.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
@@ -2,29 +2,25 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { chunkArray } from "@carbon/utils";
import { sql } from "kysely";
import { inngest } from "../../client";
-import type {
- Catalog,
- ColumnInfo,
- CompanyBackup,
- TableInfo
-} from "./company-backup";
+import type { Catalog, CompanyBackup } from "./company-backup";
import {
assertBackupImportable,
+ assertReferentiallyClosed,
assertWipeSafe,
backupAssetsDir,
backupDir,
backupNameFromSource,
bindValue,
+ buildRowTransforms,
canSetReplicationRole,
getCompanyTableCatalog,
getJobDatabaseClient,
+ isUserScopedIdentityTable,
newIdForTable,
RESTORE_INTEGRATION,
readBackup,
removeStoragePrefix,
restoreAssetsFromBackup,
- rewriteStoragePath,
- STORAGE_PATH_COLUMNS,
selectWipeableTables,
wipeScopedData,
writeBackupManifest
@@ -33,89 +29,9 @@ import { buildCompanyBackup } from "./company-export";
const INSERT_CHUNK_SIZE = 200;
-/** FKs to these collapse to the importing user when re-stamping a foreign backup. */
-const USER_REF_TABLES = new Set(["user", "employee"]);
-
type ServiceRole = ReturnType<typeof getCarbonServiceRole>;
type JobDatabase = ReturnType<typeof getJobDatabaseClient>;
-type Transform = (value: unknown) => unknown;
-
-/**
- * Per-column transforms used when re-stamping a FOREIGN backup onto this company:
- * every id is remapped to a fresh one, companyId/companyGroupId point at the
- * target, FKs follow the id remap, user refs collapse to the importing user, and
- * storage paths are rewritten. For an OWN backup (remap=false) every column is
- * identity — ids and scope already belong here.
- */
-function buildRowTransforms(
- table: TableInfo,
- columns: ColumnInfo[],
- ctx: {
- remap: boolean;
- companyId: string;
- userId: string;
- targetGroupId: string | null;
- sourceCompanyId: string;
- idMaps: Map<string, Map<string, string>>;
- idRewrite: Map<string, string>;
- }
-): Transform[] {
- const identity: Transform = (v) => v;
- if (!ctx.remap) return columns.map(() => identity);
-
- const fkByColumn = new Map(table.foreignKeys.map((fk) => [fk.column, fk]));
- return columns.map((col) => {
- const fk = fkByColumn.get(col.name);
- if (col.name === "id" && table.hasId) {
- const map = ctx.idMaps.get(table.name)!;
- return (v) => map.get(v as string) ?? v;
- }
- if (col.name === "companyId") return () => ctx.companyId;
- if (col.name === "companyGroupId") return () => ctx.targetGroupId;
- if (STORAGE_PATH_COLUMNS.has(col.name)) {
- return (v) =>
- typeof v === "string"
- ? rewriteStoragePath(
- v,
- ctx.sourceCompanyId,
- ctx.companyId,
- ctx.idRewrite
- )
- : v;
- }
- if (fk) {
- if (USER_REF_TABLES.has(fk.refTable)) {
- return (v) => (v == null ? v : ctx.userId);
- }
- if (fk.refTable === "company") {
- return (v) => (v === ctx.sourceCompanyId ? ctx.companyId : v);
- }
- if (fk.refTable === "companyGroup") {
- return (v) => (v == null ? v : ctx.targetGroupId);
- }
- if (fk.refColumn === "id" && ctx.idMaps.has(fk.refTable)) {
- const map = ctx.idMaps.get(fk.refTable)!;
- return (v) => {
- if (v == null) return v;
- const mapped = map.get(v as string);
- if (mapped) return mapped;
- // The referenced row isn't in the backup. Keeping the stale id would
- // dangle (FK checks are relaxed during load, so it would commit and
- // only fail later in MRP/etc). Drop it when nullable; otherwise abort
- // the whole restore — never commit a corrupt reference.
- if (col.isNullable) return null;
- throw new Error(
- `Backup is inconsistent: ${table.name}.${col.name} references a ` +
- `${fk.refTable} (${String(v)}) that isn't in the backup.`
- );
- };
- }
- }
- return identity;
- });
-}
-
/**
* Wipe the company's restorable tables and reload them from `backup`. Two modes:
* - `remap=false` (own backup / snapshot): ids and scope already belong to this
@@ -147,11 +63,15 @@ async function wipeAndLoad(
}
// Wipe every restorable table (so tables empty in the backup end up empty);
- // reload only those the backup actually has rows for.
+ // reload only those the backup actually has rows for. On a foreign restore the
+ // wipe set also includes user-scoped identity tables (so their stale rows can't
+ // dangle at remapped parents — cascade won't clear them under replica mode), but
+ // they are NEVER reloaded: their source rows belong to the source's users.
const byName = new Map(catalog.tables.map((t) => [t.name, t]));
- const wipeTables = selectWipeableTables(catalog, { includeGroup });
+ const wipeTables = selectWipeableTables(catalog, { includeGroup, remap });
const loadTables = wipeTables.filter(
- (t) => (backup.data[t.name]?.length ?? 0) > 0
+ (t) =>
+ !isUserScopedIdentityTable(t) && (backup.data[t.name]?.length ?? 0) > 0
);
const backupColumns = new Map(
backup.manifest.tables.map((t) => [t.name, new Set(t.columns)])
@@ -455,6 +375,15 @@ export const companyRestoreFunction = inngest.createFunction(
);
}
+ // Referential-closure preflight — BEFORE the snapshot/wipe so a backup
+ // that would dangle a NOT-NULL FK fails with the complete list of gaps
+ // and leaves the company's data untouched, rather than throwing on the
+ // first bad row partway through the load.
+ const closure = assertReferentiallyClosed(catalog, backup);
+ if (!closure.ok) {
+ throw new Error(`This backup can't be restored: ${closure.reason}`);
+ }
+
// 1. Snapshot current state (incl. storage) so a revert can undo this.
// IDEMPOTENT: if a prior attempt already recorded a snapshot, reuse
// it — never re-snapshot, or a retry after the wipe committed would
diff --git a/packages/jobs/vitest.config.ts b/packages/jobs/vitest.config.ts
new file mode 100644
index 0000000000..9a3c27eaed
--- /dev/null
+++ b/packages/jobs/vitest.config.ts
@@ -0,0 +1 @@
+export { default } from "@carbon/config/vitest";
diff --git a/packages/react/package.json b/packages/react/package.json
index c12c1b19f5..31bc54bda5 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -7,6 +7,7 @@
"@carbon/tiptap": "workspace:*",
"@nanostores/react": "catalog:",
"@carbon/utils": "workspace:*",
+ "@base-ui/react": "1.6.0",
"@radix-ui/react-accordion": "1.2.12",
"@radix-ui/react-avatar": "1.1.11",
"@radix-ui/react-checkbox": "1.3.3",
diff --git a/packages/react/src/Date/DatePicker.tsx b/packages/react/src/Date/DatePicker.tsx
index ded917c817..489822ec69 100644
--- a/packages/react/src/Date/DatePicker.tsx
+++ b/packages/react/src/Date/DatePicker.tsx
@@ -11,6 +11,7 @@ import { IconButton } from "../IconButton";
import { InputGroup } from "../Input";
import {
Popover,
+ PopoverAnchor,
PopoverContent,
PopoverFooter,
PopoverTrigger
@@ -102,11 +103,14 @@ const DatePicker = (
<LuBan className="!text-destructive-foreground absolute right-[12px] top-[12px]" />
)}
</div>
- <div className="flex-shrink-0 -mt-px">
- <PopoverTrigger tabIndex={-1}>
+ {/* Anchor (not Trigger) so the calendar button isn't wrapped
+ in a second <button>; the popover open state is driven by
+ react-aria's buttonProps on FieldButton. */}
+ <PopoverAnchor asChild>
+ <div className="flex-shrink-0 -mt-px">
<FieldButton {...buttonProps} isPressed={state.isOpen} />
- </PopoverTrigger>
- </div>
+ </div>
+ </PopoverAnchor>
</InputGroup>
</>
)}
diff --git a/packages/react/src/Popover.tsx b/packages/react/src/Popover.tsx
index 835d34e913..ef9e281bba 100644
--- a/packages/react/src/Popover.tsx
+++ b/packages/react/src/Popover.tsx
@@ -10,6 +10,8 @@ const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
+const PopoverAnchor = PopoverPrimitive.Anchor;
+
const PopoverContent = forwardRef<
ElementRef<typeof PopoverPrimitive.Content>,
ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
@@ -63,6 +65,7 @@ const PopoverClose = PopoverPrimitive.Close;
export {
Popover,
+ PopoverAnchor,
PopoverClose,
PopoverContent,
PopoverFooter,
diff --git a/packages/react/src/Tooltip.tsx b/packages/react/src/Tooltip.tsx
index 5dde2c7119..060b3509da 100644
--- a/packages/react/src/Tooltip.tsx
+++ b/packages/react/src/Tooltip.tsx
@@ -1,39 +1,113 @@
"use client";
-import * as TooltipPrimitive from "@radix-ui/react-tooltip";
-import type { ComponentPropsWithoutRef, ElementRef } from "react";
-import { forwardRef } from "react";
+import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip";
+import type { ReactElement } from "react";
+import { forwardRef, isValidElement } from "react";
import { cn } from "./utils/cn";
-const TooltipProvider = TooltipPrimitive.Provider;
+/**
+ * Base UI Tooltip wrapped to preserve the Radix-compatible API the codebase
+ * already uses (`Tooltip` / `TooltipTrigger asChild` / `TooltipContent side=…`).
+ *
+ * Why Base UI: Radix's Tooltip swallowed the first click on a trigger that was
+ * also a modal Dialog/Drawer trigger (tooltip open → focus/pointer fight on
+ * close), so hovering an icon button then clicking it did nothing. Base UI's
+ * tooltip composes cleanly with other triggers.
+ *
+ * Delay: the old Radix wrapper forced `delayDuration = 0` on every tooltip
+ * (instant). Base UI's Trigger defaults to 600ms, so each Root is wrapped in a
+ * Provider whose `delay` defaults to 0 to keep the original snappy behavior.
+ */
-const Tooltip = ({
- delayDuration = 0,
- ...props
-}: TooltipPrimitive.TooltipProps) => (
- <TooltipPrimitive.Root delayDuration={delayDuration} {...props} />
+type ProviderProps = TooltipPrimitive.Provider.Props & {
+ /** Radix-compat alias for Base UI's `delay`. */
+ delayDuration?: number;
+};
+
+const TooltipProvider = ({ delayDuration, delay, ...props }: ProviderProps) => (
+ <TooltipPrimitive.Provider delay={delay ?? delayDuration ?? 0} {...props} />
+);
+TooltipProvider.displayName = "TooltipProvider";
+
+type RootProps = TooltipPrimitive.Root.Props & {
+ /** Radix-compat alias; mapped to the surrounding Provider's `delay`. */
+ delayDuration?: number;
+};
+
+const Tooltip = ({ delayDuration = 50, ...props }: RootProps) => (
+ <TooltipPrimitive.Provider delay={delayDuration}>
+ <TooltipPrimitive.Root {...props} />
+ </TooltipPrimitive.Provider>
+);
+Tooltip.displayName = "Tooltip";
+
+type TriggerProps = TooltipPrimitive.Trigger.Props & {
+ /** Radix-compat: render the single child as the trigger element. */
+ asChild?: boolean;
+};
+
+const TooltipTrigger = forwardRef<HTMLButtonElement, TriggerProps>(
+ ({ asChild, children, ...props }, ref) => {
+ if (asChild && isValidElement(children)) {
+ return (
+ <TooltipPrimitive.Trigger
+ ref={ref}
+ render={children as ReactElement}
+ {...props}
+ />
+ );
+ }
+ return (
+ <TooltipPrimitive.Trigger ref={ref} {...props}>
+ {children}
+ </TooltipPrimitive.Trigger>
+ );
+ }
+);
+TooltipTrigger.displayName = "TooltipTrigger";
+
+type ContentProps = TooltipPrimitive.Popup.Props &
+ Pick<
+ TooltipPrimitive.Positioner.Props,
+ "side" | "sideOffset" | "align" | "alignOffset"
+ >;
+
+const TooltipContent = forwardRef<HTMLDivElement, ContentProps>(
+ (
+ {
+ className,
+ side = "top",
+ sideOffset = 4,
+ align = "center",
+ alignOffset = 0,
+ ...props
+ },
+ ref
+ ) => (
+ <TooltipPrimitive.Portal>
+ <TooltipPrimitive.Positioner
+ side={side}
+ sideOffset={sideOffset}
+ align={align}
+ alignOffset={alignOffset}
+ className="z-50"
+ >
+ <TooltipPrimitive.Popup
+ ref={ref}
+ className={cn(
+ "z-50 w-fit max-w-xs overflow-hidden rounded-md border border-border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md",
+ "origin-[var(--transform-origin)] transition-[transform,opacity] duration-150",
+ "data-[starting-style]:scale-95 data-[starting-style]:opacity-0",
+ "data-[ending-style]:scale-95 data-[ending-style]:opacity-0",
+ className
+ )}
+ {...props}
+ />
+ </TooltipPrimitive.Positioner>
+ </TooltipPrimitive.Portal>
+ )
);
-Tooltip.displayName = TooltipPrimitive.Root.displayName;
-
-const TooltipTrigger = TooltipPrimitive.Trigger;
-
-const TooltipContent = forwardRef<
- ElementRef<typeof TooltipPrimitive.Content>,
- ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
->(({ className, sideOffset = 4, ...props }, ref) => (
- <TooltipPrimitive.Portal>
- <TooltipPrimitive.Content
- ref={ref}
- sideOffset={sideOffset}
- className={cn(
- "z-50 overflow-hidden rounded-md border border-border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
- className
- )}
- {...props}
- />
- </TooltipPrimitive.Portal>
-));
-TooltipContent.displayName = TooltipPrimitive.Content.displayName;
+TooltipContent.displayName = "TooltipContent";
export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger };
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2d7cd22c33..6e17a61f0b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2422,6 +2422,9 @@ importers:
typescript:
specifier: 'catalog:'
version: 5.8.3
+ vitest:
+ specifier: 'catalog:'
packages/kv:
dependencies:
@@ -2627,6 +2630,9 @@ importers:
packages/react:
dependencies:
+ '@base-ui/react':
+ specifier: 1.6.0
'@carbon/database':
specifier: workspace:*
version: link:../database
@@ -3639,6 +3645,33 @@ packages:
resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==}
engines: {node: '>=6.9.0'}
+ '@base-ui/[email protected]':
+ resolution: {integrity: sha512-/jzjTWJYXhRFO45Bev9lc3cHbmjzCMpUqbMZ2AgKy/z25mY9B6shGSNcXcjQar9n5doM0KYW1W8fcFv2jZBuMw==}
+ engines: {node: '>=14.0.0'}
+ peerDependencies:
+ '@date-fns/tz': ^1.2.0
+ '@types/react': 18.3.28
+ date-fns: ^4.0.0
+ react: 18.3.1
+ react-dom: 18.3.1
+ peerDependenciesMeta:
+ '@date-fns/tz':
+ optional: true
+ '@types/react':
+ optional: true
+ date-fns:
+ optional: true
+
+ '@base-ui/[email protected]':
+ resolution: {integrity: sha512-gFFiltORVmW/N6IILTGxizP3PBpVpysqML1ALY5Vk0mH+7faVkCknOU31goYHN5Aoek2dkjxva1XOD2Ce9WuIg==}
+ peerDependencies:
+ '@types/react': 18.3.28
+ react: 18.3.1
+ react-dom: 18.3.1
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+
'@biomejs/[email protected]':
resolution: {integrity: sha512-Qjsgoe6FEBxWAUzwFGFrB+1+M8y/y5kwmg5CHac+GSVOdmOIqsAiXM5QMVGZJ1eCUCLlPZtq4aFAQ0eawEUuUA==}
engines: {node: '>=14.21.3'}
@@ -13516,6 +13549,9 @@ packages:
resolution: {integrity: sha512-QT7FVMXfWOYFbeRBF6nu+I6tr2Tf3u0q8RIEjNob/heKY/nh7drD/k7eeMFmSQgnTtCzLDcCu/XEnpW2wk4xCQ==}
engines: {node: '>=9.3.0 || >=8.10.0 <9.0.0'}
+ resolution: {integrity: sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==}
+
resolution: {integrity: sha512-bKu4LhXSecP6krvhfDzyDESApYdNfjirD5kykkT1xO0Cj9TKSiGh5Void4pGTs3Am+inSnp4dg0B5XzdwHBJOQ==}
engines: {node: '>=18'}
@@ -15513,6 +15549,29 @@ snapshots:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.28.5
+ dependencies:
+ '@babel/runtime': 7.29.2
+ '@floating-ui/react-dom': 2.1.8([email protected]([email protected]))([email protected])
+ '@floating-ui/utils': 0.2.11
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.28
+
+ dependencies:
+ '@babel/runtime': 7.29.2
+ '@floating-ui/utils': 0.2.11
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ reselect: 5.2.0
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.28
+
'@biomejs/[email protected]':
optionalDependencies:
'@biomejs/cli-darwin-arm64': 2.3.8
@@ -26934,6 +26993,8 @@ snapshots:
transitivePeerDependencies:
- supports-color
+
dependencies:
'@react-email/render': 0.0.16([email protected]([email protected]))([email protected])
@@ -28273,8 +28334,8 @@ snapshots:
picomatch: 4.0.4
std-env: 4.0.0
tinybench: 2.9.0
- tinyexec: 1.1.1
- tinyglobby: 0.2.16
+ tinyexec: 1.2.4
+ tinyglobby: 0.2.17
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0
@@ -28301,8 +28362,8 @@ snapshots:
picomatch: 4.0.4
std-env: 4.0.0
tinybench: 2.9.0
- tinyexec: 1.1.1
- tinyglobby: 0.2.16
+ tinyexec: 1.2.4
+ tinyglobby: 0.2.17
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0
@@ -28329,8 +28390,8 @@ snapshots:
picomatch: 4.0.4
std-env: 4.0.0
tinybench: 2.9.0
- tinyexec: 1.1.1
- tinyglobby: 0.2.16
+ tinyexec: 1.2.4
+ tinyglobby: 0.2.17
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0
@@ -28357,8 +28418,8 @@ snapshots:
picomatch: 4.0.4
std-env: 4.0.0
tinybench: 2.9.0
- tinyexec: 1.1.1
- tinyglobby: 0.2.16
+ tinyexec: 1.2.4
+ tinyglobby: 0.2.17
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0
@@ -28385,8 +28446,8 @@ snapshots:
picomatch: 4.0.4
std-env: 4.0.0
tinybench: 2.9.0
- tinyexec: 1.1.1
- tinyglobby: 0.2.16
+ tinyexec: 1.2.4
+ tinyglobby: 0.2.17
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0
@@ -28413,8 +28474,8 @@ snapshots:
picomatch: 4.0.4
std-env: 4.0.0
tinybench: 2.9.0
- tinyexec: 1.1.1
- tinyglobby: 0.2.16
+ tinyexec: 1.2.4
+ tinyglobby: 0.2.17
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0