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
| Table | Purpose | RLS tier |
|---|---|---|
gl_accounts | Chart of accounts: code, name, type, normal balance, parent, active | env |
gl_account_balances | Per (period, gl account, currency) debit/credit totals - the trial-balance hot read | env |
mapping_rules | (product_type, instruction_type) → (debit GL, credit GL) with priority for specificity | env |
journal_entries | One row per projected ledger posting; ledger_posting_id unique per env (the idempotency key) | env |
journal_lines | Balanced debit/credit lines per entry | env |
gl_periods | Accounting periods with status (open, closed) | env |
close_runs | Period-close executions, idempotent per period | env |
fx_rates | Effective-dated, append-only rate catalogue per pair | env |
revaluation_runs | Period-end revaluation executions, idempotent per (period, account, currency) | env |
accounting.outbox / accounting.audit_journal | Producer 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
| Audience | Routes | Auth gate | Events emitted |
|---|---|---|---|
| Chart of accounts | GET/POST /v1/gl-accounts, GET/PUT /v1/gl-accounts/{id}, POST /v1/gl-accounts/{id}/deactivate | bank8:accounting:gl:read / :write | glaccount:created, glaccount:updated |
| Mapping | GET/POST /v1/mapping-rules, GET/PUT/DELETE /v1/mapping-rules/{id}, GET /v1/mapping-rules/resolve | bank8:accounting:mapping:read / :write | mappingrule:upserted |
| Journal | GET /v1/journal-entries, GET /v1/journal-entries/{id}, GET /v1/journal-entries/unmapped | bank8:accounting:journal:read | - |
| Statements | GET /v1/trial-balance, GET /v1/statements/profit-loss, GET /v1/statements/balance-sheet | bank8:accounting:statements:read | - |
| Periods | GET /v1/periods, POST /v1/periods, POST /v1/periods/{id}/close, POST /v1/periods/{id}/reopen | bank8:accounting:periods:read / :write | period:closed, period:reopened |
| FX | GET/POST /v1/fx-rates, GET /v1/fx-rates/{base}/{quote} | bank8:accounting:fx:read / :write | fx:rate:upserted |
| Revaluation | POST /v1/revaluation/run, GET /v1/revaluation/runs | bank8:accounting:revaluation:read / :write | revaluation:completed |
| Internal | POST /v1/internal/schedules/run (Cron proxy-back: period reminders, revaluation) | Shield + M2M | - |
| Admin/SDUI | GET /v1/admin/ui/{page}, GET /v1/admin/overview | bank8: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:
| Statement | Derivation |
|---|---|
| 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 earnings | Rolled 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.
scopeis a pre-filter, never the decision. - Tenant + RLS:
set_tenant_contextawaited on the same connection/transaction as the data query; explicitWHERE env_id = $Non every statement. Every tableENABLE+FORCE ROW LEVEL SECURITY; the service role isNOBYPASSRLS. - 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 onperiod. All use partial unique indexes, so re-delivery collides on insert rather than relying on a read-then-write check. - Audit:
accounting.audit_journalin the same transaction, plus Sys audit push. - TLS: PQ-TLS via
sentin8-tls.
6. Failure Modes & Recovery
| Failure | Behaviour |
|---|---|
| Ledger API unavailable | Projection stalls and reports lag; the money path is unaffected. Backfill on resume from the journal read API. |
| Mapping missing | Entry 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 replay | Absorbed by the ledger_posting_id unique index. |
| Close re-run | Absorbed by the (period) unique index on close_runs. |
gl:imbalance | Consumed 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
- Balanced per entry. Every
journal_entriesrow's lines satisfySUM(debit) == SUM(credit). Enforced by a post-insert check inside the same transaction; a violation rolls back and emitsgl:imbalance. - Exactly once per posting.
UNIQUE (env_id, ledger_posting_id)onjournal_entries. - 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. - Rates are append-only. No UPDATE or DELETE on
fx_rates- corrections are new effective-dated rows. - No cross-service table access. Accounting reads ledger data only
through the ledger's public API; it holds no grant on
ledger.*. - No guessed sides. An unresolved mapping parks the entry; the service never invents a GL account to keep the flow moving.
- 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_iduniqueness absorbs a duplicate event; an unbalanced entry is rejected and emitsgl:imbalance; close re-run rolls retained earnings once;fx_ratesrejects UPDATE; a mapping to an inactive account fails validation; noaccountingview referencesledger.*. - 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.