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(production): serialize job dependency rebuild in scheduling engine (#1408)

Brad Barbine32a9b94688f
diff --git a/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts b/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts
index fec3a923e7..ef5bc4ebeb 100644
--- a/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts
+++ b/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts
@@ -1,5 +1,5 @@
import type { SupabaseClient } from "@supabase/supabase-js";
-import type { Kysely } from "kysely";
+import { sql, type Kysely } from "kysely";
import type { DB } from "../database.ts";
import type { Database } from "../types.ts";
import {
@@ -346,33 +346,45 @@ export class SchedulingEngine {
.filter((op) => op.reworkId)
.map((op) => op.id!);
- let deleteQuery = this.db
- .deleteFrom("jobOperationDependency")
- .where("jobId", "=", this.jobId);
-
- if (reworkOpIds.length > 0) {
- deleteQuery = deleteQuery
- .where("operationId", "not in", reworkOpIds)
- .where("dependsOnId", "not in", reworkOpIds);
- }
-
- await deleteQuery.execute();
-
- // Insert new dependencies
const records = dependenciesToRecords(
allDependencies,
this.jobId,
this.companyId
);
- if (records.length > 0) {
- for (const record of records) {
- await this.db
+ // Rebuild atomically. Two schedule runs for the same job can overlap
+ // (an Inngest retry racing a still-running invocation, or a direct
+ // functions.invoke alongside the queued one); interleaved delete/insert
+ // then violates jobOperationDependency_pk. The advisory lock serializes
+ // the rebuild per job, and onConflict absorbs any edge that survives a
+ // race with trigger-rework's inserts.
+ await this.db.transaction().execute(async (trx) => {
+ await sql`SELECT pg_advisory_xact_lock(hashtextextended(${`schedule:dependencies:${this.jobId}`}, 0))`.execute(
+ trx
+ );
+
+ let deleteQuery = trx
+ .deleteFrom("jobOperationDependency")
+ .where("jobId", "=", this.jobId);
+
+ if (reworkOpIds.length > 0) {
+ deleteQuery = deleteQuery
+ .where("operationId", "not in", reworkOpIds)
+ .where("dependsOnId", "not in", reworkOpIds);
+ }
+
+ await deleteQuery.execute();
+
+ if (records.length > 0) {
+ await trx
.insertInto("jobOperationDependency")
- .values(record)
+ .values(records)
+ .onConflict((oc) =>
+ oc.columns(["operationId", "dependsOnId"]).doNothing()
+ )
.execute();
}
- }
+ });
// Update operations with no dependencies to Ready status
for (const [opId, deps] of allDependencies) {