B2B Second Inventory Stock Deploy Notes
Deploy order, the variant row count check, the required permissions:sync and role grant, intermediate states, verification and the rollback runbook for bb phase 3 migrations 0063 and 0064.
B2B Second Inventory (bb) — Stock Deploy Notes
These notes cover migrations 0063_bb_inventory and 0064_bb_inventory_jobs_audit. Phase 1's pre-deploy replay, backup and smoke steps in Deploy Notes still apply. This page adds what phase 3 changes.
Commands marked not run were checked to exist in package.json or psql and read against the scripts, but were not executed against a database when this page was written.
1. Before you deploy: count the variants
Migration 0063 ends with one statement that inserts a stock row for every row of bb_product_variant, soft-deleted ones included. Backend rule 06 forbids a single-statement backfill over 10,000 rows (06-schema-integrity-rules.md, "single-statement backfill of > 10,000 rows"). Count first:
SELECT count(*) FROM bb_product_variant;- 10,000 or fewer: deploy as written.
- Above 10,000: stop. The backfill becomes a contract change and goes back to planning. Do not deploy
0063as written.
The count includes soft-deleted variants, because the backfill does.
2. Deploy order
- Back up and replay as in Deploy Notes.
- Migrate, in a quiet window:
pnpm db:migrate. - Sync permissions:
pnpm --filter @nano-store/api permissions:sync. - Restart the API and the workers.
- Deploy Admin #2 after the backend.
- Grant: a superadmin opens Admin #2 Roles and gives each bb role its
BB_Inventory_*codes (andBB_Catalog_*for the job screens).
Why the window must be quiet
The two migrations apply as one batch in one transaction with SET LOCAL lock_timeout = '5s'. The batch takes SHARE ROW EXCLUSIVE on admin_users and bb_product_variant (the new foreign keys) and ACCESS EXCLUSIVE on bb_audit and bb_catalog_job (the widened CHECKs). Staff writes, variant writes and every bb write wait or fail briefly. A lock that cannot be had in 5 s aborts the whole batch with nothing applied and the ledger unchanged; run it again.
permissions:sync is required
Neither migration inserts a BB_Inventory_* permission row. permissions:sync creates the five rows (CREATE, READ, UPDATE, DELETE, RESTORE) and grants them to nobody: a new bb permission is never granted to admin, and never to superadmin by the script.
Without it:
- The Roles screen has no Inventory module, so no role can be granted anything.
- A superadmin still passes every route check (the guard bypasses), so the screens look fine to the person deploying them. A bb staff member gets 403.
In a development database, permissions:sync reported "Added 5 missing permissions" and "0 role pairs granted". Re-running it is safe: it only adds what is missing. The guard reads Postgres per request, so the Roles screen showed the module without a restart; restart anyway, as the order above says.
The grant step is manual
After the sync, nothing can use stock except a superadmin. Open Admin #2, Roles, pick each bb role, and tick the Inventory actions it needs:
| To let a role | Grant |
|---|---|
| See stock and ledgers | BB_Inventory_READ |
| Adjust, bulk adjust, change a threshold | BB_Inventory_READ + BB_Inventory_UPDATE |
| Import stock | BB_Catalog_CREATE + BB_Inventory_CREATE + BB_Inventory_UPDATE (and BB_Inventory_READ + BB_Catalog_READ to see the job) |
| Export stock | BB_Catalog_READ + BB_Inventory_READ |
BB_Inventory_DELETE and BB_Inventory_RESTORE are not checked by any route; granting them does nothing.
3. Intermediate states
| State | Effect |
|---|---|
| New backend, old Admin #2 | Supported. Everything is additive. The one visible difference: deleting a variant that holds stock answers a code (BB_VARIANT_HAS_STOCK) old Admin #2 does not know, and no variant has stock until the new Admin #2 ships |
| Old backend, new Admin #2 | Not supported. The nav shows for a superadmin and every stock read answers 404. Deploy the backend first and do not reverse the order |
| Between migrate and restart | The old app can create a variant with no stock row. Stock routes answer 404 BB_INVENTORY_NOT_FOUND for it until the hourly reconcile creates the row |
| Admin #1 and the storefront | No effect. No cross-repo cache invalidation exists for bb |
4. Verify after deploy
Read-only checks, not run by this page:
SELECT count(*) FROM permission WHERE module = 'BB_Inventory'; -- 5
SELECT (SELECT count(*) FROM bb_product_variant) AS variants,
(SELECT count(*) FROM bb_inventory) AS stock_rows; -- equal- The two counts in the second query are equal right after the migrate. A gap later means a creation path skipped its row; the reconcile heals it and logs an ERROR.
- Superadmin:
GET /api/admin/bb/inventoryanswers 200. - A bb role with
BB_Inventory_READonly: the same route answers 200,POST .../adjustanswers 403. - After the next top of the hour, the API log shows
BbInventoryReconcileScheduler [success]andBbInventoryReconcileProcessor [success] ... healed=0 examined=N drifted=0. This needs the MAINTENANCE worker running andAPI_RUNTIME_PROFILEnotfast.
5. Rollback
migrate-down.ts refuses production URLs, so every production rollback step is by hand, with the backup already taken.
What a code-only rollback does
Rolling the code back leaves the tables in place and harmless: retail never reads them. A stock job still in the queue then fails, because the old import planner has no inventory case; that failure is contained to the job.
The down guards
Both down scripts refuse to run, naming the counts:
down/0063_bb_inventory.down.sqlrefuses while anybb_inventory_movementrow exists or anybb_inventory.quantityis not 0. It does not look at a changed threshold orversion. That configuration is protected only by 0064's guard, so 0064's down runs first.down/0064_bb_inventory_jobs_audit.down.sqlrefuses whilebb_auditholds aninventoryrow orbb_catalog_jobholds aninventoryjob row.
Every stock write also writes the ledger and bb_audit, and both are append-only. After the first stock write or the first stock job, both guards always fire: 0063 and 0064 are forward-fix only after first use. Getting past a guard means truncating the ledger or bb_audit, which destroys the record of who changed what. Only the owner, in writing, may authorise that. No agent and no runbook step does it.
Runbook: before the first stock write or stock job
Back up first. In one transaction, in this order:
SET LOCAL lock_timeout = '5s'.- The body of
down/0064_bb_inventory_jobs_audit.down.sql. Its guard runs first. - The body of
down/0063_bb_inventory.down.sql. - Delete both ledger rows from
drizzle.__drizzle_migrations, matched byhash. DELETE FROM permission WHERE module = 'BB_Inventory'.role_permissioncascades, so any grant made in the Roles screen goes with it.
Compute the two hashes (the SHA-256 of each file's contents, as migrate-down.ts does):
sha256sum packages/db/src/migrations/0063_bb_inventory.sql packages/db/src/migrations/0064_bb_inventory_jobs_audit.sqlRun the transaction with psql (not run; read the output of each step before trusting it):
psql "$DIRECT_DATABASE_URL" -v ON_ERROR_STOP=1 --single-transaction \
-c "SET LOCAL lock_timeout = '5s'" \
-f packages/db/src/migrations/down/0064_bb_inventory_jobs_audit.down.sql \
-f packages/db/src/migrations/down/0063_bb_inventory.down.sql \
-c "DELETE FROM drizzle.__drizzle_migrations WHERE hash IN ('<0063 hash>', '<0064 hash>')" \
-c "DELETE FROM permission WHERE module = 'BB_Inventory'"Then roll the code back, in the same order as phase 2. Phase 2's outbox_events delete and queue obliterate are not copied: bb_catalog also carries phase 2's jobs, and 0064's guard already refuses while a stock job row exists.
Phase 2's runbook now depends on this one
Phase 2's runbook A drops bb_product_variant. With 0063 applied, that fails on the stock row's foreign key. Roll phase 3 back first, then run phase 2's runbook. Phase 1's runbook A step 3 (DELETE FROM permission WHERE module LIKE 'BB\_%') also removes BB_Inventory, so step 5 above is only needed when rolling back phase 3 alone.
After first use
Not a runbook step. It needs the owner's written decision to destroy the ledger and bb_audit history.
6. See Also
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.
B2B Second Inventory Orders API Reference
Endpoint reference for the bb phase 4 admin order API — create, list, detail, notes, cancel, sales receipt PDF, and the pickers and submission check behind the new-order form — with permissions, throttles, idempotency and known limits.