reddb-io-server 1.1.0

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
//! Transaction Coordinator
//!
//! Central coordinator for transaction lifecycle management.

use super::lock::{LockManager, LockMode, LockResult};
use super::log::{TransactionLog, WalConfig};
use super::savepoint::TxnSavepoints;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::time::{Duration, Instant};

/// Transaction ID
pub type TxnId = u64;

/// Timestamp
pub type Timestamp = u64;

fn tx_lock_error(context: &'static str) -> TxnError {
    TxnError::Internal(format!("{context} lock poisoned"))
}

fn read_guard_or_err<'a, T>(
    lock: &'a RwLock<T>,
    context: &'static str,
) -> Result<RwLockReadGuard<'a, T>, TxnError> {
    lock.read().map_err(|_| tx_lock_error(context))
}

fn write_guard_or_err<'a, T>(
    lock: &'a RwLock<T>,
    context: &'static str,
) -> Result<RwLockWriteGuard<'a, T>, TxnError> {
    lock.write().map_err(|_| tx_lock_error(context))
}

fn recover_read_guard<'a, T>(lock: &'a RwLock<T>) -> RwLockReadGuard<'a, T> {
    match lock.read() {
        Ok(guard) => guard,
        Err(poisoned) => poisoned.into_inner(),
    }
}

fn recover_write_guard<'a, T>(lock: &'a RwLock<T>) -> RwLockWriteGuard<'a, T> {
    match lock.write() {
        Ok(guard) => guard,
        Err(poisoned) => poisoned.into_inner(),
    }
}

/// Transaction error types
#[derive(Debug, Clone)]
pub enum TxnError {
    /// Transaction not found
    NotFound(TxnId),
    /// Transaction already committed
    AlreadyCommitted(TxnId),
    /// Transaction already aborted
    AlreadyAborted(TxnId),
    /// Write-write conflict
    WriteConflict { key: Vec<u8>, holder: TxnId },
    /// Deadlock detected
    Deadlock(Vec<TxnId>),
    /// Lock limit exceeded
    LockLimitExceeded { limit: usize },
    /// Lock timeout
    LockTimeout { key: Vec<u8>, timeout: Duration },
    /// Validation failed (optimistic)
    ValidationFailed {
        key: Vec<u8>,
        expected_ts: Timestamp,
        actual_ts: Timestamp,
    },
    /// WAL error
    LogError(String),
    /// Savepoint not found
    SavepointNotFound(String),
    /// Transaction timeout
    Timeout(TxnId),
    /// Internal error
    Internal(String),
}

impl std::fmt::Display for TxnError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TxnError::NotFound(id) => write!(f, "Transaction {} not found", id),
            TxnError::AlreadyCommitted(id) => write!(f, "Transaction {} already committed", id),
            TxnError::AlreadyAborted(id) => write!(f, "Transaction {} already aborted", id),
            TxnError::WriteConflict { key, holder } => {
                write!(f, "Write conflict on {:?}, held by txn {}", key, holder)
            }
            TxnError::Deadlock(cycle) => write!(f, "Deadlock detected: {:?}", cycle),
            TxnError::LockLimitExceeded { limit } => {
                write!(f, "Lock limit exceeded: max {}", limit)
            }
            TxnError::LockTimeout { key, timeout } => {
                write!(f, "Lock timeout on {:?} after {:?}", key, timeout)
            }
            TxnError::ValidationFailed {
                key,
                expected_ts,
                actual_ts,
            } => {
                write!(
                    f,
                    "Validation failed for {:?}: expected ts {}, actual {}",
                    key, expected_ts, actual_ts
                )
            }
            TxnError::LogError(msg) => write!(f, "WAL error: {}", msg),
            TxnError::SavepointNotFound(name) => write!(f, "Savepoint '{}' not found", name),
            TxnError::Timeout(id) => write!(f, "Transaction {} timed out", id),
            TxnError::Internal(msg) => write!(f, "Internal error: {}", msg),
        }
    }
}

impl std::error::Error for TxnError {}

/// Transaction state
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TxnState {
    /// Active and running
    Active,
    /// Preparing to commit (2PC)
    Preparing,
    /// Committed
    Committed,
    /// Aborted
    Aborted,
}

/// Isolation level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IsolationLevel {
    /// Read uncommitted (no isolation)
    ReadUncommitted,
    /// Read committed (see committed values)
    ReadCommitted,
    /// Repeatable read / Snapshot isolation
    #[default]
    SnapshotIsolation,
    /// Serializable (full isolation)
    Serializable,
}

/// Transaction configuration
#[derive(Debug, Clone)]
pub struct TxnConfig {
    /// Default isolation level
    pub isolation_level: IsolationLevel,
    /// Lock timeout
    pub lock_timeout: Duration,
    /// Transaction timeout
    pub txn_timeout: Duration,
    /// Enable optimistic concurrency
    pub optimistic: bool,
    /// Enable WAL
    pub wal_enabled: bool,
    /// WAL sync mode
    pub wal_sync: WalSyncMode,
}

/// WAL sync mode
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WalSyncMode {
    /// Sync on every commit (safest, slowest)
    EveryCommit,
    /// Sync periodically (balance)
    Periodic(Duration),
    /// Don't sync (fastest, least safe)
    None,
}

impl TxnConfig {
    /// Create default config
    pub fn new() -> Self {
        Self {
            isolation_level: IsolationLevel::SnapshotIsolation,
            lock_timeout: Duration::from_secs(30),
            txn_timeout: Duration::from_secs(300),
            optimistic: true,
            wal_enabled: true,
            wal_sync: WalSyncMode::EveryCommit,
        }
    }

    /// Set isolation level
    pub fn with_isolation(mut self, level: IsolationLevel) -> Self {
        self.isolation_level = level;
        self
    }

    /// Set lock timeout
    pub fn with_lock_timeout(mut self, timeout: Duration) -> Self {
        self.lock_timeout = timeout;
        self
    }

    /// Enable/disable optimistic concurrency
    pub fn with_optimistic(mut self, enabled: bool) -> Self {
        self.optimistic = enabled;
        self
    }
}

impl Default for TxnConfig {
    fn default() -> Self {
        Self::new()
    }
}

/// Transaction handle (returned to callers)
#[derive(Debug, Clone)]
pub struct TxnHandle {
    /// Transaction ID
    pub id: TxnId,
    /// Start timestamp
    pub start_ts: Timestamp,
    /// Isolation level
    pub isolation: IsolationLevel,
}

impl TxnHandle {
    /// Get transaction ID
    pub fn id(&self) -> TxnId {
        self.id
    }

    /// Get start timestamp
    pub fn start_ts(&self) -> Timestamp {
        self.start_ts
    }
}

/// Internal transaction state
struct TransactionState {
    /// Transaction handle info
    handle: TxnHandle,
    /// Current state
    state: TxnState,
    /// Start time
    start_time: Instant,
    /// Read set (keys read)
    read_set: Vec<(Vec<u8>, Timestamp)>,
    /// Write set (keys written with old values for rollback)
    write_set: Vec<WriteEntry>,
    /// Savepoints (per-transaction)
    savepoints: TxnSavepoints,
    /// Locks held
    locks_held: Vec<Vec<u8>>,
}

/// Write set entry
#[derive(Debug, Clone)]
struct WriteEntry {
    /// Key
    key: Vec<u8>,
    /// Old value (for rollback)
    old_value: Option<Vec<u8>>,
    /// New value
    new_value: Option<Vec<u8>>,
    /// Operation timestamp
    timestamp: Timestamp,
}

/// Active transaction representation
pub struct Transaction {
    /// Transaction ID
    id: TxnId,
    /// Coordinator reference
    coordinator: Arc<TransactionManager>,
}

impl Transaction {
    /// Get transaction ID
    pub fn id(&self) -> TxnId {
        self.id
    }

    /// Record a read
    pub fn record_read(&self, key: &[u8], read_ts: Timestamp) {
        self.coordinator.record_read(self.id, key, read_ts);
    }

    /// Record a write
    pub fn record_write(&self, key: &[u8], old_value: Option<&[u8]>, new_value: Option<&[u8]>) {
        self.coordinator
            .record_write(self.id, key, old_value, new_value);
    }

    /// Create savepoint
    pub fn savepoint(&self, name: &str) -> Result<(), TxnError> {
        self.coordinator.create_savepoint(self.id, name)
    }

    /// Rollback to savepoint
    pub fn rollback_to(&self, name: &str) -> Result<(), TxnError> {
        self.coordinator.rollback_to_savepoint(self.id, name)
    }

    /// Commit transaction
    pub fn commit(self) -> Result<(), TxnError> {
        self.coordinator.commit(self.id)
    }

    /// Abort transaction
    pub fn abort(self) -> Result<(), TxnError> {
        self.coordinator.abort(self.id)
    }
}

/// Transaction manager
pub struct TransactionManager {
    /// Configuration
    config: TxnConfig,
    /// Next transaction ID
    next_id: AtomicU64,
    /// Current timestamp
    current_ts: AtomicU64,
    /// Active transactions
    transactions: RwLock<HashMap<TxnId, TransactionState>>,
    /// Lock manager
    lock_manager: LockManager,
    /// Transaction log
    log: Option<TransactionLog>,
    /// Committed timestamps per key (for validation)
    committed_ts: RwLock<HashMap<Vec<u8>, Timestamp>>,
}

impl TransactionManager {
    /// Create new transaction manager
    pub fn new(config: TxnConfig) -> Self {
        let log = if config.wal_enabled {
            Some(TransactionLog::new(WalConfig::default()))
        } else {
            None
        };

        Self {
            config,
            next_id: AtomicU64::new(1),
            current_ts: AtomicU64::new(1),
            transactions: RwLock::new(HashMap::new()),
            lock_manager: LockManager::with_defaults(),
            log: log.and_then(|r| r.ok()),
            committed_ts: RwLock::new(HashMap::new()),
        }
    }

    /// Create with default config
    pub fn with_default_config() -> Self {
        Self::new(TxnConfig::default())
    }

    /// Get configuration
    pub fn config(&self) -> &TxnConfig {
        &self.config
    }

    /// Get next timestamp
    fn next_timestamp(&self) -> Timestamp {
        self.current_ts.fetch_add(1, Ordering::SeqCst)
    }

    /// Begin a new transaction
    pub fn begin(&self) -> TxnHandle {
        self.begin_with_isolation(self.config.isolation_level)
    }

    /// Begin transaction with specific isolation level
    pub fn begin_with_isolation(&self, isolation: IsolationLevel) -> TxnHandle {
        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
        let start_ts = self.next_timestamp();

        let handle = TxnHandle {
            id,
            start_ts,
            isolation,
        };

        let state = TransactionState {
            handle: handle.clone(),
            state: TxnState::Active,
            start_time: Instant::now(),
            read_set: Vec::new(),
            write_set: Vec::new(),
            savepoints: TxnSavepoints::new(id),
            locks_held: Vec::new(),
        };

        // Log transaction begin
        if let Some(ref log) = self.log {
            let _ = log.log_begin(id);
        }

        recover_write_guard(&self.transactions).insert(id, state);

        handle
    }

    /// Begin with Transaction wrapper
    pub fn begin_transaction(self: &Arc<Self>) -> Transaction {
        let handle = self.begin();
        Transaction {
            id: handle.id,
            coordinator: Arc::clone(self),
        }
    }

    /// Record a read operation
    pub fn record_read(&self, txn_id: TxnId, key: &[u8], read_ts: Timestamp) {
        let mut txns = recover_write_guard(&self.transactions);
        if let Some(state) = txns.get_mut(&txn_id) {
            if state.state == TxnState::Active {
                state.read_set.push((key.to_vec(), read_ts));
            }
        }
    }

    /// Record a write operation
    pub fn record_write(
        &self,
        txn_id: TxnId,
        key: &[u8],
        old_value: Option<&[u8]>,
        new_value: Option<&[u8]>,
    ) {
        let timestamp = self.next_timestamp();

        let mut txns = recover_write_guard(&self.transactions);
        if let Some(state) = txns.get_mut(&txn_id) {
            if state.state == TxnState::Active {
                let entry = WriteEntry {
                    key: key.to_vec(),
                    old_value: old_value.map(|v| v.to_vec()),
                    new_value: new_value.map(|v| v.to_vec()),
                    timestamp,
                };

                // Log the write
                if let Some(ref log) = self.log {
                    if let Some(old) = old_value {
                        if let Some(new) = new_value {
                            let _ =
                                log.log_update(txn_id, key.to_vec(), old.to_vec(), new.to_vec());
                        } else {
                            let _ = log.log_delete(txn_id, key.to_vec(), old.to_vec());
                        }
                    } else if let Some(new) = new_value {
                        let _ = log.log_insert(txn_id, key.to_vec(), new.to_vec());
                    }
                }

                state.write_set.push(entry);
            }
        }
    }

    /// Acquire lock for key
    pub fn acquire_lock(&self, txn_id: TxnId, key: &[u8], mode: LockMode) -> Result<(), TxnError> {
        // Check transaction is active
        {
            let txns = read_guard_or_err(&self.transactions, "transaction manager state")?;
            let state = txns.get(&txn_id).ok_or(TxnError::NotFound(txn_id))?;
            if state.state != TxnState::Active {
                return Err(TxnError::AlreadyAborted(txn_id));
            }
        }

        // Try to acquire lock with timeout
        match self
            .lock_manager
            .acquire_with_timeout(txn_id, key, mode, self.config.lock_timeout)
        {
            LockResult::Granted | LockResult::Upgraded | LockResult::AlreadyHeld => {
                // Record lock (even if already held - idempotent)
                let mut txns = write_guard_or_err(&self.transactions, "transaction manager state")?;
                if let Some(state) = txns.get_mut(&txn_id) {
                    if !state.locks_held.contains(&key.to_vec()) {
                        state.locks_held.push(key.to_vec());
                    }
                }
                Ok(())
            }
            LockResult::Waiting => {
                // This shouldn't happen with acquire_with_timeout (it blocks)
                Err(TxnError::Internal(
                    "Lock returned Waiting unexpectedly".to_string(),
                ))
            }
            LockResult::Timeout => Err(TxnError::LockTimeout {
                key: key.to_vec(),
                timeout: self.config.lock_timeout,
            }),
            LockResult::Deadlock(cycle) => Err(TxnError::Deadlock(cycle)),
            LockResult::LockLimitExceeded => Err(TxnError::LockLimitExceeded {
                limit: self.lock_manager.config().max_locks_per_txn,
            }),
            LockResult::TxnNotFound => Err(TxnError::NotFound(txn_id)),
        }
    }

    /// Release all locks for transaction
    fn release_locks(&self, txn_id: TxnId) {
        let locks = {
            let txns = recover_read_guard(&self.transactions);
            txns.get(&txn_id)
                .map(|s| s.locks_held.clone())
                .unwrap_or_default()
        };

        for key in locks {
            self.lock_manager.release(txn_id, &key);
        }
    }

    /// Validate transaction (optimistic concurrency check)
    fn validate(&self, txn_id: TxnId) -> Result<(), TxnError> {
        let txns = read_guard_or_err(&self.transactions, "transaction manager state")?;
        let state = txns.get(&txn_id).ok_or(TxnError::NotFound(txn_id))?;

        if !self.config.optimistic {
            return Ok(());
        }

        let committed = read_guard_or_err(&self.committed_ts, "transaction manager committed_ts")?;

        // Check read set: no key was modified since we read it
        for (key, read_ts) in &state.read_set {
            if let Some(&commit_ts) = committed.get(key) {
                if commit_ts > *read_ts && commit_ts > state.handle.start_ts {
                    return Err(TxnError::ValidationFailed {
                        key: key.clone(),
                        expected_ts: *read_ts,
                        actual_ts: commit_ts,
                    });
                }
            }
        }

        Ok(())
    }

    /// Commit transaction
    pub fn commit(&self, txn_id: TxnId) -> Result<(), TxnError> {
        // Validate
        self.validate(txn_id)?;

        let commit_ts = self.next_timestamp();

        // Update state to committed
        {
            let mut txns = write_guard_or_err(&self.transactions, "transaction manager state")?;
            let state = txns.get_mut(&txn_id).ok_or(TxnError::NotFound(txn_id))?;

            match state.state {
                TxnState::Active | TxnState::Preparing => {
                    state.state = TxnState::Committed;
                }
                TxnState::Committed => return Err(TxnError::AlreadyCommitted(txn_id)),
                TxnState::Aborted => return Err(TxnError::AlreadyAborted(txn_id)),
            }

            // Update committed timestamps for written keys
            let mut committed =
                write_guard_or_err(&self.committed_ts, "transaction manager committed_ts")?;
            for entry in &state.write_set {
                committed.insert(entry.key.clone(), commit_ts);
            }
        }

        // Log commit
        if let Some(ref log) = self.log {
            let _ = log.log_commit(txn_id);

            // Flush if configured
            if matches!(self.config.wal_sync, WalSyncMode::EveryCommit) {
                let _ = log.flush();
            }
        }

        // Release locks
        self.release_locks(txn_id);

        Ok(())
    }

    /// Abort transaction
    pub fn abort(&self, txn_id: TxnId) -> Result<(), TxnError> {
        // Update state to aborted
        {
            let mut txns = write_guard_or_err(&self.transactions, "transaction manager state")?;
            let state = txns.get_mut(&txn_id).ok_or(TxnError::NotFound(txn_id))?;

            match state.state {
                TxnState::Active | TxnState::Preparing => {
                    state.state = TxnState::Aborted;
                }
                TxnState::Committed => return Err(TxnError::AlreadyCommitted(txn_id)),
                TxnState::Aborted => return Err(TxnError::AlreadyAborted(txn_id)),
            }
        }

        // Log abort
        if let Some(ref log) = self.log {
            let _ = log.log_abort(txn_id);
        }

        // Release locks
        self.release_locks(txn_id);

        Ok(())
    }

    /// Create savepoint
    pub fn create_savepoint(&self, txn_id: TxnId, name: &str) -> Result<(), TxnError> {
        let mut txns = write_guard_or_err(&self.transactions, "transaction manager state")?;
        let state = txns.get_mut(&txn_id).ok_or(TxnError::NotFound(txn_id))?;

        if state.state != TxnState::Active {
            return Err(TxnError::AlreadyAborted(txn_id));
        }

        let write_set_index = state.write_set.len();
        let lock_count = state.locks_held.len();
        // Use 0 for LSN - coordinator doesn't track LSNs at this level
        state
            .savepoints
            .create(name.to_string(), 0, lock_count, write_set_index);

        Ok(())
    }

    /// Rollback to savepoint
    pub fn rollback_to_savepoint(&self, txn_id: TxnId, name: &str) -> Result<(), TxnError> {
        let mut txns = write_guard_or_err(&self.transactions, "transaction manager state")?;
        let state = txns.get_mut(&txn_id).ok_or(TxnError::NotFound(txn_id))?;

        if state.state != TxnState::Active {
            return Err(TxnError::AlreadyAborted(txn_id));
        }

        let savepoint = state
            .savepoints
            .get(name)
            .ok_or_else(|| TxnError::SavepointNotFound(name.to_string()))?;

        // Truncate write set to savepoint
        state.write_set.truncate(savepoint.write_set_index);

        // Remove savepoint and all after it
        state.savepoints.release(name);

        Ok(())
    }

    /// Get transaction state
    pub fn get_state(&self, txn_id: TxnId) -> Option<TxnState> {
        self.transactions
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .get(&txn_id)
            .map(|s| s.state)
    }

    /// Check if transaction is active
    pub fn is_active(&self, txn_id: TxnId) -> bool {
        self.get_state(txn_id) == Some(TxnState::Active)
    }

    /// Get active transaction count
    pub fn active_count(&self) -> usize {
        self.transactions
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .values()
            .filter(|s| s.state == TxnState::Active)
            .count()
    }

    /// Get oldest active transaction timestamp
    pub fn oldest_active_ts(&self) -> Option<Timestamp> {
        self.transactions
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .values()
            .filter(|s| s.state == TxnState::Active)
            .map(|s| s.handle.start_ts)
            .min()
    }

    /// Cleanup finished transactions
    pub fn cleanup(&self, max_age: Duration) {
        let mut txns = recover_write_guard(&self.transactions);
        let now = Instant::now();

        txns.retain(|_, state| {
            if state.state == TxnState::Active {
                true
            } else {
                now.duration_since(state.start_time) < max_age
            }
        });
    }
}

impl Default for TransactionManager {
    fn default() -> Self {
        Self::with_default_config()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_begin_commit() {
        let tm = TransactionManager::with_default_config();

        let handle = tm.begin();
        assert!(tm.is_active(handle.id));

        tm.commit(handle.id).unwrap();
        assert!(!tm.is_active(handle.id));
        assert_eq!(tm.get_state(handle.id), Some(TxnState::Committed));
    }

    #[test]
    fn test_begin_abort() {
        let tm = TransactionManager::with_default_config();

        let handle = tm.begin();
        assert!(tm.is_active(handle.id));

        tm.abort(handle.id).unwrap();
        assert!(!tm.is_active(handle.id));
        assert_eq!(tm.get_state(handle.id), Some(TxnState::Aborted));
    }

    #[test]
    fn test_double_commit() {
        let tm = TransactionManager::with_default_config();

        let handle = tm.begin();
        tm.commit(handle.id).unwrap();

        assert!(matches!(
            tm.commit(handle.id),
            Err(TxnError::AlreadyCommitted(_))
        ));
    }

    #[test]
    fn test_transaction_wrapper() {
        let tm = Arc::new(TransactionManager::with_default_config());

        let txn = tm.begin_transaction();
        let id = txn.id();

        txn.record_write(b"key1", None, Some(b"value1"));
        txn.commit().unwrap();

        assert!(!tm.is_active(id));
    }

    #[test]
    fn test_savepoints() {
        let tm = TransactionManager::with_default_config();

        let handle = tm.begin();

        tm.record_write(handle.id, b"key1", None, Some(b"v1"));
        tm.create_savepoint(handle.id, "sp1").unwrap();

        tm.record_write(handle.id, b"key2", None, Some(b"v2"));
        tm.record_write(handle.id, b"key3", None, Some(b"v3"));

        // Rollback to savepoint
        tm.rollback_to_savepoint(handle.id, "sp1").unwrap();

        // Should be able to commit
        tm.commit(handle.id).unwrap();
    }

    #[test]
    fn test_isolation_levels() {
        let tm = TransactionManager::with_default_config();

        let h1 = tm.begin_with_isolation(IsolationLevel::ReadCommitted);
        let h2 = tm.begin_with_isolation(IsolationLevel::SnapshotIsolation);

        assert_eq!(h1.isolation, IsolationLevel::ReadCommitted);
        assert_eq!(h2.isolation, IsolationLevel::SnapshotIsolation);

        tm.abort(h1.id).unwrap();
        tm.abort(h2.id).unwrap();
    }

    #[test]
    fn test_active_count() {
        let tm = TransactionManager::with_default_config();

        assert_eq!(tm.active_count(), 0);

        let h1 = tm.begin();
        let h2 = tm.begin();
        assert_eq!(tm.active_count(), 2);

        tm.commit(h1.id).unwrap();
        assert_eq!(tm.active_count(), 1);

        tm.abort(h2.id).unwrap();
        assert_eq!(tm.active_count(), 0);
    }

    #[test]
    fn test_oldest_active_ts() {
        let tm = TransactionManager::with_default_config();

        let h1 = tm.begin();
        let ts1 = h1.start_ts;

        let _h2 = tm.begin();

        assert_eq!(tm.oldest_active_ts(), Some(ts1));
    }

    #[test]
    fn test_config() {
        let config = TxnConfig::new()
            .with_isolation(IsolationLevel::Serializable)
            .with_lock_timeout(Duration::from_secs(10))
            .with_optimistic(false);

        assert_eq!(config.isolation_level, IsolationLevel::Serializable);
        assert_eq!(config.lock_timeout, Duration::from_secs(10));
        assert!(!config.optimistic);
    }
}