Reference

Architecture Decisions

Key design decisions for schema.sql. Each record documents the context, choice made, and trade-offs accepted.


ADR-001: SQLite / Cloudflare D1 over PostgreSQL

Status: Accepted

Context: AIB runs on an AI-native Paperclip agent stack deployed to Cloudflare Workers. The agent organisation needs a persistence layer accessible from Workers with low latency, no connection pooling overhead, and zero infrastructure management.

Decision: SQLite via Cloudflare D1 as the sole database engine.

Rationale:

  • Workers have native D1 bindings — no TCP connection overhead
  • SQLite DDL is a single portable file; every agent can validate schema offline
  • D1 supports PRAGMA foreign_key_check and PRAGMA integrity_check for CI validation
  • Regulatory reporting reads are bursty but low-volume for a single-institution private bank

Consequences:

  • STORED generated columns not supported by D1 (SQLite 3.37 limitation) — all computed columns must be VIRTUAL
  • No CHECK constraints across rows — GL balance enforcement delegated to application layer
  • Full-text search requires FTS5 extension (not used in V1–V10 schema)
  • No native JSON type — JSON stored as TEXT, validated at application layer

ADR-002: Single-file DDL (schema.sql)

Status: Accepted

Context: Schema is used as a reference artifact as well as a deployable DDL. Multiple potential consumers: CI validation, local SQLite testing, Cloudflare D1 deployment, TOGAF documentation.

Decision: Hybrid. A generated full-schema snapshot (schema.sql and db/migrations/schema_d1.sql, 387 tables / 493 indexes) plus numbered incremental migrations under db/migrations/ (0001_initial.sql … 0014_research.sql). The snapshot is for fresh deploys and CI; the numbered migrations carry incremental change history (everything after V11).

Rationale:

  • Fresh deploy / CI in one step: wrangler d1 execute aib-mock --file=schema.sql (or schema_d1.sql)
  • Numbered migrations give an auditable, ordered change history for incremental application
  • All changes are additive (new tables / columns) so the snapshot assembles cleanly and migrations never break prior state
  • check-counts.mjs asserts CREATE-TABLE count parity across both migrations and the snapshot, so they cannot silently diverge

Consequences:

  • Two artifacts to keep in lock-step (guarded by check:counts): every new table lands in a numbered migration and both snapshot files
  • Snapshot grows with each version (now ~14k lines); incremental consumers apply only the new migration
  • ALTER TABLE statements must follow all CREATE TABLE blocks (SQLite ALTER TABLE ADD COLUMN requires the target table to exist)

ADR-003: Tip-Off Prohibition Enforced at DB Layer

Status: Accepted

Context: SPG Art. 16 (STR) and MAR Art. 16(2) (STOR) both prohibit tipping off a suspect that a report has been filed. Violation is a criminal offence in Liechtenstein.

Decision: Enforce the prohibition with CHECK(tipped_off = 0) on both str.tipped_off and stor_report.tipped_off. The column cannot be set to any value other than 0.

Rationale:

  • Critical compliance constraint with criminal liability — application-layer enforcement is insufficient
  • DB-layer CHECK prevents any code path (including direct SQL by an agent) from setting tipped_off = 1
  • Cost is near-zero; a DEFAULT 0 CHECK(tipped_off = 0) column adds no storage or query overhead

Consequences:

  • If a legitimate operational need to mark a tipped-off case arises, a schema change is required (not a config change)
  • Test scenarios must work around this constraint — test inserts cannot set tipped_off = 1

ADR-004: VIRTUAL Generated Columns for All Compliance Ratios

Status: Accepted

Context: Many regulatory ratios (LCR, NSFR, leverage ratio, DSCR, hedge effectiveness ratio, IRRBB SOT breach flags) must be computed from stored inputs. The question is whether to compute at write time (STORED) or read time (VIRTUAL).

Decision: All computed columns use GENERATED ALWAYS AS (...) VIRTUAL. No STORED generated columns anywhere in the schema.

Rationale:

  • Cloudflare D1 does not support STORED generated columns
  • VIRTUAL columns have no storage cost and no write-time computation overhead
  • Compliance ratios are typically read as part of reporting queries, not filtered in WHERE clauses at high frequency
  • Inputs can change (e.g. tier1_capital updated) without triggering a re-computation batch

Consequences:

  • Generated columns cannot reference other generated columns (SQLite constraint) — e.g. debt_service_coverage_ratio in loan_creditworthiness_assessment must reference input columns directly, not total_annual_debt_service (which is itself VIRTUAL)
  • Complex multi-step derived values (e.g. stressed DSCR requiring stressed income) must be broken into separate VIRTUAL columns each referencing only base inputs
  • WHERE clauses on VIRTUAL columns do not use covering indexes — range queries on ratios are slightly less efficient

ADR-005: ref_country Primary Key as iso2 (Two-Letter Code)

Status: Accepted

Context: Country references are needed across dozens of tables (client nationality, counterparty jurisdiction, MiCA passporting states, DORA data storage locations, FATF high-risk flag). A surrogate id key versus the natural iso2 code.

Decision: ref_country PK is iso2 TEXT (ISO 3166-1 alpha-2). All foreign keys use REFERENCES ref_country(iso2).

Rationale:

  • ISO 3166-1 alpha-2 codes are stable, globally unambiguous, and human-readable in queries
  • Eliminates join to decode country — WHERE jurisdiction = 'LI' rather than WHERE jurisdiction_id = 42
  • Regulatory forms (FATCA, CRS, EMIR) use ISO 3166-1 alpha-2 natively

Consequences:

  • Any column referencing country must be defined as TEXT REFERENCES ref_country(iso2), not TEXT REFERENCES ref_country(code) — a common mistake when extending the schema
  • Kosovo (XK) and other non-UN-member territories must be explicitly inserted into ref_country before use

ADR-006: Scaffold Table Pattern for Enacted-but-Pending Regulations

Status: Accepted

Context: Several regulations are enacted (legally in force) but with enforcement dates in 2026–2028 (CSRD, EU AI Act, AMLA, Digital Euro, crypto prudential CRR3 Art. 501d). Including these now vs. deferring to a later version.

Decision: Include scaffold tables now, clearly marked with -- SCAFFOLD: regulation pending / enforcement YYYY comments in the DDL. Fields are representative of the final regulation, not placeholder.

Rationale:

  • Regulations are enacted law; the schema should reflect what AIB will need to comply with
  • Agents can begin implementing classification and ingestion logic before enforcement
  • Scaffold tables are excluded from the expected deploy count only to the extent they add 11 tables total (clearly documented in README Schema Stats)
  • CSRD double materiality assessments require multi-year data accumulation — starting now avoids a data gap at first mandatory reporting

Consequences:

  • Schema must be kept in sync with evolving regulatory technical standards (ESRS, BCBS SCO60 RTS) before enforcement
  • cbdc_account is a placeholder for the Digital Euro intermediated model — fields may change materially before the ECB finalises the regulation

ADR-007: Index Naming Convention (idx_{prefix}_{column})

Status: Accepted

Context: 387 tables across a single SQLite file means 493+ indexes. SQLite requires globally unique index names within a database. Without a convention, naming conflicts arise as the schema grows.

Decision: All indexes named idx_{table_prefix}_{column(s)} where table_prefix is the first 4–5 characters of the table name. Example: idx_lcr_hqla_date for lcr_hqla_item.valuation_date.

Rationale:

  • Prevents cross-table naming conflicts without requiring a lookup
  • Names remain human-readable in sqlite_master queries
  • Consistent with the alphabetical section naming (A–J for V2, K–AA for V3, LLL–ZZZ for V8, AAAA–NNNN for V9, AAAAA–JJJJJ for V10)

Consequences:

  • Table renames require index renames (acceptable — no renames occur in V1–V10)
  • Very short table names (e.g. str, ubo) require disambiguation: idx_str_client, idx_ubo_client

ADR-008: Dual-Authorisation Encoded in bank_transaction

Status: Accepted

Context: BankG and SPG require dual authorisation for material payment instructions. The schema must prevent single-person approval of large or high-risk transactions.

Decision: bank_transaction carries dual_auth_required, auth_1_by, auth_2_by columns. Transaction remains in status = 'awaiting_dual_auth' until both authorisations are recorded. auth_1_by and auth_2_by must differ (enforced at application layer).

Rationale:

  • DB layer encodes the state machine; application enforces the auth_1 ≠ auth_2 rule
  • SQLite cannot enforce inequality constraints across two columns without a trigger; triggers are avoided to keep schema portable across D1 versions
  • The state machine (pending → awaiting_dual_auth → approved → executed) is auditable via audit_log

Consequences:

  • Application code must check auth_1_by != auth_2_by before setting status = 'approved'
  • Threshold logic (which transactions require dual auth) is application-configured, not schema-encoded — allows regulatory threshold changes without a schema migration

ADR-009: Section Naming for Schema Versions (A–J, K–AA, LLL–ZZZ, AAAA–NNNN, AAAAA–JJJJJ)

Status: Accepted

Context: schema.sql is a single append-only file. Each version adds a named section to identify when each block was added. A consistent naming convention aids audit and forensic review.

Decision: Version section identifiers use sequential capital-letter groupings:

  • V2: Sections A–J (10 sections)
  • V3: Sections K–AA (17 sections, continuing from J)
  • V8: Sections LLL–ZZZ (3-letter)
  • V9: Sections AAAA–NNNN (4-letter, 14 sections)
  • V10: Sections AAAAA–JJJJJ (5-letter, 10 sections)

Rationale:

  • Avoids collision with earlier single-letter and double-letter section names as the file grows
  • Letter-length encodes the schema generation — one letter = V2, four letters = V9
  • No dependency on version numbers in the DDL itself; sections are structural markers

Consequences:

  • Section identifiers are metadata only — not used in any SQL query
  • Future versions (V11+) would use 6-letter identifiers (AAAAAA–...)

ADR-010: Retention Periods Encoded as retain_until Columns

Status: Accepted

Context: EEA/Liechtenstein regulations impose different retention periods across domains: SPG = 10yr from end of relationship, MiFID II = 5yr from transaction, DORA = 5yr from incident closure, GDPR = duration of legal basis. Retention must be auditable per record.

Decision: Every table with a retention obligation carries a retain_until TEXT column (ISO 8601 date string). Populated at INSERT by the writing agent based on the applicable regulation. A global retention schedule is documented in README.md and enforced by a compliance calendar entry.

Rationale:

  • Per-record retention is required by GDPR Art. 5(1)(e) (storage limitation) — a single table-level policy is insufficient when records have different retention triggers (e.g. account opened vs. account closed)
  • ISO 8601 strings are sortable and D1-compatible without datetime type casting
  • Centralising the schedule in documentation (not hard-coded triggers) allows FMA-sanctioned retention extensions without a schema migration

Consequences:

  • Deletion sweeps must query WHERE retain_until < date('now') — not automatic
  • Agents must calculate and populate retain_until correctly at insert; schema does not enforce correctness
  • audit_log is intentionally exempt — it is immutable and subject to a separate AIB retention policy

ADR-011: Production-Target Persistence on a Bank-Grade PostgreSQL-Compatible Engine

Status: Proposed

Context: ADR-001 chose SQLite/Cloudflare D1 for the AI-native agent stack. As a reference/mock persistence layer that is fine. But D1 (SQLite) is not a credible production core for a regulated Liechtenstein private bank, and the 99.95%/99.99% availability and RTO 15 min / RPO 5 min targets (REQ-NFR-001/REQ-NFR-002/REQ-NFR-003) need a transactional engine with synchronous-or-near-synchronous replication and automated failover. See aib-cloud-infrastructure-research §5.

Decision: The production-target core database is a bank-grade, PostgreSQL-wire-compatible engine — distributed SQL (CockroachDB; alternatively YugabyteDB) for the strongest RPO/RTO and exit-ability, or managed PostgreSQL (Aurora/AlloyDB/Azure PG Flexible) where a hyperscaler tier is used. ADR-001 is not superseded for the simulation: D1/SQLite remains the mock/reference store; schema.sql is unchanged.

Rationale:

  • CockroachDB delivers RPO=0 / RTO < 9 s via Raft quorum and is PCI-DSS L1 + SOC 2 Type II certified; Aurora Global Database delivers RPO in seconds / RPO=0 on managed failover — both clear the 15 min / 5 min target with headroom (verified June 2026).
  • PostgreSQL-wire compatibility + K8s self-hostability keeps the engine portable across sovereign and hyperscaler providers, directly supporting the DORA exit obligation (ADR-014).
  • Keeps the mock buildable on D1 while the documented target reflects real best-practice.

Consequences:

  • The production target diverges from the deployed mock; the schema must be expressed in portable SQL (the existing single-file DDL ports cleanly to Postgres with type adjustments).
  • Proprietary engines (Spanner, Aurora) maximise features but weaken exit-ability — preferred only for non-core or with a documented second source.
  • HA/failover design and a tested DR runbook become mandatory artifacts (Phase F).

ADR-012: Per-Workload Sovereignty Tiering (Two-Gate Model)

Status: Proposed

Context: AIB processes Liechtenstein banking-secrecy data under DORA, GDPR/DSG and sector-localisation rules (SPG/VVG/WPG). A single "all on one cloud" choice cannot satisfy both sovereignty and cost/maturity. See aib-cloud-infrastructure-research §2, §7.

Decision: Each workload passes two hard gates before cost/latency/maturity are scored: (1) a sovereignty floor on the EU Cloud Sovereignty Framework SEAL scale, and (2) DORA exit-ability + concentration risk. Client/PII core DB and the immutable audit log require SEAL-3 (CH-sovereign or EU-native); AML/trading/payments/reporting are sovereign-preferred (SEAL-2/3); analytics/MIS and burst AI may run hyperscaler-EU (SEAL-1/2). Any workload touching client-identifying data inherits the SEAL-3 floor.

Rationale:

  • The US CLOUD Act reaches data held by US-parent providers regardless of EU physical location; only EU/CH operation + customer-held keys insulates Bankgeheimnis data.
  • SEAL is the first auditable, EU-official sovereignty metric (binding in the €180m EU procurement, 17 Apr 2026); using it as a veto gate makes tiering defensible to the FMA.

Consequences:

  • Workload placement depends on AIB's own CIF designations in the DORA Register of Information — these must be confirmed first.
  • Some convenience/cost is sacrificed on CIF tiers; cost wins are confined to non-CIF workloads.

ADR-013: EU-/CH-Resident Key Management (XKS / HYOK)

Status: Proposed

Context: Encryption at rest with provider-held keys does not defeat the CLOUD Act — the provider can be compelled to use keys it possesses. REQ-REG-015 mandates AES-256 + EU/EEA residency; the conservative reading for client data is CLOUD-Act-immune key custody. See aib-cloud-infrastructure-research §5.

Decision: Key material for client/PII and audit data is held in an EU-/CH-resident HSM outside the hyperscaler via External Key Store (XKS) / Hold-Your-Own-Key — e.g. Securosys CloudsHSM (CH + DE) shipping the AWS XKS proxy + Azure BYOK, or Azure Managed HSM (FIPS 140-3 L3). TLS private keys at the edge use Cloudflare Keyless SSL (keys on AIB's HSM).

Rationale:

  • "The CLOUD Act becomes irrelevant when the provider never possesses your keys" — keys never leaving CH/EU jurisdiction satisfies the Schrems II technical-measure test.

Consequences:

  • Introduces an HSM availability dependency on the crypto path → the HSM must be HA and low-latency to the data plane; an HSM outage can block crypto operations.
  • Key-ceremony, rotation (quarterly per P6) and HSM DR become operational requirements.

ADR-014: Multi-Provider, Portable-by-Design (Concentration + DORA Exit)

Status: Proposed

Context: aib-ict-concentration-risk flags 100% Cloudflare for compute + primary DB + WAF as the highest, FMA-reportable risk. DORA Art. 28–30 + the subcontracting RTS (CDR (EU) 2025/532) require tested exit strategies and concentration-risk assessment; AWS/Azure/Google/IBM/Oracle are designated CTPPs (18 Nov 2025). See aib-cloud-infrastructure-research §6.

Decision: Split CIF workloads across a sovereign primary + a portable second source, built on Kubernetes + Terraform IaC + open/PG-wire engines so the workload and data can be repatriated within the contracted, tested exit window. Cloudflare is retained but demoted to edge-only (Regional Services + Keyless SSL), decoupled from the data plane.

Rationale:

  • Portability makes the legally-required DORA exit plan technically real and removes the existential single-provider dependency.
  • Separating edge from data plane keeps Cloudflare's DDoS/WAF value without concentrating data on a single US provider.

Consequences:

  • Higher design and operational complexity (cross-provider networking, dual-running for exit tests) and some loss of proprietary-PaaS convenience.
  • aib-ict-concentration-risk and the Art. 30 contracts/RoI must be updated to the multi-provider posture.

ADR-015: Immutable Audit Ledger via PostgreSQL + Hash Chain + WORM

Status: Proposed

Context: P5 and ADR-003 require an immutable, hash-chained, append-only audit trail (audit_log). The purpose-built managed option Amazon QLDB is retired (end-of-support 31 July 2025). See aib-cloud-infrastructure-research §5.

Decision: Implement the immutable audit ledger as PostgreSQL + pgAudit + application-level SHA-256 hash chain (prev_hash/row_hash) + Object-Lock Compliance-Mode WORM for the digest/archive, on a sovereign store. Managed alternative where Azure is in use: Azure SQL ledger tables / Azure Confidential Ledger (enclave, Merkle, ~$3/day from 1 Mar 2025).

Rationale:

  • Preserves the existing hash-chain design and the BEFORE UPDATE/DELETE abort triggers, portably and sovereignly.
  • Object Lock Compliance Mode is irreversible even to root — strong tamper-evidence for the 10-yr retention.
  • Avoids building on a retired service (QLDB excluded).

Consequences:

  • The DIY pattern shifts integrity-proof engineering onto AIB (verification tooling for the hash chain + digest receipts).
  • Compliance-Mode retention windows are irreversible — size them carefully.

ADR-016: DORA-Compliant AI Inference Around the Retained OpenRouter Gateway

Status: Proposed

Context: OpenRouter is the deliberate, standing LLM inference gateway for the Paperclip agents (it is not being replaced). DORA treats the LLM provider as an ICT third party requiring RoI registration + an exit plan; client PII must not leak to the model. See aib-cloud-infrastructure-research §5.

Decision: Retain OpenRouter and harden the pattern: EU base URL (https://eu.openrouter.ai) + enforced Zero Data Retention (zdr=true) + deny-data-collection, with bank-side PII redaction/tokenisation before the gateway, and an EU-sovereign LLM fallback (Mistral / Azure OpenAI EU Data Zone / Bedrock in AWS European Sovereign Cloud / self-hosted EU GPU for the most sensitive prompts).

Rationale:

  • Keeps inference in the EU with no retention, while data minimisation ensures no client-identifying data reaches the model.
  • OpenRouter as a swappable provider-abstraction layer improves DORA exit-ability (model/provider portability).

Consequences:

  • OpenRouter EU in-region routing is enterprise-gated by request → must be contracted, not assumed.
  • Residual CLOUD-Act risk on US-parent fallbacks → prefer Mistral-on-sovereign / self-hosted EU GPU for PII-bearing inference.
  • The gateway + each fallback must appear in the DORA Register of Information with exit terms.