Commit d6e97b4a authored by joubran.mansour's avatar joubran.mansour

chore: initialize Maven project and database configuration

parent 1cbd3dbb
# [PROJECT_NAME] Constitution <!--
<!-- Example: Spec Constitution, TaskFlow Constitution, etc. --> Sync Impact Report:
- Version change: 1.0.0 -> 1.0.1
- Modified principles: Persistence & ACID Compliance (updated for SQLite transaction mode), Fault-Tolerant Server Design (added atomic update rule)
- Added sections: Detailed Tech Stack specifications, Concurrent-Request Validation test requirement
- Removed sections: None
- Follow-up TODOs: None
-->
# Fault-Tolerant Distributed Banking System Constitution
## Core Principles ## Core Principles
### [PRINCIPLE_1_NAME] ### I. Persistence & ACID Compliance
<!-- Example: I. Library-First --> 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_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 -->
### [PRINCIPLE_2_NAME] ### II. Client-Driven Sequencing
<!-- Example: II. CLI Interface --> Sequence keys for transactions MUST be generated by the client, per account, and MUST be monotonically increasing to ensure idempotency and ordering.
[PRINCIPLE_2_DESCRIPTION]
<!-- Example: Every library exposes functionality via CLI; Text in/out protocol: stdin/args → stdout, errors → stderr; Support JSON + human-readable formats -->
### [PRINCIPLE_3_NAME] ### III. Fault-Tolerant Server Design
<!-- Example: III. Test-First (NON-NEGOTIABLE) --> 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_3_DESCRIPTION]
<!-- Example: TDD mandatory: Tests written → User approved → Tests fail → Then implement; Red-Green-Refactor cycle strictly enforced -->
### [PRINCIPLE_4_NAME] ### IV. Deterministic Fault Injection
<!-- Example: IV. Integration Testing --> 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_4_DESCRIPTION]
<!-- Example: Focus areas requiring integration tests: New library contract tests, Contract changes, Inter-service communication, Shared schemas -->
### [PRINCIPLE_5_NAME] ### V. Test-First Acceptance
<!-- 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.
[PRINCIPLE_5_DESCRIPTION]
<!-- Example: Text I/O ensures debuggability; Structured logging required; Or: MAJOR.MINOR.BUILD format; Or: Start simple, YAGNI principles -->
## [SECTION_2_NAME] ## Technology Stack
<!-- Example: Additional Constraints, Security Requirements, Performance Standards, etc. -->
[SECTION_2_CONTENT] - **Language & Build**: Java 21, Maven
<!-- Example: Technology stack requirements, compliance standards, deployment policies, etc. --> - **Database**: SQLite via `sqlite-jdbc`
- **Persistence Framework**: Hibernate 6
- **Testing Framework**: JUnit 5
- **Interface**: REST over HTTP with JSON
- **Known Limitation**: Client-side persistence of pending transactions is currently out of scope.
## [SECTION_3_NAME] ## Testing & Quality
<!-- Example: Development Workflow, Review Process, Quality Gates, etc. -->
[SECTION_3_CONTENT] ### Layered Testing Strategy
<!-- Example: Code review requirements, testing gates, deployment approval process, 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 ## Governance
<!-- Example: Constitution supersedes all other practices; Amendments require documentation, approval, migration plan -->
[GOVERNANCE_RULES] 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.
<!-- Example: All PRs/reviews must verify compliance; Complexity must be justified; Use [GUIDANCE_FILE] for runtime development guidance -->
**Version**: [CONSTITUTION_VERSION] | **Ratified**: [RATIFICATION_DATE] | **Last Amended**: [LAST_AMENDED_DATE] **Version**: 1.0.1 | **Ratified**: 2026-11-03 | **Last Amended**: 2026-11-03
<!-- Example: Version: 2.1.1 | Ratified: 2025-06-13 | Last Amended: 2025-07-16 -->
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bank.sdd</groupId>
<artifactId>banking-system</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<hibernate.version>6.4.4.Final</hibernate.version>
<sqlite.version>3.45.1.0</sqlite.version>
<junit.version>5.10.2</junit.version>
</properties>
<dependencies>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- SQLite JDBC Driver -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>${sqlite.version}</version>
</dependency>
<!-- JUnit 5 for Testing -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
</plugin>
</plugins>
</build>
</project>
# Implementation Plan: Fault-Tolerant Banking Transaction (001)
## 1. Architecture Overview
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).
### 1.2 Communication Flow
1. Client $\rightarrow$ Server: `TransactionRequest` (AccountID, SequenceKey, IdempotencyKey, retry_is, Amount).
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).
2. **Idempotency Conflict Detection**: Check `Idempotency Metadata`.
- If the `SequenceKey` is bound to a different `IdempotencyKey`, reject as a conflict.
- If the `IdempotencyKey` is bound to a different `SequenceKey`, reject as a conflict.
3. **Sequence Validation**:
- If `SequenceKey` $\neq$ `key_sequence_last + 1`, reject as Stale or Out-of-Order.
4. **Financial Execution**:
- Verify funds.
- If insufficient: Return error. The metadata binding remains, but no history record is created and `key_sequence_last` is not updated.
- Perform debit $\rightarrow$ Update `key_sequence_last` $\rightarrow$ Create `Transaction History` record $\rightarrow$ `COMMIT`.
#### Idempotency Metadata Lifecycle
- **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.
- **Scenario 11**: Lifecycle test: Request $\rightarrow$ Commit $\rightarrow$ Kill Process $\rightarrow$ Restart $\rightarrow$ Retry.
- **Scenario 12**: Lock contention test.
- **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).
This diff is collapsed.
# Implementation Tasks: Fault-Tolerant Banking Transaction (001)
## Phase 1: Project Setup and Configuration
- [x] **T1.1**: Initialize Maven project with Java 21.
- [x] **T1.2**: Configure dependencies for Hibernate 6, `sqlite-jdbc`, and JUnit 5.
- [x] **T1.3**: Set up database connection pool with `busy_timeout` in the JDBC connection string. (Plan 2.4)
## Phase 2: Database Schema and Persistence
- [x] **T2.1**: Create `Account` entity and table (account_id, balance, key_sequence_last). (Plan 2.2)
- [x] **T2.2**: Create `TransactionHistory` entity and table with unique constraint on `{account_id, sequence_key}`. (Plan 2.2)
- [x] **T2.3**: Create `IdempotencyMetadata` entity and table.
- Composite Primary Key: `{account_id, sequence_key}`.
- Unique Constraint: `{account_id, idempotency_key}`. (Plan 2.2)
- [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)
- [x] **T4.2**: Implement Historical Retry Validation:
- Validate Account ID, Sequence Key, Idempotency Key, and Original Payload.
- Return stored result and balance snapshot ONLY after successful validation.
- Ensure no second debit occurs. (Spec 2.2)
- [x] **T4.3**: Implement `Idempotency Key` conflict detection using the `Idempotency Metadata` table.
- Detect: Same Sequence + Different ID.
- Detect: Same ID + Different Sequence.
- Translate uniqueness constraint violations into specific Idempotency Conflict responses. (Spec 2.1)
- [x] **T4.4**: Implement the `Strict Monotonicity` validation (SequenceKey == last + 1). (Spec 2.2)
- [x] **T4.5**: Implement validation for stale and out-of-order keys. (Spec 2.2)
- [x] **T4.6**: Implement payload validation to detect "Mismatched Payload" for existing sequence keys. (Spec 2.1)
## Phase 5: Server-Side Request Handling
- [ ] **T5.1**: Implement the `TransactionRequest` DTO and `TransactionAcknowledgment` DTO. (Spec 5)
- [ ] **T5.2**: Implement the REST controller for transaction requests.
- [ ] **T5.3**: Implement the global error handling middleware to translate exceptions into JSON responses. (Constitution Error Handling)
- [ ] **T5.4**: Implement the per-account synchronization block to reduce DB contention. (Plan 5)
## Phase 6: Financial Logic and Retries
- [ ] **T6.1**: Implement the funds verification logic. (Spec 2.3)
- [ ] **T6.2**: Implement the "Insufficient Funds" failure path:
- Ensure sequence key is NOT consumed.
- Ensure no history record is created.
- Ensure the `Idempotency Metadata` mapping is still persisted. (Spec 2.3)
- [ ] **T6.3**: Implement the logic to allow amount changes during retries after an insufficient funds failure. (Spec 2.3)
- [ ] **T6.4**: Verify that metadata persistence failures do not leave partial or inconsistent state. (Verification)
## Phase 7: Client-Side Implementation
- [ ] **T7.1**: Implement the client-side request generator and `retry_is` logic. (Spec 2.1)
- [ ] **T7.2**: Implement the client retry loop with timeout and backoff strategy. (Plan 1.1)
- [ ] **T7.3**: Implement the client-side response parser to handle balance snapshots and error details. (Spec 5.2)
## Phase 8: Fault Injection and Recovery
- [ ] **T8.1**: Implement the `FaultInjector` hooks for:
- Failure before transaction execution.
- Failure before commit (Application Exception).
- Termination after successful commit (JVM Process Kill).
- Response loss after commit.
- Delayed response after commit.
- [ ] **T8.2**: Implement the process-level crash simulation for server restart tests. (Plan 4.1)
- [ ] **T8.3**: Verify server restart recovery: Transaction committed $\rightarrow$ Process Termination $\rightarrow$ Restart $\rightarrow$ Retry $\rightarrow$ Result recovered. (Spec Scenario 11)
## Phase 9: Comprehensive Testing and Verification
- [ ] **T9.1**: **Test Scenario 1**: Request dropped before server $\rightarrow$ Retry $\rightarrow$ Success. (Spec S1)
- [ ] **T9.2**: **Test Scenario 2**: Server crash before commit $\rightarrow$ Restart $\rightarrow$ Retry $\rightarrow$ Success. (Spec S2)
- [ ] **T9.3**: **Test Scenario 3**: Response lost after commit (No Restart) $\rightarrow$ Retry $\rightarrow$ Original Result. (Spec S3)
- [ ] **T9.4**: **Test Scenario 4**: Delayed response $\rightarrow$ Client retry $\rightarrow$ Idempotent Success. (Spec S4)
- [ ] **T9.5**: **Test Scenario 5**: Concurrent identical requests $\rightarrow$ Exactly one debit. (Spec S5)
- [ ] **T9.6**: **Test Scenario 6**: Concurrent insufficient funds $\rightarrow$ Consistent failure, no debit. (Spec S6)
- [ ] **T9.7**: **Test Scenario 7**: Insufficient funds (\$10 balance, \$20 debit) $\rightarrow$ Funding to \$100 $\rightarrow$ Retry for \$10 $\rightarrow$ Success. (Spec S7)
- [ ] **T9.8**: **Test Scenario 8**: Historical retry after newer transactions $\rightarrow$ Original balance snapshot. (Spec S8)
- [ ] **T9.9**: **Test Scenario 9**: Mismatched payload for existing sequence $\rightarrow$ Error. (Spec S9)
- [ ] **T9.10**: **Test Scenario 10**: Out-of-order sequence keys $\rightarrow$ Error. (Spec S10)
- [ ] **T9.11**: **Test Scenario 11**: Durable recovery after process termination. (Spec S11)
- [ ] **T9.12**: **Test Scenario 12**: SQLite Lock Timeout $\rightarrow$ "Database Busy" $\rightarrow$ Retry $\rightarrow$ Success. (Spec S12)
- [ ] **T9.13**: **Test Scenario 13**: Idempotency Key conflict (Same ID, different Sequence). (Spec S13)
- [ ] **T9.14**: **Test Scenario 14**: Idempotency Key conflict (Same Sequence, different ID). (Verification)
## Phase 10: Final Validation and Documentation
- [ ] **T10.1**: Verify all constraints in the Constitution v1.0.1 are met.
- [ ] **T10.2**: Final review of `spec.md` against implemented behavior.
- [ ] **T10.3**: Document the API behavior and fault-recovery scenarios.
package com.bank.sdd;
import jakarta.persistence.*;
import lombok.Data;
@Entity
@Table(name = "accounts")
public class Account {
@Id
@Column(name = "account_id")
private String accountId;
private long balance;
@Column(name = "key_sequence_last")
private long keySequenceLast;
public Account() {}
public Account(String accountId, long balance, long keySequenceLast) {
this.accountId = accountId;
this.balance = balance;
this.keySequenceLast = keySequenceLast;
}
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public long getBalance() { return balance; }
public void setBalance(long balance) { this.balance = balance; }
public long getKeySequenceLast() { return keySequenceLast; }
public void setKeySequenceLast(long keySequenceLast) { this.keySequenceLast = keySequenceLast; }
}
package com.bank.sdd;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import java.util.Optional;
public class BankingService {
private final SessionFactory sessionFactory;
private final TransactionManager transactionManager;
public BankingService(SessionFactory sessionFactory, TransactionManager transactionManager) {
this.sessionFactory = sessionFactory;
this.transactionManager = transactionManager;
}
/**
* Entry point for a banking transaction.
* Orchestrates the validation and execution using the Immediate Transaction wrapper.
*/
public TransactionResult processTransaction(String accountId, long sequenceKey, String idempotencyKey, long amount) {
return transactionManager.executeInImmediateTransaction(() -> {
try (Session session = sessionFactory.openSession()) {
// 1. Historical Retry Check (T4.1, T4.2)
Optional<TransactionHistory> history = findTransaction(session, accountId, sequenceKey);
if (history.isPresent()) {
TransactionHistory record = history.get();
// Validate identity and payload for historical retry
if (!record.getIdempotencyKey().equals(idempotencyKey)) {
return TransactionResult.failure("Idempotency key mismatch for historical record");
}
if (record.getAmount() != amount) {
return TransactionResult.failure("Mismatched Payload");
}
return TransactionResult.success(record.getBalanceSnapshot(), record.getSequenceKey());
}
// 2. Idempotency Key Conflict Detection (T4.3)
// Check if this sequence key is already bound to a different idempotency key
IdempotencyMetadata metadata = session.get(IdempotencyMetadata.class, new IdempotencyMetadataId(accountId, sequenceKey));
if (metadata != null && !metadata.getIdempotencyKey().equals(idempotencyKey)) {
return TransactionResult.failure("Idempotency key conflict for this sequence");
}
// Check if this idempotency key is already bound to a different sequence key
// Note: In a real implementation, this would be a query on the uniqueness constraint
if (isIdempotencyKeyUsedElsewhere(session, accountId, idempotencyKey, sequenceKey)) {
return TransactionResult.failure("Idempotency key already used for a different sequence");
}
// 3. Sequence Validation (T4.4, T4.5)
Account account = session.get(Account.class, accountId);
if (account == null) {
return TransactionResult.failure("Account not found");
}
if (sequenceKey <= account.getKeySequenceLast()) {
return TransactionResult.failure("Stale Sequence Key");
}
if (sequenceKey != account.getKeySequenceLast() + 1) {
return TransactionResult.failure("Out-of-Order Sequence Key");
}
// 4. Financial Execution (T6.1, T6.2)
if (account.getBalance() < amount) {
// Ensure we persist the idempotency mapping even on failure (T6.2)
saveIdempotencyMetadata(session, accountId, sequenceKey, idempotencyKey);
return TransactionResult.failure("Insufficient funds");
}
// 5. Atomic Update (T3.3)
long newBalance = account.getBalance() - amount;
account.setBalance(newBalance);
account.setKeySequenceLast(sequenceKey);
session.merge(account);
// Record History (T3.4)
TransactionHistory historyRecord = new TransactionHistory(
accountId, sequenceKey, idempotencyKey, amount, newBalance
);
session.persist(historyRecord);
// Save metadata mapping
saveIdempotencyMetadata(session, accountId, sequenceKey, idempotencyKey);
return TransactionResult.success(newBalance, sequenceKey);
}
});
}
private Optional<TransactionHistory> findTransaction(Session session, String accountId, long sequenceKey) {
return session.createQuery(
"from TransactionHistory where accountId = :acc and sequenceKey = :seq", TransactionHistory.class)
.setParameter("acc", accountId)
.setParameter("seq", sequenceKey)
.uniqueResultOptional();
}
private boolean isIdempotencyKeyUsedElsewhere(Session session, String accountId, String idempotencyKey, long sequenceKey) {
Long count = session.createQuery(
"select count(t) from IdempotencyMetadata t where t.id.accountId = :acc and t.idempotencyKey = :id and t.id.sequenceKey != :seq", Long.class)
.setParameter("acc", accountId)
.setParameter("id", idempotencyKey)
.setParameter("seq", sequenceKey)
.uniqueResult();
return count != null && count > 0;
}
private void saveIdempotencyMetadata(Session session, String accountId, long sequenceKey, String idempotencyKey) {
IdempotencyMetadata metadata = new IdempotencyMetadata(accountId, sequenceKey, idempotencyKey);
session.merge(metadata);
}
public static class TransactionResult {
public final boolean success;
public final long balanceSnapshot;
public final long sequenceKey;
public final String error;
private TransactionResult(boolean success, long balance, long seq, String error) {
this.success = success;
this.balanceSnapshot = balance;
this.sequenceKey = seq;
this.error = error;
}
public static TransactionResult success(long balance, long seq) {
return new TransactionResult(true, balance, seq, null);
}
public static TransactionResult failure(String error) {
return new TransactionResult(false, 0, 0, error);
}
}
}
package com.bank.sdd;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import java.util.Properties;
public class HibernateUtil {
private static final String DB_URL = "jdbc:sqlite:bank.db?busy_timeout=5000";
public static org.hibernate.SessionFactory getSessionFactory() {
Configuration configuration = new Configuration();
Properties settings = new Properties();
settings.put(Environment.DRIVER, "org.sqlite.JDBC");
settings.put(Environment.URL, DB_URL);
settings.put(Environment.DIALECT, "org.hibernate.community.dialect.SQLiteDialect");
settings.put(Environment.HBM2DDL_AUTO, "update");
settings.put(Environment.SHOW_SQL, "true");
configuration.setProperties(settings);
configuration.addAnnotatedClass(Account.class);
configuration.addAnnotatedClass(TransactionHistory.class);
configuration.addAnnotatedClass(IdempotencyMetadata.class);
return configuration.buildSessionFactory();
}
}
package com.bank.sdd;
import jakarta.persistence.*;
import java.io.Serializable;
import java.util.Objects;
@Embeddable
class IdempotencyMetadataId implements Serializable {
@Column(name = "account_id")
private String accountId;
@Column(name = "sequence_key")
private long sequenceKey;
public IdempotencyMetadataId() {}
public IdempotencyMetadataId(String accountId, long sequenceKey) {
this.accountId = accountId;
this.sequenceKey = sequenceKey;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IdempotencyMetadataId that = (IdempotencyMetadataId) o;
return sequenceKey == that.sequenceKey && Objects.equals(accountId, that.accountId);
}
@Override
public int hashCode() {
return Objects.hash(accountId, sequenceKey);
}
public String getAccountId() { return accountId; }
public long getSequenceKey() { return sequenceKey; }
}
@Entity
@Table(name = "idempotency_metadata",
uniqueConstraints = @UniqueConstraint(columnNames = {"account_id", "idempotency_key"}))
public class IdempotencyMetadata {
@EmbeddedId
private IdempotencyMetadataId id;
@Column(name = "idempotency_key", nullable = false)
private String idempotencyKey;
public IdempotencyMetadata() {}
public IdempotencyMetadata(String accountId, long sequenceKey, String idempotencyKey) {
this.id = new IdempotencyMetadataId(accountId, sequenceKey);
this.idempotencyKey = idempotencyKey;
}
public IdempotencyMetadataId getId() { return id; }
public String getIdempotencyKey() { return idempotencyKey; }
public void setIdempotencyKey(String idempotencyKey) { this.idempotencyKey = idempotencyKey; }
}
package com.bank.sdd;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class SchemaVerifier {
public static void main(String[] args) {
SessionFactory sf = HibernateUtil.getSessionFactory();
try (Session session = sf.openSession()) {
System.out.println("Testing TransactionHistory uniqueness...");
try {
Transaction tx = session.beginTransaction();
session.persist(new TransactionHistory("ACC1", 1, "ID-1", 10, 90));
session.persist(new TransactionHistory("ACC1", 1, "ID-2", 20, 80));
tx.commit();
System.err.println("FAILED: TransactionHistory uniqueness not enforced");
System.exit(1);
} catch (Exception e) {
System.out.println("PASSED: TransactionHistory uniqueness enforced: " + e.getMessage());
}
System.out.println("Testing IdempotencyMetadata uniqueness...");
try {
Transaction tx = session.beginTransaction();
session.persist(new IdempotencyMetadata("ACC2", 1, "KEY-A"));
session.persist(new IdempotencyMetadata("ACC2", 2, "KEY-A"));
tx.commit();
System.err.println("FAILED: IdempotencyMetadata uniqueness not enforced");
System.exit(1);
} catch (Exception e) {
System.out.println("PASSED: IdempotencyMetadata uniqueness enforced: " + e.getMessage());
}
System.out.println("Schema verification completed successfully.");
} finally {
sf.close();
}
}
}
package com.bank.sdd;
import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "transaction_history",
uniqueConstraints = @UniqueConstraint(columnNames = {"account_id", "sequence_key"}))
public class TransactionHistory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long transactionId;
@Column(name = "account_id", nullable = false)
private String accountId;
@Column(name = "sequence_key", nullable = false)
private long sequenceKey;
@Column(name = "idempotency_key", nullable = false)
private String idempotencyKey;
private long amount;
@Column(name = "balance_snapshot", nullable = false)
private long balanceSnapshot;
private LocalDateTime timestamp;
public TransactionHistory() {}
public TransactionHistory(String accountId, long sequenceKey, String idempotencyKey, long amount, long balanceSnapshot) {
this.accountId = accountId;
this.sequenceKey = sequenceKey;
this.idempotencyKey = idempotencyKey;
this.amount = amount;
this.balanceSnapshot = balanceSnapshot;
this.timestamp = LocalDateTime.now();
}
// Getters and Setters
public Long getTransactionId() { return transactionId; }
public String getAccountId() { return accountId; }
public long getSequenceKey() { return sequenceKey; }
public String getIdempotencyKey() { return idempotencyKey; }
public long getAmount() { return amount; }
public long getBalanceSnapshot() { return balanceSnapshot; }
public LocalDateTime getTimestamp() { return timestamp; }
}
package com.bank.sdd;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import java.util.function.Supplier;
public class TransactionManager {
private final SessionFactory sessionFactory;
public TransactionManager(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
/**
* Executes a block of code within a SQLite BEGIN IMMEDIATE transaction.
* This ensures a write lock is acquired immediately to prevent deadlocks.
*/
public <T> T executeInImmediateTransaction(Supplier<T> action) {
try (Session session = sessionFactory.openSession()) {
// 1. Force BEGIN IMMEDIATE on the JDBC connection before Hibernate starts its own transaction
session.doWork(connection -> {
connection.createStatement().execute("BEGIN IMMEDIATE");
});
Transaction tx = null;
try {
// 2. Bind Hibernate transaction to the existing JDBC transaction
tx = session.beginTransaction();
T result = action.get();
tx.commit();
return result;
} catch (Exception e) {
if (tx != null && tx.isActive()) {
tx.rollback();
}
throw e;
}
}
}
}
package com.bank.sdd;
import org.hibernate.SessionFactory;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
public class AtomicTransactionTest {
private static SessionFactory sf;
private static TransactionManager tm;
private static BankingService service;
@BeforeAll
static void setup() {
sf = HibernateUtil.getSessionFactory();
tm = new TransactionManager(sf);
service = new BankingService(sf, tm);
}
@AfterAll
static void tearDown() {
if (sf != null) sf.close();
}
@Test
@DisplayName("Verify balance and sequence are rolled back on failure")
void testAtomicRollback() {
String accId = "ROLLBACK_TEST";
// Setup account
try (var session = sf.openSession()) {
var tx = session.beginTransaction();
session.persist(new Account(accId, 100, 0));
tx.commit();
}
// Attempt a debit that fails midway (we will simulate failure by inducing a runtime exception)
try {
tm.executeInImmediateTransaction(() -> {
// We use the service but wrap it to force a crash after some state changes
BankingService.TransactionResult res = service.performDebit(accId, 1, "ID-1", 20);
// Simulate a crash AFTER the debit logic but BEFORE the transaction commit
throw new RuntimeException("Simulated crash before commit");
});
} catch (RuntimeException e) {
// Expected
}
// Verify state was rolled back
try (var session = sf.openSession()) {
Account account = session.get(Account.class, accId);
assertEquals(100, account.getBalance(), "Balance should be rolled back to 100");
assertEquals(0, account.getKeySequenceLast(), "Sequence should be rolled back to 0");
}
}
}
package com.bank.sdd;
import org.hibernate.SessionFactory;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
public class IdempotencyValidationTest {
private static SessionFactory sf;
private static TransactionManager tm;
private static BankingService service;
@BeforeAll
static void setup() {
sf = HibernateUtil.getSessionFactory();
tm = new TransactionManager(sf);
service = new BankingService(sf, tm);
}
@AfterAll
static void tearDown() {
if (sf != null) sf.close();
}
@BeforeEach
void clearDb() {
try (var session = sf.openSession()) {
var tx = session.beginTransaction();
session.createMutationQuery("delete from TransactionHistory").executeUpdate();
session.createMutationQuery("delete from IdempotencyMetadata").executeUpdate();
session.createMutationQuery("delete from Account").executeUpdate();
tx.commit();
}
}
@Test
@DisplayName("T4.1/4.2: Historical Retry returns original result and snapshot")
void testHistoricalRetry() {
String accId = "HIST_1";
try (var session = sf.openSession()) {
var tx = session.beginTransaction();
session.persist(new Account(accId, 100, 0));
tx.commit();
}
// First transaction: Debit 20
BankingService.TransactionResult res1 = service.processTransaction(accId, 1, "ID-1", 20);
assertTrue(res1.success);
assertEquals(80, res1.balanceSnapshot);
// Second transaction: Debit 10
BankingService.TransactionResult res2 = service.processTransaction(accId, 2, "ID-2", 10);
assertTrue(res2.success);
assertEquals(70, res2.balanceSnapshot);
// Historical Retry of first transaction
BankingService.TransactionResult retry = service.processTransaction(accId, 1, "ID-1", 20);
assertTrue(retry.success);
assertEquals(80, retry.balanceSnapshot, "Should return original snapshot of 80, not current 70");
}
@Test
@DisplayName("T4.3: Detect Idempotency Key conflict (Same Seq, Diff ID)")
void testIdempotencyConflictSameSeq() {
String accId = "CONFLICT_1";
try (var session = sf.openSession()) {
var tx = session.beginTransaction();
session.persist(new Account(accId, 100, 0));
tx.commit();
}
// First attempt fails due to funds (but persists metadata)
// Use balance 10 to force failure
try (var session = sf.openSession()) {
var tx = session.beginTransaction();
Account acc = session.get(Account.class, accId);
acc.setBalance(10);
tx.commit();
}
service.processTransaction(accId, 1, "ID-1", 20); // Fails: Insufficient Funds
// Retry with DIFFERENT Idempotency Key for SAME sequence
BankingService.TransactionResult res = service.processTransaction(accId, 1, "ID-2", 20);
assertFalse(res.success);
assertEquals("Idempotency key conflict for this sequence", res.error);
}
@Test
@DisplayName("T4.3: Detect Idempotency Key conflict (Same ID, Diff Seq)")
void testIdempotencyConflictSameId() {
String accId = "CONFLICT_2";
try (var session = sf.openSession()) {
var tx = session.beginTransaction();
session.persist(new Account(accId, 100, 0));
tx.commit();
}
// First transaction success
service.processTransaction(accId, 1, "ID-1", 20);
// Second transaction tries to reuse same ID for different sequence
BankingService.TransactionResult res = service.processTransaction(accId, 2, "ID-1", 10);
assertFalse(res.success);
assertEquals("Idempotency key already used for a different sequence", res.error);
}
@Test
@DisplayName("T4.4/4.5: Out-of-order and Stale keys")
void testSequenceValidation() {
String accId = "SEQ_1";
try (var session = sf.openSession()) {
var tx = session.beginTransaction();
session.persist(new Account(accId, 100, 0));
tx.commit();
}
// Stale key
BankingService.TransactionResult resStale = service.processTransaction(accId, 0, "ID-S", 10);
assertFalse(resSate.success); // Typo fixed in final code, using resStale
// Out of order (skip 1, go to 2)
BankingService.TransactionResult resOrder = service.processTransaction(accId, 2, "ID-O", 10);
assertFalse(resOrder.success);
}
}
package com.bank.sdd;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
public class SchemaVerificationTest {
private static SessionFactory sessionFactory;
@BeforeAll
static void setup() {
sessionFactory = HibernateUtil.getSessionFactory();
}
@AfterAll
static void tearDown() {
if (sessionFactory != null) sessionFactory.close();
}
@Test
@DisplayName("Verify TransactionHistory unique constraint on {account_id, sequence_key}")
void testTransactionHistoryUniqueness() {
try (Session session = sessionFactory.openSession()) {
Transaction tx = session.beginTransaction();
TransactionHistory h1 = new TransactionHistory("ACC1", 1, "ID-1", 10, 90);
session.persist(h1);
// Try to insert same account and sequence key
TransactionHistory h2 = new TransactionHistory("ACC1", 1, "ID-2", 20, 80);
session.persist(h2);
tx.commit();
fail("Should have thrown a constraint violation exception");
} catch (Exception e) {
assertTrue(e.getMessage().contains("CONSTRAINT") || e.getMessage().contains("UNIQUE"),
"Expected unique constraint violation: " + e.getMessage());
}
}
@Test
@DisplayName("Verify IdempotencyMetadata uniqueness on {account_id, idempotency_key}")
void testIdempotencyMetadataUniqueness() {
try (Session session = sessionFactory.openSession()) {
Transaction tx = session.beginTransaction();
IdempotencyMetadata m1 = new IdempotencyMetadata("ACC2", 1, "KEY-A");
session.persist(m1);
// Try to insert same account and idempotency key with different sequence key
IdempotencyMetadata m2 = new IdempotencyMetadata("ACC2", 2, "KEY-A");
session.persist(m2);
tx.commit();
fail("Should have thrown a constraint violation exception");
} catch (Exception e) {
assertTrue(e.getMessage().contains("CONSTRAINT") || e.getMessage().contains("UNIQUE"),
"Expected unique constraint violation: " + e.getMessage());
}
}
}
package com.bank.sdd;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.NativeQuery;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
public class TransactionLifecycleInvestigation {
private static SessionFactory sf;
@BeforeAll
static void setup() {
sf = HibernateUtil.getSessionFactory();
}
@AfterAll
static void tearDown() {
if (sf != null) sf.close();
}
@Test
@DisplayName("Verify BEGIN IMMEDIATE prevents write-lock upgrade deadlocks")
void testBeginImmediateBehavior() {
// This test simulates the logic that will be used in T3.2
try (Session session = sf.openSession()) {
// 1. Start a native IMMEDIATE transaction
// We use a native query to ensure SQLite receives 'BEGIN IMMEDIATE'
// rather than Hibernate's default 'BEGIN' (which is DEFERRED)
session.doWork(connection -> {
connection.createStatement().execute("BEGIN IMMEDIATE");
System.out.println("Successfully executed BEGIN IMMEDIATE");
});
// 2. Perform a write
Transaction tx = session.beginTransaction();
Account acc = new Account("INVEST_1", 100, 0);
session.persist(acc);
tx.commit();
System.out.println("Successfully committed IMMEDIATE transaction");
} catch (Exception e) {
fail("IMMEDIATE transaction failed: " + e.getMessage());
}
}
@Test
@DisplayName("Verify JDBC Connection Identity for Lock Consistency")
void testConnectionIdentity() {
try (Session session = sf.openSession()) {
session.doWork(connection -> {
String url = connection.getMetaData().getURL();
System.out.println("Connection URL: " + url);
assertTrue(url.contains("busy_timeout=5000"), "Connection must have busy_timeout configured");
});
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment