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: scope job-operation dependency checks to the owning company

aashubb36f0acd47e
diff --git a/.claude/rules/workflow-edge-function.md b/.claude/rules/workflow-edge-function.md
index 6102797eea..0564f1a6cb 100644
--- a/.claude/rules/workflow-edge-function.md
+++ b/.claude/rules/workflow-edge-function.md
@@ -23,10 +23,23 @@ pnpm db:function:new <name> # → supabase functions new (root script)
Creates `packages/database/supabase/functions/<name>/index.ts`.
-## 2. Register in config.toml (required to deploy)
+## 2. Register in config.toml (settings, NOT a deploy gate)
-Add an entry to `packages/database/supabase/config.toml`. Without it the function
-is not deployed.
+Add an entry to `packages/database/supabase/config.toml`.
+
+**A missing entry does not stop the function from deploying.** `ci/src/migrations.ts`
+runs `supabase functions deploy` with **no function name**, and that deploys every
+directory under `supabase/functions/` regardless of `config.toml`. The entry only
+overrides per-function settings, `verify_jwt` above all.
+<!-- UNVERIFIED: the CLI's default for an unregistered function's verify_jwt is
+documented as true, but that was not confirmed against a deployed Carbon function. -->
+
+`schedule` and `trigger-rework` are both live today with no `config.toml` entry.
+That is the trap: an unregistered function looks unshipped in this file while being
+reachable in production, so its in-function authorization is the only gate it has —
+`trigger-rework` had none until
+`.ai/specs/2026-08-25-backup-durability.md` Part 3. Register the function anyway
+(it is where a future reader looks), but never treat absence as "not deployed".
```toml
[functions.<name>]
@@ -152,8 +165,15 @@ const { data, error } = await client.functions.invoke("post-receipt", {
Real call sites: `serviceRole.functions.invoke("create", { body: {...} })`,
`...invoke("mrp", { body: { ...params } })`, `...invoke("schedule", { body })`,
-`...invoke("import-csv", { body })`. The **route's** `requirePermissions` is the
-real auth gate for these service-role invocations.
+`...invoke("import-csv", { body })`.
+
+The route's `requirePermissions` is **not** sufficient on its own, and believing it
+was is what produced the cross-tenant write in
+`.ai/specs/2026-08-25-backup-durability.md` Part 3. It proves the CALLER may act in
+`companyId`; it proves nothing about the RECORD IDS in the body, which usually come
+straight from the URL. When the invocation is service-role, RLS is not there to
+catch the mismatch either. So a function that takes a record id must re-read that
+record under `companyId` itself and 404 on a miss — `schedule` does this for `jobId`.
## 6. Local dev
@@ -168,15 +188,17 @@ that calls `client.functions.invoke("<name>", ...)`.
Deployment is **all-at-once**, not per-function. On push to `main` touching
`packages/database/supabase/**`, CI runs `supabase functions deploy`
(`ci/src/migrations.ts`), which deploys every `[functions.*]` with `enabled = true`
-from `config.toml`. There is **no `npm run db:deploy` / `db:deploy` script** — that
-was stale. Self-hosted instances sync separately via a server-side script
-(`.github/workflows/functions.yml`). You don't run a deploy manually; merging to
-`main` with the `config.toml` entry present is what ships it.
+(`supabase functions deploy`, no arguments → every directory under
+`supabase/functions/`, `config.toml` entry or not). There is **no
+`npm run db:deploy` / `db:deploy` script** — that was stale. Self-hosted instances
+sync separately via a server-side script (`.github/workflows/functions.yml`). You
+don't run a deploy manually; merging to `main` is what ships it.
## Checklist
- [ ] `pnpm db:function:new <name>` (file at `functions/<name>/index.ts`)
-- [ ] `[functions.<name>]` added to `config.toml` (`enabled`, `verify_jwt`)
+- [ ] `[functions.<name>]` added to `config.toml` (`enabled`, `verify_jwt`) — for
+ the settings and for discoverability, NOT because it gates the deploy
- [ ] CORS `OPTIONS` short-circuit returning `corsHeaders`
- [ ] zod `payloadValidator` (`companyId` + `userId` always; discriminated union for multi-op)
- [ ] Auth via `requirePermissions(req, companyId, userId, { <action>: "<module>" })`
diff --git a/packages/database/supabase/functions/schedule/index.ts b/packages/database/supabase/functions/schedule/index.ts
index 551553d83b..3fee1bf7bb 100644
--- a/packages/database/supabase/functions/schedule/index.ts
+++ b/packages/database/supabase/functions/schedule/index.ts
@@ -35,6 +35,25 @@ serve(async (req: Request) => {
const client = await requirePermissions(req, companyId, userId, { update: "production" });
+ // `requirePermissions` proved the caller may update production in
+ // `companyId`. It did NOT prove `jobId` belongs to that company — both
+ // arrive in the same payload, from callers that pass a URL segment straight
+ // through on a service-role client. Without this, a request pairing one
+ // company's id with another company's job rebuilds the victim's dependency
+ // rows stamped with the caller's `companyId`.
+ // See .ai/specs/2026-08-25-backup-durability.md Part 3.
+ const job = await db
+ .selectFrom("job")
+ .select(["id", "companyId"])
+ .where("id", "=", jobId)
+ .executeTakeFirst();
+
+ // 404, not 403: a job in another company must be indistinguishable from a
+ // job that does not exist.
+ if (!job || job.companyId !== companyId) {
+ return errorResponse("Job not found in this company", 404);
+ }
+
const engine = new SchedulingEngine({
client,
db,
diff --git a/packages/database/supabase/functions/trigger-rework/index.ts b/packages/database/supabase/functions/trigger-rework/index.ts
index 48b4cb665e..a87867bc4c 100644
--- a/packages/database/supabase/functions/trigger-rework/index.ts
+++ b/packages/database/supabase/functions/trigger-rework/index.ts
@@ -4,6 +4,7 @@ import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";
import z from "npm:zod@^3.24.1";
import { getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
+import { requirePermissions } from "../lib/supabase.ts";
import type { DB } from "../lib/types.ts";
const pool = getConnectionPool(1);
@@ -348,9 +349,15 @@ async function triggerRework(
// 7b. Convergence: downstream ops that depended on triggeredAt also depend
// on the last rework op so the DAG merges back.
+ // Filter on `jobId`, not `companyId`: dependency edges are per-job, and
+ // `jobId` is the column the scheduler's own rebuild filters on. Trusting the
+ // row's stamped `companyId` would trust exactly the field that cross-tenant
+ // mis-stamping makes unreliable. Without any filter this read reaches every
+ // tenant's edges and re-inserts them under this job's company.
const downstreamDeps = await trx
.selectFrom("jobOperationDependency")
.select(["operationId"])
+ .where("jobId", "=", jobId)
.where("dependsOnId", "=", triggeredAtJobOperationId)
.where("operationId", "not in", clonedOperationIds)
.execute();
@@ -425,6 +432,32 @@ serve(async (req) => {
const body = parsed.data;
+ // This function had NO authorization gate at all. It writes rework
+ // operations, dependency edges and productionQuantity rows, so it needs the
+ // same gate every other write function uses. Note `requirePermissions`
+ // short-circuits for a service_role caller (the two MES callers), which is
+ // exactly why the ownership check below — not this call — is what protects
+ // those paths.
+ await requirePermissions(req, body.companyId, body.userId, {
+ update: "production",
+ });
+
+ // `jobId` and `companyId` both arrive in the payload, and nothing proved
+ // they belong together. Without this, a request pairing one company's id
+ // with another company's job writes rows attributed to the wrong tenant.
+ // See .ai/specs/2026-08-25-backup-durability.md Part 3.
+ const job = await db
+ .selectFrom("job")
+ .select(["id", "companyId"])
+ .where("id", "=", body.jobId)
+ .executeTakeFirst();
+
+ // 404, not 403: a job in another company must be indistinguishable from a
+ // job that does not exist.
+ if (!job || job.companyId !== body.companyId) {
+ return errorResponse("Job not found in this company", 404);
+ }
+
console.info(
`🔰 Starting rework for job ${body.jobId}: go back to ${body.targetJobOperationId} from ${body.triggeredAtJobOperationId}`
);
diff --git a/packages/database/supabase/migrations/20260825075035_harden-operation-dependency-scope.sql b/packages/database/supabase/migrations/20260825075035_harden-operation-dependency-scope.sql
new file mode 100644
index 0000000000..0907ac4d25
--- /dev/null
+++ b/packages/database/supabase/migrations/20260825075035_harden-operation-dependency-scope.sql
@@ -0,0 +1,264 @@
+-- Operation-dependency readiness must not be decided by another tenant's rows.
+--
+-- `jobOperationDependency` carries its own "companyId", but its FKs to
+-- "jobOperation" and "job" are single-column, so Postgres only guarantees the
+-- referenced row exists SOMEWHERE. A write path that pairs one company's id with
+-- another company's job therefore produces rows attributed to the wrong tenant,
+-- and all three readiness functions below counted them, because none filtered by
+-- company at all.
+--
+-- The guard is deliberately `jo."companyId" = self."companyId"` — the two
+-- operations in a dependency must belong to the same company — and NOT a filter
+-- on `dep."companyId"`. That distinction is load-bearing: a mis-stamped row still
+-- describes a real dependency between two real operations, so keying off the
+-- operations keeps it counted, while keying off the row's own label would make it
+-- vanish and flip a genuinely-waiting operation to Ready.
+--
+-- Each function is REPLACED WHOLE, so each body below is copied verbatim from its
+-- own LATEST definition, with only the guard added:
+-- check_operation_dependencies <- 20250429130223_operation-dependencies.sql
+-- set_initial_dependency_status <- 20250429130223_operation-dependencies.sql
+-- finish_job_operation <- 20260417000300_storage-unit-recreate-dependents.sql
+-- Taking finish_job_operation from the 2025 file instead would silently drop the
+-- released-job guard (20251214180817) and the whole last-operation block that
+-- completes the job, posts finished goods to inventory and notifies — do not.
+--
+-- See .ai/specs/2026-08-25-backup-durability.md Part 3.
+
+CREATE OR REPLACE FUNCTION check_operation_dependencies(operation_id TEXT)
+RETURNS BOOLEAN
+SECURITY DEFINER
+SET search_path = public
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ incomplete_deps INTEGER;
+BEGIN
+ SELECT COUNT(*)
+ INTO incomplete_deps
+ FROM "jobOperationDependency" dep
+ JOIN "jobOperation" self ON self.id = dep."operationId"
+ JOIN "jobOperation" jo ON jo.id = dep."dependsOnId"
+ WHERE dep."operationId" = operation_id
+ AND jo."companyId" = self."companyId"
+ AND jo.status != 'Done';
+
+ RETURN incomplete_deps = 0;
+END;
+$$;
+
+-- Same guard. This is the one that can set an operation to Waiting, so without it
+-- another tenant's row can hold a real operation back the moment its dependencies
+-- are created.
+CREATE OR REPLACE FUNCTION set_initial_dependency_status()
+RETURNS TRIGGER
+SECURITY DEFINER
+SET search_path = public
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ -- Don't update if operation is already Done or In Progress
+ IF EXISTS (
+ SELECT 1
+ FROM "jobOperation"
+ WHERE id = NEW."operationId"
+ AND status IN ('Done', 'In Progress', 'Canceled')
+ ) THEN
+ RETURN NEW;
+ END IF;
+
+ -- Check if there are any incomplete dependencies
+ IF EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep
+ JOIN "jobOperation" self ON self.id = dep."operationId"
+ JOIN "jobOperation" jo ON jo.id = dep."dependsOnId"
+ WHERE dep."operationId" = NEW."operationId"
+ AND jo."companyId" = self."companyId"
+ AND jo.status != 'Done'
+ ) THEN
+ -- Set status to Waiting if there are incomplete dependencies
+ UPDATE "jobOperation"
+ SET status = 'Waiting'
+ WHERE id = NEW."operationId";
+ ELSE
+ -- Set status to Ready if all dependencies are done or there are no dependencies
+ UPDATE "jobOperation"
+ SET status = 'Ready'
+ WHERE id = NEW."operationId";
+ END IF;
+
+ RETURN NEW;
+END;
+$$;
+
+-- Body verbatim from 20260417000300; the ONLY change is the companyId guard in
+-- the NOT EXISTS.
+CREATE OR REPLACE FUNCTION finish_job_operation()
+RETURNS TRIGGER AS $$
+DECLARE
+ job_status TEXT;
+BEGIN
+ -- Get current job status
+ SELECT status INTO job_status FROM "job" WHERE id = NEW."jobId";
+
+ -- Only process job completion logic if job is in active state (has been released)
+ -- Jobs in Draft or Planned status should not trigger completion since dependencies
+ -- are only created during scheduling
+ IF job_status NOT IN ('Ready', 'In Progress', 'Paused') THEN
+ RETURN NEW;
+ END IF;
+
+ -- Set endTime for all open production events
+ UPDATE "productionEvent"
+ SET "endTime" = NOW()
+ WHERE "jobOperationId" = NEW.id AND "endTime" IS NULL;
+
+ -- Find all operations that depend on this one and might be ready
+ UPDATE "jobOperation" op
+ SET status = 'Ready'
+ WHERE EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep
+ WHERE dep."operationId" = op.id
+ AND dep."dependsOnId" = NEW.id
+ AND op.status = 'Waiting'
+ )
+ AND NOT EXISTS (
+ -- Check no other dependencies are incomplete
+ SELECT 1
+ FROM "jobOperationDependency" dep2
+ JOIN "jobOperation" jo2 ON jo2.id = dep2."dependsOnId"
+ WHERE dep2."operationId" = op.id
+ AND jo2."companyId" = op."companyId"
+ AND jo2.status != 'Done'
+ AND jo2.id != NEW.id
+ );
+
+ -- Set the job operation status to Done
+ NEW.status = 'Done';
+
+ -- If this is the last operation, mark the job as Done
+ IF is_last_job_operation(NEW.id) THEN
+ DECLARE
+ request_id TEXT;
+ notify_url TEXT;
+ api_url TEXT;
+ anon_key TEXT;
+ group_ids TEXT[];
+ assigned_to TEXT;
+ sales_order_id TEXT;
+ BEGIN
+ -- Get job details
+ DECLARE
+ job_item_id TEXT;
+ job_quantity_to_produce INTEGER;
+ job_location_id TEXT;
+ job_storage_unit_id TEXT;
+ job_quantity INTEGER;
+ quantity_complete INTEGER;
+
+ BEGIN
+
+
+ SELECT "locationId", "storageUnitId", "quantity"
+ INTO job_location_id, job_storage_unit_id, job_quantity
+ FROM "job"
+ WHERE "id" = NEW."jobId";
+
+ -- Use full job quantity if quantityComplete is 0
+ quantity_complete := CASE
+ WHEN NEW."quantityComplete" = 0 THEN job_quantity
+ ELSE NEW."quantityComplete"
+ END;
+
+
+
+ -- Get sales order info
+ SELECT "salesOrderId" INTO sales_order_id FROM "job" WHERE "id" = NEW."jobId";
+
+ IF sales_order_id IS NOT NULL THEN
+ -- Make-to-order: just update job status with quantityComplete
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "quantityComplete" = quantity_complete,
+ "updatedAt" = NOW(),
+ "updatedBy" = NEW."updatedBy"
+ WHERE id = NEW."jobId";
+ ELSE
+ -- Make-to-stock: update job status to Done and invoke edge function for inventory
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "updatedAt" = NOW(),
+ "updatedBy" = NEW."updatedBy"
+ WHERE id = NEW."jobId";
+
+ -- Invoke the issue edge function to handle inventory
+ PERFORM util.invoke_edge_function(
+ name => 'issue',
+ body => CASE
+ WHEN job_storage_unit_id IS NOT NULL THEN
+ jsonb_build_object(
+ 'type', 'jobCompleteInventory',
+ 'jobId', NEW."jobId",
+ 'companyId', NEW."companyId",
+ 'userId', NEW."updatedBy",
+ 'quantityComplete', quantity_complete,
+ 'locationId', job_location_id,
+ 'shelfId', job_storage_unit_id
+ )
+ ELSE
+ jsonb_build_object(
+ 'type', 'jobCompleteInventory',
+ 'jobId', NEW."jobId",
+ 'companyId', NEW."companyId",
+ 'userId', NEW."updatedBy",
+ 'quantityComplete', quantity_complete,
+ 'locationId', job_location_id
+ )
+ END
+ );
+ END IF;
+ END;
+
+ SELECT "apiUrl", "anonKey" INTO api_url, anon_key FROM "config" LIMIT 1;
+ notify_url := api_url || '/functions/v1/trigger';
+
+ SELECT "assignee", "salesOrderId" INTO assigned_to, sales_order_id FROM "job" WHERE "id" = NEW."jobId";
+
+ IF sales_order_id IS NULL THEN
+ SELECT "inventoryJobCompletedNotificationGroup" INTO group_ids FROM "companySettings" WHERE "id" = NEW."companyId";
+ ELSE
+ SELECT "salesJobCompletedNotificationGroup" INTO group_ids FROM "companySettings" WHERE "id" = NEW."companyId";
+ END IF;
+
+ IF assigned_to IS NOT NULL THEN
+ SELECT array_append(group_ids, assigned_to) INTO group_ids;
+ END IF;
+
+ IF array_length(group_ids, 1) > 0 THEN
+ SELECT net.http_post(
+ notify_url,
+ jsonb_build_object(
+ 'type', 'notify',
+ 'event', 'job-completed',
+ 'documentId', NEW."jobId",
+ 'companyId', NEW."companyId",
+ 'recipient', jsonb_build_object(
+ 'type', 'group',
+ 'groupIds', group_ids
+ )
+ )::jsonb,
+ '{}'::jsonb,
+ jsonb_build_object('Content-Type', 'application/json', 'Authorization', 'Bearer ' || anon_key)
+ ) INTO request_id;
+ END IF;
+
+ END;
+ END IF;
+
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
diff --git a/packages/jobs/src/inngest/functions/scheduled/index.ts b/packages/jobs/src/inngest/functions/scheduled/index.ts
index 04e07d1ad6..1742c89bae 100644
--- a/packages/jobs/src/inngest/functions/scheduled/index.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/index.ts
@@ -7,6 +7,7 @@ export {
export { mrpFunction } from "./mrp";
export { notificationDigestFunction } from "./notification-digest";
export { notificationPurgeFunction } from "./notification-purge";
+export { tenantIntegrityFunction } from "./tenant-integrity";
export { updateExchangeRatesFunction } from "./update-exchange-rates";
export { weeklyFunction } from "./weekly";
export { workflowRunRetentionFunction } from "./workflow-run-retention";
diff --git a/packages/jobs/src/inngest/functions/scheduled/tenant-integrity.test.ts b/packages/jobs/src/inngest/functions/scheduled/tenant-integrity.test.ts
new file mode 100644
index 0000000000..c5cd6402ec
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/scheduled/tenant-integrity.test.ts
@@ -0,0 +1,164 @@
+import {
+ type DatabaseConnection,
+ type Driver,
+ DummyDriver,
+ Kysely,
+ PostgresAdapter,
+ PostgresIntrospector,
+ PostgresQueryCompiler,
+ type QueryResult
+} from "kysely";
+import { describe, expect, it } from "vitest";
+import type { JobDatabase } from "../../../db";
+import type { Catalog, ColumnInfo, TableInfo } from "../tasks/company-backup";
+import { findExportScopeViolations } from "../tasks/company-backup";
+import { exportScope } from "./tenant-integrity";
+
+/** Compiles SQL without a connection; every query returns no rows. */
+const emptyDb = new Kysely<never>({
+ dialect: {
+ createAdapter: () => new PostgresAdapter(),
+ createDriver: () => new DummyDriver(),
+ createIntrospector: (i) => new PostgresIntrospector(i),
+ createQueryCompiler: () => new PostgresQueryCompiler()
+ }
+}) as unknown as JobDatabase;
+
+/** Same, but every count query answers with `n` rows out of scope. */
+function dbReturningCount(n: number): JobDatabase {
+ const connection: DatabaseConnection = {
+ executeQuery: async <R>(): Promise<QueryResult<R>> => ({
+ rows: [{ n: String(n) } as unknown as R]
+ }),
+ // biome-ignore lint/correctness/useYield: never streamed in these tests
+ streamQuery: async function* () {}
+ };
+ const driver: Driver = {
+ init: async () => {},
+ acquireConnection: async () => connection,
+ beginTransaction: async () => {},
+ commitTransaction: async () => {},
+ rollbackTransaction: async () => {},
+ releaseConnection: async () => {},
+ destroy: async () => {}
+ };
+ return new Kysely<never>({
+ dialect: {
+ createAdapter: () => new PostgresAdapter(),
+ createDriver: () => driver,
+ createIntrospector: (i) => new PostgresIntrospector(i),
+ createQueryCompiler: () => new PostgresQueryCompiler()
+ }
+ }) as unknown as JobDatabase;
+}
+
+const col = (name: string, isNullable = false): ColumnInfo => ({
+ name,
+ dataType: "text",
+ udtName: "text",
+ isNullable,
+ isGenerated: false,
+ hasDefault: false
+});
+
+const table = (
+ name: string,
+ columns: ColumnInfo[],
+ foreignKeys: TableInfo["foreignKeys"] = []
+): TableInfo => ({
+ name,
+ columns,
+ scope: { kind: "direct", column: "companyId" },
+ scopeColumn: "companyId",
+ pkColumns: ["id", "companyId"],
+ uniqueColumns: [],
+ hasId: false,
+ foreignKeys
+});
+
+/** A child with a NOT-NULL FK to a scoped parent — the shape the guard checks. */
+const catalogWithOneNotNullFk = (): Catalog => ({
+ schemaVersion: "test",
+ tables: [
+ table("job", [col("id"), col("companyId")]),
+ table(
+ "jobOperationDependency",
+ [col("jobId"), col("companyId")],
+ [{ column: "jobId", refTable: "job", refColumn: "id" }]
+ )
+ ]
+});
+
+describe("exportScope", () => {
+ it("excludes secret tables and indexes every table by name", () => {
+ const catalog: Catalog = {
+ schemaVersion: "test",
+ tables: [
+ table("job", [col("id"), col("companyId")]),
+ table("apiKey", [col("id"), col("companyId")])
+ ]
+ };
+ const { exportable, byName } = exportScope(catalog);
+
+ // apiKey is in SECRET_TABLES: it must never be exported...
+ expect(exportable.map((t) => t.name)).toEqual(["job"]);
+ // ...but it stays in the name index, because another table's FK may still
+ // resolve through it.
+ expect([...byName.keys()].sort()).toEqual(["apiKey", "job"]);
+ });
+});
+
+describe("findExportScopeViolations", () => {
+ it("reports nothing when every reference resolves in scope", async () => {
+ const { exportable, byName } = exportScope(catalogWithOneNotNullFk());
+
+ const violations = await findExportScopeViolations(
+ emptyDb,
+ exportable,
+ byName,
+ "company-a",
+ "group-a"
+ );
+
+ expect(violations).toEqual([]);
+ });
+
+ it("names the table and column when a NOT-NULL reference escapes scope", async () => {
+ const { exportable, byName } = exportScope(catalogWithOneNotNullFk());
+
+ const violations = await findExportScopeViolations(
+ dbReturningCount(3),
+ exportable,
+ byName,
+ "company-a",
+ "group-a"
+ );
+
+ expect(violations).toEqual(["jobOperationDependency.jobId → job (3 rows)"]);
+ });
+
+ it("ignores a nullable reference, which a restore nulls rather than dangles", async () => {
+ const catalog: Catalog = {
+ schemaVersion: "test",
+ tables: [
+ table("job", [col("id"), col("companyId")]),
+ table(
+ "jobOperationDependency",
+ [col("jobId", true), col("companyId")],
+ [{ column: "jobId", refTable: "job", refColumn: "id" }]
+ )
+ ]
+ };
+ const { exportable, byName } = exportScope(catalog);
+
+ const violations = await findExportScopeViolations(
+ dbReturningCount(3),
+ exportable,
+ byName,
+ "company-a",
+ "group-a"
+ );
+
+ expect(violations).toEqual([]);
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/scheduled/tenant-integrity.ts b/packages/jobs/src/inngest/functions/scheduled/tenant-integrity.ts
new file mode 100644
index 0000000000..18ae688353
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/scheduled/tenant-integrity.ts
@@ -0,0 +1,90 @@
+import { getJobDatabaseClient, type JobDatabase } from "../../../db";
+import { inngest } from "../../client";
+import type { Catalog, TableInfo } from "../tasks/company-backup";
+import {
+ findExportScopeViolations,
+ getCompanyTableCatalog,
+ SECRET_TABLES
+} from "../tasks/company-backup";
+
+/**
+ * Cross-tenant reference monitor.
+ *
+ * `findExportScopeViolations` already finds NOT-NULL foreign keys that escape a
+ * company's scope — it is the guard that refuses to produce an unrestorable
+ * backup. The problem is that it only runs when somebody clicks "Create backup",
+ * so a cross-tenant write can sit undetected until a customer's export fails.
+ * This runs the same query nightly, for every company, and logs what it finds.
+ *
+ * Internal monitoring only: a cross-tenant reference is an engineering
+ * escalation, not a message for the customer. Nothing is written and no marker
+ * row is created — a finding here means a write path is attributing rows to the
+ * wrong tenant, and that needs a human.
+ *
+ * 05:00 keeps it clear of workflow-run-retention at 04:00 and backup-maintenance
+ * at 03:00, so the three never contend for the connection pool.
+ */
+export const tenantIntegrityFunction = inngest.createFunction(
+ { id: "tenant-integrity", retries: 2 },
+ { cron: "0 5 * * *" },
+ async ({ step, logger }) => {
+ return await step.run("scan-cross-tenant-refs", async () => {
+ const db = getJobDatabaseClient(1);
+ const catalog = await getCompanyTableCatalog(db);
+ const { exportable, byName } = exportScope(catalog);
+
+ const companies = await db
+ .selectFrom("company")
+ .select(["id", "companyGroupId"])
+ .execute();
+
+ let companiesWithViolations = 0;
+ let totalViolations = 0;
+
+ for (const company of companies) {
+ const violations = await findExportScopeViolations(
+ db,
+ exportable,
+ byName,
+ company.id,
+ company.companyGroupId ?? null
+ );
+ if (violations.length === 0) continue;
+
+ companiesWithViolations++;
+ totalViolations += violations.length;
+ logger.error("Cross-tenant references found", {
+ companyId: company.id,
+ count: violations.length,
+ violations
+ });
+ }
+
+ const result = {
+ companiesScanned: companies.length,
+ companiesWithViolations,
+ totalViolations
+ };
+ logger.info("tenant-integrity scan complete", result);
+ return result;
+ });
+ }
+);
+
+/**
+ * The exportable table set and name index, built exactly as `buildCompanyBackup`
+ * builds them. Shared shape rather than a second definition, so the monitor and
+ * the export can never disagree about what counts as a violation.
+ */
+export function exportScope(catalog: Catalog): {
+ exportable: TableInfo[];
+ byName: Map<string, TableInfo>;
+} {
+ const secretTables = new Set<string>(SECRET_TABLES);
+ return {
+ exportable: catalog.tables.filter((t) => !secretTables.has(t.name)),
+ byName: new Map(catalog.tables.map((t) => [t.name, t]))
+ };
+}
+
+export type { JobDatabase };
diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.ts
index e39842b5d3..84c03b70ea 100644
--- a/packages/jobs/src/inngest/index.ts
+++ b/packages/jobs/src/inngest/index.ts
@@ -61,6 +61,7 @@ import {
mrpFunction,
notificationDigestFunction,
notificationPurgeFunction,
+ tenantIntegrityFunction,
updateExchangeRatesFunction,
weeklyFunction,
workflowRunRetentionFunction
@@ -147,6 +148,7 @@ export const functions = [
notificationDigestFunction,
notificationPurgeFunction,
workflowRunRetentionFunction,
+ tenantIntegrityFunction,
// Integrations
jiraSyncFunction,
linearSyncFunction,