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
//! Transaction management methods.
//!
//! Provides closures and manual transaction control for both read and write operations.
use crate::api::transaction::{ReadTransaction, WriteTransaction};
use crate::core::error::{Result, ResultExt, TransactionError};
use crate::core::hlc::HybridTimestamp;
use crate::core::temporal::Timestamp;
use crate::db::AletheiaDB;
use crate::storage::index_persistence::tracker::PersistenceTracker;
use crate::storage::wal::WriteOptions;
use std::sync::Arc;
/// Record persistence mutations after a successful commit.
///
/// Only scans write flags when persistence tracking is active,
/// avoiding unnecessary buffer scans when persistence is disabled.
fn record_tx_mutations(tracker: Option<&Arc<PersistenceTracker>>, tx: &WriteTransaction) {
if let Some(tracker) = tracker {
if tx.has_node_writes() || tx.has_edge_writes() {
tracker.record_graph_mutation();
tracker.record_temporal_mutation();
// Labels are interned strings, so node/edge writes always mutate the interner
tracker.record_string_mutation();
}
if tx.has_vector_writes() {
tracker.record_vector_mutation();
}
}
}
impl AletheiaDB {
/// Compute a snapshot timestamp that is strictly greater than the last commit
/// timestamp, ensuring all previously committed transactions are visible.
///
/// The MVCC visibility check uses strict less-than (`commit_ts < snapshot_ts`),
/// so the snapshot must be strictly greater than the most recent commit to see it.
/// When the system clock advances past the last commit, `now()` is sufficient.
/// When it hasn't (e.g., multiple operations within the same clock tick), we
/// advance one logical tick past the last commit.
fn snapshot_timestamp_for_read(&self) -> Result<Timestamp> {
// Capture current time before acquiring lock to minimize lock contention
let now = crate::core::temporal::time::now();
let last_commit =
*self
.current_timestamp
.lock()
.map_err(|_| TransactionError::LockPoisoned {
resource: "current_timestamp".to_string(),
})?;
if now > last_commit {
// Wallclock advanced past the last commit — now is sufficient
Ok(now)
} else {
// Wallclock hasn't advanced — advance one logical tick past the last
// commit so that `commit_ts < snapshot_ts` holds for all committed txns.
// Use checked_add to handle potential overflow (theoretically requires
// 4B+ events per microsecond, but we handle it for correctness).
let next_logical =
last_commit
.logical()
.checked_add(1)
.ok_or(crate::core::error::Error::Temporal(
crate::core::error::TemporalError::LogicalCounterOverflow {
wallclock: last_commit.wallclock(),
current_logical: last_commit.logical(),
},
))?;
// SAFETY: wallclock is copied from an existing valid HybridTimestamp,
// and next_logical is bounded by u32::MAX via checked_add above.
Ok(HybridTimestamp::new_unchecked(
last_commit.wallclock(),
next_logical,
))
}
}
/// Create a new read-only transaction.
///
/// Read-only transactions are lightweight and have zero overhead:
/// - No write buffer
/// - No WAL logging
/// - Snapshot-based reads for consistency
/// - No commit overhead
///
/// # Errors
///
/// Returns an error if the timestamp lock is poisoned.
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::AletheiaDB;
/// # use aletheiadb::core::NodeId;
/// # use aletheiadb::api::ReadOps;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// # let node_id = NodeId::new(1)?;
/// let tx = db.read_transaction()?;
/// let node = tx.get_node(node_id)?;
/// // No commit needed - transaction is read-only
/// # Ok(())
/// # }
/// ```
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn read_transaction(&self) -> Result<ReadTransaction> {
let result = (|| {
let tx_id = self.tx_id_gen.next();
let snapshot_timestamp = self.snapshot_timestamp_for_read()?;
self.visibility_manager.register_active(tx_id);
let snapshot = self.visibility_manager.capture_snapshot(snapshot_timestamp);
Ok(ReadTransaction::new(
tx_id,
snapshot,
Arc::clone(&self.current),
Arc::clone(&self.visibility_manager),
Arc::clone(&self.historical),
))
})();
result.record_error_metric()
}
/// Execute a read-only operation in a transaction.
///
/// This is a closure-based API that automatically manages the transaction lifecycle.
/// The transaction is automatically cleaned up after the closure completes.
///
/// The error type is generic, allowing you to use custom error types that implement
/// `From<aletheiadb::Error>` for seamless error conversion with the `?` operator.
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::AletheiaDB;
/// # use aletheiadb::core::NodeId;
/// # use aletheiadb::api::ReadOps;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// # let node_id = NodeId::new(1)?;
/// // With AletheiaDB's error type (default)
/// let name: Option<aletheiadb::PropertyValue> = db.read(|tx| {
/// let node = tx.get_node(node_id)?;
/// Ok::<_, aletheiadb::Error>(node.get_property("name").cloned())
/// })?;
///
/// // With custom error type
/// #[derive(Debug)]
/// enum RepositoryError {
/// Database(aletheiadb::Error),
/// NotFound,
/// }
///
/// impl From<aletheiadb::Error> for RepositoryError {
/// fn from(e: aletheiadb::Error) -> Self {
/// RepositoryError::Database(e)
/// }
/// }
///
/// let name: Result<String, RepositoryError> = db.read(|tx| {
/// let node = tx.get_node(node_id)?; // ? operator works!
/// node.get_property("name")
/// .and_then(|v| v.as_str())
/// .map(|s| s.to_string())
/// .ok_or(RepositoryError::NotFound)
/// });
/// # Ok(())
/// # }
/// ```
pub fn read<F, T, E>(&self, f: F) -> std::result::Result<T, E>
where
F: FnOnce(&ReadTransaction) -> std::result::Result<T, E>,
E: From<crate::core::error::Error>,
{
let tx = self.read_transaction().map_err(E::from)?;
f(&tx)
}
/// Create a new write transaction.
///
/// Write transactions provide full ACID guarantees:
/// - **Atomicity**: All-or-nothing commit via write buffering
/// - **Consistency**: Referential integrity validation before commit
/// - **Isolation**: Snapshot Isolation with write-write conflict detection
/// - **Durability**: WAL with fsync for true durability
///
/// # Errors
///
/// Returns an error if the timestamp lock is poisoned.
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::{AletheiaDB, PropertyMapBuilder};
/// # use aletheiadb::core::NodeId;
/// # use aletheiadb::api::WriteOps;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// # let props = PropertyMapBuilder::new().build();
/// # let edge_props = PropertyMapBuilder::new().build();
/// # let other = NodeId::new(2)?;
/// let mut tx = db.write_transaction()?;
/// let node_id = tx.create_node("Person", props)?;
/// tx.create_edge(node_id, other, "KNOWS", edge_props)?;
/// tx.commit()?; // or tx.rollback()
/// # Ok(())
/// # }
/// ```
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn write_transaction(&self) -> Result<WriteTransaction> {
let result = (|| {
let tx_id = self.tx_id_gen.next();
let snapshot_timestamp = self.snapshot_timestamp_for_read()?;
self.visibility_manager.register_active(tx_id);
let snapshot = self.visibility_manager.capture_snapshot(snapshot_timestamp);
Ok(WriteTransaction::new_with_clock_observed_at(
tx_id,
snapshot,
Arc::clone(&self.current),
Arc::clone(&self.historical),
Arc::clone(&self.temporal_indexes),
Arc::clone(&self.wal),
Arc::clone(&self.current_timestamp),
Arc::clone(&self.commit_clock_observed_at),
Arc::clone(&self.visibility_manager),
Arc::clone(&self.node_id_gen),
Arc::clone(&self.edge_id_gen),
Arc::clone(&self.version_id_gen),
))
})();
result.record_error_metric()
}
/// Execute a write operation in a transaction.
///
/// This is a closure-based API that automatically manages the transaction lifecycle.
/// The transaction is automatically committed on Ok, or rolled back on Err.
///
/// The error type is generic, allowing you to use custom error types that implement
/// `From<aletheiadb::Error>` for seamless error conversion with the `?` operator.
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::{AletheiaDB, PropertyMapBuilder};
/// # use aletheiadb::core::NodeId;
/// # use aletheiadb::api::WriteOps;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// # let props = PropertyMapBuilder::new().build();
/// # let edge_props = PropertyMapBuilder::new().build();
/// # let other = NodeId::new(2)?;
/// # fn validate_node(id: NodeId) -> bool { true }
/// // With AletheiaDB's error type (default)
/// let node_id = db.write(|tx| {
/// let id = tx.create_node("Person", props.clone())?;
/// tx.create_edge(id, other, "KNOWS", edge_props.clone())?;
/// Ok::<_, aletheiadb::Error>(id)
/// })?;
///
/// #[derive(Debug)]
/// enum RepositoryError {
/// Database(aletheiadb::Error),
/// ValidationFailed,
/// }
/// impl From<aletheiadb::Error> for RepositoryError {
/// fn from(e: aletheiadb::Error) -> Self { RepositoryError::Database(e) }
/// }
///
/// // With custom error type
/// let node_id: Result<NodeId, RepositoryError> = db.write(|tx| {
/// let id = tx.create_node("Person", props)?; // ? operator works!
/// if !validate_node(id) {
/// return Err(RepositoryError::ValidationFailed);
/// }
/// Ok(id)
/// });
/// # Ok(())
/// # }
/// ```
pub fn write<F, T, E>(&self, f: F) -> std::result::Result<T, E>
where
F: FnOnce(&mut WriteTransaction) -> std::result::Result<T, E>,
E: From<crate::core::error::Error>,
{
let mut tx = self.write_transaction().map_err(E::from)?;
let result = f(&mut tx)?;
record_tx_mutations(self.persistence_tracker.as_ref(), &tx);
tx.commit().map_err(E::from)?;
Ok(result)
}
/// Execute a write operation and return both the result and commit timestamp.
///
/// This is useful for benchmarks and tests that need to query the database
/// at the exact commit timestamp to verify temporal semantics.
///
/// The error type is generic, allowing you to use custom error types that implement
/// `From<aletheiadb::Error>` for seamless error conversion with the `?` operator.
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::{AletheiaDB, PropertyMapBuilder};
/// # use aletheiadb::core::NodeId;
/// # use aletheiadb::core::temporal::Timestamp;
/// # use aletheiadb::api::WriteOps;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// # let properties = PropertyMapBuilder::new().build();
/// // With AletheiaDB's error type (default)
/// let (node_id, commit_ts) = db.write_with_timestamp(|tx| {
/// tx.create_node("Person", properties.clone())
/// })?;
///
/// // Query at exact commit timestamp
/// let node = db.get_node_at_time(node_id, commit_ts, commit_ts)?;
///
/// #[derive(Debug)]
/// enum RepositoryError {
/// Database(aletheiadb::Error),
/// }
/// impl From<aletheiadb::Error> for RepositoryError {
/// fn from(e: aletheiadb::Error) -> Self { RepositoryError::Database(e) }
/// }
///
/// // With custom error type
/// let result: Result<(NodeId, Timestamp), RepositoryError> =
/// db.write_with_timestamp(|tx| {
/// let id = tx.create_node("Person", properties)?;
/// Ok(id)
/// });
/// # Ok(())
/// # }
/// ```
pub fn write_with_timestamp<F, T, E>(&self, f: F) -> std::result::Result<(T, Timestamp), E>
where
F: FnOnce(&mut WriteTransaction) -> std::result::Result<T, E>,
E: From<crate::core::error::Error>,
{
let mut tx = self.write_transaction().map_err(E::from)?;
let result = f(&mut tx)?;
record_tx_mutations(self.persistence_tracker.as_ref(), &tx);
let commit_ts = tx.commit_with_timestamp().map_err(E::from)?;
Ok((result, commit_ts))
}
/// Execute a write operation with custom durability options.
///
/// This allows overriding the database's default durability mode for
/// specific transactions. Useful for bulk loading (Async mode) or
/// critical operations (Synchronous mode override).
///
/// The error type is generic, allowing you to use custom error types that implement
/// `From<aletheiadb::Error>` for seamless error conversion with the `?` operator.
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::{AletheiaDB, WriteOptions, DurabilityMode, PropertyMap};
/// # use aletheiadb::api::WriteOps;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = AletheiaDB::new()?;
/// let bulk_data = vec![PropertyMap::new()];
///
/// // Use Async mode for bulk loading (faster but less durable)
/// let mode = DurabilityMode::async_mode_validated(100)?;
/// let options = WriteOptions::new().with_durability(mode);
///
/// // With AletheiaDB's error type (default)
/// db.write_with_options(options.clone(), |tx| {
/// for item in &bulk_data {
/// tx.create_node("Item", item.clone())?;
/// }
/// Ok::<_, aletheiadb::Error>(())
/// })?;
///
/// #[derive(Debug)]
/// enum RepositoryError {
/// Database(aletheiadb::Error),
/// }
/// impl From<aletheiadb::Error> for RepositoryError {
/// fn from(e: aletheiadb::Error) -> Self { RepositoryError::Database(e) }
/// }
///
/// // With custom error type
/// let result: Result<(), RepositoryError> = db.write_with_options(options, |tx| {
/// for item in &bulk_data {
/// tx.create_node("Item", item.clone())?; // ? operator works!
/// }
/// Ok(())
/// });
/// # Ok(())
/// # }
/// ```
pub fn write_with_options<F, T, E>(
&self,
options: WriteOptions,
f: F,
) -> std::result::Result<T, E>
where
F: FnOnce(&mut WriteTransaction) -> std::result::Result<T, E>,
E: From<crate::core::error::Error>,
{
let mut tx = self
.write_transaction_with_options(options)
.map_err(E::from)?;
let result = f(&mut tx)?;
record_tx_mutations(self.persistence_tracker.as_ref(), &tx);
tx.commit().map_err(E::from)?;
Ok(result)
}
/// Create a write transaction with custom durability options.
///
/// This is the low-level API for creating transactions with specific
/// durability settings. The transaction must be manually committed or
/// rolled back.
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::{AletheiaDB, WriteOptions, DurabilityMode, PropertyMapBuilder};
/// # use aletheiadb::api::WriteOps;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// # let props = PropertyMapBuilder::new().build();
/// let options = WriteOptions::new()
/// .with_durability(DurabilityMode::Synchronous);
///
/// let mut tx = db.write_transaction_with_options(options)?;
/// tx.create_node("Critical", props)?;
/// tx.commit()?;
/// # Ok(())
/// # }
/// ```
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn write_transaction_with_options(
&self,
options: WriteOptions,
) -> Result<WriteTransaction> {
let result = (|| {
let tx_id = self.tx_id_gen.next();
let snapshot_timestamp = self.snapshot_timestamp_for_read()?;
self.visibility_manager.register_active(tx_id);
let snapshot = self.visibility_manager.capture_snapshot(snapshot_timestamp);
let durability = options.effective_durability(self.default_durability);
Ok(WriteTransaction::new_with_durability_and_clock_observed_at(
tx_id,
snapshot,
Arc::clone(&self.current),
Arc::clone(&self.historical),
Arc::clone(&self.temporal_indexes),
Arc::clone(&self.wal),
Arc::clone(&self.current_timestamp),
Arc::clone(&self.commit_clock_observed_at),
Arc::clone(&self.visibility_manager),
Arc::clone(&self.node_id_gen),
Arc::clone(&self.edge_id_gen),
Arc::clone(&self.version_id_gen),
durability,
))
})();
result.record_error_metric()
}
}