oxiz-solver 0.2.0

Main CDCL(T) Solver API for OxiZ
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
//! Backtrack Manager for SMT Solver.
//!
//! Manages:
//! - Decision stack and backtracking
//! - Trail of assignments
//! - Undo/redo operations
//! - Incremental solving state

#[allow(unused_imports)]
use crate::prelude::*;
use oxiz_core::ast::TermId;

/// Backtrack manager for incremental SMT solving.
pub struct BacktrackManager {
    /// Decision stack: levels and their decision literals
    decision_stack: Vec<DecisionLevel>,
    /// Current decision level
    current_level: usize,
    /// Trail of all assignments
    trail: Vec<Assignment>,
    /// Variable to trail index mapping
    var_to_trail: FxHashMap<TermId, usize>,
    /// Undo stack for theory-specific operations
    undo_stack: Vec<UndoAction>,
    /// Checkpoint stack for incremental solving
    checkpoints: Vec<Checkpoint>,
    /// Statistics
    stats: BacktrackStats,
}

/// A decision level in the search.
#[derive(Debug, Clone)]
pub struct DecisionLevel {
    /// Level number
    pub level: usize,
    /// Decision literal at this level (if any)
    pub decision: Option<Assignment>,
    /// Trail position at start of this level
    pub trail_start: usize,
}

/// An assignment to a variable.
#[derive(Debug, Clone)]
pub struct Assignment {
    /// Variable being assigned
    pub var: TermId,
    /// Assigned value
    pub value: bool,
    /// Decision level at which this was assigned
    pub level: usize,
    /// Reason for assignment (None = decision, Some = propagation)
    pub reason: Option<ReasonClause>,
}

/// Reason for a propagation.
#[derive(Debug, Clone)]
pub enum ReasonClause {
    /// Boolean clause that caused propagation
    BooleanClause(Vec<TermId>),
    /// Theory propagation
    TheoryPropagation(TheoryReason),
}

/// Theory-specific reason for propagation.
#[derive(Debug, Clone)]
pub struct TheoryReason {
    /// Theory identifier
    pub theory_id: usize,
    /// Theory-specific explanation
    pub explanation: Vec<TermId>,
}

/// Undo action for theory operations.
#[derive(Debug, Clone)]
pub enum UndoAction {
    /// Undo an equality assertion
    UndoEquality(TermId, TermId),
    /// Undo a bound update
    UndoBound(TermId, BoundUpdate),
    /// Undo an array store
    UndoArrayStore(TermId),
    /// Generic theory undo with callback identifier
    TheoryUndo(usize, Vec<TermId>),
}

/// Bound update information.
#[derive(Debug, Clone)]
pub struct BoundUpdate {
    /// Old lower bound
    pub old_lower: Option<i64>,
    /// Old upper bound
    pub old_upper: Option<i64>,
}

/// Checkpoint for incremental solving.
#[derive(Debug, Clone)]
pub struct Checkpoint {
    /// Decision level at checkpoint
    pub level: usize,
    /// Trail size at checkpoint
    pub trail_size: usize,
    /// Undo stack size at checkpoint
    pub undo_size: usize,
}

/// Backtrack statistics.
#[derive(Debug, Clone, Default)]
pub struct BacktrackStats {
    /// Number of decisions made
    pub decisions: usize,
    /// Number of propagations
    pub propagations: usize,
    /// Number of backtracks
    pub backtracks: usize,
    /// Number of full restarts
    pub restarts: usize,
    /// Number of undo operations
    pub undos: usize,
    /// Maximum decision level reached
    pub max_level: usize,
}

impl BacktrackManager {
    /// Create a new backtrack manager.
    pub fn new() -> Self {
        Self {
            decision_stack: vec![DecisionLevel {
                level: 0,
                decision: None,
                trail_start: 0,
            }],
            current_level: 0,
            trail: Vec::new(),
            var_to_trail: FxHashMap::default(),
            undo_stack: Vec::new(),
            checkpoints: Vec::new(),
            stats: BacktrackStats::default(),
        }
    }

    /// Make a decision: assign variable at a new decision level.
    pub fn decide(&mut self, var: TermId, value: bool) -> Result<(), String> {
        self.current_level += 1;
        self.stats.decisions += 1;

        if self.current_level > self.stats.max_level {
            self.stats.max_level = self.current_level;
        }

        let assignment = Assignment {
            var,
            value,
            level: self.current_level,
            reason: None, // Decision has no reason
        };

        // Record trail position
        let trail_start = self.trail.len();

        // Push decision level
        self.decision_stack.push(DecisionLevel {
            level: self.current_level,
            decision: Some(assignment.clone()),
            trail_start,
        });

        // Add to trail
        self.assign(assignment)?;

        Ok(())
    }

    /// Propagate: assign variable due to constraint propagation.
    pub fn propagate(
        &mut self,
        var: TermId,
        value: bool,
        reason: ReasonClause,
    ) -> Result<(), String> {
        self.stats.propagations += 1;

        let assignment = Assignment {
            var,
            value,
            level: self.current_level,
            reason: Some(reason),
        };

        self.assign(assignment)?;

        Ok(())
    }

    /// Assign a variable.
    fn assign(&mut self, assignment: Assignment) -> Result<(), String> {
        // Check if already assigned
        if let Some(&trail_idx) = self.var_to_trail.get(&assignment.var) {
            let existing = &self.trail[trail_idx];
            if existing.value != assignment.value {
                return Err(format!(
                    "Conflict: variable {:?} already assigned differently",
                    assignment.var
                ));
            }
            // Already assigned with same value
            return Ok(());
        }

        // Record trail position
        let trail_idx = self.trail.len();
        self.var_to_trail.insert(assignment.var, trail_idx);

        // Add to trail
        self.trail.push(assignment);

        Ok(())
    }

    /// Backtrack to a specific decision level.
    pub fn backtrack(&mut self, target_level: usize) -> Result<(), String> {
        if target_level > self.current_level {
            return Err("Cannot backtrack to higher level".to_string());
        }

        if target_level == self.current_level {
            return Ok(()); // Nothing to do
        }

        self.stats.backtracks += 1;

        // Find trail position for target level
        // We want to keep assignments at target_level, so we use the trail_start of the next level
        let target_trail_pos = if target_level + 1 < self.decision_stack.len() {
            self.decision_stack[target_level + 1].trail_start
        } else {
            // No assignments to remove (shouldn't happen if backtracking to lower level)
            self.trail.len()
        };

        // Undo assignments
        while self.trail.len() > target_trail_pos {
            if let Some(assignment) = self.trail.pop() {
                self.var_to_trail.remove(&assignment.var);
            }
        }

        // Undo theory operations
        self.undo_to_level(target_level)?;

        // Update decision stack
        self.decision_stack.truncate(target_level + 1);
        self.current_level = target_level;

        Ok(())
    }

    /// Restart: backtrack to level 0.
    pub fn restart(&mut self) -> Result<(), String> {
        self.stats.restarts += 1;
        self.backtrack(0)
    }

    /// Record an undo action.
    pub fn record_undo(&mut self, action: UndoAction) {
        self.undo_stack.push(action);
    }

    /// Undo theory operations to target level.
    fn undo_to_level(&mut self, _target_level: usize) -> Result<(), String> {
        // Find how many undo operations to perform
        // (Simplified: undo all operations beyond target level)

        let mut undos_to_apply = Vec::new();

        // Collect undo operations (in reverse order)
        // Pop directly instead of checking last() then popping
        while let Some(undo) = self.undo_stack.pop() {
            undos_to_apply.push(undo);

            // Stop condition (simplified)
            if undos_to_apply.len() > 100 {
                break;
            }
        }

        // Apply undo operations
        for undo in undos_to_apply {
            self.apply_undo(undo)?;
            self.stats.undos += 1;
        }

        Ok(())
    }

    /// Apply an undo operation.
    fn apply_undo(&mut self, _action: UndoAction) -> Result<(), String> {
        // Theory-specific undo logic would go here
        // This is a placeholder
        Ok(())
    }

    /// Create a checkpoint for incremental solving.
    pub fn push_checkpoint(&mut self) {
        self.checkpoints.push(Checkpoint {
            level: self.current_level,
            trail_size: self.trail.len(),
            undo_size: self.undo_stack.len(),
        });
    }

    /// Pop to most recent checkpoint.
    pub fn pop_checkpoint(&mut self) -> Result<(), String> {
        if let Some(checkpoint) = self.checkpoints.pop() {
            self.backtrack(checkpoint.level)?;

            // Restore undo stack size
            self.undo_stack.truncate(checkpoint.undo_size);

            Ok(())
        } else {
            Err("No checkpoint to pop".to_string())
        }
    }

    /// Get current decision level.
    pub fn current_level(&self) -> usize {
        self.current_level
    }

    /// Check if variable is assigned.
    pub fn is_assigned(&self, var: TermId) -> bool {
        self.var_to_trail.contains_key(&var)
    }

    /// Get assignment for variable.
    pub fn get_assignment(&self, var: TermId) -> Option<&Assignment> {
        if let Some(&trail_idx) = self.var_to_trail.get(&var) {
            self.trail.get(trail_idx)
        } else {
            None
        }
    }

    /// Get all assignments at current level.
    pub fn current_assignments(&self) -> &[Assignment] {
        &self.trail
    }

    /// Get decision at specific level.
    pub fn get_decision(&self, level: usize) -> Option<&Assignment> {
        if level < self.decision_stack.len() {
            self.decision_stack[level].decision.as_ref()
        } else {
            None
        }
    }

    /// Get statistics.
    pub fn stats(&self) -> &BacktrackStats {
        &self.stats
    }

    /// Reset statistics.
    pub fn reset_stats(&mut self) {
        self.stats = BacktrackStats::default();
    }
}

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

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

    #[test]
    fn test_backtrack_manager() {
        let mgr = BacktrackManager::new();
        assert_eq!(mgr.current_level(), 0);
        assert_eq!(mgr.stats.decisions, 0);
    }

    #[test]
    fn test_decide() {
        let mut mgr = BacktrackManager::new();

        let var = TermId::from(1);
        mgr.decide(var, true)
            .expect("test operation should succeed");

        assert_eq!(mgr.current_level(), 1);
        assert_eq!(mgr.stats.decisions, 1);
        assert!(mgr.is_assigned(var));
    }

    #[test]
    fn test_propagate() {
        let mut mgr = BacktrackManager::new();

        let var1 = TermId::from(1);
        mgr.decide(var1, true)
            .expect("test operation should succeed");

        let var2 = TermId::from(2);
        let reason = ReasonClause::BooleanClause(vec![var1]);
        mgr.propagate(var2, false, reason)
            .expect("test operation should succeed");

        assert_eq!(mgr.stats.propagations, 1);
        assert!(mgr.is_assigned(var2));
    }

    #[test]
    fn test_backtrack() {
        let mut mgr = BacktrackManager::new();

        let var1 = TermId::from(1);
        mgr.decide(var1, true)
            .expect("test operation should succeed");

        let var2 = TermId::from(2);
        mgr.decide(var2, false)
            .expect("test operation should succeed");

        assert_eq!(mgr.current_level(), 2);

        mgr.backtrack(1).expect("test operation should succeed");

        assert_eq!(mgr.current_level(), 1);
        assert!(mgr.is_assigned(var1));
        assert!(!mgr.is_assigned(var2));
    }

    #[test]
    fn test_restart() {
        let mut mgr = BacktrackManager::new();

        mgr.decide(TermId::from(1), true)
            .expect("test operation should succeed");
        mgr.decide(TermId::from(2), false)
            .expect("test operation should succeed");

        mgr.restart().expect("test operation should succeed");

        assert_eq!(mgr.current_level(), 0);
        assert_eq!(mgr.stats.restarts, 1);
        assert_eq!(mgr.trail.len(), 0);
    }

    #[test]
    fn test_checkpoint() {
        let mut mgr = BacktrackManager::new();

        mgr.decide(TermId::from(1), true)
            .expect("test operation should succeed");
        mgr.push_checkpoint();

        mgr.decide(TermId::from(2), false)
            .expect("test operation should succeed");

        mgr.pop_checkpoint().expect("test operation should succeed");

        assert_eq!(mgr.current_level(), 1);
        assert!(!mgr.is_assigned(TermId::from(2)));
    }

    #[test]
    fn test_get_assignment() {
        let mut mgr = BacktrackManager::new();

        let var = TermId::from(1);
        mgr.decide(var, true)
            .expect("test operation should succeed");

        let assignment = mgr
            .get_assignment(var)
            .expect("test operation should succeed");
        assert!(assignment.value);
        assert_eq!(assignment.level, 1);
        assert!(assignment.reason.is_none());
    }
}