Skip to content

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

feat(audit): schema-driven FK snapshots via display registry

naveenkash7a7e737d715f
diff --git a/.claude/rules/audit-log-system.md b/.claude/rules/audit-log-system.md
index 539da29823..4fa5e4f22c 100644
--- a/.claude/rules/audit-log-system.md
+++ b/.claude/rules/audit-log-system.md
@@ -52,7 +52,8 @@ Other config knobs:
- `skipFields: ["updatedAt", "updatedBy", "embedding"]` — excluded from diffs (matched top-level and as nested `.suffix`).
- `retentionDays: 30`
- `archivePath: "audit-logs/{companyId}/{year}/{month}.jsonl.gz"` and `archiveBucket: "private"`.
-- `createFields` (allowlist of columns surfaced on INSERT) and `snapshotFields` (FK display values frozen into the diff) are declared per table.
+- `createFields` (allowlist of columns surfaced on INSERT) is declared per table.
+- `fkDisplayRegistry` — display columns per FK *target* table (e.g. `supplier: ["name"]`, `user: ["fullName"]`). FK columns are discovered from the schema at runtime via the `get_foreign_key_map` RPC (reads `pg_constraint`; only FKs referencing the target's `id`; returns `targetHasCompanyId` so non-tenant targets like `user` skip the companyId filter). Any changed FK column whose target is in the registry gets its display values frozen into the diff automatically; targets missing from the registry degrade to showing the raw id. Per-column `snapshotFields` on a table config still exist as overrides and win over the registry.
Types live in `audit.types.ts`: `AuditLogEntry`, `CreateAuditLogEntry`, `AuditDiff`, `AuditDiffEntry`,
`AuditMetadata`, `AuditOperation`, `AuditLogFilters`, `AuditLogResponse`, `AuditLogArchive`, `AuditLogConfig`.
@@ -65,8 +66,10 @@ DB triggers added via `attach_event_trigger(...)` push table changes onto a PGMQ
`handlerType = 'AUDIT'`. The queue dispatcher (`packages/jobs/src/inngest/.../queue.ts`) batches AUDIT
records and emits `carbon/event-audit`. `auditFunction` in
`packages/jobs/src/inngest/functions/events/audit.ts` (Inngest id `event-handler-audit`) computes diffs
-(`computeDiff` / `computeCreateDiff` / `computeNestedDiff`, honoring `skipFields`), resolves snapshot FKs,
-and writes via `client.rpc("insert_audit_log_batch", { p_company_id, p_entries })`.
+(`computeDiff` / `computeCreateDiff` / `computeNestedDiff`, honoring `skipFields`), resolves FK snapshots
+(`applyFkSnapshots`: FK topology from `get_foreign_key_map` cached per process, display columns from
+`fkDisplayRegistry`, override precedence in `events/fk-snapshots.ts` → `resolveSnapshotSpec`, one batched
+lookup per target table), and writes via `client.rpc("insert_audit_log_batch", { p_company_id, p_entries })`.
## Query / management functions
diff --git a/packages/database/src/audit.config.ts b/packages/database/src/audit.config.ts
index 96ac22b19c..b5bb7ede0d 100644
--- a/packages/database/src/audit.config.ts
+++ b/packages/database/src/audit.config.ts
@@ -580,6 +580,52 @@ export const auditConfig = {
archiveBucket: "private"
} as const;
+// ---------------------------------------------------------------------------
+// FK display registry
+// ---------------------------------------------------------------------------
+
+/**
+ * Display columns per FK *target* table, keyed by the table being pointed at
+ * — one entry per referenced table, reused by every FK that points there.
+ *
+ * The audit handler discovers which diff columns are FKs (and what they
+ * reference) from the schema itself via the `get_foreign_key_map` RPC, then
+ * uses this registry to decide what to read from the target row and freeze
+ * into the diff as `snapshot.old` / `snapshot.new`. A target table missing
+ * from this registry degrades gracefully: the diff keeps the raw id.
+ *
+ * Per-column `snapshotFields` on a table config still win over this registry
+ * (use them to pick different columns for one specific FK).
+ *
+ * A single-column list renders as an inline pill in the audit drawer; a
+ * multi-column list renders as an expanded section.
+ */
+export const fkDisplayRegistry: {
+ [T in TableName]?: readonly ColumnOf<T>[];
+} = {
+ address: ["addressLine1", "city"],
+ contact: ["fullName"],
+ customer: ["name"],
+ customerLocation: ["name"],
+ customerStatus: ["name"],
+ customerType: ["name"],
+ department: ["name"],
+ employeeType: ["name"],
+ item: ["readableId"],
+ location: ["name"],
+ paymentTerm: ["name"],
+ process: ["name"],
+ shift: ["name"],
+ shippingMethod: ["name"],
+ shippingTerm: ["name"],
+ supplier: ["name"],
+ supplierLocation: ["name"],
+ supplierType: ["name"],
+ unitOfMeasure: ["name"],
+ user: ["fullName"],
+ workCenter: ["name"]
+} as const;
+
// ---------------------------------------------------------------------------
// Derived types
// ---------------------------------------------------------------------------
diff --git a/packages/database/supabase/migrations/20260724130930_audit-fk-map.sql b/packages/database/supabase/migrations/20260724130930_audit-fk-map.sql
new file mode 100644
index 0000000000..2b1f341296
--- /dev/null
+++ b/packages/database/supabase/migrations/20260724130930_audit-fk-map.sql
@@ -0,0 +1,56 @@
+-- FK topology for audit-log snapshots.
+--
+-- The audit handler freezes FK targets' display values into diffs
+-- ("Supplier: Acme → Bolton") so history stays readable after renames or
+-- deletes. Which column points at which table was previously hand-declared
+-- per FK in audit.config.ts (`snapshotFields`) — 15 columns covered out of
+-- the ~280 business FKs on audited tables. Postgres already knows the
+-- topology; this function exposes it so the handler can resolve every FK
+-- automatically, with audit.config.ts only supplying per-target display
+-- columns (`fkDisplayRegistry`).
+--
+-- For each FK constraint on the given tables, returns the local column that
+-- references the target's "id" column. Composite FKs like
+-- (col, companyId) → (id, companyId) are handled by pairing conkey/confkey
+-- positionally and keeping only the id-referencing pair. FKs that reference
+-- a non-id column (e.g. currencyCode.code) are excluded — the snapshot
+-- lookup queries the target by id.
+--
+-- "targetHasCompanyId" tells the handler whether the snapshot lookup can be
+-- tenant-scoped (most tables) or not (e.g. "user").
+
+CREATE OR REPLACE FUNCTION public.get_foreign_key_map(p_table_names TEXT[])
+RETURNS TABLE(
+ "tableName" TEXT,
+ "columnName" TEXT,
+ "targetTable" TEXT,
+ "targetHasCompanyId" BOOLEAN
+)
+LANGUAGE sql
+STABLE
+AS $$
+ SELECT DISTINCT
+ c.relname::TEXT,
+ a.attname::TEXT,
+ tc.relname::TEXT,
+ EXISTS (
+ SELECT 1 FROM pg_attribute ca
+ WHERE ca.attrelid = con.confrelid
+ AND ca.attname = 'companyId'
+ AND NOT ca.attisdropped
+ )
+ FROM pg_constraint con
+ JOIN pg_class c ON c.oid = con.conrelid
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ JOIN pg_class tc ON tc.oid = con.confrelid
+ JOIN pg_namespace tn ON tn.oid = tc.relnamespace
+ CROSS JOIN LATERAL unnest(con.conkey, con.confkey) AS k(attnum, refattnum)
+ JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = k.attnum
+ JOIN pg_attribute ra ON ra.attrelid = con.confrelid AND ra.attnum = k.refattnum
+ WHERE con.contype = 'f'
+ AND n.nspname = 'public'
+ AND tn.nspname = 'public'
+ AND ra.attname = 'id'
+ AND a.attname <> 'id'
+ AND c.relname = ANY(p_table_names)
+$$;
diff --git a/packages/jobs/src/inngest/functions/events/audit.ts b/packages/jobs/src/inngest/functions/events/audit.ts
index e637f99bdd..593951afd4 100644
--- a/packages/jobs/src/inngest/functions/events/audit.ts
+++ b/packages/jobs/src/inngest/functions/events/audit.ts
@@ -1,7 +1,11 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import type { TableConfig } from "@carbon/database/audit.config";
+import type {
+ SnapshotFieldEntry,
+ TableConfig
+} from "@carbon/database/audit.config";
import {
auditConfig,
+ getAuditableTableNames,
getCreateFields,
getEntityConfigsForTable,
getSnapshotFields,
@@ -19,6 +23,8 @@ import { getLogger } from "@carbon/logger";
import { groupBy, tiptapToText } from "@carbon/utils";
import { z } from "zod";
import { inngest } from "../../client";
+import type { FkMap, FkMapRow } from "./fk-snapshots";
+import { parseFkMapRows, resolveSnapshotSpec } from "./fk-snapshots";
const log = getLogger("jobs", "audit");
@@ -476,10 +482,48 @@ export const auditFunction = inngest.createFunction(
);
/**
- * For every entry whose tableConfig declares `snapshotFields`, look up the
- * FK target's display columns and freeze them onto the diff entry under
- * `snapshot.old` / `snapshot.new`. One batched query per target table —
- * proportional to distinct FK targets, not to entries.
+ * FK topology of the audited tables, fetched once per process from the
+ * `get_foreign_key_map` RPC (which reads pg_constraint). Cached forever:
+ * schema only changes on deploys, which restart the worker. Failures are
+ * not cached, so the next batch retries the fetch.
+ */
+let fkMapCache: FkMap | null = null;
+
+async function getFkMap(
+ client: ReturnType<typeof getCarbonServiceRole>
+): Promise<FkMap> {
+ if (fkMapCache) return fkMapCache;
+ try {
+ const { data, error } = await (client as any).rpc("get_foreign_key_map", {
+ p_table_names: getAuditableTableNames()
+ });
+ if (error || !data) {
+ log.error(
+ "get_foreign_key_map failed; only declared snapshotFields will resolve",
+ { error }
+ );
+ return new Map();
+ }
+ fkMapCache = parseFkMapRows(data as FkMapRow[]);
+ return fkMapCache;
+ } catch (err) {
+ log.error(
+ "get_foreign_key_map threw; only declared snapshotFields will resolve",
+ {
+ error: err
+ }
+ );
+ return new Map();
+ }
+}
+
+/**
+ * For every FK column that changed, look up the FK target's display columns
+ * and freeze them onto the diff entry under `snapshot.old` / `snapshot.new`.
+ * FK columns are discovered from the schema (`getFkMap`) with display
+ * columns from `fkDisplayRegistry`; per-column `snapshotFields` overrides
+ * win. One batched query per target table — proportional to distinct FK
+ * targets, not to entries.
*/
async function applyFkSnapshots(
client: ReturnType<typeof getCarbonServiceRole>,
@@ -502,33 +546,49 @@ async function applyFkSnapshots(
const refs: Ref[] = [];
const idsByTable = new Map<string, Set<string>>();
const colsByTable = new Map<string, Set<string>>();
+ const companyScopedByTable = new Map<string, boolean>();
+ const fkMap = await getFkMap(client);
for (const entry of entries) {
if (!entry.diff) continue;
+
+ const overrides = new Map<string, SnapshotFieldEntry>();
const configs = getEntityConfigsForTable(entry.tableName).filter(
(c) => c.entityType === entry.entityType
);
for (const { tableConfig } of configs) {
- const snapshots = getSnapshotFields(tableConfig as TableConfig);
- for (const snap of snapshots) {
- const change = entry.diff[snap.column];
- if (!change) continue;
- refs.push({
- diffEntry: change,
- table: snap.table,
- displayColumns: snap.displayColumns
- });
-
- const ids = idsByTable.get(snap.table) ?? new Set<string>();
- if (typeof change.old === "string") ids.add(change.old);
- if (typeof change.new === "string") ids.add(change.new);
- idsByTable.set(snap.table, ids);
-
- const cols = colsByTable.get(snap.table) ?? new Set<string>();
- for (const c of snap.displayColumns) cols.add(c);
- colsByTable.set(snap.table, cols);
+ for (const snap of getSnapshotFields(tableConfig as TableConfig)) {
+ overrides.set(snap.column, snap);
}
}
+
+ for (const [column, change] of Object.entries(entry.diff)) {
+ if (!change) continue;
+ const spec = resolveSnapshotSpec(
+ entry.tableName,
+ column,
+ overrides,
+ fkMap
+ );
+ if (!spec) continue;
+
+ refs.push({
+ diffEntry: change,
+ table: spec.table,
+ displayColumns: spec.displayColumns
+ });
+
+ const ids = idsByTable.get(spec.table) ?? new Set<string>();
+ if (typeof change.old === "string") ids.add(change.old);
+ if (typeof change.new === "string") ids.add(change.new);
+ idsByTable.set(spec.table, ids);
+
+ const cols = colsByTable.get(spec.table) ?? new Set<string>();
+ for (const c of spec.displayColumns) cols.add(c);
+ colsByTable.set(spec.table, cols);
+
+ companyScopedByTable.set(spec.table, spec.hasCompanyId);
+ }
}
if (refs.length === 0) return;
@@ -543,11 +603,16 @@ async function applyFkSnapshots(
const selectClause = ["id", ...cols].join(", ");
try {
- const { data, error } = await (client as any)
+ let query = (client as any)
.from(table)
.select(selectClause)
- .eq("companyId", companyId)
.in("id", Array.from(ids));
+ // Tenant-scope the lookup unless the target table has no companyId
+ // (e.g. "user" — global identity).
+ if (companyScopedByTable.get(table) !== false) {
+ query = query.eq("companyId", companyId);
+ }
+ const { data, error } = await query;
if (error || !data) continue;
diff --git a/packages/jobs/src/inngest/functions/events/fk-snapshots.test.ts b/packages/jobs/src/inngest/functions/events/fk-snapshots.test.ts
new file mode 100644
index 0000000000..6a6e73a371
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/events/fk-snapshots.test.ts
@@ -0,0 +1,180 @@
+import type { SnapshotFieldEntry } from "@carbon/database/audit.config";
+import { fkDisplayRegistry } from "@carbon/database/audit.config";
+import { describe, expect, it } from "vitest";
+import type { FkMapRow } from "./fk-snapshots";
+import { fkMapKey, parseFkMapRows, resolveSnapshotSpec } from "./fk-snapshots";
+
+// resolveSnapshotSpec is the single decision point for "does this changed
+// column get a human-readable snapshot, and from where" — these tests pin
+// its precedence (override > schema FK + registry > nothing) so audit rows
+// don't silently lose or misattribute snapshots.
+
+const NO_OVERRIDES: ReadonlyMap<string, SnapshotFieldEntry> = new Map();
+
+function fkMapOf(...rows: FkMapRow[]) {
+ return parseFkMapRows(rows);
+}
+
+describe("parseFkMapRows / fkMapKey", () => {
+ it("keys entries by table.column", () => {
+ const map = fkMapOf({
+ tableName: "purchaseOrder",
+ columnName: "supplierId",
+ targetTable: "supplier",
+ targetHasCompanyId: true
+ });
+ expect(map.get(fkMapKey("purchaseOrder", "supplierId"))).toEqual({
+ targetTable: "supplier",
+ targetHasCompanyId: true
+ });
+ expect(map.get(fkMapKey("purchaseOrder", "locationId"))).toBeUndefined();
+ });
+});
+
+describe("resolveSnapshotSpec — automatic path (schema FK + registry)", () => {
+ it("resolves a schema-discovered FK whose target is in the registry", () => {
+ const fkMap = fkMapOf({
+ tableName: "purchaseOrder",
+ columnName: "supplierId",
+ targetTable: "supplier",
+ targetHasCompanyId: true
+ });
+ expect(
+ resolveSnapshotSpec("purchaseOrder", "supplierId", NO_OVERRIDES, fkMap)
+ ).toEqual({
+ table: "supplier",
+ displayColumns: fkDisplayRegistry.supplier,
+ hasCompanyId: true
+ });
+ });
+
+ it("propagates hasCompanyId=false for global targets like user", () => {
+ const fkMap = fkMapOf({
+ tableName: "salesOrder",
+ columnName: "assignee",
+ targetTable: "user",
+ targetHasCompanyId: false
+ });
+ expect(
+ resolveSnapshotSpec("salesOrder", "assignee", NO_OVERRIDES, fkMap)
+ ).toEqual({
+ table: "user",
+ displayColumns: fkDisplayRegistry.user,
+ hasCompanyId: false
+ });
+ });
+
+ it("returns null when the FK target has no registry entry", () => {
+ const fkMap = fkMapOf({
+ tableName: "job",
+ columnName: "someObscureId",
+ targetTable: "tableNobodyRegistered",
+ targetHasCompanyId: true
+ });
+ expect(
+ resolveSnapshotSpec("job", "someObscureId", NO_OVERRIDES, fkMap)
+ ).toBeNull();
+ });
+
+ it("returns null for a non-FK column", () => {
+ expect(
+ resolveSnapshotSpec("purchaseOrder", "status", NO_OVERRIDES, fkMapOf())
+ ).toBeNull();
+ });
+
+ it("returns null for nested diff keys", () => {
+ const fkMap = fkMapOf({
+ tableName: "purchaseOrder",
+ columnName: "supplierId",
+ targetTable: "supplier",
+ targetHasCompanyId: true
+ });
+ expect(
+ resolveSnapshotSpec(
+ "purchaseOrder",
+ "notes.supplierId",
+ NO_OVERRIDES,
+ fkMap
+ )
+ ).toBeNull();
+ });
+});
+
+describe("resolveSnapshotSpec — overrides (declared snapshotFields)", () => {
+ const override: SnapshotFieldEntry = {
+ column: "supplierId",
+ table: "supplier",
+ displayColumns: ["name", "readableId"]
+ };
+ const overrides = new Map([["supplierId", override]]);
+
+ it("prefers the override's display columns over the registry", () => {
+ const fkMap = fkMapOf({
+ tableName: "purchaseOrder",
+ columnName: "supplierId",
+ targetTable: "supplier",
+ targetHasCompanyId: true
+ });
+ expect(
+ resolveSnapshotSpec("purchaseOrder", "supplierId", overrides, fkMap)
+ ).toEqual({
+ table: "supplier",
+ displayColumns: ["name", "readableId"],
+ hasCompanyId: true
+ });
+ });
+
+ it("resolves an override even when the fkMap is empty (RPC unavailable)", () => {
+ expect(
+ resolveSnapshotSpec("purchaseOrder", "supplierId", overrides, fkMapOf())
+ ).toEqual({
+ table: "supplier",
+ displayColumns: ["name", "readableId"],
+ hasCompanyId: true
+ });
+ });
+
+ it("defaults to tenant-scoped when the override target disagrees with the schema FK", () => {
+ const fkMap = fkMapOf({
+ tableName: "purchaseOrder",
+ columnName: "supplierId",
+ targetTable: "someOtherTable",
+ targetHasCompanyId: false
+ });
+ const spec = resolveSnapshotSpec(
+ "purchaseOrder",
+ "supplierId",
+ overrides,
+ fkMap
+ );
+ expect(spec?.table).toBe("supplier");
+ expect(spec?.hasCompanyId).toBe(true);
+ });
+});
+
+describe("fkDisplayRegistry", () => {
+ it("covers every target the previously hand-declared snapshotFields used", () => {
+ // The 7 tables the old per-FK allowlist pointed at — the registry must
+ // keep them covered so the migration to automatic discovery loses nothing.
+ for (const target of [
+ "customerType",
+ "customerStatus",
+ "supplierType",
+ "location",
+ "process",
+ "supplier",
+ "supplierLocation",
+ "paymentTerm",
+ "shippingMethod",
+ "shippingTerm",
+ "customer",
+ "customerLocation"
+ ] as const) {
+ expect(
+ fkDisplayRegistry[target],
+ `registry is missing "${target}"`
+ ).toBeDefined();
+ expect(fkDisplayRegistry[target]!.length).toBeGreaterThan(0);
+ }
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/events/fk-snapshots.ts b/packages/jobs/src/inngest/functions/events/fk-snapshots.ts
new file mode 100644
index 0000000000..80671e8e93
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/events/fk-snapshots.ts
@@ -0,0 +1,96 @@
+import type { SnapshotFieldEntry } from "@carbon/database/audit.config";
+import { fkDisplayRegistry } from "@carbon/database/audit.config";
+
+/**
+ * FK topology for the audited tables, discovered from the schema via the
+ * `get_foreign_key_map` RPC: which columns point at which table, and whether
+ * the target table is tenant-scoped. Keyed `"${tableName}.${columnName}"`.
+ */
+export type FkMapEntry = {
+ targetTable: string;
+ targetHasCompanyId: boolean;
+};
+
+export type FkMap = ReadonlyMap<string, FkMapEntry>;
+
+export type FkMapRow = {
+ tableName: string;
+ columnName: string;
+ targetTable: string;
+ targetHasCompanyId: boolean;
+};
+
+export function fkMapKey(tableName: string, columnName: string): string {
+ return `${tableName}.${columnName}`;
+}
+
+export function parseFkMapRows(
+ rows: readonly FkMapRow[]
+): Map<string, FkMapEntry> {
+ const map = new Map<string, FkMapEntry>();
+ for (const row of rows) {
+ map.set(fkMapKey(row.tableName, row.columnName), {
+ targetTable: row.targetTable,
+ targetHasCompanyId: row.targetHasCompanyId
+ });
+ }
+ return map;
+}
+
+/**
+ * What to snapshot for one diff column: the FK target table, the display
+ * columns to freeze, and whether the lookup can be tenant-scoped.
+ */
+export type SnapshotSpec = {
+ table: string;
+ displayColumns: readonly string[];
+ hasCompanyId: boolean;
+};
+
+/**
+ * Resolve the snapshot spec for a changed column, or null if the column is
+ * not a snapshot-able FK.
+ *
+ * Precedence:
+ * 1. A per-column `snapshotFields` override on the table config — explicit
+ * display columns for this one FK.
+ * 2. Schema-discovered FK (fkMap) whose target table is in
+ * `fkDisplayRegistry` — the automatic path covering every FK.
+ *
+ * Nested diff keys ("notes.content") and non-FK columns miss both and
+ * resolve to null — the diff keeps its raw values.
+ */
+export function resolveSnapshotSpec(
+ tableName: string,
+ column: string,
+ overrides: ReadonlyMap<string, SnapshotFieldEntry>,
+ fkMap: FkMap
+): SnapshotSpec | null {
+ const fk = fkMap.get(fkMapKey(tableName, column));
+
+ const override = overrides.get(column);
+ if (override) {
+ return {
+ table: override.table,
+ displayColumns: override.displayColumns,
+ // The override's target may differ from the schema FK's target (or the
+ // fkMap may be unavailable); only trust the fkMap's tenancy flag when
+ // it describes the same target table. Default to tenant-scoped — the
+ // behavior overrides always had.
+ hasCompanyId:
+ fk && fk.targetTable === override.table ? fk.targetHasCompanyId : true
+ };
+ }
+
+ if (!fk) return null;
+ const displayColumns = (
+ fkDisplayRegistry as Record<string, readonly string[] | undefined>
+ )[fk.targetTable];
+ if (!displayColumns || displayColumns.length === 0) return null;
+
+ return {
+ table: fk.targetTable,
+ displayColumns,
+ hasCompanyId: fk.targetHasCompanyId
+ };
+}