ADR-00036 — Deferred, Approval-Gated Balance Mutation and a Database-Enforced Immutable Ledger for Stock Entry

By Engineering Team•October 8, 2026•7 min read
  • Status: Approved / Implemented
  • Date: 2026-10-08
  • Authors: Engineering Team

Context

BRD-019 commits the business to two guarantees that pull in opposite directions if implemented naively: a flagged movement must not change stock on hand until a second person approves it (BR-02), and the resulting history of movements must never be editable or erasable once it exists (BR-01). Satisfying the first naturally suggests applying a movement’s effect immediately and reversing it if a supervisor later declines it; satisfying the second naturally suggests writing that history is either append-only by code discipline, or something stronger. inventory-service’s admin Stock Entry feature (domain/stockentry/, service/stockentry/) resolves both with one specific design: this ADR records why.


Decision Drivers (FRs & NFRs)

See SR-020 for the full requirement list.

  • FR-03/FR-05 (Creation Has No Effect; Approval Is the Only Thing That Mutates the Balance): a newly-recorded movement must sit inert until a distinct approval action occurs.
  • FR-08 (Rejection Is a Pure Status Flip): declining a movement must leave the balance and the ledger completely untouched.
  • FR-06 (Approval Reuses Checkout’s Own Balance-Mutation Routine): whichever mechanism applies the mutation at approval time must be the same one SR-019 already specifies for checkout consumption, not a second implementation.
  • FR-12 (A Written Ledger Entry Can Never Be Changed or Removed): this must hold even against a caller with full administrative or direct-database access — not only against every application code path choosing never to attempt one.
  • FR-13 (Balance Invariants Must Always Hold): physical/reserved/available counts must never go negative or fall out of their defined relationship, enforced independently of application logic.

Options Evaluated — Part 1: When a Movement’s Balance Effect Actually Takes Place

Option 1 — Deferred, approval-gated mutation: creation has zero balance effect; only approval mutates (CHOSEN)

CreateStockEntry inserts the movement’s header and line items in a PENDING status and stops there — no balance mutation, no ledger write. Only ApproveStockEntry applies every line’s signed quantity change, writes the corresponding ledger entries, and flips status to APPROVED, all inside one database transaction. RejectStockEntry only flips status to REJECTED.

  • Pros:
    • Rejection needs no reversal logic at all. Because nothing was ever applied, declining a movement is a one-column status update — there is no “undo a mutation that already happened” code path to get right, and therefore no class of bug where an undo doesn’t perfectly cancel the original effect (e.g. a rounding or ordering mismatch between apply and reverse).
    • The ledger only ever records what actually, finally happened. Every stock_ledger_entries row corresponds to a movement that is genuinely in effect — there’s no intermediate “applied-then-reversed” pair of rows to reconcile when reading history, and no risk of a reader seeing a transient, later-reversed balance state.
    • A PENDING movement can be freely corrected (FR-04) without any balance bookkeeping concern. Because a pending movement never touched the balance, editing its line items before approval is just editing rows — no “re-derive what the balance would be if this edit were reapplied” logic is needed.
  • Cons & Accepted Trade-offs:
    • A supervisor’s view of “current stock on hand” never reflects a pending movement until it’s approved, even though the movement is already recorded — accepted because BRD-019 BR-02 explicitly requires the movement to have no effect until approved; showing its effect early would contradict the guarantee itself, not just the implementation choice.
    • Approval is doing more work in one transaction (balance mutation plus ledger write plus, for Opening Entry, the initialization-guard mark) than a simpler “the mutation already happened at creation” design would ask of it — accepted because it’s still one database transaction, and FR-06 means this is the same transaction shape checkout consumption already relies on.

Option 2 — Immediate-apply, reverse-on-rejection (NOT CHOSEN)

Apply a movement’s balance effect the moment it’s created, and if a supervisor later rejects it, apply the exact inverse mutation to cancel it out.

  • Cons (Why Rejected):
    • Requires a correctness-critical reversal path that the chosen design doesn’t need at all. The inverse mutation has to exactly cancel the original — same sign-handling rules, same row-locking, same ledger-balance-before/after bookkeeping, just run backwards — doubling the surface area where a bug in the balance-mutation logic could exist, for a code path (reversal) that exists purely to undo something that arguably should never have happened yet.
    • Produces a ledger with two rows for every eventually-rejected movement (the original apply, then the reversing entry) rather than zero — technically still an accurate history, but a reader has to understand “net effect, not literal row count” to interpret it, instead of the chosen design’s simpler invariant that a ledger row only ever exists for a movement that is, and remains, in effect.
    • Directly contradicts BRD-019 BR-02’s framing — “must not change stock on hand until approved” reads most naturally as “has not yet happened,” not “has happened but is reversible.” The chosen design matches the business requirement’s own language without needing a reinterpretation.

Options Evaluated — Part 2: Enforcing That the Ledger Can Never Be Changed

Option 1 — Database-level trigger rejecting any UPDATE/DELETE on the ledger table (CHOSEN)

A BEFORE UPDATE OR DELETE trigger on stock_ledger_entries, backed by a PL/pgSQL function that unconditionally raises an exception, so any attempt to modify or remove a ledger row — from any code path, any role, or a direct database session — fails at the database itself.

  • Pros:
    • Holds even against access the application layer doesn’t control. An application-only convention (“the service code simply never issues an UPDATE/DELETE against this table”) is only as strong as every current and future caller of the database — a migration script, a one-off support query, or a future engineer unfamiliar with the convention could all violate it silently. A database trigger makes the guarantee independent of who or what is connecting.
    • Matches FR-12’s own wording exactly — “under any circumstance, including … a direct database connection” is not something application code can enforce on its own; it specifically requires the guarantee to live below the application layer.
    • Zero ongoing discipline required. Once the trigger exists, no code review, lint rule, or team convention has to keep re-verifying that nothing ever updates this table — the database refuses it unconditionally, permanently.
  • Cons & Accepted Trade-offs:
    • A genuine future need to correct a ledger row (e.g. a data-entry mistake discovered after the fact) has no “edit” path at all — only a new, compensating ledger entry could record a correction. Accepted deliberately: an editable audit trail is a contradiction in terms for this use case, and a compensating-entry pattern is the standard way financial/inventory ledgers handle a discovered error without rewriting history — the same posture already taken for payment records (ADR-00028).

Option 2 — Application-only convention: service code simply never updates or deletes a ledger row (NOT CHOSEN)

Rely on service/stockentry/ and service/stockbalance/ never containing an UPDATE/DELETE statement against stock_ledger_entries, enforced by code review and the repository layer’s own method set (no update/delete method exposed for this table).

  • Cons (Why Rejected):
    • Doesn’t satisfy FR-12’s “including a direct database connection” requirement at all — a convention that only constrains the Go application code says nothing about a migration, an ad hoc psql session, or a future service in a different language that gains access to the same schema.
    • The absence of an update/delete repository method is a weaker guarantee than it looks — it stops this service’s own code from calling one, but doesn’t stop a new method from being added later by someone who didn’t know the convention existed, especially since nothing about the schema itself signals “this table is append-only.”

Final Decision

Balance mutation is deferred until explicit approval (Part 1, Option 1). CreateStockEntry records a movement with zero effect on stock; only ApproveStockEntry — in one transaction — applies the mutation, writes the ledger entry, and (for Opening Entry) marks the initialization guard; RejectStockEntry is a pure status flip with no reversal logic required, because nothing was ever applied to reverse. Ledger immutability is enforced at the database level via a trigger (Part 2, Option 1), not left as an application-only convention — stock_ledger_entries rejects any UPDATE/DELETE unconditionally, regardless of caller, matching BRD-019 BR-01’s absolute framing rather than a best-effort one. The same posture — an append-only ledger over a permanent financial/operational record — was already taken for payment transactions in ADR-00028; this decision applies the same append-only posture to the inventory domain, strengthened here with a database-level trigger rather than relying solely on the write path’s own discipline.