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.

Merge remote-tracking branch 'origin/main' into fix/sales-order-sequence-collision

aashu6aacf8788ece
diff --cc .ai/lessons.md
index 6935dbc3d1,a9cbf9f5b0..c35c90cab6
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@@ -3416,12 -3480,19 +3480,29 @@@ After any commit, check its `.po` diff
**Applies to:** `packages/jobs/src/inngest/functions/notifications/notify.ts`; any job that fans out events with large payloads.
+ ## A failed COPY in a plain-text dump can swallow the rest of the restore
+
+ **Context:** On 2026-10-09 a `crbn restore` of a prod cluster backup ended with ✅. The restored database had no index, constraint, trigger or policy in `public`, and an empty migration ledger. The trailing `migration up --include-all` would then have replayed all 1,159 migrations.
+
+ **Problem:** The local stack's auth, storage and realtime tables come from its own service images, and they are older than prod's. Prod's `storage.objects` has a column (`archived_at`) that the local table does not have. A `COPY` that names an unknown column or table fails when psql parses it, so psql never enters copy mode. It then reads the block's data rows as SQL. In that data an unbalanced quote opened a string that never closed, so psql read the rest of the file as part of it. With `ON_ERROR_STOP=0`, nothing failed. The same drift also reaches DDL. The backup's newer `storage.protect_bucket_control_columns` trigger reads columns that the local `storage.buckets` does not have, so every bucket insert failed. Those service-schema objects survive later restores, because a restore drops only `public`. Separately, a Supabase backup is not one consistent snapshot: it contained payments whose journal it did not hold. So 15 foreign keys could not be validated.
+
+ **Rule:** Do not trust a restore that ran with `ON_ERROR_STOP=0` until you verify it by name. `scripts/restore-database.sh` now does these things:
+
+ 1. It fits each non-public `COPY` to the local columns, and drops the block when the local table does not exist.
+ 2. It skips function definitions owned by the auth, storage and realtime admin roles. Those functions belong to the local service images.
+ 3. It checks each `public` index, constraint, trigger and policy from the dump, and the ledger row count. It re-adds a foreign key that cannot be validated as `NOT VALID`.
+ 4. It exits 1 on any shortfall, and `crbn restore` then does not migrate.
+
+ A ✓ that a script prints after a step that is allowed to fail is not evidence. Read the state back.
+
+ **Applies to:** `scripts/restore-database.sh`, `packages/dev/src/commands/restore.ts`, and any tool that loads a plain-text dump through psql.
++
+## A caller-supplied document number used to leave the counter behind
+
+**Context:** Documents take their number from `get_next_sequence` unless the caller supplies one: a custom ID typed into `SequenceOrCustomId`, or an MCP / API upsert (`upsertSalesOrder`, `upsertQuote`, `upsertPurchaseOrder`, `upsertJob`, …) whose create path requires the number.
+
+**Problem:** A supplied number never moved the `sequence` row. Once the counter reached a number an agent or a user had already used, every new document failed on the unique constraint ("Failed to insert sales order") until someone moved the counter by hand.
+
+**Rule:** The counter is kept ahead in the database, not in app code: the `sync_advance_document_sequence` after-interceptor moves `sequence.next` past any number saved in the sequence's format, on insert and on a number change. A new numbered table must be added to that interceptor's `CASE` and given the interceptor in `attachments.ts`; the `document-sequence-synced` conformance check fails CI for a new counter that is neither covered nor in its `EXEMPT_COUNTERS`. Never "fix" a collision by retrying `get_next_sequence`.
+
+**Applies to:** `packages/database/src/event-system/handlers/sync_advance_document_sequence.sql`, `util.document_sequence_pattern`, any table with a readable document number.
diff --cc docs/content/docs/reference/sequences.mdx
index 4f3fb0a416,dffa5a477c..56306efbdf
--- a/docs/content/docs/reference/sequences.mdx
+++ b/docs/content/docs/reference/sequences.mdx
@@@ -80,11 -82,8 +80,11 @@@ A document saved with a number it was g
### A sequence field won't save (Current, Step, or Size)
`sequenceValidator` bounds them (`settings.models.ts:285-292`): Current `≥ 0`, Step `≥ 1`, Size `1`–`20`. Values outside those ranges are rejected.
-### My `%{hh}` or `%{ss}` token shows up literally in the number
-Customers, suppliers, and quotes are numbered by a database trigger through the `get_next_sequence` RPC, which interpolates only `%{yyyy}`, `%{yy}`, `%{mm}`, `%{dd}` (`20241115101526_rpc-get-next-sequence.sql:42-51`). Server-function-generated documents support all six tokens. Use date tokens only for customer/supplier/quote prefixes.
+### Current jumped ahead on its own
+A document was saved with a higher number in the sequence's format, by a custom ID, the API, or an AI agent through MCP. Current moved up to it so the next automatic number does not collide. If the jump came from a typo, set Current back under Settings → Sequences, but not below the highest number already used.
+
+### "Failed to insert …" because the number is already taken
- Before `20261009171423_advance-document-sequence.sql`, a number chosen by the caller never moved the counter, so the counter later issued a number that already existed. `20261009171437_backfill-document-sequences.sql` moved every counter that was behind past the highest existing number. On the sales order form, typing a number that already exists shows "Sales order … already exists" on the field.
++Before `20261012043717_advance-document-sequence.sql`, a number chosen by the caller never moved the counter, so the counter later issued a number that already existed. `20261012043741_backfill-document-sequences.sql` moved every counter that was behind past the highest existing number. On the sales order form, typing a number that already exists shows "Sales order … already exists" on the field.
### Editing a sequence didn't renumber existing documents
By design: numbers are written at creation and never recomputed.
diff --cc packages/checks/src/run.ts
index 27eccf014e,a714ade494..3e1818fad3
--- a/packages/checks/src/run.ts
+++ b/packages/checks/src/run.ts
@@@ -12,12 -12,9 +12,13 @@@ import type
StructureCheck,
Violation
} from "./check";
+import {
+ DOCUMENT_SEQUENCE_SYNCED,
+ findUnsyncedDocumentSequences
+} from "./conformance/document-sequence-synced";
import { edgeFunctionAuthorizesCaller } from "./conformance/edge-function-authorizes-caller";
import { indexRedirectBeforeLoaders } from "./conformance/index-redirect-before-loaders";
+ import { journalStatusFilter } from "./conformance/journal-status-filter";
import { moduleShape } from "./conformance/module-shape";
import {
MANAGED_FUNCTION_SETS,
diff --cc packages/database/supabase/migrations/20261012043717_advance-document-sequence.sql
index 1d5f06fb4e,0000000000..1d5f06fb4e
mode 100644,000000..100644
--- a/packages/database/supabase/migrations/20261012043717_advance-document-sequence.sql
+++ b/packages/database/supabase/migrations/20261012043717_advance-document-sequence.sql
diff --cc packages/database/supabase/migrations/20261012043729_get-next-sequence-no-truncate.sql
index 90c7295daf,0000000000..90c7295daf
mode 100644,000000..100644
--- a/packages/database/supabase/migrations/20261012043729_get-next-sequence-no-truncate.sql
+++ b/packages/database/supabase/migrations/20261012043729_get-next-sequence-no-truncate.sql
diff --cc packages/database/supabase/migrations/20261012043741_backfill-document-sequences.sql
index a868f830a2,0000000000..a868f830a2
mode 100644,000000..100644
--- a/packages/database/supabase/migrations/20261012043741_backfill-document-sequences.sql
+++ b/packages/database/supabase/migrations/20261012043741_backfill-document-sequences.sql
diff --cc packages/jobs/manifests/schema.json
index b961105847,52240ccd68..2913fbba58
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@@ -1,11 -1,11 +1,11 @@@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20261009163952",
- "schemaVersion": "20261009181437",
++ "schemaVersion": "20261012043741",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-10-09T15:41:38.767Z",
- "exportedAt": "2026-10-09T20:27:01.988Z",
++ "exportedAt": "2026-10-12T04:41:12.765Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",