B2B Second Inventory Stock Backend Documentation
Internal architecture of the bb phase 3 stock — composition, data model, the single stock writer, lock order, import and export handlers, the hourly reconcile, error contract and file map.
B2B Second Inventory (bb) — Stock Backend Documentation
1. Module Scope
Phase 3 owns, in the bb module:
bb_inventory(one counter row per variant) andbb_inventory_movement(its append-only ledger)adjustBbStock, the only writer ofbb_inventory.quantity, andlockBbVariantForStock, the lock every stock write takes first- The stock admin routes, the stock job routes, and the
inventoryentity in the existingbb_catalog_jobpipeline - The hourly reconcile on the MAINTENANCE queue
- The delete-with-stock guard on bb variants
It does not own holds, reservations, oversell, projections or any retail inventory code. The bb stock core and retail's write service are duplicated on purpose: they encode different rules, and the bb module must not import retail inventory.
2. Composition
| Piece | Location |
|---|---|
| Stock core | modules/bb/inventory-shared/bb-inventory-write.ts (adjustBbStock, createBbInventoryRows), bb-inventory-lock.ts (lockBbVariantForStock), bb-inventory.constants.ts |
| Stock routes | modules/bb/admin/inventory/ (bb-inventory-admin.controller.ts, bb-inventory-bulk.controller.ts, read, write and bulk services, dto/) |
| Stock job routes | modules/bb/admin/job/bb-job-inventory.controller.ts, dto/create-bb-inventory-export.dto.ts, bb-job-permissions.ts |
| Import | modules/bb/jobs/import/bb-import-inventory.writer.ts, plus the inventory branches in bb-import-rows.ts, bb-import-cells.ts, bb-catalog-import.processor.ts |
| Export | modules/bb/jobs/export/bb-export-rows.ts (BB_INVENTORY_EXPORT_COLUMNS, inventoryBatch), jobs/bb-catalog-export-filter.ts |
| Reconcile | modules/bb/jobs/inventory-reconcile/ (scheduler, processor, passes, module) |
| Schema | packages/db/src/schema/bb/bb-inventory.ts |
| Migrations | packages/db/src/migrations/0063_bb_inventory.sql, 0064_bb_inventory_jobs_audit.sql (down scripts in down/) |
| Permissions | packages/db/src/authorization/permission-catalog.ts (BB_Inventory in BB_PERMISSION_MODULES and BB_ASSIGNABLE_MODULES) |
| Queue and job names | packages/jobs/src/index.ts (MaintenanceJob.RECONCILE_BB_INVENTORY = "maintenance.reconcile_bb_inventory") |
| Registration | BbInventoryAdminModule in admin/bb-admin-aggregate.module.ts; BbInventoryReconcileModule in maintenance/maintenance-worker.module.ts; the handler in maintenance/workers/maintenance-queue.processor.ts |
The swagger allowlist needs no edit: the admin document derives the bb leaves from the aggregate module's imports.
3. Data Model
bb_inventory
Primary key variant_id. Columns: product_id, quantity (default 0), low_stock_threshold (default 5), stock_status (generated, stored), version (default 1), last_movement_at, last_reconciled_at, drift_detected_at, created_at, updated_at.
| Constraint | Meaning |
|---|---|
fk_bb_inventory_variant on (variant_id, product_id), restrict | The row cannot outlive its variant, and the product id cannot disagree with the variant's |
chk_bb_inventory_quantity_range | 0 to 1,000,000,000 |
chk_bb_inventory_threshold_range | 0 to 1,000,000,000 |
chk_bb_inventory_version | At least 1 |
chk_bb_inventory_drift_audited | drift_detected_at set implies last_reconciled_at set |
chk_bb_inventory_last_movement | quantity of 0, or last_movement_at set. Evaluated per statement, which is why adjustBbStock moves both in one UPDATE |
Indexes: product, (updated_at, variant_id), (quantity, variant_id), (stock_status, variant_id), (last_reconciled_at NULLS FIRST, variant_id), and a partial index on variant_id where drift_detected_at IS NOT NULL.
stock_status is out_of_stock when quantity <= 0, low_stock when quantity <= low_stock_threshold, else in_stock.
bb_inventory_movement
id (bigserial, the cursor), public_id, variant_id, product_id, reason, quantity_delta, quantity_after, note, actor_admin_id, actor_name, correlation_id, created_at.
| Constraint | Meaning |
|---|---|
fk_bb_inventory_movement_inventory, restrict | A ledger row needs its stock row |
fk_bb_inventory_movement_actor_admin_id, restrict | A staff row with movements cannot be hard-deleted; the failure maps to 401 AUTH_SESSION_ACTOR_NOT_FOUND when an actor no longer exists |
chk_bb_inventory_movement_reason | restock, recount, damage, theft, correction, import |
chk_bb_inventory_movement_delta | Not 0 |
chk_bb_inventory_movement_after | At least 0 |
chk_bb_inventory_movement_note | Null, or trimmed and 1 to 1,000 characters |
chk_bb_inventory_movement_reason_sign | restock positive; damage and theft negative |
chk_bb_inventory_movement_import_correlation | An import movement has a correlation_id |
A trigger (bb_inventory_movement_no_mutation) rejects every UPDATE and DELETE on the ledger.
Changes to existing tables
bb_audit.chk_bb_audit_entity_typeandbb_catalog_job.chk_bb_catalog_job_entitygaininventory.- Partial unique index
bb_catalog_job_inventory_file_uniqueonsource_sha256whereentity = 'inventory' AND kind = 'import' AND status IN ('queued','processing','completed'). - Audit redaction for entity
inventorykeepsquantityandlowStockThresholdvisible.
Backfill
Migration 0063 ends with one INSERT ... SELECT that creates a row at 0 for every bb_product_variant, deleted ones included. It writes no movement. It is a single statement over the whole table: see Deploy for the row-count check before it runs.
4. Runtime Rules and Domain Invariants
One writer
adjustBbStock is the only code that writes bb_inventory.quantity and the only writer of the ledger. It takes the lock result as a parameter so a write cannot be spelled without the lock. A source-scan spec fails the build if another file writes the counter, or if a variant insert does not create its stock row.
adjustBbStock runs one guarded statement:
UPDATE bb_inventory
SET quantity = quantity + :delta, last_movement_at = now(), updated_at = now()
WHERE variant_id = :id AND quantity + :delta BETWEEN 0 AND 1000000000
RETURNING ...There is no read to go stale. If it returns no row, a second read tells a missing row (404 BB_INVENTORY_NOT_FOUND, logged ERROR) from a refused change (409 BB_INVENTORY_INSUFFICIENT_STOCK for a negative delta, 400 BB_INVENTORY_QUANTITY_LIMIT otherwise). It then inserts the ledger row from the UPDATE's RETURNING and, in per_movement mode, the audit row. A refusal is a thrown HttpException that writes nothing, so a savepoint per bulk item or import row needs no raw CHECK handling.
The reason-sign refusal runs before the UPDATE, so the CHECK chk_bb_inventory_movement_reason_sign never fires. A delta outside the contract, or a note outside chk_bb_inventory_movement_note, is a programming error and stays a 5xx: the DTOs and the import own those preconditions.
Lock order
lockBbVariantForStock takes FOR SHARE on the product and the variant, in that order, then the guarded UPDATE locks the stock row. FOR SHARE conflicts with the FOR UPDATE that a variant or product delete takes, so a delete and an adjust cannot interleave; it does not conflict with another adjust, so sibling variants do not queue. A deleted row is checked after the lock so it gets its typed 404. The lock timeout is set inside the function because a rolled-back savepoint undoes set_config.
Caller rule: lock several variants in ascending order. The core does not sort. Bulk adjust sorts by (product_id, variant_id) (orderBbStockTargets), as does the import. Two writers that lock the same rows in opposite orders deadlock; Postgres aborts one with 40P01, which surfaces as 409 BB_CATALOG_BUSY with nothing committed.
The threshold write takes the same two locks, then FOR UPDATE on the stock row, so it queues behind an adjust of that row.
Variant create and delete
Every path that inserts a variant also calls createBbInventoryRows in the same transaction (ON CONFLICT DO NOTHING, so a repeat never resets a counter): product create and variant create. Variant delete locks the product and its live variants with FOR UPDATE (lockBbProductWithLiveVariants), which conflicts with an adjust's share lock, then reads the quantity; above 0 it throws 409 BB_VARIANT_HAS_STOCK. Only the single variant delete checks this.
Import
writeBbInventoryRows resolves all ids first (live variants of live products), marks unresolved lines variant_not_live, sorts the rest by (product_id, variant_id), and writes each line in a savepoint with reason import and the job's public id as correlationId. The lock can still answer product or variant not found if the row is deleted between the resolve and the lock; that line is also reported as variant_not_live. A missing stock row is reported the same way and logged. The row loop's collected errors reject the whole job (Import rejected: N row(s) have errors; nothing was written.) and the import transaction rolls back. Row errors are returned in file order.
The parser refuses a repeated variantPublicId (duplicate_variant) and takes the delta through ^[+-]?\d{1,9}$ (delta_format), then rejects 0 and anything over 1,000,000. The note is trimmed after un-escaping; blank is null; a NUL is refused (not_utf8); over 1,000 code points is note_too_long.
Export
countBbExportMatches (enqueue-time cap check) and inventoryBatch (the file) both inner-join bb_inventory, bb_product_variant and bb_product and apply the same inventoryWhere: product and variant not deleted, search on product name or SKU, optional stockStatus. The keyset is bb_inventory.variant_id.
Identical-file guard
submitImport computes the file's SHA-256 before insert. A 23505 on bb_catalog_job_inventory_file_unique first looks for a job with the caller's Idempotency-Key (a retry of the same request replays that job), and otherwise throws 409 BB_JOB_INVENTORY_FILE_ALREADY_IMPORTED. A failed or cancelled job leaves the status set, so it frees the file. If purging old job rows is ever added, it must keep inventory import rows or accept losing this guard.
Reconcile
Scheduler: @Cron(EVERY_HOUR, { timeZone: "Asia/Kathmandu", name: "bb_inventory_reconcile" }); job id bb_inventory_reconcile_<yyyyMMddHH> (UTC hour bucket); enqueued straight on the MAINTENANCE queue with no outbox, the same documented exemption as the catalog sweep. It never fires under API_RUNTIME_PROFILE=fast.
Processor: runs healBbInventoryOrphans (limit 500) and auditBbInventoryDrift (batch 1,000, BB_INVENTORY_RECONCILE_BATCH_SIZE), each in its own try/catch. It never rethrows: a throwing hourly job would only retry into the same failure. Log lines carry maintenance.reconcile_bb_inventory requestId=... jobId=...:
| Line | Level | Meaning |
|---|---|---|
[start] | log | Run began |
bb_inventory row was missing; created at 0 variant=... | ERROR | One orphan healed |
bb_inventory drift variant=... quantity=... ledgerAfter=... | ERROR | One row flagged or still flagged |
bb_inventory drift read failed variant=... / audit stamp failed variant=... | ERROR | One row skipped; it stays oldest and leads the next batch |
[success] ... healed=N examined=N drifted=N readFailed=0 stampFailed=0 | log | Both passes completed with no failed row |
[failure] ... | ERROR | A pass threw, or a read or stamp failed |
Drift is computed in one SQL statement per row, so the counter, the newest movement and the chain are read from one snapshot. The stamp is a separate short transaction behind the lock timeout; it sets updated_at = updated_at explicitly so the default list order does not move. It sets last_reconciled_at = now() on every examined row and drift_detected_at = COALESCE(drift_detected_at, now()) when drifted, or null when clean. The audit pass reads only live variants of live products. The heal pass reads live variants (it does not filter on the product).
Capacity: one rotation of 50,000 variants is about 50 hourly runs.
5. Audit
| Action | Entity | Written by |
|---|---|---|
bb.inventory.adjust | inventory, entity id = variant public id | Every movement: single adjust, each bulk item, each import row. Changes: quantity before and after |
bb.inventory.update | inventory | A threshold change. Changes: lowStockThreshold |
An unchanged threshold writes no audit row. A job cancel writes bb.catalog_job.cancel with entity inventory. The reconcile writes no audit row.
6. Configuration
No new environment variables. Behaviour that matters:
| Setting | Effect |
|---|---|
API_RUNTIME_PROFILE=fast | ScheduleModule is skipped: no reconcile runs |
| bb catalog lock timeout | 5 s via setBbCatalogLockTimeout; a wait beyond it answers 409 BB_CATALOG_BUSY |
bb_catalog worker | Concurrency 1; stock imports and catalog imports share it |
| MAINTENANCE worker | Must run for the reconcile to execute |
7. Error Contract
The eight new codes, their statuses and the routes that return them are in the stock API reference. Two rules:
BB_INVENTORY_NOT_FOUNDis logged as an ERROR on every occurrence: a live variant without a row means a creation path skippedcreateBbInventoryRows.- A browser pass observed that the string
BB_INVENTORY_INSUFFICIENT_STOCKdoes not appear in the API log for a refused adjust; only the message does. Search the log by message, not by code.
8. Tests Recorded
Spec files added or extended in phase 3. This page records what exists; it does not record a pass or fail result.
| Area | Files |
|---|---|
| Schema | packages/db/src/schema/bb/bb-inventory-constraints.spec.ts, bb-inventory-ddl.spec.ts |
| Stock core | inventory-shared/__tests__/ (bb-inventory-concurrency, -create-paths, -lock, -write) |
| Stock routes | admin/inventory/__tests__/ (access, bulk, dto, input, read, write, idempotency-wiring) |
| Jobs | jobs/__tests__/bb-inventory-import, -import-rows, -export, -export-count, -job-authority; admin/job/__tests__/bb-job-inventory.int.spec.ts |
| Reconcile | jobs/inventory-reconcile/__tests__/ (reconcile.int, reconcile.queue.int, scheduler) |
| Single writer | shared/__tests__/bb-inventory-single-writer.spec.ts |
9. Known Limits
- Reconcile reports; it does not repair. A flagged row stays flagged until an operator records a
correctionand the next pass confirms it. - Import is all or nothing per file. One bad row rejects the file; the operator fixes and re-uploads.
- Identical file, not identical effect. The SHA-256 guard stops a re-sent file; two different files can move the same variant.
- No stock on deleted variants. Stock routes refuse a deleted variant. The core can reach a deleted variant's retained row only through
lockBbVariantForStock(..., { allowDeleted: true }), and no phase 3 caller passes it. - Product delete and bulk delete do not check stock. Only the single variant delete returns
BB_VARIANT_HAS_STOCK. - Down migrations stop after first use. See Deploy.
10. See Also
B2B Second Inventory Stock Feature Overview
Phase 3 of the bb (B2B second inventory) area — a stock counter per variant, an append-only movement ledger, adjust and bulk adjust, a low-stock threshold, stock import and export jobs, and an hourly report-only drift check.
B2B Second Inventory Stock API Reference
Endpoint reference for the bb phase 3 admin stock API — stock list and detail, movements, adjust, bulk adjust, low-stock threshold, and stock import/export jobs — with contracts, permissions and error codes.