# Fault-Tolerant Distributed Banking System Constitution
## Core Principles
### [PRINCIPLE_1_NAME]
<!-- Example: I. Library-First -->
[PRINCIPLE_1_DESCRIPTION]
<!-- Example: Every feature starts as a standalone library; Libraries must be self-contained, independently testable, documented; Clear purpose required - no organizational-only libraries -->
### I. Persistence & ACID Compliance
The system MUST use SQLite file-based persistence. All transactions MUST adhere to ACID properties. To handle SQLite's lack of row-level locking, the system MUST use `IMMEDIATE` transaction mode and a configured `busy_timeout` to ensure concurrent requests wait instead of failing.
### [PRINCIPLE_2_NAME]
<!-- Example: II. CLI Interface -->
[PRINCIPLE_2_DESCRIPTION]
<!-- Example: Every library exposes functionality via CLI; Text in/out protocol: stdin/args → stdout, errors → stderr; Support JSON + human-readable formats -->
### II. Client-Driven Sequencing
Sequence keys for transactions MUST be generated by the client, per account, and MUST be monotonically increasing to ensure idempotency and ordering.
### [PRINCIPLE_3_NAME]
<!-- Example: III. Test-First (NON-NEGOTIABLE) -->
[PRINCIPLE_3_DESCRIPTION]
<!-- Example: TDD mandatory: Tests written → User approved → Tests fail → Then implement; Red-Green-Refactor cycle strictly enforced -->
### III. Fault-Tolerant Server Design
The server MUST be designed to handle concurrent identical requests without duplicating transactions. Specifically, the debit operation and the update of `key_sequence_last` MUST occur within a single, atomic transaction.
### [PRINCIPLE_4_NAME]
<!-- Example: IV. Integration Testing -->
[PRINCIPLE_4_DESCRIPTION]
<!-- Example: Focus areas requiring integration tests: New library contract tests, Contract changes, Inter-service communication, Shared schemas -->
### IV. Deterministic Fault Injection
Fault injection MUST be implemented as configurable hook points within the server (pre-execution, mid-transaction, post-commit) and via middleware for request drops. Faults MUST be deterministic (e.g., "drop the first reply") to allow for reproducible testing.
### [PRINCIPLE_5_NAME]
<!-- Example: V. Observability, VI. Versioning & Breaking Changes, VII. Simplicity -->
No feature is accepted until it passes the defined testing policy. Automated tests, specifically covering fault scenarios, are a non-negotiable prerequisite for feature completion.
## [SECTION_2_NAME]
<!-- Example: Additional Constraints, Security Requirements, Performance Standards, etc. -->
The system MUST implement a layered testing approach:
1.**Unit Tests**: For core business logic and utility functions.
2.**Integration Tests**: To verify the interaction between the REST API, Hibernate, and the SQLite database.
3.**Fault-Injection Suite**: Dedicated tests that exercise the fault-injector hooks to verify system resilience.
4.**Concurrency Validation**: A specific test scenario involving many identical simultaneous requests MUST be implemented to prove that only one debit occurs.
### Concurrency & Error Handling
-**Concurrency**: Strict Locking (using `synchronized` blocks or `java.util.concurrent.locks`) MUST be used in conjunction with SQLite's `IMMEDIATE` transactions to ensure thread-safety.
-**Error Handling**: An exception-based (`try-catch`) strategy MUST be used, coupled with a global REST middleware to translate internal failures into standardized JSON error responses.
## Governance
<!-- Example: Constitution supersedes all other practices; Amendments require documentation, approval, migration plan -->
[GOVERNANCE_RULES]
<!-- Example: All PRs/reviews must verify compliance; Complexity must be justified; Use [GUIDANCE_FILE] for runtime development guidance -->
This constitution serves as the highest authority for project technical decisions. Any amendments to these principles MUST be documented, approved by stakeholders, and include a migration plan for existing implementations.
The system follows a classic client-server architecture. The server acts as the authoritative source of truth for account balances and transaction sequences, utilizing a local SQLite database for ACID-compliant persistence.
### 1.1 Component Responsibilities
#### Client
-**Request Generation**: Constructs transaction requests with monotonically increasing sequence keys.
-**Retry Logic**: Manages timeouts and retry attempts using a backoff strategy.
-**State Tracking**: Tracks pending transactions and manages the `retry_is` flag.
-**Validation**: Parses server acknowledgments to determine if a debit succeeded or if a retry is needed.
#### Server
-**Request Handling**: Validates transaction identity and sequence ordering.
-**Concurrency Control**: Uses Java synchronization (optimization) and SQLite `IMMEDIATE` transactions (primary mechanism) to prevent race conditions.
-**Business Logic**: Performs fund verification and executes debits.
-**Persistence**: Manages the account state, transaction history, and idempotency metadata.
-**Fault Injection**: Provides hooks to simulate failures (drop, crash, delay).
2. Server $\rightarrow$ SQLite: `BEGIN IMMEDIATE` $\rightarrow$ Validate $\rightarrow$ Debit $\rightarrow$ Update Sequence $\rightarrow$ Record History $\rightarrow$ `COMMIT`.
3. Server $\rightarrow$ Client: `TransactionAcknowledgment` (Status, BalanceSnapshot, SequenceKey, Error).
## 2. Technical Design
### 2.1 Technology Stack
-**Language**: Java 21.
-**Build System**: Maven.
-**Persistence**: Hibernate 6 with `sqlite-jdbc`.
-**Database**: SQLite (File-based).
-**Testing**: JUnit 5.
### 2.2 Database Schema Design
#### Account Table
-`account_id` (PK): Unique identifier.
-`balance`: Current funds.
-`key_sequence_last`: The last successfully committed sequence key.
#### Transaction History Table
-`transaction_id` (PK): Auto-increment.
-`account_id` (FK): Reference to Account.
-`sequence_key`: The sequence key processed.
-`idempotency_key`: The key provided by the client.
-`amount`: Debited amount.
-`balance_snapshot`: The balance immediately after the debit.
-`timestamp`: Execution time.
-**Constraint**: Unique constraint on `{account_id, sequence_key}`.
#### Idempotency Metadata Table
-`account_id` (PK/FK): Reference to Account.
-`sequence_key` (PK): The sequence key.
-`idempotency_key`: The bound idempotency key.
-**Constraint**: Unique constraint on `{account_id, idempotency_key}`.
-*Note*: This table tracks the binding of `Sequence Key` $\rightarrow$ `Idempotency Key` for all attempts.
### 2.3 Transaction Processing Strategy
#### Transaction Workflow
The entire validation and execution sequence MUST be wrapped in a single SQLite `BEGIN IMMEDIATE` transaction to prevent state changes between validation and commit.
1.**Identity Check (Read-only)**: Check if `{AccountID, SequenceKey}` exists in `Transaction History`.
-**If exists**: Return the original result and `balance_snapshot` (Historical Retry).
-**Creation**: A mapping is created in `Idempotency Metadata` the first time a `{Account ID, Sequence Key}` is processed.
-**Persistence**: This mapping is preserved regardless of whether the transaction succeeds (Commit) or fails (Insufficient Funds).
-**Commitment**: Once a transaction is committed to `Transaction History`, the metadata mapping remains as the authoritative link for that sequence key.
### 2.4 SQLite Concurrency and Lock Handling
#### Lock Acquisition
-**Hibernate Integration**: To execute `BEGIN IMMEDIATE`, the server MUST use a native SQL query (`session.createNativeQuery("BEGIN IMMEDIATE").executeUpdate()`) before any Hibernate-managed operations occur, ensuring Hibernate does not start a default `DEFERRED` transaction.
-**Timeout Configuration**: `busy_timeout` is configured via the JDBC connection string (e.g., `jdbc:sqlite:bank.db?busy_timeout=5000`) to ensure consistency across all database connections.
#### Lock Timeout Behavior
-**Error Handling**: If the lock cannot be acquired within the timeout, the server returns a "Database Busy" error.
-**Safety**: Since no state changes occur before the `COMMIT`, retries after a lock timeout are naturally idempotent.
## 3. Fault Tolerance & Recovery
| Failure | Recovery Mechanism |
| :--- | :--- |
| **Dropped Request** | Client timeout $\rightarrow$ Retry $\rightarrow$ Server treats as first-time request. |
| **Crash Before Commit** | SQLite ensures the transaction is rolled back. Retry $\rightarrow$ Server treats as first-time request. |
| **Crash After Commit** | Transaction is durable in SQLite. Retry $\rightarrow$ Server finds sequence in `Transaction History` $\rightarrow$ returns cached result. |
| **Delayed Response** | Client retries while original is processing. Server's `synchronized` block/`IMMEDIATE` lock ensures sequential processing $\rightarrow$ Retry finds committed result. |
## 4. Testing Strategy
### 4.1 Test Levels
-**Unit Tests**: Logic for sequence validation and identity matching.
-**Integration Tests**: Hibernate $\rightarrow$ SQLite interaction and `IMMEDIATE` lock behavior.
-**Concurrency Tests**: Using `CompletableFuture` to fire $N$ identical requests.
-**Fault-Injection Tests**: Using a `FaultInjector` class that can be configured to throw exceptions or drop responses at specific hook points.
-**Process-Level Tests**: Testing server restarts by starting/stopping the application process.
### 4.2 Mapping Specification Scenarios to Tests
-**Scenario 1-4**: Fault-injection suite simulating drops, crashes, and delays.
-**Scenario 5-6**: Concurrency suite verifying single-debit and consistent failure outcomes.
-**Scenario 7**: Functional test for funding $\rightarrow$ retry $\rightarrow$ amount change.
-**Scenario 8**: Integration test verifying historical record retrieval.
-**Scenario 9-10**: Validation tests for mismatched payloads and out-of-order keys.
-**Test Case**: Start a transaction that holds the lock $\rightarrow$ Fire a second request $\rightarrow$ Verify "Database Busy" error $\rightarrow$ Release first lock $\rightarrow$ Retry second request $\rightarrow$ Verify exactly one debit.
-**Scenario 13**: Validation test for Idempotency Key mapping conflicts.
### 5. Engineering Considerations
-**Locking Granularity**: Java `synchronized` blocks are an optimization to reduce database contention and prevent multiple threads from attempting to start an `IMMEDIATE` transaction for the same account. SQLite `IMMEDIATE` locking remains the primary concurrency mechanism.
-**Snapshotting**: The `balance_snapshot` must be captured inside the same transaction as the debit.
-**Fault Injection Points**:
-**Application Exception**: Throwing a `RuntimeException` inside the business logic (simulates app crash).
-**Process Crash**: Killing the JVM process (simulates OS/hardware crash after commit).
-**Response Drop**: Dropping the HTTP response before it reaches the client (simulates network failure).
-[x]**T2.4**: Verify schema creation and both uniqueness constraints (Sequence $\rightarrow$ ID and ID $\rightarrow$ Sequence) using integration tests.
## Phase 3: Core Transaction Foundation
-[x]**T3.1**: **Investigation**: Verify compatibility of `BEGIN IMMEDIATE` with Hibernate transaction lifecycle.
- Research JDBC connection identity and Hibernate's transaction start behavior.
- Verify that `BEGIN IMMEDIATE` occurs before any database reads/writes.
- Test commit/rollback behavior and ensure no conflicting transaction management.
-[x]**T3.2**: Implement the chosen atomic transaction wrapper based on T3.1 findings.
-[x]**T3.3**: Implement the atomic debit and `key_sequence_last` update logic. (Constitution III)
-[x]**T3.4**: Implement balance snapshot capture within the atomic transaction. (Plan 2.3)
-[x]**T3.5**: Verify atomic updates: a failed commit must rollback both balance and sequence key. (Verification)
## Phase 4: Idempotency and Sequence Validation
-[x]**T4.1**: Implement the `Transaction Identity` lookup in `Transaction History`. (Spec 2.1)