oxirs-rule 0.2.4

Forward/backward rule engine for RDFS, OWL, and SWRL reasoning
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
//! Transaction Support for Reasoning Operations
//!
//! Provides ACID (Atomicity, Consistency, Isolation, Durability) transactions
//! for rule-based reasoning operations.
//!
//! # Features
//!
//! - **Atomicity**: All-or-nothing updates
//! - **Consistency**: Maintain knowledge base integrity
//! - **Isolation**: Concurrent transaction support
//! - **Durability**: Persist committed changes
//! - **Rollback**: Undo uncommitted changes
//!
//! # Example
//!
//! ```rust
//! use oxirs_rule::transaction::{TransactionManager, IsolationLevel};
//! use oxirs_rule::{RuleEngine, RuleAtom, Term};
//!
//! let mut manager = TransactionManager::new();
//! let mut engine = RuleEngine::new();
//!
//! // Begin transaction
//! let tx_id = manager.begin_transaction(IsolationLevel::ReadCommitted).expect("should succeed");
//!
//! // Perform operations
//! let fact = RuleAtom::Triple {
//!     subject: Term::Constant("john".to_string()),
//!     predicate: Term::Constant("age".to_string()),
//!     object: Term::Literal("30".to_string()),
//! };
//!
//! manager.add_fact(tx_id, fact).expect("should succeed");
//!
//! // Commit or rollback
//! manager.commit(tx_id).expect("should succeed");
//! ```

use crate::RuleAtom;
use anyhow::Result;
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use tracing::{debug, info, warn};

/// Transaction identifier
pub type TransactionId = u64;

/// Isolation level for transactions
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IsolationLevel {
    /// Read uncommitted (lowest isolation)
    ReadUncommitted,
    /// Read committed
    ReadCommitted,
    /// Repeatable read
    RepeatableRead,
    /// Serializable (highest isolation)
    Serializable,
}

/// Transaction state
#[derive(Debug, Clone, PartialEq)]
pub enum TransactionState {
    /// Transaction is active
    Active,
    /// Transaction is being committed
    Committing,
    /// Transaction has been committed
    Committed,
    /// Transaction is being rolled back
    RollingBack,
    /// Transaction has been aborted
    Aborted,
}

/// Transaction operation
#[derive(Debug, Clone)]
pub enum Operation {
    /// Add a fact
    AddFact(RuleAtom),
    /// Remove a fact
    RemoveFact(RuleAtom),
    /// Add multiple facts
    AddFacts(Vec<RuleAtom>),
    /// Remove multiple facts
    RemoveFacts(Vec<RuleAtom>),
}

/// Transaction record
#[derive(Debug, Clone)]
pub struct Transaction {
    /// Transaction ID
    pub id: TransactionId,
    /// Isolation level
    pub isolation_level: IsolationLevel,
    /// Current state
    pub state: TransactionState,
    /// Operations performed
    pub operations: Vec<Operation>,
    /// Timestamp when started
    pub start_time: u64,
    /// Timestamp when completed (if completed)
    pub end_time: Option<u64>,
}

/// Transaction manager
pub struct TransactionManager {
    /// Active transactions
    transactions: Arc<Mutex<HashMap<TransactionId, Transaction>>>,
    /// Next transaction ID
    next_id: Arc<Mutex<TransactionId>>,
    /// Committed facts
    committed_facts: Arc<Mutex<Vec<RuleAtom>>>,
    /// Transaction log for durability
    log: Arc<Mutex<VecDeque<LogEntry>>>,
    /// Current timestamp
    timestamp: Arc<Mutex<u64>>,
    /// Maximum log size
    max_log_size: usize,
}

/// Log entry for durability
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct LogEntry {
    transaction_id: TransactionId,
    operation: Operation,
    timestamp: u64,
}

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

impl TransactionManager {
    /// Create a new transaction manager
    pub fn new() -> Self {
        Self {
            transactions: Arc::new(Mutex::new(HashMap::new())),
            next_id: Arc::new(Mutex::new(0)),
            committed_facts: Arc::new(Mutex::new(Vec::new())),
            log: Arc::new(Mutex::new(VecDeque::new())),
            timestamp: Arc::new(Mutex::new(0)),
            max_log_size: 10000,
        }
    }

    /// Begin a new transaction
    pub fn begin_transaction(&self, isolation_level: IsolationLevel) -> Result<TransactionId> {
        let mut next_id = self.next_id.lock().expect("lock poisoned");
        let tx_id = *next_id;
        *next_id += 1;

        let mut timestamp = self.timestamp.lock().expect("lock poisoned");
        *timestamp += 1;
        let start_time = *timestamp;

        let transaction = Transaction {
            id: tx_id,
            isolation_level,
            state: TransactionState::Active,
            operations: Vec::new(),
            start_time,
            end_time: None,
        };

        let mut transactions = self.transactions.lock().expect("lock poisoned");
        transactions.insert(tx_id, transaction);

        info!(
            "Started transaction {} with isolation level {:?}",
            tx_id, isolation_level
        );

        Ok(tx_id)
    }

    /// Add a fact within a transaction
    pub fn add_fact(&self, tx_id: TransactionId, fact: RuleAtom) -> Result<()> {
        let mut transactions = self.transactions.lock().expect("lock poisoned");

        let transaction = transactions
            .get_mut(&tx_id)
            .ok_or_else(|| anyhow::anyhow!("Transaction {} not found", tx_id))?;

        if transaction.state != TransactionState::Active {
            return Err(anyhow::anyhow!(
                "Transaction {} is not active (state: {:?})",
                tx_id,
                transaction.state
            ));
        }

        transaction
            .operations
            .push(Operation::AddFact(fact.clone()));

        debug!("Added fact to transaction {}", tx_id);
        Ok(())
    }

    /// Remove a fact within a transaction
    pub fn remove_fact(&self, tx_id: TransactionId, fact: RuleAtom) -> Result<()> {
        let mut transactions = self.transactions.lock().expect("lock poisoned");

        let transaction = transactions
            .get_mut(&tx_id)
            .ok_or_else(|| anyhow::anyhow!("Transaction {} not found", tx_id))?;

        if transaction.state != TransactionState::Active {
            return Err(anyhow::anyhow!("Transaction {} is not active", tx_id));
        }

        transaction.operations.push(Operation::RemoveFact(fact));

        debug!("Removed fact in transaction {}", tx_id);
        Ok(())
    }

    /// Add multiple facts within a transaction
    pub fn add_facts(&self, tx_id: TransactionId, facts: Vec<RuleAtom>) -> Result<()> {
        let mut transactions = self.transactions.lock().expect("lock poisoned");

        let transaction = transactions
            .get_mut(&tx_id)
            .ok_or_else(|| anyhow::anyhow!("Transaction {} not found", tx_id))?;

        if transaction.state != TransactionState::Active {
            return Err(anyhow::anyhow!("Transaction {} is not active", tx_id));
        }

        transaction
            .operations
            .push(Operation::AddFacts(facts.clone()));

        debug!("Added {} facts to transaction {}", facts.len(), tx_id);
        Ok(())
    }

    /// Commit a transaction
    pub fn commit(&self, tx_id: TransactionId) -> Result<()> {
        let mut transactions = self.transactions.lock().expect("lock poisoned");

        let transaction = transactions
            .get_mut(&tx_id)
            .ok_or_else(|| anyhow::anyhow!("Transaction {} not found", tx_id))?;

        if transaction.state != TransactionState::Active {
            return Err(anyhow::anyhow!(
                "Cannot commit transaction {} in state {:?}",
                tx_id,
                transaction.state
            ));
        }

        // Change state to committing
        transaction.state = TransactionState::Committing;

        // Apply operations to committed facts
        let mut committed_facts = self.committed_facts.lock().expect("lock poisoned");

        for operation in &transaction.operations {
            match operation {
                Operation::AddFact(fact) => {
                    committed_facts.push(fact.clone());
                    self.log_operation(tx_id, operation.clone())?;
                }
                Operation::RemoveFact(fact) => {
                    committed_facts.retain(|f| f != fact);
                    self.log_operation(tx_id, operation.clone())?;
                }
                Operation::AddFacts(facts) => {
                    committed_facts.extend(facts.clone());
                    self.log_operation(tx_id, operation.clone())?;
                }
                Operation::RemoveFacts(facts) => {
                    for fact in facts {
                        committed_facts.retain(|f| f != fact);
                    }
                    self.log_operation(tx_id, operation.clone())?;
                }
            }
        }

        // Update transaction state
        let mut timestamp = self.timestamp.lock().expect("lock poisoned");
        *timestamp += 1;
        transaction.end_time = Some(*timestamp);
        transaction.state = TransactionState::Committed;

        info!("Committed transaction {}", tx_id);
        Ok(())
    }

    /// Rollback a transaction
    pub fn rollback(&self, tx_id: TransactionId) -> Result<()> {
        let mut transactions = self.transactions.lock().expect("lock poisoned");

        let transaction = transactions
            .get_mut(&tx_id)
            .ok_or_else(|| anyhow::anyhow!("Transaction {} not found", tx_id))?;

        if transaction.state != TransactionState::Active {
            return Err(anyhow::anyhow!(
                "Cannot rollback transaction {} in state {:?}",
                tx_id,
                transaction.state
            ));
        }

        // Change state to rolling back
        transaction.state = TransactionState::RollingBack;

        // Discard all operations
        transaction.operations.clear();

        // Update transaction state
        let mut timestamp = self.timestamp.lock().expect("lock poisoned");
        *timestamp += 1;
        transaction.end_time = Some(*timestamp);
        transaction.state = TransactionState::Aborted;

        warn!("Rolled back transaction {}", tx_id);
        Ok(())
    }

    /// Get committed facts
    pub fn get_committed_facts(&self) -> Vec<RuleAtom> {
        let committed_facts = self.committed_facts.lock().expect("lock poisoned");
        committed_facts.clone()
    }

    /// Get transaction state
    pub fn get_transaction_state(&self, tx_id: TransactionId) -> Option<TransactionState> {
        let transactions = self.transactions.lock().expect("lock poisoned");
        transactions.get(&tx_id).map(|tx| tx.state.clone())
    }

    /// Check if transaction is active
    pub fn is_active(&self, tx_id: TransactionId) -> bool {
        matches!(
            self.get_transaction_state(tx_id),
            Some(TransactionState::Active)
        )
    }

    /// Log an operation for durability
    fn log_operation(&self, tx_id: TransactionId, operation: Operation) -> Result<()> {
        let mut log = self.log.lock().expect("lock poisoned");
        let mut timestamp = self.timestamp.lock().expect("lock poisoned");
        *timestamp += 1;

        let entry = LogEntry {
            transaction_id: tx_id,
            operation,
            timestamp: *timestamp,
        };

        log.push_back(entry);

        // Trim log if it exceeds max size
        while log.len() > self.max_log_size {
            log.pop_front();
        }

        Ok(())
    }

    /// Get statistics
    pub fn get_stats(&self) -> TransactionStats {
        let transactions = self.transactions.lock().expect("lock poisoned");
        let committed_facts = self.committed_facts.lock().expect("lock poisoned");
        let log = self.log.lock().expect("lock poisoned");

        let active_count = transactions
            .values()
            .filter(|tx| tx.state == TransactionState::Active)
            .count();

        let committed_count = transactions
            .values()
            .filter(|tx| tx.state == TransactionState::Committed)
            .count();

        let aborted_count = transactions
            .values()
            .filter(|tx| tx.state == TransactionState::Aborted)
            .count();

        TransactionStats {
            total_transactions: transactions.len(),
            active_transactions: active_count,
            committed_transactions: committed_count,
            aborted_transactions: aborted_count,
            committed_facts: committed_facts.len(),
            log_entries: log.len(),
        }
    }

    /// Clear completed transactions
    pub fn gc_completed_transactions(&self) {
        let mut transactions = self.transactions.lock().expect("lock poisoned");
        transactions.retain(|_, tx| {
            tx.state == TransactionState::Active || tx.state == TransactionState::Committing
        });
        debug!("Garbage collected completed transactions");
    }
}

/// Transaction statistics
#[derive(Debug, Clone)]
pub struct TransactionStats {
    pub total_transactions: usize,
    pub active_transactions: usize,
    pub committed_transactions: usize,
    pub aborted_transactions: usize,
    pub committed_facts: usize,
    pub log_entries: usize,
}

impl std::fmt::Display for TransactionStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Total: {}, Active: {}, Committed: {}, Aborted: {}, Facts: {}, Log: {}",
            self.total_transactions,
            self.active_transactions,
            self.committed_transactions,
            self.aborted_transactions,
            self.committed_facts,
            self.log_entries
        )
    }
}

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

    #[test]
    fn test_begin_transaction() -> Result<(), Box<dyn std::error::Error>> {
        let manager = TransactionManager::new();
        let tx_id = manager.begin_transaction(IsolationLevel::ReadCommitted)?;

        assert_eq!(tx_id, 0);
        assert!(manager.is_active(tx_id));
        Ok(())
    }

    #[test]
    fn test_add_fact() -> Result<(), Box<dyn std::error::Error>> {
        let manager = TransactionManager::new();
        let tx_id = manager.begin_transaction(IsolationLevel::ReadCommitted)?;

        let fact = RuleAtom::Triple {
            subject: Term::Constant("john".to_string()),
            predicate: Term::Constant("age".to_string()),
            object: Term::Literal("30".to_string()),
        };

        manager.add_fact(tx_id, fact)?;
        assert!(manager.is_active(tx_id));
        Ok(())
    }

    #[test]
    fn test_commit() -> Result<(), Box<dyn std::error::Error>> {
        let manager = TransactionManager::new();
        let tx_id = manager.begin_transaction(IsolationLevel::ReadCommitted)?;

        let fact = RuleAtom::Triple {
            subject: Term::Constant("john".to_string()),
            predicate: Term::Constant("age".to_string()),
            object: Term::Literal("30".to_string()),
        };

        manager.add_fact(tx_id, fact)?;
        manager.commit(tx_id)?;

        let committed_facts = manager.get_committed_facts();
        assert_eq!(committed_facts.len(), 1);
        assert_eq!(
            manager.get_transaction_state(tx_id),
            Some(TransactionState::Committed)
        );
        Ok(())
    }

    #[test]
    fn test_rollback() -> Result<(), Box<dyn std::error::Error>> {
        let manager = TransactionManager::new();
        let tx_id = manager.begin_transaction(IsolationLevel::ReadCommitted)?;

        let fact = RuleAtom::Triple {
            subject: Term::Constant("john".to_string()),
            predicate: Term::Constant("age".to_string()),
            object: Term::Literal("30".to_string()),
        };

        manager.add_fact(tx_id, fact)?;
        manager.rollback(tx_id)?;

        let committed_facts = manager.get_committed_facts();
        assert_eq!(committed_facts.len(), 0);
        assert_eq!(
            manager.get_transaction_state(tx_id),
            Some(TransactionState::Aborted)
        );
        Ok(())
    }

    #[test]
    fn test_multiple_transactions() -> Result<(), Box<dyn std::error::Error>> {
        let manager = TransactionManager::new();

        let tx1 = manager.begin_transaction(IsolationLevel::ReadCommitted)?;
        let tx2 = manager.begin_transaction(IsolationLevel::ReadCommitted)?;

        assert_ne!(tx1, tx2);
        assert!(manager.is_active(tx1));
        assert!(manager.is_active(tx2));
        Ok(())
    }

    #[test]
    fn test_stats() -> Result<(), Box<dyn std::error::Error>> {
        let manager = TransactionManager::new();
        manager.begin_transaction(IsolationLevel::ReadCommitted)?;

        let stats = manager.get_stats();
        assert_eq!(stats.active_transactions, 1);
        assert_eq!(stats.total_transactions, 1);
        Ok(())
    }
}