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(db): make sequence number generation atomic to prevent duplicate ids
Sidwebworksb7ea47d3696c
diff --git a/apps/erp/app/modules/accounting/accounting.server.ts b/apps/erp/app/modules/accounting/accounting.server.tsindex 82954302b6..244c30fbd2 100644--- a/apps/erp/app/modules/accounting/accounting.server.ts+++ b/apps/erp/app/modules/accounting/accounting.server.ts@@ -1,5 +1,6 @@import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";import { toStoredAmount } from "@carbon/utils";+import { sql } from "kysely";import { interpolateSequenceDate } from "~/utils/string";import { acquisitionLines } from "./accounting.utils";@@ -8,30 +9,28 @@ async function getNextSequence(tableName: string,companyId: string) {+ // Atomic increment: the UPDATE takes the row lock before reading, so two+ // concurrent transactions can't both read the same "next" and return the+ // same sequence number.const sequence = await trx- .selectFrom("sequence")- .selectAll()+ .updateTable("sequence")+ .set({+ next: sql<number>`"next" + "step"`,+ updatedBy: "system"+ }).where("table", "=", tableName).where("companyId", "=", companyId)+ .returning(["next", "prefix", "suffix", "size"]).executeTakeFirstOrThrow();- const { prefix, suffix, next, size, step } = sequence;+ const { prefix, suffix, next, size } = sequence;if (!Number.isInteger(next)) throw new Error("Next is not an integer");- if (!Number.isInteger(step)) throw new Error("Step is not an integer");if (!Number.isInteger(size)) throw new Error("Size is not an integer");- const nextValue = next! + step!;- const nextSequence = nextValue.toString().padStart(size!, "0");+ const nextSequence = next!.toString().padStart(size!, "0");const derivedPrefix = interpolateSequenceDate(prefix);const derivedSuffix = interpolateSequenceDate(suffix);- await trx- .updateTable("sequence")- .set({ next: nextValue, updatedBy: "system" })- .where("table", "=", tableName)- .where("companyId", "=", companyId)- .execute();-return `${derivedPrefix}${nextSequence}${derivedSuffix}`;}diff --git a/packages/database/supabase/functions/shared/get-next-sequence.ts b/packages/database/supabase/functions/shared/get-next-sequence.tsindex 377c8b28b4..11d2b2e820 100644--- a/packages/database/supabase/functions/shared/get-next-sequence.ts+++ b/packages/database/supabase/functions/shared/get-next-sequence.ts@@ -1,4 +1,4 @@-import { Transaction } from "kysely";+import { sql, Transaction } from "kysely";// Type-only import from postgres/index.ts (not lib/database.ts) keeps the// Deno-only driver out of the graph so this file is also importable from the// node-side @carbon/database/quality engine.@@ -10,34 +10,28 @@ export async function getNextSequence(tableName: string,companyId: string) {- // get current purchase invoice sequence number+ // Atomic increment: the UPDATE takes the row lock before reading, so two+ // concurrent transactions can't both read the same "next" and return the+ // same sequence number.const sequence = await trx- .selectFrom("sequence")- .selectAll()+ .updateTable("sequence")+ .set({+ next: sql<number>`"next" + "step"`,+ updatedBy: "system",+ }).where("table", "=", tableName).where("companyId", "=", companyId)+ .returning(["next", "prefix", "suffix", "size"]).executeTakeFirstOrThrow();- const { prefix, suffix, next, size, step } = sequence;- if (!Number.isInteger(step)) throw new Error("Next is not an integer");- if (!Number.isInteger(step)) throw new Error("Step is not an integer");+ const { prefix, suffix, next, size } = sequence;+ if (!Number.isInteger(next)) throw new Error("Next is not an integer");if (!Number.isInteger(size)) throw new Error("Size is not an integer");- const nextValue = next! + step!;- const nextSequence = nextValue.toString().padStart(size!, "0");+ const nextSequence = next!.toString().padStart(size!, "0");const derivedPrefix = interpolateSequenceDate(prefix);const derivedSuffix = interpolateSequenceDate(suffix);- await trx- .updateTable("sequence")- .set({- next: nextValue,- updatedBy: "system",- })- .where("table", "=", tableName)- .where("companyId", "=", companyId)- .execute();-return `${derivedPrefix}${nextSequence}${derivedSuffix}`;}@@ -48,6 +42,14 @@ export async function getNextRevisionSequence(sequenceValue: string,companyId: string) {+ // There is no counter row to lock — the next revision is max(revisionId) + 1,+ // and a concurrent transaction's uncommitted insert is invisible to us. An+ // advisory transaction lock serializes revision creation per entity so two+ // transactions can't both compute the same max.+ await sql`SELECT pg_advisory_xact_lock(hashtextextended(${`revision:${tableName}:${sequenceColumn}:${sequenceValue}:${companyId}`}, 0))`.execute(+ trx+ );+const relatedSequences = await trx// @ts-ignore - we're using variables for table names.selectFrom(tableName)diff --git a/packages/database/supabase/migrations/20260730185058_fix-get-next-sequence-race.sql b/packages/database/supabase/migrations/20260730185058_fix-get-next-sequence-race.sqlnew file mode 100644index 0000000000..05f36f5afb--- /dev/null+++ b/packages/database/supabase/migrations/20260730185058_fix-get-next-sequence-race.sql@@ -0,0 +1,59 @@+-- Fix a read-then-write race in get_next_sequence: two concurrent callers both+-- read the same "next", both wrote the same absolute value, and both returned+-- the same sequence number. The atomic UPDATE ... RETURNING takes the row lock+-- first, so a concurrent caller blocks and then reads the committed value.+CREATE OR REPLACE FUNCTION get_next_sequence(+ sequence_name text,+ company_id text+)+RETURNS text+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public+AS $$+DECLARE+ v_prefix text;+ v_suffix text;+ v_next_value integer;+ v_size integer;+ v_next_sequence text;+ v_derived_prefix text;+ v_derived_suffix text;+BEGIN+ IF session_user = 'authenticator' THEN+ IF NOT (has_role('employee', company_id) OR has_valid_api_key_for_company(company_id)) THEN+ RAISE EXCEPTION 'Insufficient permissions';+ END IF;+ END IF;++ UPDATE sequence+ SET next = next + step,+ "updatedBy" = 'system'+ WHERE "table" = sequence_name+ AND "companyId" = company_id+ RETURNING next, prefix, suffix, size+ INTO v_next_value, v_prefix, v_suffix, v_size;++ IF NOT FOUND THEN+ RAISE EXCEPTION 'Sequence not found for table % and company %', sequence_name, company_id;+ END IF;++ -- Format sequence number+ v_next_sequence := lpad(v_next_value::text, COALESCE(v_size, 4), '0');++ -- Interpolate date variables in prefix/suffix+ v_derived_prefix := COALESCE(v_prefix, '');+ v_derived_prefix := replace(v_derived_prefix, '%{yyyy}', to_char(current_date, 'YYYY'));+ v_derived_prefix := replace(v_derived_prefix, '%{yy}', to_char(current_date, 'YY'));+ v_derived_prefix := replace(v_derived_prefix, '%{mm}', to_char(current_date, 'MM'));+ v_derived_prefix := replace(v_derived_prefix, '%{dd}', to_char(current_date, 'DD'));++ v_derived_suffix := COALESCE(v_suffix, '');+ v_derived_suffix := replace(v_derived_suffix, '%{yyyy}', to_char(current_date, 'YYYY'));+ v_derived_suffix := replace(v_derived_suffix, '%{yy}', to_char(current_date, 'YY'));+ v_derived_suffix := replace(v_derived_suffix, '%{mm}', to_char(current_date, 'MM'));+ v_derived_suffix := replace(v_derived_suffix, '%{dd}', to_char(current_date, 'DD'));++ RETURN v_derived_prefix || v_next_sequence || v_derived_suffix;+END;+$$;