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
//! ACID transaction implementation with full isolation and durability guarantees
use super::{IsolationLevel, MvccSnapshot, WalEntry, WriteAheadLog};
use crate::model::Quad;
use crate::OxirsError;
use scirs2_core::metrics::{Counter, Timer};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
/// Transaction ID (monotonically increasing)
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct TransactionId(pub u64);
impl TransactionId {
/// Get the raw transaction ID
pub fn raw(&self) -> u64 {
self.0
}
}
/// Transaction state
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransactionState {
/// Transaction is active
Active,
/// Transaction is preparing to commit
Preparing,
/// Transaction committed successfully
Committed,
/// Transaction was aborted
Aborted,
}
/// ACID transaction with full guarantees
pub struct AcidTransaction {
/// Transaction ID
id: TransactionId,
/// Current state
state: TransactionState,
/// Isolation level
isolation: IsolationLevel,
/// MVCC snapshot (for snapshot isolation)
#[allow(dead_code)]
snapshot: Option<MvccSnapshot>,
/// Pending quad insertions
pending_inserts: Vec<Quad>,
/// Pending quad deletions
pending_deletes: Vec<Quad>,
/// Read set (for conflict detection)
read_set: HashMap<Quad, u64>,
/// Write set (for validation)
write_set: HashMap<Quad, QuadVersion>,
/// Write-Ahead Log
wal: Arc<RwLock<WriteAheadLog>>,
/// Optional backing store to which committed inserts/deletes are applied
/// during [`AcidTransaction::commit`]. When `None`, the transaction only
/// records durability entries in the WAL (e.g. for tests or callers that
/// apply the pending sets themselves via [`AcidTransaction::pending_inserts`]).
store: Option<Arc<dyn crate::Store>>,
/// Commit counter
commit_counter: Arc<Counter>,
/// Abort counter
abort_counter: Arc<Counter>,
/// Commit timer
commit_timer: Arc<Timer>,
}
/// Versioned quad for MVCC
#[derive(Debug, Clone)]
struct QuadVersion {
/// The quad
#[allow(dead_code)]
quad: Quad,
/// Version number
version: u64,
/// Creating transaction ID
#[allow(dead_code)]
created_by: TransactionId,
/// Deleting transaction ID (if deleted)
deleted_by: Option<TransactionId>,
}
impl AcidTransaction {
/// Create a new ACID transaction
pub(super) fn new(
id: TransactionId,
isolation: IsolationLevel,
snapshot: Option<MvccSnapshot>,
wal: Arc<RwLock<WriteAheadLog>>,
commit_counter: Arc<Counter>,
abort_counter: Arc<Counter>,
commit_timer: Arc<Timer>,
) -> Self {
Self {
id,
state: TransactionState::Active,
isolation,
snapshot,
pending_inserts: Vec::new(),
pending_deletes: Vec::new(),
read_set: HashMap::new(),
write_set: HashMap::new(),
wal,
store: None,
commit_counter,
abort_counter,
commit_timer,
}
}
/// Attach a backing store so that [`AcidTransaction::commit`] applies the
/// transaction's pending inserts and deletes to it atomically with the WAL
/// commit record. Without a store the committed changes would only be
/// recorded in the WAL and never become visible in the data set.
pub fn with_store(mut self, store: Arc<dyn crate::Store>) -> Self {
self.store = Some(store);
self
}
/// Get the transaction ID
pub fn id(&self) -> TransactionId {
self.id
}
/// Get the current transaction state
pub fn state(&self) -> TransactionState {
self.state
}
/// Get the isolation level
pub fn isolation(&self) -> IsolationLevel {
self.isolation
}
/// Insert a quad into the transaction
pub fn insert(&mut self, quad: Quad) -> Result<bool, OxirsError> {
self.check_active()?;
// Check if already in pending inserts
if self.pending_inserts.contains(&quad) {
return Ok(false);
}
// Check if in pending deletes (re-insertion)
if let Some(pos) = self.pending_deletes.iter().position(|q| q == &quad) {
self.pending_deletes.remove(pos);
return Ok(true);
}
// Record in write set for validation
self.write_set.insert(
quad.clone(),
QuadVersion {
quad: quad.clone(),
version: self.id.0,
created_by: self.id,
deleted_by: None,
},
);
// Add to pending inserts
self.pending_inserts.push(quad.clone());
// Write to WAL for durability
self.write_to_wal(WalEntry::Insert {
tx_id: self.id.0,
quad,
})?;
Ok(true)
}
/// Delete a quad from the transaction
pub fn delete(&mut self, quad: Quad) -> Result<bool, OxirsError> {
self.check_active()?;
// Check if already in pending deletes
if self.pending_deletes.contains(&quad) {
return Ok(false);
}
// Check if in pending inserts (delete before commit)
if let Some(pos) = self.pending_inserts.iter().position(|q| q == &quad) {
self.pending_inserts.remove(pos);
return Ok(true);
}
// Record in write set for validation
if let Some(version) = self.write_set.get_mut(&quad) {
version.deleted_by = Some(self.id);
} else {
self.write_set.insert(
quad.clone(),
QuadVersion {
quad: quad.clone(),
version: self.id.0,
created_by: self.id,
deleted_by: Some(self.id),
},
);
}
// Add to pending deletes
self.pending_deletes.push(quad.clone());
// Write to WAL for durability
self.write_to_wal(WalEntry::Delete {
tx_id: self.id.0,
quad,
})?;
Ok(true)
}
/// Record a read for conflict detection
pub fn record_read(&mut self, quad: &Quad) -> Result<(), OxirsError> {
self.check_active()?;
// Record in read set with current version
self.read_set.insert(quad.clone(), self.id.0);
Ok(())
}
/// Validate the transaction before commit
fn validate(&self) -> Result<(), OxirsError> {
// For serializable isolation, check for conflicts
if self.isolation == IsolationLevel::Serializable {
// Check read-write conflicts
for (quad, version) in &self.read_set {
if let Some(write_version) = self.write_set.get(quad) {
if write_version.version > *version {
return Err(OxirsError::ConcurrencyError(
"Read-write conflict detected".to_string(),
));
}
}
}
}
// 1. Check for duplicate inserts within the same transaction
let mut seen_inserts = std::collections::HashSet::new();
for quad in &self.pending_inserts {
if !seen_inserts.insert(quad) {
return Err(OxirsError::Store(format!(
"Duplicate insert detected in transaction: {:?}",
quad
)));
}
}
// 2. Check for conflicting operations (insert and delete of the same quad)
for insert_quad in &self.pending_inserts {
for delete_quad in &self.pending_deletes {
if insert_quad == delete_quad {
return Err(OxirsError::Store(format!(
"Conflicting insert/delete operations for quad: {:?}",
insert_quad
)));
}
}
}
// 3. Check for write-write conflicts in write set
let mut write_conflicts = 0;
for (quad, version) in &self.write_set {
// If a quad has been both created and deleted in this transaction
if version.deleted_by.is_some() && version.created_by == self.id {
write_conflicts += 1;
}
// Check version consistency
if version.version > self.id.0 {
return Err(OxirsError::ConcurrencyError(format!(
"Version inconsistency detected for quad: {:?}",
quad
)));
}
}
// 4. Transaction size validation (prevent excessive operations)
const MAX_PENDING_OPS: usize = 1_000_000; // 1 million operations per transaction
let total_ops = self.pending_inserts.len() + self.pending_deletes.len();
if total_ops > MAX_PENDING_OPS {
return Err(OxirsError::Store(format!(
"Transaction exceeds maximum operation limit: {} > {}",
total_ops, MAX_PENDING_OPS
)));
}
// 5. Validate quad components for inserts
for quad in &self.pending_inserts {
// Validate subject is not blank if strict validation needed
// (This is a placeholder - actual validation depends on RDF semantics)
// Validate predicate is a named node (RDF requirement)
use crate::model::RdfTerm;
if quad.predicate().as_str().is_empty() {
return Err(OxirsError::Store(
"Invalid predicate in quad: predicate cannot be empty".to_string(),
));
}
// Validate object is not null/invalid
// (Actual validation would check RDF term validity)
}
// 6. Check for snapshot isolation violations
if self.isolation == IsolationLevel::Snapshot {
// Ensure no reads have been invalidated by concurrent writes
// This is a simplified check - full implementation would query the snapshot manager
if !self.read_set.is_empty() && write_conflicts > self.pending_deletes.len() / 2 {
return Err(OxirsError::ConcurrencyError(
"Snapshot isolation violation: too many write conflicts".to_string(),
));
}
}
// 7. Validate referential integrity (graph-level constraints)
// Check that deleted quads actually exist in pending operations or database
// This is a simplified check - full implementation would query the store
for delete_quad in &self.pending_deletes {
// Ensure we're not deleting something we just inserted
if self.pending_inserts.contains(delete_quad) {
return Err(OxirsError::Store(format!(
"Cannot delete quad that was just inserted: {:?}",
delete_quad
)));
}
}
// 8. Check for potential deadlocks (simplified)
// In a full implementation, this would use a deadlock detection algorithm
if self.read_set.len() > 1000 && self.write_set.len() > 1000 {
tracing::warn!(
"Transaction {} has large read/write sets - potential deadlock risk",
self.id.0
);
}
tracing::debug!(
"Transaction {} validated: {} inserts, {} deletes, {} reads, {} writes",
self.id.0,
self.pending_inserts.len(),
self.pending_deletes.len(),
self.read_set.len(),
self.write_set.len()
);
Ok(())
}
/// Commit the transaction with full ACID guarantees
pub fn commit(mut self) -> Result<(), OxirsError> {
self.check_active()?;
// Start timing the commit
let _timer_guard = self.commit_timer.start();
// Transition to preparing state
self.state = TransactionState::Preparing;
// Validate before commit
self.validate()?;
// Write commit record to WAL (durability)
self.write_to_wal(WalEntry::Commit { tx_id: self.id.0 })?;
// Force WAL to disk for durability guarantee
self.flush_wal()?;
// Apply the committed changes to the backing store (redo phase). The
// commit record is already durable, so a crash between here and full
// application is recoverable by replaying the WAL. Deletions are
// applied before insertions to mirror the pending-operation ordering.
if let Some(store) = &self.store {
for quad in &self.pending_deletes {
store.remove_quad(quad)?;
}
for quad in &self.pending_inserts {
store.insert_quad(quad.clone())?;
}
}
// Transition to committed state
self.state = TransactionState::Committed;
// Update metrics
self.commit_counter.add(1);
tracing::info!(
"Transaction {} committed successfully with {} inserts and {} deletes",
self.id.0,
self.pending_inserts.len(),
self.pending_deletes.len()
);
Ok(())
}
/// Abort the transaction
pub fn abort(mut self) -> Result<(), OxirsError> {
if self.state == TransactionState::Committed {
return Err(OxirsError::Store(
"Cannot abort committed transaction".to_string(),
));
}
// Write abort record to WAL
self.write_to_wal(WalEntry::Abort { tx_id: self.id.0 })?;
// Transition to aborted state
self.state = TransactionState::Aborted;
// Update metrics
self.abort_counter.add(1);
// Clear pending operations
self.pending_inserts.clear();
self.pending_deletes.clear();
self.read_set.clear();
self.write_set.clear();
tracing::info!("Transaction {} aborted", self.id.0);
Ok(())
}
/// Get pending insertions
pub fn pending_inserts(&self) -> &[Quad] {
&self.pending_inserts
}
/// Get pending deletions
pub fn pending_deletes(&self) -> &[Quad] {
&self.pending_deletes
}
/// Get the number of operations in this transaction
pub fn operation_count(&self) -> usize {
self.pending_inserts.len() + self.pending_deletes.len()
}
// Private helper methods
/// Check if transaction is active
fn check_active(&self) -> Result<(), OxirsError> {
if self.state != TransactionState::Active {
return Err(OxirsError::Store(format!(
"Transaction is not active (state: {:?})",
self.state
)));
}
Ok(())
}
/// Write an entry to the WAL
fn write_to_wal(&self, entry: WalEntry) -> Result<(), OxirsError> {
let mut wal = self
.wal
.write()
.map_err(|_| OxirsError::ConcurrencyError("WAL lock poisoned".to_string()))?;
wal.append(entry)
}
/// Flush WAL to disk
fn flush_wal(&self) -> Result<(), OxirsError> {
let mut wal = self
.wal
.write()
.map_err(|_| OxirsError::ConcurrencyError("WAL lock poisoned".to_string()))?;
wal.flush()
}
}
impl Drop for AcidTransaction {
fn drop(&mut self) {
// Auto-abort if not committed
if self.state == TransactionState::Active {
tracing::warn!(
"Transaction {} dropped without commit or abort, auto-aborting",
self.id.0
);
let _ = self.write_to_wal(WalEntry::Abort { tx_id: self.id.0 });
self.abort_counter.add(1);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{GraphName, Literal, NamedNode, Object, Predicate, Subject};
use tempfile::tempdir;
fn create_test_quad(id: usize) -> Quad {
Quad::new(
Subject::NamedNode(
NamedNode::new(format!("http://s{}", id)).expect("valid IRI from format"),
),
Predicate::NamedNode(
NamedNode::new(format!("http://p{}", id)).expect("valid IRI from format"),
),
Object::Literal(Literal::new(format!("value{}", id))),
GraphName::DefaultGraph,
)
}
#[test]
fn test_transaction_insert() -> Result<(), OxirsError> {
let dir = tempdir().map_err(|e| OxirsError::Io(e.to_string()))?;
let wal = Arc::new(RwLock::new(WriteAheadLog::new(dir.path())?));
let mut tx = AcidTransaction::new(
TransactionId(1),
IsolationLevel::Snapshot,
None,
wal,
Arc::new(Counter::new("test.commits".to_string())),
Arc::new(Counter::new("test.aborts".to_string())),
Arc::new(Timer::new("test.commit_time".to_string())),
);
let quad = create_test_quad(1);
assert!(tx.insert(quad.clone())?);
assert!(!tx.insert(quad)?); // Duplicate insert
assert_eq!(tx.pending_inserts().len(), 1);
Ok(())
}
#[test]
fn test_transaction_delete() -> Result<(), OxirsError> {
let dir = tempdir().map_err(|e| OxirsError::Io(e.to_string()))?;
let wal = Arc::new(RwLock::new(WriteAheadLog::new(dir.path())?));
let mut tx = AcidTransaction::new(
TransactionId(1),
IsolationLevel::Snapshot,
None,
wal,
Arc::new(Counter::new("test.commits".to_string())),
Arc::new(Counter::new("test.aborts".to_string())),
Arc::new(Timer::new("test.commit_time".to_string())),
);
let quad = create_test_quad(1);
assert!(tx.delete(quad.clone())?);
assert!(!tx.delete(quad)?); // Duplicate delete
assert_eq!(tx.pending_deletes().len(), 1);
Ok(())
}
#[test]
fn test_transaction_commit() -> Result<(), OxirsError> {
let dir = tempdir().map_err(|e| OxirsError::Io(e.to_string()))?;
let wal = Arc::new(RwLock::new(WriteAheadLog::new(dir.path())?));
let mut tx = AcidTransaction::new(
TransactionId(1),
IsolationLevel::Snapshot,
None,
wal,
Arc::new(Counter::new("test.commits".to_string())),
Arc::new(Counter::new("test.aborts".to_string())),
Arc::new(Timer::new("test.commit_time".to_string())),
);
let quad = create_test_quad(1);
tx.insert(quad)?;
assert_eq!(tx.state(), TransactionState::Active);
tx.commit()?;
// Note: Can't check state after commit since it consumes self
Ok(())
}
#[test]
fn test_transaction_abort() -> Result<(), OxirsError> {
let dir = tempdir().map_err(|e| OxirsError::Io(e.to_string()))?;
let wal = Arc::new(RwLock::new(WriteAheadLog::new(dir.path())?));
let mut tx = AcidTransaction::new(
TransactionId(1),
IsolationLevel::Snapshot,
None,
wal,
Arc::new(Counter::new("test.commits".to_string())),
Arc::new(Counter::new("test.aborts".to_string())),
Arc::new(Timer::new("test.commit_time".to_string())),
);
let quad = create_test_quad(1);
tx.insert(quad)?;
assert_eq!(tx.state(), TransactionState::Active);
tx.abort()?;
// Note: Can't check state after abort since it consumes self
Ok(())
}
#[test]
fn test_commit_applies_inserts_and_deletes_to_store() -> Result<(), OxirsError> {
use crate::rdf_store::RdfStore;
use crate::Store as StoreTrait;
let dir = tempdir().map_err(|e| OxirsError::Io(e.to_string()))?;
let wal = Arc::new(RwLock::new(WriteAheadLog::new(dir.path())?));
let store: Arc<dyn crate::Store> = Arc::new(RdfStore::new()?);
// Pre-seed a quad that the transaction will delete on commit.
let existing = create_test_quad(99);
StoreTrait::insert_quad(&*store, existing.clone())?;
assert_eq!(StoreTrait::len(&*store)?, 1);
let mut tx = AcidTransaction::new(
TransactionId(1),
IsolationLevel::Snapshot,
None,
wal,
Arc::new(Counter::new("test.commits".to_string())),
Arc::new(Counter::new("test.aborts".to_string())),
Arc::new(Timer::new("test.commit_time".to_string())),
)
.with_store(store.clone());
let new_quad = create_test_quad(1);
tx.insert(new_quad.clone())?;
tx.delete(existing.clone())?;
// Before commit, the store is unchanged.
assert_eq!(StoreTrait::len(&*store)?, 1);
tx.commit()?;
// After commit, the insert is visible and the delete has been applied.
assert_eq!(StoreTrait::len(&*store)?, 1);
let all = StoreTrait::quads(&*store)?;
assert!(all.contains(&new_quad), "committed insert must be visible");
assert!(!all.contains(&existing), "committed delete must be applied");
Ok(())
}
}