stateset-db 1.22.0

Database implementations for StateSet iCommerce
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
//! Transaction abstraction with saga support
//!
//! Provides ACID transactions and distributed saga pattern for multi-step operations.

use thiserror::Error;

/// Error types for transaction operations
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum TransactionError {
    #[error("Transaction failed: {0}")]
    TransactionFailed(String),

    #[error("Compensating action failed for step {step}: {error}")]
    CompensationError { step: String, error: String },

    #[error("Transaction already committed")]
    AlreadyCommitted,

    #[error("Transaction already rolled back")]
    AlreadyRolledback,

    #[error("Transaction not active")]
    NotActive,
}

/// Result type for transaction operations
pub type TransactionResult<T> = Result<T, TransactionError>;

/// Transaction lifecycle state
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransactionState {
    /// Transaction is active and can execute steps
    Active,
    /// Transaction completed successfully
    Committed,
    /// Transaction rolled back
    RolledBack,
    /// Transaction failed during execution
    Failed,
}

/// Trait for operations that can participate in transactions
pub trait Transactional {
    type Output;

    /// Execute the operation
    fn execute(&self) -> TransactionResult<Self::Output>;

    /// Compensate/rollback the operation
    fn compensate(&self) -> TransactionResult<()>;
}

/// Trait for repository-level transaction support
pub trait TransactionalRepository {
    /// Begin a new transaction
    fn begin_transaction(&self) -> TransactionResult<TransactionHandle>;

    /// Execute operations within a transaction
    fn with_transaction<F, T>(&self, f: F) -> TransactionResult<T>
    where
        F: FnOnce(&mut Self) -> TransactionResult<T>;
}

/// Handle for an active transaction
pub struct TransactionHandle {
    id: String,
    state: TransactionState,
    operations: Vec<Box<dyn Transactional<Output = ()>>>,
    completed_operations: usize,
}

impl std::fmt::Debug for TransactionHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TransactionHandle")
            .field("id", &self.id)
            .field("state", &self.state)
            .field("operations_len", &self.operations.len())
            .finish()
    }
}

impl TransactionHandle {
    /// Create a new transaction handle
    #[must_use]
    pub fn new() -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            state: TransactionState::Active,
            operations: Vec::new(),
            completed_operations: 0,
        }
    }

    /// Get the transaction ID
    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Get the current state
    #[must_use]
    pub const fn state(&self) -> TransactionState {
        self.state
    }

    /// Add an operation to the transaction
    pub fn add_operation(&mut self, operation: Box<dyn Transactional<Output = ()>>) {
        self.operations.push(operation);
    }

    /// Commit the transaction (execute all operations)
    pub fn commit(&mut self) -> TransactionResult<()> {
        if self.state != TransactionState::Active {
            return Err(TransactionError::NotActive);
        }

        self.completed_operations = 0;

        // Execute all operations
        for op in &self.operations {
            match op.execute() {
                Ok(()) => {
                    self.completed_operations += 1;
                }
                Err(e) => {
                    self.state = TransactionState::Failed;
                    // Try to compensate
                    Self::compensate(&self.operations[..self.completed_operations])?;
                    return Err(e);
                }
            }
        }

        self.state = TransactionState::Committed;
        Ok(())
    }

    /// Rollback the transaction by compensating completed operations
    pub fn rollback(&mut self) -> TransactionResult<()> {
        if self.state != TransactionState::Active {
            return Err(TransactionError::NotActive);
        }

        Self::compensate(&self.operations[..self.completed_operations])?;
        self.state = TransactionState::RolledBack;
        Ok(())
    }

    /// Compensate completed operations (called on rollback or failure)
    fn compensate(completed: &[Box<dyn Transactional<Output = ()>>]) -> TransactionResult<()> {
        // Compensate in reverse order
        for op in completed.iter().rev() {
            if let Err(e) = op.compensate() {
                return Err(TransactionError::CompensationError {
                    step: "unknown".to_string(),
                    error: e.to_string(),
                });
            }
        }
        Ok(())
    }
}

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

/// Saga pattern for distributed transactions
///
/// Sagas execute a sequence of operations with compensating actions
/// to handle failures gracefully.
#[derive(Debug)]
pub struct Saga {
    handle: TransactionHandle,
}

impl Saga {
    /// Create a new saga
    #[must_use]
    pub fn new() -> Self {
        Self { handle: TransactionHandle::new() }
    }

    /// Add a step to the saga
    pub fn add_step(&mut self, operation: Box<dyn Transactional<Output = ()>>) -> &mut Self {
        self.handle.add_operation(operation);
        self
    }

    /// Execute the saga
    pub fn execute(&mut self) -> TransactionResult<()> {
        self.handle.commit()
    }
}

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

/// Builder for transaction batches
#[must_use]
pub struct TransactionBuilder {
    operations: Vec<Box<dyn Transactional<Output = ()>>>,
}

impl std::fmt::Debug for TransactionBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TransactionBuilder")
            .field("operations_len", &self.operations.len())
            .finish()
    }
}

impl TransactionBuilder {
    /// Create a new transaction builder
    pub fn new() -> Self {
        Self { operations: Vec::new() }
    }

    /// Add an operation to the batch.
    pub fn push(mut self, operation: Box<dyn Transactional<Output = ()>>) -> Self {
        self.operations.push(operation);
        self
    }

    /// Build and execute the transaction
    pub fn execute(self) -> TransactionResult<()> {
        let mut handle = TransactionHandle::new();
        for op in self.operations {
            handle.add_operation(op);
        }
        handle.commit()
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    // ------------------------------------------------------------------
    // Helpers
    // ------------------------------------------------------------------

    struct SimpleOperation {
        name: String,
        executed: Arc<Mutex<bool>>,
        compensated: Arc<Mutex<bool>>,
    }

    impl Transactional for SimpleOperation {
        type Output = ();

        fn execute(&self) -> TransactionResult<()> {
            *self.executed.lock().unwrap() = true;
            // Simulate failure for testing
            if self.name.contains("fail") {
                Err(TransactionError::TransactionFailed("Simulated failure".into()))
            } else {
                Ok(())
            }
        }

        fn compensate(&self) -> TransactionResult<()> {
            *self.compensated.lock().unwrap() = true;
            Ok(())
        }
    }

    /// An operation whose compensation also fails.
    struct FailingCompensation;

    impl Transactional for FailingCompensation {
        type Output = ();

        fn execute(&self) -> TransactionResult<()> {
            Ok(())
        }

        fn compensate(&self) -> TransactionResult<()> {
            Err(TransactionError::CompensationError {
                step: "failing_comp".into(),
                error: "comp failed".into(),
            })
        }
    }

    /// Tracks execution order via an append-to-vec pattern.
    struct OrderTracker {
        log: Arc<Mutex<Vec<String>>>,
        label: String,
        should_fail: bool,
    }

    impl Transactional for OrderTracker {
        type Output = ();

        fn execute(&self) -> TransactionResult<()> {
            self.log.lock().unwrap().push(format!("exec:{}", self.label));
            if self.should_fail {
                Err(TransactionError::TransactionFailed(format!("{} failed", self.label)))
            } else {
                Ok(())
            }
        }

        fn compensate(&self) -> TransactionResult<()> {
            self.log.lock().unwrap().push(format!("comp:{}", self.label));
            Ok(())
        }
    }

    fn simple_op(name: &str) -> (SimpleOperation, Arc<Mutex<bool>>, Arc<Mutex<bool>>) {
        let executed = Arc::new(Mutex::new(false));
        let compensated = Arc::new(Mutex::new(false));
        (
            SimpleOperation {
                name: name.into(),
                executed: executed.clone(),
                compensated: compensated.clone(),
            },
            executed,
            compensated,
        )
    }

    // ------------------------------------------------------------------
    // Original tests (preserved)
    // ------------------------------------------------------------------

    #[test]
    fn test_successful_transaction() {
        let mut handle = TransactionHandle::new();

        let executed = Arc::new(Mutex::new(false));
        let compensated = Arc::new(Mutex::new(false));

        handle.add_operation(Box::new(SimpleOperation {
            name: "op1".into(),
            executed: executed.clone(),
            compensated: compensated.clone(),
        }));

        handle.commit().unwrap();
        assert_eq!(handle.state(), TransactionState::Committed);
        assert!(*executed.lock().unwrap());
        assert!(!(*compensated.lock().unwrap()));
    }

    #[test]
    fn test_rollback_without_executing_does_not_compensate() {
        let mut handle = TransactionHandle::new();

        let executed = Arc::new(Mutex::new(false));
        let compensated = Arc::new(Mutex::new(false));

        handle.add_operation(Box::new(SimpleOperation {
            name: "op1".into(),
            executed: executed.clone(),
            compensated: compensated.clone(),
        }));

        handle.rollback().unwrap();
        assert_eq!(handle.state(), TransactionState::RolledBack);
        assert!(!(*executed.lock().unwrap()));
        assert!(!(*compensated.lock().unwrap()));
    }

    #[test]
    fn test_failed_transaction_with_compensation() {
        let mut handle = TransactionHandle::new();

        let executed1 = Arc::new(Mutex::new(false));
        let compensated1 = Arc::new(Mutex::new(false));
        let executed2 = Arc::new(Mutex::new(false));
        let compensated2 = Arc::new(Mutex::new(false));

        handle.add_operation(Box::new(SimpleOperation {
            name: "op1".into(),
            executed: executed1.clone(),
            compensated: compensated1.clone(),
        }));

        handle.add_operation(Box::new(SimpleOperation {
            name: "op2-fail".into(),
            executed: executed2.clone(),
            compensated: compensated2.clone(),
        }));

        assert!(handle.commit().is_err());
        assert_eq!(handle.state(), TransactionState::Failed);
        assert!(*executed1.lock().unwrap());
        assert!(*executed2.lock().unwrap());
        assert!(*compensated1.lock().unwrap());
        assert!(!(*compensated2.lock().unwrap()));
    }

    #[test]
    fn test_saga_builder() {
        let executed1 = Arc::new(Mutex::new(false));
        let executed2 = Arc::new(Mutex::new(false));

        let result = TransactionBuilder::new()
            .push(Box::new(SimpleOperation {
                name: "op1".into(),
                executed: executed1.clone(),
                compensated: Arc::new(Mutex::new(false)),
            }))
            .push(Box::new(SimpleOperation {
                name: "op2".into(),
                executed: executed2.clone(),
                compensated: Arc::new(Mutex::new(false)),
            }))
            .execute();

        assert!(result.is_ok());
        assert!(*executed1.lock().unwrap());
        assert!(*executed2.lock().unwrap());
    }

    // ------------------------------------------------------------------
    // New tests — TransactionError Display
    // ------------------------------------------------------------------

    #[test]
    fn test_transaction_failed_display() {
        let err = TransactionError::TransactionFailed("timeout".into());
        let msg = format!("{err}");
        assert_eq!(msg, "Transaction failed: timeout");
    }

    #[test]
    fn test_compensation_error_display() {
        let err = TransactionError::CompensationError {
            step: "debit_account".into(),
            error: "insufficient funds".into(),
        };
        let msg = format!("{err}");
        assert!(msg.contains("debit_account"));
        assert!(msg.contains("insufficient funds"));
    }

    #[test]
    fn test_already_committed_display() {
        let err = TransactionError::AlreadyCommitted;
        let msg = format!("{err}");
        assert_eq!(msg, "Transaction already committed");
    }

    #[test]
    fn test_already_rolledback_display() {
        let err = TransactionError::AlreadyRolledback;
        let msg = format!("{err}");
        assert_eq!(msg, "Transaction already rolled back");
    }

    #[test]
    fn test_not_active_display() {
        let err = TransactionError::NotActive;
        let msg = format!("{err}");
        assert_eq!(msg, "Transaction not active");
    }

    #[test]
    fn test_transaction_error_debug() {
        let err = TransactionError::TransactionFailed("boom".into());
        let dbg = format!("{err:?}");
        assert!(dbg.contains("TransactionFailed"));
    }

    // ------------------------------------------------------------------
    // New tests — TransactionState
    // ------------------------------------------------------------------

    #[test]
    fn test_transaction_state_initial_is_active() {
        let handle = TransactionHandle::new();
        assert_eq!(handle.state(), TransactionState::Active);
    }

    #[test]
    fn test_state_transitions_to_committed_on_success() {
        let mut handle = TransactionHandle::new();
        handle.commit().unwrap();
        assert_eq!(handle.state(), TransactionState::Committed);
    }

    #[test]
    fn test_state_transitions_to_rolled_back() {
        let mut handle = TransactionHandle::new();
        handle.rollback().unwrap();
        assert_eq!(handle.state(), TransactionState::RolledBack);
    }

    #[test]
    fn test_state_transitions_to_failed_on_error() {
        let mut handle = TransactionHandle::new();
        let (op, _, _) = simple_op("fail-me");
        handle.add_operation(Box::new(op));
        assert!(handle.commit().is_err());
        assert_eq!(handle.state(), TransactionState::Failed);
    }

    #[test]
    fn test_commit_after_commit_returns_not_active() {
        let mut handle = TransactionHandle::new();
        handle.commit().unwrap();
        let err = handle.commit().unwrap_err();
        assert!(matches!(err, TransactionError::NotActive));
    }

    #[test]
    fn test_rollback_after_commit_returns_not_active() {
        let mut handle = TransactionHandle::new();
        handle.commit().unwrap();
        let err = handle.rollback().unwrap_err();
        assert!(matches!(err, TransactionError::NotActive));
    }

    #[test]
    fn test_commit_after_rollback_returns_not_active() {
        let mut handle = TransactionHandle::new();
        handle.rollback().unwrap();
        let err = handle.commit().unwrap_err();
        assert!(matches!(err, TransactionError::NotActive));
    }

    #[test]
    fn test_rollback_after_rollback_returns_not_active() {
        let mut handle = TransactionHandle::new();
        handle.rollback().unwrap();
        let err = handle.rollback().unwrap_err();
        assert!(matches!(err, TransactionError::NotActive));
    }

    #[test]
    fn test_commit_after_failure_returns_not_active() {
        let mut handle = TransactionHandle::new();
        let (op, _, _) = simple_op("fail-op");
        handle.add_operation(Box::new(op));
        assert!(handle.commit().is_err());
        let err = handle.commit().unwrap_err();
        assert!(matches!(err, TransactionError::NotActive));
    }

    #[test]
    fn test_rollback_after_failure_returns_not_active() {
        let mut handle = TransactionHandle::new();
        let (op, _, _) = simple_op("fail-op");
        handle.add_operation(Box::new(op));
        assert!(handle.commit().is_err());
        let err = handle.rollback().unwrap_err();
        assert!(matches!(err, TransactionError::NotActive));
    }

    #[test]
    fn test_transaction_state_equality() {
        assert_eq!(TransactionState::Active, TransactionState::Active);
        assert_ne!(TransactionState::Active, TransactionState::Committed);
        assert_ne!(TransactionState::Committed, TransactionState::RolledBack);
        assert_ne!(TransactionState::RolledBack, TransactionState::Failed);
    }

    #[test]
    fn test_transaction_state_clone() {
        let s = TransactionState::Active;
        let s2 = s;
        assert_eq!(s, s2);
    }

    #[test]
    fn test_transaction_state_debug() {
        let dbg = format!("{:?}", TransactionState::Committed);
        assert_eq!(dbg, "Committed");
    }

    // ------------------------------------------------------------------
    // New tests — TransactionHandle
    // ------------------------------------------------------------------

    #[test]
    fn test_handle_has_unique_id() {
        let h1 = TransactionHandle::new();
        let h2 = TransactionHandle::new();
        assert_ne!(h1.id(), h2.id());
    }

    #[test]
    fn test_handle_id_is_uuid_format() {
        let handle = TransactionHandle::new();
        // UUID v4 format: 8-4-4-4-12
        assert_eq!(handle.id().len(), 36);
        assert_eq!(handle.id().chars().filter(|c| *c == '-').count(), 4);
    }

    #[test]
    fn test_handle_default_is_active() {
        let handle = TransactionHandle::default();
        assert_eq!(handle.state(), TransactionState::Active);
    }

    #[test]
    fn test_handle_debug() {
        let handle = TransactionHandle::new();
        let dbg = format!("{handle:?}");
        assert!(dbg.contains("TransactionHandle"));
        assert!(dbg.contains("Active"));
    }

    #[test]
    fn test_commit_empty_transaction_succeeds() {
        let mut handle = TransactionHandle::new();
        // No operations added — commit should succeed vacuously
        handle.commit().unwrap();
        assert_eq!(handle.state(), TransactionState::Committed);
    }

    #[test]
    fn test_rollback_empty_transaction_succeeds() {
        let mut handle = TransactionHandle::new();
        handle.rollback().unwrap();
        assert_eq!(handle.state(), TransactionState::RolledBack);
    }

    #[test]
    fn test_operations_execute_in_order() {
        let log = Arc::new(Mutex::new(Vec::<String>::new()));

        let mut handle = TransactionHandle::new();
        for label in ["first", "second", "third"] {
            handle.add_operation(Box::new(OrderTracker {
                log: log.clone(),
                label: label.into(),
                should_fail: false,
            }));
        }

        handle.commit().unwrap();
        let entries = log.lock().unwrap();
        assert_eq!(*entries, vec!["exec:first", "exec:second", "exec:third"]);
    }

    #[test]
    fn test_compensation_runs_in_reverse_order() {
        let log = Arc::new(Mutex::new(Vec::<String>::new()));

        let mut handle = TransactionHandle::new();
        handle.add_operation(Box::new(OrderTracker {
            log: log.clone(),
            label: "A".into(),
            should_fail: false,
        }));
        handle.add_operation(Box::new(OrderTracker {
            log: log.clone(),
            label: "B".into(),
            should_fail: false,
        }));
        handle.add_operation(Box::new(OrderTracker {
            log: log.clone(),
            label: "C".into(),
            should_fail: true, // This one fails
        }));

        assert!(handle.commit().is_err());
        let entries = log.lock().unwrap();
        // exec:A, exec:B, exec:C (fails), comp:B, comp:A (reverse of completed)
        assert_eq!(*entries, vec!["exec:A", "exec:B", "exec:C", "comp:B", "comp:A"]);
    }

    #[test]
    fn test_first_operation_fails_no_compensation_needed() {
        let log = Arc::new(Mutex::new(Vec::<String>::new()));

        let mut handle = TransactionHandle::new();
        handle.add_operation(Box::new(OrderTracker {
            log: log.clone(),
            label: "first".into(),
            should_fail: true,
        }));
        handle.add_operation(Box::new(OrderTracker {
            log: log.clone(),
            label: "second".into(),
            should_fail: false,
        }));

        assert!(handle.commit().is_err());
        let entries = log.lock().unwrap();
        // Only the first exec runs, and since completed_operations=0, no compensation
        assert_eq!(*entries, vec!["exec:first"]);
    }

    #[test]
    fn test_many_operations_all_succeed() {
        let mut handle = TransactionHandle::new();
        let mut flags = Vec::new();

        for i in 0..20 {
            let (op, exec, _comp) = simple_op(&format!("op{i}"));
            handle.add_operation(Box::new(op));
            flags.push(exec);
        }

        handle.commit().unwrap();
        assert_eq!(handle.state(), TransactionState::Committed);
        for (i, flag) in flags.iter().enumerate() {
            assert!(*flag.lock().unwrap(), "Operation {i} should have been executed");
        }
    }

    // ------------------------------------------------------------------
    // New tests — Saga
    // ------------------------------------------------------------------

    #[test]
    fn test_saga_new_creates_active_handle() {
        let saga = Saga::new();
        assert_eq!(saga.handle.state(), TransactionState::Active);
    }

    #[test]
    fn test_saga_default() {
        let saga = Saga::default();
        assert_eq!(saga.handle.state(), TransactionState::Active);
    }

    #[test]
    fn test_saga_debug() {
        let saga = Saga::new();
        let dbg = format!("{saga:?}");
        assert!(dbg.contains("Saga"));
    }

    #[test]
    fn test_saga_executes_all_steps() {
        let (op1, exec1, _) = simple_op("step1");
        let (op2, exec2, _) = simple_op("step2");

        let mut saga = Saga::new();
        saga.add_step(Box::new(op1));
        saga.add_step(Box::new(op2));
        saga.execute().unwrap();

        assert!(*exec1.lock().unwrap());
        assert!(*exec2.lock().unwrap());
    }

    #[test]
    fn test_saga_compensates_on_failure() {
        let (op1, exec1, comp1) = simple_op("step1");
        let (op2, _exec2, _comp2) = simple_op("step2-fail");

        let mut saga = Saga::new();
        saga.add_step(Box::new(op1));
        saga.add_step(Box::new(op2));

        assert!(saga.execute().is_err());
        assert!(*exec1.lock().unwrap());
        assert!(*comp1.lock().unwrap());
    }

    #[test]
    fn test_saga_add_step_returns_self() {
        let (op, _, _) = simple_op("x");
        let mut saga = Saga::new();
        let returned = saga.add_step(Box::new(op));
        // Should return &mut Self for chaining
        assert_eq!(returned.handle.state(), TransactionState::Active);
    }

    #[test]
    fn test_saga_empty_execute_succeeds() {
        let mut saga = Saga::new();
        saga.execute().unwrap();
    }

    // ------------------------------------------------------------------
    // New tests — TransactionBuilder
    // ------------------------------------------------------------------

    #[test]
    fn test_builder_new() {
        let builder = TransactionBuilder::new();
        let dbg = format!("{builder:?}");
        assert!(dbg.contains("TransactionBuilder"));
        assert!(dbg.contains("0"));
    }

    #[test]
    fn test_builder_default() {
        let builder = TransactionBuilder::default();
        let dbg = format!("{builder:?}");
        assert!(dbg.contains("TransactionBuilder"));
    }

    #[test]
    fn test_builder_empty_execute_succeeds() {
        let result = TransactionBuilder::new().execute();
        assert!(result.is_ok());
    }

    #[test]
    fn test_builder_chaining() {
        let (op1, exec1, _) = simple_op("a");
        let (op2, exec2, _) = simple_op("b");
        let (op3, exec3, _) = simple_op("c");

        TransactionBuilder::new()
            .push(Box::new(op1))
            .push(Box::new(op2))
            .push(Box::new(op3))
            .execute()
            .unwrap();

        assert!(*exec1.lock().unwrap());
        assert!(*exec2.lock().unwrap());
        assert!(*exec3.lock().unwrap());
    }

    #[test]
    fn test_builder_failure_compensates() {
        let (op1, _exec1, comp1) = simple_op("ok");
        let (op2, _, _) = simple_op("fail-here");

        let result = TransactionBuilder::new().push(Box::new(op1)).push(Box::new(op2)).execute();

        assert!(result.is_err());
        assert!(*comp1.lock().unwrap());
    }

    // ------------------------------------------------------------------
    // TransactionResult type alias
    // ------------------------------------------------------------------

    #[test]
    fn test_transaction_result_ok() {
        fn returns_ok() -> TransactionResult<i32> {
            Ok(42)
        }
        let value = returns_ok();
        assert_eq!(value.unwrap(), 42);
    }

    #[test]
    fn test_transaction_result_err() {
        let result: TransactionResult<()> = Err(TransactionError::NotActive);
        assert!(result.is_err());
    }

    // ------------------------------------------------------------------
    // Compensation failure
    // ------------------------------------------------------------------

    #[test]
    fn test_failing_compensation_propagates_error() {
        let mut handle = TransactionHandle::new();
        handle.add_operation(Box::new(FailingCompensation));

        let (fail_op, _, _) = simple_op("fail-trigger");
        handle.add_operation(Box::new(fail_op));

        let err = handle.commit().unwrap_err();
        // The commit fails due to the second op, then compensation of the first
        // op also fails, so we should get a CompensationError
        assert!(
            matches!(err, TransactionError::CompensationError { .. }),
            "Expected CompensationError, got: {err:?}"
        );
    }
}