tensorlogic-infer 0.1.0

Execution and autodiff traits for TensorLogic inference engines
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
//! Speculative execution for computation graphs.
//!
//! This module implements speculative execution techniques:
//! - **Branch prediction**: Predict conditional branches and execute speculatively
//! - **Prefetching**: Pre-execute likely future operations
//! - **Rollback mechanisms**: Discard incorrect speculative results
//! - **Confidence scoring**: Track prediction accuracy
//! - **Adaptive strategies**: Learn from prediction success/failure
//!
//! ## Example
//!
//! ```rust,ignore
//! use tensorlogic_infer::{SpeculativeExecutor, PredictionStrategy, RollbackPolicy};
//!
//! // Create speculative executor
//! let executor = SpeculativeExecutor::new()
//!     .with_strategy(PredictionStrategy::HistoryBased)
//!     .with_rollback_policy(RollbackPolicy::Immediate)
//!     .with_confidence_threshold(0.7);
//!
//! // Execute with speculation
//! let result = executor.execute_speculative(&graph, &inputs)?;
//!
//! // Check speculation stats
//! let stats = executor.get_stats();
//! println!("Speculation success rate: {:.1}%", stats.success_rate * 100.0);
//! ```

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use thiserror::Error;

/// Speculative execution errors.
#[derive(Error, Debug, Clone, PartialEq)]
pub enum SpeculativeError {
    #[error("Speculation failed: {0}")]
    SpeculationFailed(String),

    #[error("Rollback failed: {0}")]
    RollbackFailed(String),

    #[error("Invalid prediction: {0}")]
    InvalidPrediction(String),

    #[error("Checkpoint not found: {0}")]
    CheckpointNotFound(String),
}

/// Node ID in the computation graph.
pub type NodeId = String;

/// Prediction strategy for speculative execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PredictionStrategy {
    /// Always predict most frequent branch
    MostFrequent,
    /// Use recent history to predict
    HistoryBased,
    /// Use static analysis and heuristics
    Static,
    /// Adaptive strategy that learns over time
    Adaptive,
    /// Always speculate on true branch
    AlwaysTrue,
    /// Never speculate (conservative)
    Never,
}

/// Rollback policy when speculation is incorrect.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RollbackPolicy {
    /// Immediately rollback on misprediction
    Immediate,
    /// Continue speculation and rollback later
    Lazy,
    /// Checkpoint-based rollback
    Checkpoint,
}

/// Branch outcome.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BranchOutcome {
    True,
    False,
    Unknown,
}

/// Speculative task representing work done speculatively.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpeculativeTask {
    pub task_id: u64,
    pub node_id: NodeId,
    pub predicted_branch: BranchOutcome,
    pub confidence: f64,
    pub started_at: u64, // timestamp in microseconds
    pub completed: bool,
    pub correct: Option<bool>, // None if not yet validated
}

/// Branch history entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct BranchHistory {
    node_id: NodeId,
    outcomes: VecDeque<BranchOutcome>,
    max_history: usize,
}

impl BranchHistory {
    fn new(node_id: NodeId, max_history: usize) -> Self {
        Self {
            node_id,
            outcomes: VecDeque::new(),
            max_history,
        }
    }

    fn add_outcome(&mut self, outcome: BranchOutcome) {
        if self.outcomes.len() >= self.max_history {
            self.outcomes.pop_front();
        }
        self.outcomes.push_back(outcome);
    }

    fn predict(&self) -> (BranchOutcome, f64) {
        if self.outcomes.is_empty() {
            return (BranchOutcome::Unknown, 0.0);
        }

        let true_count = self
            .outcomes
            .iter()
            .filter(|&&o| o == BranchOutcome::True)
            .count();
        let false_count = self
            .outcomes
            .iter()
            .filter(|&&o| o == BranchOutcome::False)
            .count();
        let total = true_count + false_count;

        if total == 0 {
            return (BranchOutcome::Unknown, 0.0);
        }

        if true_count > false_count {
            (BranchOutcome::True, true_count as f64 / total as f64)
        } else {
            (BranchOutcome::False, false_count as f64 / total as f64)
        }
    }
}

/// Speculation statistics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpeculationStats {
    pub total_speculations: usize,
    pub correct_speculations: usize,
    pub incorrect_speculations: usize,
    pub rollbacks: usize,
    pub success_rate: f64,
    pub average_confidence: f64,
    pub time_saved_us: f64,
    pub time_wasted_us: f64,
}

/// Checkpoint for rollback.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Checkpoint {
    checkpoint_id: u64,
    node_id: NodeId,
    timestamp: u64,
    // In real implementation, this would store actual state
}

/// Speculative executor.
pub struct SpeculativeExecutor {
    strategy: PredictionStrategy,
    rollback_policy: RollbackPolicy,
    confidence_threshold: f64,
    max_speculation_depth: usize,
    branch_history: HashMap<NodeId, BranchHistory>,
    active_tasks: HashMap<u64, SpeculativeTask>,
    checkpoints: HashMap<u64, Checkpoint>,
    next_task_id: u64,
    next_checkpoint_id: u64,
    stats: SpeculationStats,
    history_length: usize,
}

impl SpeculativeExecutor {
    /// Create a new speculative executor with default settings.
    pub fn new() -> Self {
        Self {
            strategy: PredictionStrategy::HistoryBased,
            rollback_policy: RollbackPolicy::Immediate,
            confidence_threshold: 0.6,
            max_speculation_depth: 3,
            branch_history: HashMap::new(),
            active_tasks: HashMap::new(),
            checkpoints: HashMap::new(),
            next_task_id: 0,
            next_checkpoint_id: 0,
            stats: SpeculationStats {
                total_speculations: 0,
                correct_speculations: 0,
                incorrect_speculations: 0,
                rollbacks: 0,
                success_rate: 0.0,
                average_confidence: 0.0,
                time_saved_us: 0.0,
                time_wasted_us: 0.0,
            },
            history_length: 10,
        }
    }

    /// Set prediction strategy.
    pub fn with_strategy(mut self, strategy: PredictionStrategy) -> Self {
        self.strategy = strategy;
        self
    }

    /// Set rollback policy.
    pub fn with_rollback_policy(mut self, policy: RollbackPolicy) -> Self {
        self.rollback_policy = policy;
        self
    }

    /// Set confidence threshold for speculation.
    pub fn with_confidence_threshold(mut self, threshold: f64) -> Self {
        self.confidence_threshold = threshold.clamp(0.0, 1.0);
        self
    }

    /// Set maximum speculation depth.
    pub fn with_max_depth(mut self, depth: usize) -> Self {
        self.max_speculation_depth = depth;
        self
    }

    /// Predict branch outcome for a node.
    pub fn predict_branch(&self, node_id: &NodeId) -> (BranchOutcome, f64) {
        match self.strategy {
            PredictionStrategy::Never => (BranchOutcome::Unknown, 0.0),
            PredictionStrategy::AlwaysTrue => (BranchOutcome::True, 1.0),
            PredictionStrategy::MostFrequent => {
                if let Some(history) = self.branch_history.get(node_id) {
                    history.predict()
                } else {
                    (BranchOutcome::True, 0.5) // Default to true with low confidence
                }
            }
            PredictionStrategy::HistoryBased => {
                if let Some(history) = self.branch_history.get(node_id) {
                    history.predict()
                } else {
                    (BranchOutcome::Unknown, 0.0)
                }
            }
            PredictionStrategy::Static | PredictionStrategy::Adaptive => {
                // Simplified: use history if available
                if let Some(history) = self.branch_history.get(node_id) {
                    history.predict()
                } else {
                    (BranchOutcome::True, 0.5)
                }
            }
        }
    }

    /// Start speculative execution for a branch.
    pub fn speculate(&mut self, node_id: NodeId) -> Result<u64, SpeculativeError> {
        let (predicted_branch, confidence) = self.predict_branch(&node_id);

        // Only speculate if confidence exceeds threshold
        if confidence < self.confidence_threshold {
            return Err(SpeculativeError::SpeculationFailed(format!(
                "Confidence {} below threshold {}",
                confidence, self.confidence_threshold
            )));
        }

        // Check speculation depth
        let active_count = self.active_tasks.values().filter(|t| !t.completed).count();

        if active_count >= self.max_speculation_depth {
            return Err(SpeculativeError::SpeculationFailed(format!(
                "Maximum speculation depth {} reached",
                self.max_speculation_depth
            )));
        }

        // Create speculative task
        let task_id = self.next_task_id;
        self.next_task_id += 1;

        let task = SpeculativeTask {
            task_id,
            node_id: node_id.clone(),
            predicted_branch,
            confidence,
            started_at: 0, // Would be real timestamp
            completed: false,
            correct: None,
        };

        self.active_tasks.insert(task_id, task);
        self.stats.total_speculations += 1;

        Ok(task_id)
    }

    /// Validate speculative execution result.
    pub fn validate(
        &mut self,
        task_id: u64,
        actual_branch: BranchOutcome,
    ) -> Result<bool, SpeculativeError> {
        let task = self.active_tasks.get_mut(&task_id).ok_or_else(|| {
            SpeculativeError::InvalidPrediction(format!("Task {} not found", task_id))
        })?;

        let correct = task.predicted_branch == actual_branch;
        task.correct = Some(correct);
        task.completed = true;

        // Update history
        let history = self
            .branch_history
            .entry(task.node_id.clone())
            .or_insert_with(|| BranchHistory::new(task.node_id.clone(), self.history_length));
        history.add_outcome(actual_branch);

        // Update stats
        if correct {
            self.stats.correct_speculations += 1;
        } else {
            self.stats.incorrect_speculations += 1;
            // Perform rollback if needed
            self.rollback(task_id)?;
        }

        self.update_stats();

        Ok(correct)
    }

    /// Rollback speculative execution.
    fn rollback(&mut self, task_id: u64) -> Result<(), SpeculativeError> {
        match self.rollback_policy {
            RollbackPolicy::Immediate => {
                // Immediately discard speculative work
                self.active_tasks.remove(&task_id);
                self.stats.rollbacks += 1;
                Ok(())
            }
            RollbackPolicy::Lazy => {
                // Mark for later cleanup
                if let Some(task) = self.active_tasks.get_mut(&task_id) {
                    task.completed = true;
                }
                self.stats.rollbacks += 1;
                Ok(())
            }
            RollbackPolicy::Checkpoint => {
                // Restore from checkpoint
                self.restore_checkpoint(task_id)?;
                self.stats.rollbacks += 1;
                Ok(())
            }
        }
    }

    /// Create checkpoint before speculation.
    pub fn create_checkpoint(&mut self, node_id: NodeId) -> u64 {
        let checkpoint_id = self.next_checkpoint_id;
        self.next_checkpoint_id += 1;

        let checkpoint = Checkpoint {
            checkpoint_id,
            node_id,
            timestamp: 0, // Would be real timestamp
        };

        self.checkpoints.insert(checkpoint_id, checkpoint);
        checkpoint_id
    }

    /// Restore from checkpoint.
    fn restore_checkpoint(&mut self, task_id: u64) -> Result<(), SpeculativeError> {
        // Find and restore checkpoint
        let _task = self.active_tasks.get(&task_id).ok_or_else(|| {
            SpeculativeError::CheckpointNotFound(format!("No task found for id: {}", task_id))
        })?;

        // In real implementation, would restore actual state
        self.active_tasks.remove(&task_id);
        Ok(())
    }

    /// Update speculation statistics.
    fn update_stats(&mut self) {
        let total = (self.stats.correct_speculations + self.stats.incorrect_speculations) as f64;
        if total > 0.0 {
            self.stats.success_rate = self.stats.correct_speculations as f64 / total;
        }

        let confidence_sum: f64 = self.active_tasks.values().map(|t| t.confidence).sum();
        let task_count = self.active_tasks.len() as f64;
        if task_count > 0.0 {
            self.stats.average_confidence = confidence_sum / task_count;
        }
    }

    /// Get speculation statistics.
    pub fn get_stats(&self) -> &SpeculationStats {
        &self.stats
    }

    /// Clear completed speculative tasks.
    pub fn cleanup(&mut self) {
        self.active_tasks.retain(|_, task| !task.completed);
    }

    /// Reset statistics.
    pub fn reset_stats(&mut self) {
        self.stats = SpeculationStats {
            total_speculations: 0,
            correct_speculations: 0,
            incorrect_speculations: 0,
            rollbacks: 0,
            success_rate: 0.0,
            average_confidence: 0.0,
            time_saved_us: 0.0,
            time_wasted_us: 0.0,
        };
    }

    /// Get active speculation count.
    pub fn active_speculation_count(&self) -> usize {
        self.active_tasks.values().filter(|t| !t.completed).count()
    }

    /// Check if should speculate based on current state.
    pub fn should_speculate(&self, node_id: &NodeId) -> bool {
        let (_, confidence) = self.predict_branch(node_id);
        confidence >= self.confidence_threshold
            && self.active_speculation_count() < self.max_speculation_depth
    }
}

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

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

    #[test]
    fn test_speculative_executor_creation() {
        let executor = SpeculativeExecutor::new();
        assert_eq!(executor.strategy, PredictionStrategy::HistoryBased);
        assert_eq!(executor.rollback_policy, RollbackPolicy::Immediate);
        assert_eq!(executor.confidence_threshold, 0.6);
    }

    #[test]
    fn test_builder_pattern() {
        let executor = SpeculativeExecutor::new()
            .with_strategy(PredictionStrategy::Adaptive)
            .with_rollback_policy(RollbackPolicy::Checkpoint)
            .with_confidence_threshold(0.8)
            .with_max_depth(5);

        assert_eq!(executor.strategy, PredictionStrategy::Adaptive);
        assert_eq!(executor.rollback_policy, RollbackPolicy::Checkpoint);
        assert_eq!(executor.confidence_threshold, 0.8);
        assert_eq!(executor.max_speculation_depth, 5);
    }

    #[test]
    fn test_always_true_prediction() {
        let executor = SpeculativeExecutor::new().with_strategy(PredictionStrategy::AlwaysTrue);

        let (outcome, confidence) = executor.predict_branch(&"test".to_string());
        assert_eq!(outcome, BranchOutcome::True);
        assert_eq!(confidence, 1.0);
    }

    #[test]
    fn test_never_speculation() {
        let executor = SpeculativeExecutor::new().with_strategy(PredictionStrategy::Never);

        let (outcome, confidence) = executor.predict_branch(&"test".to_string());
        assert_eq!(outcome, BranchOutcome::Unknown);
        assert_eq!(confidence, 0.0);
    }

    #[test]
    fn test_speculation_below_threshold() {
        let mut executor = SpeculativeExecutor::new().with_confidence_threshold(0.9);

        let result = executor.speculate("test".to_string());
        assert!(result.is_err()); // Should fail due to low confidence
    }

    #[test]
    fn test_successful_speculation() {
        let mut executor = SpeculativeExecutor::new()
            .with_strategy(PredictionStrategy::AlwaysTrue)
            .with_confidence_threshold(0.5);

        let task_id = executor.speculate("test".to_string()).expect("unwrap");
        assert_eq!(executor.stats.total_speculations, 1);
        assert!(executor.active_tasks.contains_key(&task_id));
    }

    #[test]
    fn test_correct_validation() {
        let mut executor = SpeculativeExecutor::new()
            .with_strategy(PredictionStrategy::AlwaysTrue)
            .with_confidence_threshold(0.5);

        let task_id = executor.speculate("test".to_string()).expect("unwrap");
        let correct = executor
            .validate(task_id, BranchOutcome::True)
            .expect("unwrap");

        assert!(correct);
        assert_eq!(executor.stats.correct_speculations, 1);
        assert_eq!(executor.stats.incorrect_speculations, 0);
    }

    #[test]
    fn test_incorrect_validation() {
        let mut executor = SpeculativeExecutor::new()
            .with_strategy(PredictionStrategy::AlwaysTrue)
            .with_confidence_threshold(0.5);

        let task_id = executor.speculate("test".to_string()).expect("unwrap");
        let correct = executor
            .validate(task_id, BranchOutcome::False)
            .expect("unwrap");

        assert!(!correct);
        assert_eq!(executor.stats.correct_speculations, 0);
        assert_eq!(executor.stats.incorrect_speculations, 1);
        assert_eq!(executor.stats.rollbacks, 1);
    }

    #[test]
    fn test_history_based_prediction() {
        let mut executor = SpeculativeExecutor::new()
            .with_strategy(PredictionStrategy::AlwaysTrue) // Start with AlwaysTrue to build history
            .with_confidence_threshold(0.5);

        // Build history with mostly true outcomes
        for _ in 0..8 {
            let task_id = executor.speculate("node1".to_string()).expect("unwrap");
            executor
                .validate(task_id, BranchOutcome::True)
                .expect("unwrap");
        }

        for _ in 0..2 {
            let task_id = executor.speculate("node1".to_string()).expect("unwrap");
            executor
                .validate(task_id, BranchOutcome::False)
                .expect("unwrap");
        }

        // Switch to history-based after building history
        executor.strategy = PredictionStrategy::HistoryBased;

        // Should predict True with high confidence
        let (outcome, confidence) = executor.predict_branch(&"node1".to_string());
        assert_eq!(outcome, BranchOutcome::True);
        assert!(confidence > 0.7);
    }

    #[test]
    fn test_max_speculation_depth() {
        let mut executor = SpeculativeExecutor::new()
            .with_strategy(PredictionStrategy::AlwaysTrue)
            .with_confidence_threshold(0.5)
            .with_max_depth(2);

        executor.speculate("node1".to_string()).expect("unwrap");
        executor.speculate("node2".to_string()).expect("unwrap");

        // Third speculation should fail
        let result = executor.speculate("node3".to_string());
        assert!(result.is_err());
    }

    #[test]
    fn test_checkpoint_creation() {
        let mut executor = SpeculativeExecutor::new();
        let checkpoint_id = executor.create_checkpoint("node1".to_string());

        assert!(executor.checkpoints.contains_key(&checkpoint_id));
    }

    #[test]
    fn test_cleanup() {
        let mut executor = SpeculativeExecutor::new()
            .with_strategy(PredictionStrategy::AlwaysTrue)
            .with_confidence_threshold(0.5);

        let task_id = executor.speculate("test".to_string()).expect("unwrap");
        executor
            .validate(task_id, BranchOutcome::True)
            .expect("unwrap");

        assert!(executor.active_tasks.contains_key(&task_id));
        executor.cleanup();
        assert!(!executor.active_tasks.contains_key(&task_id));
    }

    #[test]
    fn test_success_rate_calculation() {
        let mut executor = SpeculativeExecutor::new()
            .with_strategy(PredictionStrategy::AlwaysTrue)
            .with_confidence_threshold(0.5);

        // 3 correct, 1 incorrect = 75% success rate
        for _ in 0..3 {
            let task_id = executor.speculate("test".to_string()).expect("unwrap");
            executor
                .validate(task_id, BranchOutcome::True)
                .expect("unwrap");
        }

        let task_id = executor.speculate("test".to_string()).expect("unwrap");
        executor
            .validate(task_id, BranchOutcome::False)
            .expect("unwrap");

        assert!((executor.stats.success_rate - 0.75).abs() < 0.01);
    }

    #[test]
    fn test_reset_stats() {
        let mut executor = SpeculativeExecutor::new()
            .with_strategy(PredictionStrategy::AlwaysTrue)
            .with_confidence_threshold(0.5);

        let task_id = executor.speculate("test".to_string()).expect("unwrap");
        executor
            .validate(task_id, BranchOutcome::True)
            .expect("unwrap");

        assert_eq!(executor.stats.total_speculations, 1);

        executor.reset_stats();
        assert_eq!(executor.stats.total_speculations, 0);
        assert_eq!(executor.stats.correct_speculations, 0);
    }

    #[test]
    fn test_should_speculate() {
        let mut executor = SpeculativeExecutor::new()
            .with_strategy(PredictionStrategy::AlwaysTrue)
            .with_confidence_threshold(0.5);

        assert!(executor.should_speculate(&"test".to_string()));

        // Fill up speculation depth
        for i in 0..executor.max_speculation_depth {
            executor.speculate(format!("node{}", i)).expect("unwrap");
        }

        assert!(!executor.should_speculate(&"test".to_string()));
    }

    #[test]
    fn test_active_speculation_count() {
        let mut executor = SpeculativeExecutor::new()
            .with_strategy(PredictionStrategy::AlwaysTrue)
            .with_confidence_threshold(0.5);

        assert_eq!(executor.active_speculation_count(), 0);

        executor.speculate("node1".to_string()).expect("unwrap");
        assert_eq!(executor.active_speculation_count(), 1);

        executor.speculate("node2".to_string()).expect("unwrap");
        assert_eq!(executor.active_speculation_count(), 2);
    }

    #[test]
    fn test_different_rollback_policies() {
        let strategies = vec![
            RollbackPolicy::Immediate,
            RollbackPolicy::Lazy,
            RollbackPolicy::Checkpoint,
        ];

        for policy in strategies {
            let mut executor = SpeculativeExecutor::new()
                .with_strategy(PredictionStrategy::AlwaysTrue)
                .with_rollback_policy(policy)
                .with_confidence_threshold(0.5);

            let task_id = executor.speculate("test".to_string()).expect("unwrap");
            executor
                .validate(task_id, BranchOutcome::False)
                .expect("unwrap");

            assert_eq!(executor.stats.rollbacks, 1);
        }
    }
}