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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(items): method import checks the version after it takes the row lock
Rauld8e790657ddb
diff --git a/.ai/plans/2026-10-21-method-import-append.md b/.ai/plans/2026-10-21-method-import-append.mdindex b7622af7ee..803a99204d 100644--- a/.ai/plans/2026-10-21-method-import-append.md+++ b/.ai/plans/2026-10-21-method-import-append.md@@ -75,6 +75,7 @@ import match the BOM and Bill of Process editors.| `customFields` was null where the editors write `{}`. | The import writes `{}`. || CodeRabbit: a non-numeric Op No never matched an existing operation, so a re-run added it again, and its fallback order could collide with a numeric Op No. | Op No must be a number. Op Nos compare by value. || CodeRabbit: the change notice approval check ran a separate request while a part's transaction was open. | The import reads every change notice lock before any transaction. |+| CodeRabbit: the status check read the version before the row lock, so a Draft activated in that gap was still written. | The refusals read the locked row. |The parity test (`method-import-parity.test.ts`) and the guards test(`method-import-guards.test.ts`) pin the fixes.diff --git a/.claude/rules/csv-import-system.md b/.claude/rules/csv-import-system.mdindex 833f3be358..98723009ff 100644--- a/.claude/rules/csv-import-system.md+++ b/.claude/rules/csv-import-system.md@@ -301,7 +301,10 @@ continue.column for one. Pinned by `method-import-guards.test.ts`.- **Concurrency.** `writeGroup` locks the target `makeMethod` row(`FOR UPDATE`) before it reads the version's lines, so two imports of one- file write each line once.+ file write each line once. The refusals read the status and change notice+ of the locked row, so a Draft an editor activates or links to a notice+ while the import waits is refused. A version the import created for a+ refused part rolls back with it.- **Change notice locks are read before any transaction** (`loadChangeNoticeLocks`):`getChangeNoticeEngineeringLock` checks pending approvals through a separateservice-role request, which must not run while a part's transaction is open.diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex b0df6deb1c..aebcfbe6dc 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -4101,54 +4101,51 @@ async function writeGroup(for (const [version, bucket] of g.versions) {const target = pickMethodImportTarget(methods, version);- const method =- "method" in target- ? target.method- : {- id: "",- version: target.createVersion,- status: "Draft",- changeOrderId: null- };-- const refusal = methodImportRefusal({- status: method.status,- version: method.version,- changeNoticeLock: method.changeOrderId- ? changeNoticeLockOf(ctx.changeNoticeLocks, method.changeOrderId)- : null,- revisionStatus,- releaseControl: ctx.releaseControl- });- if (refusal) {- issues.push({- row: rowOf(firstIndexOf(bucket)),- reason: `Part ${partLabel}: ${refusal}`- });- continue;- }-- let makeMethodId = method.id || createdIds.get(method.version);+ const methodVersion =+ "method" in target ? target.method.version : target.createVersion;+ let makeMethodId =+ "method" in target ? target.method.id : createdIds.get(methodVersion);if (!makeMethodId) {makeMethodId = await insertDraftMakeMethod(trx,parentItemId,- method.version,+ methodVersion,companyId,userId);- createdIds.set(method.version, makeMethodId);+ createdIds.set(methodVersion, makeMethodId);}// Imports into one version run one at a time: a second import waits- // here, then reads what the first wrote and skips it.- await trx+ // here, then reads what the first wrote and skips it. The refusal reads+ // the locked row, so it sees an editor that activated the Draft or+ // linked it to a change notice after the read above. A refused part+ // rolls back, with any version created for it.+ const locked = await trx.selectFrom("makeMethod")- .select("id")+ .select(["status", "changeOrderId"]).where("id", "=", makeMethodId).where("companyId", "=", companyId).forUpdate()- .execute();+ .executeTakeFirst();+ const refusal = locked+ ? methodImportRefusal({+ status: locked.status,+ version: methodVersion,+ changeNoticeLock: locked.changeOrderId+ ? changeNoticeLockOf(ctx.changeNoticeLocks, locked.changeOrderId)+ : null,+ revisionStatus,+ releaseControl: ctx.releaseControl+ })+ : `make method version ${methodVersion} was deleted while the import ran. Run the import again`;+ if (refusal) {+ issues.push({+ row: rowOf(firstIndexOf(bucket)),+ reason: `Part ${partLabel}: ${refusal}`+ });+ continue;+ }const existingMaterials = await trx.selectFrom("methodMaterial")diff --git a/apps/erp/test/database/method-import-guards.test.ts b/apps/erp/test/database/method-import-guards.test.tsindex 86a031ad3f..dbcbf39d65 100644--- a/apps/erp/test/database/method-import-guards.test.ts+++ b/apps/erp/test/database/method-import-guards.test.ts@@ -6,6 +6,7 @@// and two imports of one file at the same time write each line once. Runs// against the local database; skips without one.+import { sql } from "kysely";import { afterEach, describe, expect } from "vitest";import {connectLocalTestDatabase,@@ -18,6 +19,23 @@ import {type Rows = Record<string, string>[];+// Resolves once another session of this database waits on a row lock.+async function waitForLockWait(+ db: Awaited<ReturnType<typeof connectLocalTestDatabase>>+) {+ for (let attempt = 0; attempt < 200; attempt++) {+ const { rows } = await sql<{ waiting: number }>`+ SELECT count(*)::int AS waiting FROM pg_stat_activity+ WHERE datname = current_database()+ AND pid <> pg_backend_pid()+ AND wait_event_type = 'Lock'+ AND query ILIKE '%for update%'`.execute(db);+ if (rows[0]!.waiting > 0) return;+ await new Promise((resolve) => setTimeout(resolve, 25));+ }+ throw new Error("The import never waited for the row lock");+}+const bom = (parentId: string,componentId: string,@@ -253,6 +271,54 @@ describe("method import guards", () => {});+ databaseTest(+ "refuses a Draft an editor activates while the import waits for it",+ async () => {+ f = await methodImportFixture();+ const companyId = f.companyId;+ const makeMethodId = await f.methodOf("ASSY");+ const editor = await connectLocalTestDatabase();+ const watcher = await connectLocalTestDatabase();+ let commit = () => {};+ const committed = new Promise<void>((resolve) => {+ commit = resolve;+ });+ let holding = () => {};+ const held = new Promise<void>((resolve) => {+ holding = resolve;+ });+ // The editor activates the Draft and keeps its row lock until commit.+ const activate = editor.transaction().execute(async (trx) => {+ await trx+ .updateTable("makeMethod")+ .set({ status: "Active" })+ .where("id", "=", makeMethodId)+ .where("companyId", "=", companyId)+ .execute();+ holding();+ await committed;+ });+ try {+ await held;+ // The import reads the version as a Draft, then waits for the lock.+ const run = f.run("bom", [bom("ASSY", "COMP-1", "1")]);+ await waitForLockWait(watcher);+ commit();+ await activate;+ const summary = await run;+ expect(summary.errors.map((e) => e.reason)).toEqual([+ "Part ASSY rev 0: make method version 1 is Active, and only a Draft version can change. Create a new version, then set Make Method Version to it"+ ]);+ expect((await rowCounts()).materials).toBe(0);+ } finally {+ commit();+ await activate.catch(() => {});+ await editor.destroy();+ await watcher.destroy();+ }+ }+ );+databaseTest("two imports of one file at the same time write each line once",async () => {