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
843
844
845
846
847
848
849
850
//! Transaction Manager
//!
//! Provides ACID transaction support for the RedDB storage engine.
//!
//! # Transaction Lifecycle
//!
//! 1. Begin: Allocate transaction ID, write Begin record to WAL
//! 2. Read/Write: Track page reads and buffer page writes
//! 3. Commit: Write Commit record to WAL, sync WAL
//! 4. Rollback: Write Rollback record to WAL, discard buffered writes
//!
//! # Isolation Level
//!
//! Currently implements Read Committed isolation:
//! - Reads see committed data at the start of the statement
//! - No dirty reads
//! - Possible non-repeatable reads
//!
//! # References
//!
//! - Turso `core/transaction.rs` - Transaction implementation
//! - SQLite transaction documentation

use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};

use parking_lot::{Mutex, MutexGuard};

use super::append_coordinator::WalAppendCoordinator;
use super::record::WalRecord;
use super::writer::WalWriter;
use crate::storage::engine::{Page, Pager, PAGE_SIZE};

/// Global transaction ID counter
static NEXT_TX_ID: AtomicU64 = AtomicU64::new(1);

/// Generate a new unique transaction ID
fn next_transaction_id() -> u64 {
    NEXT_TX_ID.fetch_add(1, Ordering::SeqCst)
}

/// Transaction state
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TxState {
    /// Transaction is active and can perform operations
    Active,
    /// Transaction has been committed
    Committed,
    /// Transaction has been rolled back
    Aborted,
}

/// Transaction error types
#[derive(Debug)]
pub enum TxError {
    /// I/O error
    Io(io::Error),
    /// Pager error
    Pager(String),
    /// Internal lock was poisoned by a panic
    LockPoisoned(&'static str),
    /// Transaction is not active
    NotActive,
    /// Transaction already committed
    AlreadyCommitted,
    /// Transaction already aborted
    AlreadyAborted,
    /// Write conflict
    WriteConflict(u32),
    /// Invalid page data
    InvalidPage(String),
}

impl std::fmt::Display for TxError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(e) => write!(f, "I/O error: {}", e),
            Self::Pager(msg) => write!(f, "Pager error: {}", msg),
            Self::LockPoisoned(name) => write!(f, "Lock poisoned: {}", name),
            Self::NotActive => write!(f, "Transaction is not active"),
            Self::AlreadyCommitted => write!(f, "Transaction already committed"),
            Self::AlreadyAborted => write!(f, "Transaction already aborted"),
            Self::WriteConflict(page_id) => write!(f, "Write conflict on page {}", page_id),
            Self::InvalidPage(msg) => write!(f, "Invalid page: {}", msg),
        }
    }
}

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

impl From<io::Error> for TxError {
    fn from(e: io::Error) -> Self {
        Self::Io(e)
    }
}

/// A buffered page write
#[derive(Clone)]
struct BufferedWrite {
    page_id: u32,
    data: [u8; PAGE_SIZE],
}

/// A single transaction
///
/// Transactions buffer writes and commit them atomically to the WAL.
pub struct Transaction {
    /// Transaction ID
    id: u64,
    /// Transaction state
    state: TxState,
    /// Buffered page writes (page_id -> page data)
    write_set: HashMap<u32, BufferedWrite>,
    /// Pages read in this transaction (for conflict detection)
    read_set: Vec<u32>,
    /// Reference to the transaction manager
    manager: Arc<TransactionManager>,
}

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

    /// Get transaction state
    pub fn state(&self) -> TxState {
        self.state
    }

    /// Check if transaction is active
    pub fn is_active(&self) -> bool {
        self.state == TxState::Active
    }

    /// Read a page through this transaction
    ///
    /// If the page has been written in this transaction, returns the buffered version.
    /// Otherwise, reads from the pager.
    pub fn read_page(&mut self, page_id: u32) -> Result<Page, TxError> {
        if self.state != TxState::Active {
            return Err(TxError::NotActive);
        }

        // Check write set first
        if let Some(buffered) = self.write_set.get(&page_id) {
            return Ok(Page::from_bytes(buffered.data));
        }

        // Track the read
        self.read_set.push(page_id);

        // Read from pager
        self.manager
            .pager
            .read_page(page_id)
            .map_err(|e| TxError::Pager(e.to_string()))
    }

    /// Write a page through this transaction
    ///
    /// The write is buffered and will be committed to the WAL on commit.
    pub fn write_page(&mut self, page_id: u32, page: Page) -> Result<(), TxError> {
        if self.state != TxState::Active {
            return Err(TxError::NotActive);
        }

        // Buffer the write
        let mut data = [0u8; PAGE_SIZE];
        data.copy_from_slice(page.as_bytes());

        self.write_set
            .insert(page_id, BufferedWrite { page_id, data });

        Ok(())
    }

    /// Commit the transaction
    ///
    /// Writes all buffered pages to the WAL, then writes a Commit record.
    ///
    /// **Read-only fast path:** when `write_set` is empty, the
    /// transaction wrote nothing, so there is nothing to make
    /// durable. We skip the WAL append, the `wal.sync()` (which costs
    /// ~100 µs of fsync), and the pager apply loop entirely. The
    /// transaction still transitions to `Committed` and unregisters
    /// from the manager so subsequent state checks work correctly.
    /// This mirrors postgres' optimisation in `RecordTransactionCommit`
    /// (`xact.c`) which skips `XLogFlush` when nothing was written.
    pub fn commit(mut self) -> Result<(), TxError> {
        if self.state != TxState::Active {
            return match self.state {
                TxState::Committed => Err(TxError::AlreadyCommitted),
                TxState::Aborted => Err(TxError::AlreadyAborted),
                _ => Err(TxError::NotActive),
            };
        }

        // ── Read-only fast path ─────────────────────────────────────
        // No writes → no WAL record → no fsync. Saves ~100 µs per
        // read-only commit and removes contention on the WAL writer
        // mutex for read-heavy workloads.
        if self.write_set.is_empty() {
            self.state = TxState::Committed;
            self.manager.unregister_transaction(self.id);
            return Ok(());
        }

        // ── Encode phase (no lock) ──────────────────────────────────
        // Encode every WAL record into one contiguous byte blob
        // OUTSIDE any lock. This is the bulk of the per-commit work
        // and pays no contention cost — the old path encoded each
        // record while holding `Mutex<WalWriter>`, which under 16-way
        // concurrency produced the park-convoy that bottlenecked
        // `concurrent` and `insert_sequential`.
        let mut blob = Vec::with_capacity(64 + self.write_set.len() * (PAGE_SIZE + 32));
        for (page_id, buffered) in &self.write_set {
            let record = WalRecord::PageWrite {
                tx_id: self.id,
                page_id: *page_id,
                data: buffered.data.to_vec(),
            };
            blob.extend_from_slice(&record.encode());
        }
        blob.extend_from_slice(&WalRecord::Commit { tx_id: self.id }.encode());

        // ── Reserve + enqueue (lock-free) ───────────────────────────
        // One atomic fetch_add reserves our LSN range; one
        // SegQueue::push hands the bytes to the leader. Both
        // operations are wait-free for the writer.
        let commit_lsn = self.manager.coordinator.reserve_and_enqueue(blob);

        // ── Wait for durability ─────────────────────────────────────
        // If `durable_lsn >= commit_lsn` already, the leader (some
        // earlier thread) covered us — return immediately. Otherwise
        // we either become the leader and drive the drain, or park
        // on the coordinator's parking_lot::Condvar until a leader
        // publishes a `durable_lsn` past our target.
        self.manager
            .coordinator
            .commit_at_least(commit_lsn, &self.manager.wal)
            .map_err(TxError::Io)?;

        // Apply writes to pager cache (for immediate visibility)
        for (page_id, buffered) in &self.write_set {
            let page = Page::from_bytes(buffered.data);
            self.manager
                .pager
                .write_page(*page_id, page)
                .map_err(|e| TxError::Pager(e.to_string()))?;
        }

        self.state = TxState::Committed;

        // Unregister from manager
        self.manager.unregister_transaction(self.id);

        Ok(())
    }

    /// Rollback the transaction
    ///
    /// Discards all buffered writes and writes a Rollback record to the WAL.
    pub fn rollback(mut self) -> Result<(), TxError> {
        if self.state != TxState::Active {
            return match self.state {
                TxState::Committed => Err(TxError::AlreadyCommitted),
                TxState::Aborted => Err(TxError::AlreadyAborted),
                _ => Err(TxError::NotActive),
            };
        }

        // Route rollback through the coordinator so its bytes land
        // in LSN order with any concurrent commits. Going around the
        // coordinator (direct `wal.lock().append`) would race with
        // the leader's `append_bytes` and corrupt the file.
        let blob = WalRecord::Rollback { tx_id: self.id }.encode();
        let target = self.manager.coordinator.reserve_and_enqueue(blob);
        self.manager
            .coordinator
            .commit_at_least(target, &self.manager.wal)
            .map_err(TxError::Io)?;

        // Clear write set
        self.write_set.clear();
        self.state = TxState::Aborted;

        // Unregister from manager
        self.manager.unregister_transaction(self.id);

        Ok(())
    }
}

impl Drop for Transaction {
    fn drop(&mut self) {
        // If transaction is still active when dropped, it means it was neither
        // committed nor rolled back. This is a bug, but we'll clean up anyway.
        if self.state == TxState::Active {
            // Best-effort rollback through the coordinator. We can't
            // bypass the coordinator with a direct `wal.lock()` here:
            // any in-flight reservations would still be holding LSN
            // slots ahead of us and the file would gain a hole. The
            // coordinator handles ordering correctly even from Drop.
            let blob = WalRecord::Rollback { tx_id: self.id }.encode();
            let target = self.manager.coordinator.reserve_and_enqueue(blob);
            let _ = self
                .manager
                .coordinator
                .commit_at_least(target, &self.manager.wal);
            self.manager.unregister_transaction(self.id);
        }
    }
}

/// Transaction Manager
///
/// Coordinates transactions and manages the WAL.
pub struct TransactionManager {
    /// Pager for reading/writing pages
    pager: Arc<Pager>,
    /// WAL writer protected by a `parking_lot::Mutex`. The mutex is
    /// taken only by the leader-flush path inside the coordinator;
    /// concurrent writers no longer contend on it during the
    /// encode-and-append step. See [`WalAppendCoordinator`].
    wal: Mutex<WalWriter>,
    /// WAL file path
    wal_path: PathBuf,
    /// Active transaction IDs
    active_transactions: RwLock<Vec<u64>>,
    /// Lock-free append coordinator. Replaces the per-commit
    /// `wal.lock()` that used to serialise 16 concurrent writers
    /// (Roadmap #2 / issue #157). Writers reserve an LSN range via
    /// atomic fetch_add, push their encoded bytes onto a SegQueue,
    /// then call `commit_at_least` to wait for durability. The
    /// first thread into `commit_at_least` becomes the leader and
    /// drives the WAL drain + fsync; everyone else parks on the
    /// coordinator's condvar.
    coordinator: WalAppendCoordinator,
}

impl TransactionManager {
    /// Create a new transaction manager
    ///
    /// # Arguments
    ///
    /// * `pager` - The pager to use for page I/O
    /// * `wal_path` - Path to the WAL file
    pub fn new(pager: Arc<Pager>, wal_path: impl AsRef<Path>) -> io::Result<Self> {
        let wal_path = wal_path.as_ref().to_path_buf();
        let wal = WalWriter::open(&wal_path)?;
        let initial_current = wal.current_lsn();
        let initial_durable = wal.durable_lsn();

        Ok(Self {
            pager,
            wal: Mutex::new(wal),
            wal_path,
            active_transactions: RwLock::new(Vec::new()),
            coordinator: WalAppendCoordinator::new(initial_current, initial_durable),
        })
    }

    fn wal_writer(&self) -> Result<MutexGuard<'_, WalWriter>, TxError> {
        // parking_lot::Mutex does not poison on panic, so this is
        // infallible. We keep the `Result` return type to avoid
        // touching every call site, but the error variant is now
        // unreachable in normal operation. Tests that previously
        // poisoned the std::sync::Mutex deliberately have been
        // adjusted to assert the new non-poisoning behaviour.
        Ok(self.wal.lock())
    }

    fn active_transactions_write(&self) -> RwLockWriteGuard<'_, Vec<u64>> {
        self.active_transactions
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn active_transactions_read(&self) -> RwLockReadGuard<'_, Vec<u64>> {
        self.active_transactions
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    /// Begin a new transaction
    pub fn begin(self: &Arc<Self>) -> Result<Transaction, TxError> {
        let tx_id = next_transaction_id();

        // Route the Begin record through the coordinator (same
        // ordering guarantees as commit/rollback). Begin is not
        // strictly required to be durable before subsequent appends
        // — recovery treats a Begin without a matching Commit as a
        // rolled-back txn — so we don't wait on `commit_at_least`.
        // The bytes are queued and the next leader picks them up
        // alongside our own Commit record when we eventually commit.
        let blob = WalRecord::Begin { tx_id }.encode();
        let _begin_lsn = self.coordinator.reserve_and_enqueue(blob);

        // Register transaction
        {
            let mut active = self.active_transactions_write();
            active.push(tx_id);
        }

        Ok(Transaction {
            id: tx_id,
            state: TxState::Active,
            write_set: HashMap::new(),
            read_set: Vec::new(),
            manager: Arc::clone(self),
        })
    }

    /// Unregister a transaction (called on commit/rollback)
    fn unregister_transaction(&self, tx_id: u64) {
        let mut active = self.active_transactions_write();
        active.retain(|&id| id != tx_id);
    }

    /// Get list of active transaction IDs
    pub fn active_transactions(&self) -> Vec<u64> {
        self.active_transactions_read().clone()
    }

    /// Get WAL file path
    pub fn wal_path(&self) -> &Path {
        &self.wal_path
    }

    /// Get reference to pager
    pub fn pager(&self) -> &Arc<Pager> {
        &self.pager
    }

    /// Sync WAL to disk. Drains every byte that has been reserved
    /// via the coordinator — i.e. waits until the coordinator's
    /// `next_lsn` is durable.
    pub fn sync_wal(&self) -> io::Result<()> {
        let target = self.coordinator.next_lsn();
        self.coordinator.commit_at_least(target, &self.wal)
    }

    /// Check if there are active transactions
    pub fn has_active_transactions(&self) -> bool {
        !self.active_transactions_read().is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::engine::PageType;
    use std::fs;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_dir() -> PathBuf {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir().join(format!("reddb_tx_test_{}", timestamp))
    }

    fn cleanup(dir: &Path) {
        let _ = fs::remove_dir_all(dir);
    }

    #[test]
    fn test_transaction_commit() {
        let dir = temp_dir();
        let _ = fs::create_dir_all(&dir);
        let db_path = dir.join("test.db");
        let wal_path = dir.join("test.wal");

        // Create pager
        let pager = Arc::new(Pager::open_default(&db_path).unwrap());

        // Allocate a page
        let page = pager.allocate_page(PageType::BTreeLeaf).unwrap();
        let page_id = page.page_id();

        // Create transaction manager
        let tm = Arc::new(TransactionManager::new(Arc::clone(&pager), &wal_path).unwrap());

        // Begin transaction
        let mut tx = tm.begin().unwrap();
        assert!(tx.is_active());

        // Write through transaction
        let mut page = Page::new(PageType::BTreeLeaf, page_id);
        page.as_bytes_mut()[100] = 0xAB;
        tx.write_page(page_id, page).unwrap();

        // Read through transaction (should see buffered write)
        let read_page = tx.read_page(page_id).unwrap();
        assert_eq!(read_page.as_bytes()[100], 0xAB);

        // Commit
        tx.commit().unwrap();

        // Verify write is visible through pager
        let final_page = pager.read_page(page_id).unwrap();
        assert_eq!(final_page.as_bytes()[100], 0xAB);

        cleanup(&dir);
    }

    #[test]
    fn test_transaction_rollback() {
        let dir = temp_dir();
        let _ = fs::create_dir_all(&dir);
        let db_path = dir.join("test.db");
        let wal_path = dir.join("test.wal");

        // Create pager
        let pager = Arc::new(Pager::open_default(&db_path).unwrap());

        // Allocate a page and write initial value
        let mut page = pager.allocate_page(PageType::BTreeLeaf).unwrap();
        let page_id = page.page_id();
        page.as_bytes_mut()[100] = 0x11;
        pager.write_page(page_id, page).unwrap();

        // Create transaction manager
        let tm = Arc::new(TransactionManager::new(Arc::clone(&pager), &wal_path).unwrap());

        // Begin transaction
        let mut tx = tm.begin().unwrap();

        // Write through transaction
        let mut page = Page::new(PageType::BTreeLeaf, page_id);
        page.as_bytes_mut()[100] = 0xAB;
        tx.write_page(page_id, page).unwrap();

        // Read through transaction (should see buffered write)
        let read_page = tx.read_page(page_id).unwrap();
        assert_eq!(read_page.as_bytes()[100], 0xAB);

        // Rollback
        tx.rollback().unwrap();

        // Original value should be preserved
        let final_page = pager.read_page(page_id).unwrap();
        assert_eq!(final_page.as_bytes()[100], 0x11);

        cleanup(&dir);
    }

    #[test]
    fn test_multiple_transactions() {
        let dir = temp_dir();
        let _ = fs::create_dir_all(&dir);
        let db_path = dir.join("test.db");
        let wal_path = dir.join("test.wal");

        // Create pager
        let pager = Arc::new(Pager::open_default(&db_path).unwrap());

        // Allocate two pages
        let page1 = pager.allocate_page(PageType::BTreeLeaf).unwrap();
        let page2 = pager.allocate_page(PageType::BTreeLeaf).unwrap();
        let page1_id = page1.page_id();
        let page2_id = page2.page_id();

        // Create transaction manager
        let tm = Arc::new(TransactionManager::new(Arc::clone(&pager), &wal_path).unwrap());

        // Transaction 1: Write to page 1
        let mut tx1 = tm.begin().unwrap();
        let mut page1 = Page::new(PageType::BTreeLeaf, page1_id);
        page1.as_bytes_mut()[100] = 0x11;
        tx1.write_page(page1_id, page1).unwrap();
        tx1.commit().unwrap();

        // Transaction 2: Write to page 2
        let mut tx2 = tm.begin().unwrap();
        let mut page2 = Page::new(PageType::BTreeLeaf, page2_id);
        page2.as_bytes_mut()[100] = 0x22;
        tx2.write_page(page2_id, page2).unwrap();
        tx2.commit().unwrap();

        // Verify both writes
        let final_page1 = pager.read_page(page1_id).unwrap();
        let final_page2 = pager.read_page(page2_id).unwrap();
        assert_eq!(final_page1.as_bytes()[100], 0x11);
        assert_eq!(final_page2.as_bytes()[100], 0x22);

        cleanup(&dir);
    }

    #[test]
    fn test_transaction_isolation() {
        let dir = temp_dir();
        let _ = fs::create_dir_all(&dir);
        let db_path = dir.join("test.db");
        let wal_path = dir.join("test.wal");

        // Create pager
        let pager = Arc::new(Pager::open_default(&db_path).unwrap());

        // Allocate a page with initial value
        let mut page = pager.allocate_page(PageType::BTreeLeaf).unwrap();
        let page_id = page.page_id();
        page.as_bytes_mut()[100] = 0x00;
        pager.write_page(page_id, page).unwrap();

        // Create transaction manager
        let tm = Arc::new(TransactionManager::new(Arc::clone(&pager), &wal_path).unwrap());

        // Transaction 1: Begin and write (but don't commit yet)
        let mut tx1 = tm.begin().unwrap();
        let mut page1 = Page::new(PageType::BTreeLeaf, page_id);
        page1.as_bytes_mut()[100] = 0x11;
        tx1.write_page(page_id, page1).unwrap();

        // Transaction 1 should see its own write
        let tx1_read = tx1.read_page(page_id).unwrap();
        assert_eq!(tx1_read.as_bytes()[100], 0x11);

        // Another read from pager should not see uncommitted write
        let pager_read = pager.read_page(page_id).unwrap();
        assert_eq!(pager_read.as_bytes()[100], 0x00);

        // Commit tx1
        tx1.commit().unwrap();

        // Now pager should see the write
        let final_read = pager.read_page(page_id).unwrap();
        assert_eq!(final_read.as_bytes()[100], 0x11);

        cleanup(&dir);
    }

    #[test]
    fn test_active_transaction_tracking() {
        let dir = temp_dir();
        let _ = fs::create_dir_all(&dir);
        let db_path = dir.join("test.db");
        let wal_path = dir.join("test.wal");

        let pager = Arc::new(Pager::open_default(&db_path).unwrap());
        let tm = Arc::new(TransactionManager::new(Arc::clone(&pager), &wal_path).unwrap());

        assert!(!tm.has_active_transactions());

        let tx1 = tm.begin().unwrap();
        let tx1_id = tx1.id();
        assert!(tm.has_active_transactions());
        assert!(tm.active_transactions().contains(&tx1_id));

        let tx2 = tm.begin().unwrap();
        let tx2_id = tx2.id();
        assert_eq!(tm.active_transactions().len(), 2);

        tx1.commit().unwrap();
        assert!(!tm.active_transactions().contains(&tx1_id));
        assert!(tm.active_transactions().contains(&tx2_id));

        tx2.rollback().unwrap();
        assert!(!tm.has_active_transactions());

        cleanup(&dir);
    }

    #[test]
    fn test_transaction_double_commit() {
        let dir = temp_dir();
        let _ = fs::create_dir_all(&dir);
        let db_path = dir.join("test.db");
        let wal_path = dir.join("test.wal");

        let pager = Arc::new(Pager::open_default(&db_path).unwrap());
        let tm = Arc::new(TransactionManager::new(Arc::clone(&pager), &wal_path).unwrap());

        // The transaction is consumed on commit, so double commit is impossible at compile time
        // This test just verifies commit works
        let tx = tm.begin().unwrap();
        tx.commit().unwrap();

        cleanup(&dir);
    }

    #[test]
    fn test_begin_succeeds_after_panic_in_lock_holder() {
        // After Roadmap #2 the WAL mutex is `parking_lot::Mutex`,
        // which does NOT poison on panic. A previous version of this
        // test asserted that a panicking thread holding the lock
        // produced a `TxError::LockPoisoned` on the next `begin()` —
        // that was a property of `std::sync::Mutex`. The new
        // contract is the opposite: writers continue uninterrupted.
        let dir = temp_dir();
        let _ = fs::create_dir_all(&dir);
        let db_path = dir.join("test.db");
        let wal_path = dir.join("test.wal");

        let pager = Arc::new(Pager::open_default(&db_path).unwrap());
        let tm = Arc::new(TransactionManager::new(Arc::clone(&pager), &wal_path).unwrap());

        let poison_target = Arc::clone(&tm);
        let _ = std::thread::spawn(move || {
            let _guard = poison_target.wal.lock();
            panic!("would-poison the wal mutex on std::sync");
        })
        .join();

        // parking_lot recovers transparently. begin() must succeed.
        match tm.begin() {
            Ok(_) => {}
            Err(err) => panic!("begin must succeed despite prior panic: {err:?}"),
        }

        cleanup(&dir);
    }

    // ---------------------------------------------------------------
    // Perf 1.2: read-only commit fast path
    // ---------------------------------------------------------------

    #[test]
    fn read_only_commit_does_not_advance_durable_lsn() {
        let dir = temp_dir();
        let _ = fs::create_dir_all(&dir);
        let db_path = dir.join("ro_durable.db");
        let wal_path = dir.join("ro_durable.wal");

        let pager = Arc::new(Pager::open_default(&db_path).unwrap());
        let tm = Arc::new(TransactionManager::new(Arc::clone(&pager), &wal_path).unwrap());

        // Snapshot the WAL durable_lsn BEFORE the txn.
        let before = {
            let wal = tm.wal_writer().unwrap();
            wal.durable_lsn()
        };

        let tx = tm.begin().unwrap();
        // Empty write_set on purpose — read-only.
        tx.commit().unwrap();

        // After RO commit, the WAL durable_lsn must NOT have advanced.
        // No Begin record, no Commit record, no fsync.
        let after = {
            let wal = tm.wal_writer().unwrap();
            wal.durable_lsn()
        };
        assert_eq!(
            before, after,
            "read-only commit must not advance durable_lsn (was {} → {})",
            before, after
        );

        cleanup(&dir);
    }

    #[test]
    fn read_only_commit_does_not_grow_wal_file() {
        let dir = temp_dir();
        let _ = fs::create_dir_all(&dir);
        let db_path = dir.join("ro_size.db");
        let wal_path = dir.join("ro_size.wal");

        let pager = Arc::new(Pager::open_default(&db_path).unwrap());
        let tm = Arc::new(TransactionManager::new(Arc::clone(&pager), &wal_path).unwrap());

        // Snapshot file size after WAL header.
        let size_before = std::fs::metadata(&wal_path).unwrap().len();
        assert_eq!(
            size_before, 8,
            "fresh WAL must be exactly the 8-byte header"
        );

        // 100 read-only commits in a loop.
        for _ in 0..100 {
            let tx = tm.begin().unwrap();
            tx.commit().unwrap();
        }

        let size_after = std::fs::metadata(&wal_path).unwrap().len();
        assert_eq!(
            size_after, size_before,
            "100 read-only commits should not have written any WAL bytes"
        );
        cleanup(&dir);
    }

    #[test]
    fn read_only_commit_marks_transaction_committed() {
        let dir = temp_dir();
        let _ = fs::create_dir_all(&dir);
        let db_path = dir.join("ro_state.db");
        let wal_path = dir.join("ro_state.wal");

        let pager = Arc::new(Pager::open_default(&db_path).unwrap());
        let tm = Arc::new(TransactionManager::new(Arc::clone(&pager), &wal_path).unwrap());

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

        // Manager must have unregistered this txn — the active list
        // no longer contains its id.
        assert!(
            !tm.active_transactions().contains(&id),
            "RO-committed txn {id} must no longer be active in the manager"
        );

        cleanup(&dir);
    }

    #[test]
    fn writing_commit_still_syncs_after_ro_fast_path() {
        // Sanity: the fast path must NOT short-circuit a transaction
        // that did write something. Verify the writing commit path
        // still flushes WAL and the value lands in the pager.
        let dir = temp_dir();
        let _ = fs::create_dir_all(&dir);
        let db_path = dir.join("rw_after_ro.db");
        let wal_path = dir.join("rw_after_ro.wal");

        let pager = Arc::new(Pager::open_default(&db_path).unwrap());
        let allocated = pager.allocate_page(PageType::BTreeLeaf).unwrap();
        let page_id = allocated.page_id();
        let tm = Arc::new(TransactionManager::new(Arc::clone(&pager), &wal_path).unwrap());

        // First a RO commit (must take the fast path).
        let ro = tm.begin().unwrap();
        ro.commit().unwrap();

        // Then a real writing commit.
        let mut rw = tm.begin().unwrap();
        let mut page = Page::new(PageType::BTreeLeaf, page_id);
        page.as_bytes_mut()[42] = 0x77;
        rw.write_page(page_id, page).unwrap();
        rw.commit().unwrap();

        // The WAL file must now contain bytes (PageWrite + Commit
        // records, and the BufWriter has been flushed by sync()).
        let size = std::fs::metadata(&wal_path).unwrap().len();
        assert!(size > 8, "writing commit should grow the WAL");

        // The pager cache must reflect the write.
        let read_back = pager.read_page(page_id).unwrap();
        assert_eq!(read_back.as_bytes()[42], 0x77);

        cleanup(&dir);
    }
}