Skip to main content

Bank8:Accounting - Detailed Design Document

1. Scope & Context​

Bank8:Accounting owns: the accounting schema (schema-per-service - domain tables + accounting.outbox / accounting.audit_journal producer tables), the chart of accounts, the product→GL activity mapping, the journal projection, the trial balance and financial statements, the period-close lifecycle, the FX rate catalogue, the revaluation engine, and the bank8:accounting:* event family.

It does NOT own: money movement, balances, or posting atomicity (Bank8:Ledger), payment orchestration (Bank8:Payments), regulatory filing (Bank8:Reporting), prudential measurement (Bank8:Risk), AML detection (Bank8:Compliance), tenant-authored hooks (Sentin8:Func), document bytes (Sentin8:Storage), schedule timing (Sentin8:Cron), or metric aggregation (Sentin8:Stat).

2. Runtime Architecture​

Boot is shell-owned (sentin8::shell): pool, policy engine, outbox relay, audit-journal pusher, PQ-TLS. build_state adds this service's wiring and spawns the embedded projection worker.

Access-decision order (principles §4.7 - membus → bus → API): (1) MemBus state refresh first, so the admin dashboards update surgically (fail-soft); (2) durable bank8:accounting:* events through the local outbox → relay → Bus; (3) owner HTTP APIs for synchronous aggregates (trial balance, statements) and for the ledger's public posting API when revaluing.

Projection is the load-bearing path. Accounting is a derived service: it consumes committed ledger postings and produces journal entries. It holds no lock on the money path and is never consulted during a posting's commit.

The worker is idempotent per ledger posting id and never fabricates a side. An unresolvable mapping parks the entry and emits gl:imbalance - the service prefers a visible gap over a plausible wrong number.

3. Data Model​

TablePurposeRLS tier
gl_accountsChart of accounts: code, name, type, normal balance, parent, activeenv
gl_account_balancesPer (period, gl account, currency) debit/credit totals - the trial-balance hot readenv
mapping_rules(product_type, instruction_type) → (debit GL, credit GL) with priority for specificityenv
journal_entriesOne row per projected ledger posting; ledger_posting_id unique per env (the idempotency key)env
journal_linesBalanced debit/credit lines per entryenv
gl_periodsAccounting periods with status (open, closed)env
close_runsPeriod-close executions, idempotent per periodenv
fx_ratesEffective-dated, append-only rate catalogue per pairenv
revaluation_runsPeriod-end revaluation executions, idempotent per (period, account, currency)env
accounting.outbox / accounting.audit_journalProducer tables (relay/pusher)FORCE

Money precision: every amount column is NUMERIC(28,10) - the same scale the ledger uses for transactions. Rounding is applied once, at statement presentation, never at projection.

4. API Surface​

AudienceRoutesAuth gateEvents emitted
Chart of accountsGET/POST /v1/gl-accounts, GET/PUT /v1/gl-accounts/{id}, POST /v1/gl-accounts/{id}/deactivatebank8:accounting:gl:read / :writeglaccount:created, glaccount:updated
MappingGET/POST /v1/mapping-rules, GET/PUT/DELETE /v1/mapping-rules/{id}, GET /v1/mapping-rules/resolvebank8:accounting:mapping:read / :writemappingrule:upserted
JournalGET /v1/journal-entries, GET /v1/journal-entries/{id}, GET /v1/journal-entries/unmappedbank8:accounting:journal:read-
StatementsGET /v1/trial-balance, GET /v1/statements/profit-loss, GET /v1/statements/balance-sheetbank8:accounting:statements:read-
PeriodsGET /v1/periods, POST /v1/periods, POST /v1/periods/{id}/close, POST /v1/periods/{id}/reopenbank8:accounting:periods:read / :writeperiod:closed, period:reopened
FXGET/POST /v1/fx-rates, GET /v1/fx-rates/{base}/{quote}bank8:accounting:fx:read / :writefx:rate:upserted
RevaluationPOST /v1/revaluation/run, GET /v1/revaluation/runsbank8:accounting:revaluation:read / :writerevaluation:completed
InternalPOST /v1/internal/schedules/run (Cron proxy-back: period reminders, revaluation)Shield + M2M-
Admin/SDUIGET /v1/admin/ui/{page}, GET /v1/admin/overviewbank8:accounting:admin-

Trial balance contract:

GET /v1/trial-balance?period=2026-11
200 {
"period": "2026-11",
"balanced": true,
"lines": [ { "gl_account_id", "code", "name", "type",
"opening_debit", "opening_credit",
"period_debit", "period_credit",
"closing_debit", "closing_credit" } ],
"totals": { "debit": "…", "credit": "…" }
}
409 when totals disagree (body carries the delta and the offending entries)

A 409 is the designed response for a broken book - the service fails closed rather than returning an unbalanced statement.

Statement derivation:

StatementDerivation
Profit & loss (period)Sum of period activity on income and expense accounts, normal balance applied
Balance sheet (as of)Closing debit/credit on asset, liability, equity + accumulated result to date
Retained earningsRolled at period:closed from the period's net result

Admin/SDUI pages: coa, mapping, journal, trial-balance, statements, periods, fx, revaluation, overview.

5. Cross-Cutting Concerns​

  • Auth: platform token pipeline; Shield is the only gate. scope is a pre-filter, never the decision.
  • Tenant + RLS: set_tenant_context awaited on the same connection/transaction as the data query; explicit WHERE env_id = $N on every statement. Every table ENABLE + FORCE ROW LEVEL SECURITY; the service role is NOBYPASSRLS.
  • Identity: the projection worker's certificate-presenting Bus client is the single outbound identity (CERTFREE-4V). A failed certificate mint fails the consume closed - no static-token fallback.
  • Reads from the ledger: only through the public API (GET /v1/journal-events, GET /v1/postings/{id}/instructions, GET /v1/products). Never a cross-schema grant; a cross-schema grant is a defect.
  • Event emission: MemBus refresh (fail-soft) → durable outbox row in the same transaction as the domain write → relay → Bus.
  • Idempotency: journal projection keyed on ledger_posting_id; revaluation keyed on (period, account, currency); close keyed on period. All use partial unique indexes, so re-delivery collides on insert rather than relying on a read-then-write check.
  • Audit: accounting.audit_journal in the same transaction, plus Sys audit push.
  • TLS: PQ-TLS via sentin8-tls.

6. Failure Modes & Recovery​

FailureBehaviour
Ledger API unavailableProjection stalls and reports lag; the money path is unaffected. Backfill on resume from the journal read API.
Mapping missingEntry parked as unmapped, gl:imbalance emitted. No partial book.
Mapping ambiguous (two rules match)Highest priority wins; equal priority is rejected at write time, so the ambiguity cannot exist at projection time.
Posting replayAbsorbed by the ledger_posting_id unique index.
Close re-runAbsorbed by the (period) unique index on close_runs.
gl:imbalanceConsumed by Bank8:Compliance as an alert; the trial balance refuses to serve.

7. Concurrency & Performance Model​

Pool capped (3–5). The hot path is the projection UPSERT: one journal entry, N lines, and N balance-delta updates per posting - all in one transaction, bounded by the posting's instruction count. Reads are aggregate queries over gl_account_balances, which is pre-bucketed by period so the trial balance is a range scan, not a join fan-out.

Projection is single-writer per environment (consumer group), so no contention on the same entry; concurrent environments proceed in parallel. Statement reads are lock-free.

8. Invariants​

  1. Balanced per entry. Every journal_entries row's lines satisfy SUM(debit) == SUM(credit). Enforced by a post-insert check inside the same transaction; a violation rolls back and emits gl:imbalance.
  2. Exactly once per posting. UNIQUE (env_id, ledger_posting_id) on journal_entries.
  3. Closed periods are immutable. No entry may reference a gl_periods.status = 'closed' period; the projection routes a late posting to the next open period and records the remap.
  4. Rates are append-only. No UPDATE or DELETE on fx_rates - corrections are new effective-dated rows.
  5. No cross-service table access. Accounting reads ledger data only through the ledger's public API; it holds no grant on ledger.*.
  6. No guessed sides. An unresolved mapping parks the entry; the service never invents a GL account to keep the flow moving.
  7. Inactive accounts cannot receive new lines. Deactivating an account with posted history is rejected; a mapping to an inactive account fails at product activation.

9. Testing Strategy​

  • Contracts crate - shared GL/mapping/statement shapes consumed by the SDK facade and by tests.
  • Policy suite (tests/policy.rs) - the seeded scope-mirror text with the handler-action parity matrix.
  • DB invariants (tests/db_invariants.rs, against a live bank8 DB): FORCE-RLS rejection for another tenant; ledger_posting_id uniqueness absorbs a duplicate event; an unbalanced entry is rejected and emits gl:imbalance; close re-run rolls retained earnings once; fx_rates rejects UPDATE; a mapping to an inactive account fails validation; no accounting view references ledger.*.
  • Projection fixtures - a recorded ledger posting set projected to a known journal, with trial balance, P&L, and balance sheet asserted against hand-calculated totals.
  • OpenAPI drift (tests/openapi_drift.rs) - router ↔ spec sweep.
  • E2E - UI-only through the BFF, alongside the existing lifecycle spec; no live-regulator interaction.

10. Open Questions​

  • Multi-entity segmentation: entity as a COA segment vs. an environment dimension. Deferred - the current model assumes one book per environment.
  • Whether statutory XBRL taxonomies are produced here or remain exclusively with Bank8:Reporting. Current position: Reporting owns filing formats; Accounting owns the book.
  • Revaluation policy for accounts denominated in a currency with no catalogue rate - currently a hard failure (fail closed) rather than a carry-forward guess.

Architecture & Design: bank8:accounting and its underlying concepts were designed by Hamid Jahanzad.