aletheiadb 0.1.0

A high-performance bi-temporal graph database for LLM integration
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
//! Transaction support for AletheiaDB
//!
//! This module provides MVCC (Multi-Version Concurrency Control) transactions
//! with Snapshot Isolation level.
//!
//! # Transaction Types
//!
//! - [`ReadTransaction`]: Lightweight read-only transactions with zero overhead
//! - [`WriteTransaction`]: Full ACID write transactions with write buffering and WAL
//!
//! # API Styles
//!
//! **Closure-based (recommended)**:
//! ```rust,no_run
//! # use aletheiadb::{AletheiaDB, PropertyMapBuilder, properties};
//! # use aletheiadb::core::NodeId;
//! # use aletheiadb::api::transaction::{ReadOps, WriteOps};
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let db = AletheiaDB::new()?;
//! # let id = NodeId::new(1)?;
//! # let other = NodeId::new(2)?;
//! # let props = PropertyMapBuilder::new().build();
//! # let edge_props = PropertyMapBuilder::new().build();
//! // Read-only
//! let result = db.read(|tx| {
//!     // get_node might fail if node doesn't exist
//!     if let Ok(node) = tx.get_node(id) {
//!         Ok::<_, Box<dyn std::error::Error>>(node.get_property("name").cloned())
//!     } else {
//!         Ok::<_, Box<dyn std::error::Error>>(None)
//!     }
//! })?;
//!
//! // Read-write (auto-commit on Ok, auto-rollback on Err)
//! let node_id = db.write(|tx| {
//!     let node_id = tx.create_node("Person", props)?;
//!     tx.create_edge(node_id, other, "KNOWS", edge_props)?;
//!     Ok::<_, Box<dyn std::error::Error>>(node_id)
//! })?;
//! # Ok(())
//! # }
//! ```
//!
//! **Explicit handles**:
//! ```rust,no_run
//! # use aletheiadb::{AletheiaDB, PropertyMapBuilder};
//! # use aletheiadb::core::NodeId;
//! # use aletheiadb::api::transaction::WriteOps;
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let db = AletheiaDB::new()?;
//! # let n1 = NodeId::new(1)?;
//! # let n2 = NodeId::new(2)?;
//! # let props = PropertyMapBuilder::new().build();
//! let mut tx = db.write_transaction()?;
//! tx.create_node("Person", props.clone())?;
//! tx.create_edge(n1, n2, "KNOWS", props)?;
//! tx.commit()?;  // or tx.rollback()
//! # Ok(())
//! # }
//! ```

pub mod read_tx;
pub mod types;
pub mod visibility;
pub mod write;
pub mod write_buffer;

pub use read_tx::ReadTransaction;
pub use types::{TxId, TxMetadata, TxState};
pub use visibility::{TransactionSnapshot, TxVisibilityManager};
pub use write::WriteTransaction;
pub use write_buffer::{BufferedWrite, WriteBuffer};

use crate::core::error::Result;
use crate::core::graph::{Edge, Node};
#[cfg(test)]
use crate::core::id::MAX_VALID_ID;
use crate::core::id::{EdgeId, NodeId};
use crate::core::property::{PropertyMap, PropertyValue};
use crate::core::temporal::Timestamp;

/// Common read operations available in all transaction types
pub trait ReadOps {
    /// Get a node by ID.
    ///
    /// This returns the node state visible in the current transaction snapshot.
    ///
    /// # Snapshot Isolation
    ///
    /// If the node has been modified or deleted by another transaction after this
    /// transaction started, `get_node` will return the version visible at the start
    /// of this transaction (Snapshot Isolation).
    ///
    /// # Performance
    ///
    /// - **Fast Path**: O(1) lookup in current storage (hash map)
    /// - **Slow Path**: O(log N) lookup in historical storage if not found in current (or version not visible)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, core::NodeId, api::transaction::ReadOps};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let tx = db.read_transaction()?;
    /// # let node_id = NodeId::new(1)?;
    /// let node = tx.get_node(node_id)?;
    /// println!("Node label: {:?}", node.label);
    /// # Ok(())
    /// # }
    /// ```
    fn get_node(&self, id: NodeId) -> Result<Node>;

    /// Get an edge by ID.
    ///
    /// This returns the edge state visible in the current transaction snapshot.
    ///
    /// # Snapshot Isolation
    ///
    /// If the edge has been modified or deleted by another transaction after this
    /// transaction started, `get_edge` will return the version visible at the start
    /// of this transaction (Snapshot Isolation).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, core::EdgeId, api::transaction::ReadOps};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let tx = db.read_transaction()?;
    /// # let edge_id = EdgeId::new(1)?;
    /// let edge = tx.get_edge(edge_id)?;
    /// println!("Edge label: {:?}", edge.label);
    /// # Ok(())
    /// # }
    /// ```
    fn get_edge(&self, id: EdgeId) -> Result<Edge>;

    /// Get outgoing edges from a node.
    ///
    /// Returns all edges where `source == node_id` that are visible in the current snapshot.
    ///
    /// # Ordering
    ///
    /// The order of edges is **not guaranteed**. Do not rely on edges being returned
    /// in insertion order or sorted by ID. The internal storage may reorder edges
    /// during compaction or persistence.
    ///
    /// # Snapshot Isolation
    ///
    /// This method filters edges to ensure only those visible in the current transaction
    /// snapshot are returned. Edges created by concurrent transactions will not be seen.
    ///
    /// # Performance
    ///
    /// - **Time**: O(degree) to collect visible edges
    /// - **Space**: Allocates a new `Vec` containing all edge IDs
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, core::NodeId, api::transaction::ReadOps};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let tx = db.read_transaction()?;
    /// # let node_id = NodeId::new(1)?;
    /// let edges = tx.get_outgoing_edges(node_id);
    /// for edge_id in edges {
    ///     let edge = tx.get_edge(edge_id)?;
    ///     println!("-> {}", edge.target);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    fn get_outgoing_edges(&self, node_id: NodeId) -> Vec<EdgeId>;

    /// Get incoming edges to a node.
    ///
    /// Returns all edges where `target == node_id` that are visible in the current snapshot.
    ///
    /// # Ordering
    ///
    /// The order of edges is **not guaranteed**.
    ///
    /// # Snapshot Isolation
    ///
    /// This method filters edges to ensure only those visible in the current transaction
    /// snapshot are returned.
    ///
    /// # Performance
    ///
    /// - **Time**: O(degree) to collect visible edges
    /// - **Space**: Allocates a new `Vec` containing all edge IDs
    fn get_incoming_edges(&self, node_id: NodeId) -> Vec<EdgeId>;

    /// Get outgoing edges with a specific label.
    ///
    /// Returns all edges where `source == node_id` AND `label == label` that are
    /// visible in the current snapshot.
    ///
    /// # Ordering
    ///
    /// The order of edges is **not guaranteed**.
    ///
    /// # Performance
    ///
    /// - **Time**: O(degree) scan with label filtering
    /// - **Space**: Allocates a new `Vec` containing matching edge IDs
    fn get_outgoing_edges_with_label(&self, node_id: NodeId, label: &str) -> Vec<EdgeId>;

    /// Get the approximate number of nodes in the database.
    ///
    /// # Consistency Note
    ///
    /// This returns the **current** count of committed nodes in the storage engine.
    /// Unlike `get_node()`, this count is **NOT snapshot-isolated**. It may include
    /// nodes created by transactions that committed after this read transaction started.
    ///
    /// This design choice enables O(1) performance without scanning the entire
    /// database to filter visibility for every node.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, api::transaction::ReadOps};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let tx = db.read_transaction()?;
    /// let count = tx.node_count();
    /// println!("Database contains {} nodes", count);
    /// # Ok(())
    /// # }
    /// ```
    fn node_count(&self) -> usize;

    /// Get the approximate number of edges in the database.
    ///
    /// # Consistency Note
    ///
    /// This returns the **current** count of committed edges in the storage engine.
    /// Unlike `get_edge()`, this count is **NOT snapshot-isolated**. It may include
    /// edges created by transactions that committed after this read transaction started.
    ///
    /// This design choice enables O(1) performance without scanning the entire
    /// database to filter visibility for every edge.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, api::transaction::ReadOps};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let tx = db.read_transaction()?;
    /// let count = tx.edge_count();
    /// println!("Database contains {} edges", count);
    /// # Ok(())
    /// # }
    /// ```
    fn edge_count(&self) -> usize;

    /// Find nodes by label and property value.
    ///
    /// Returns the IDs of all nodes with the given label whose specified property
    /// equals the given value. Only nodes visible in the current snapshot are returned.
    ///
    /// # Performance
    ///
    /// - **Time**: O(N) where N = nodes with the given label
    /// - **Space**: O(M) where M = number of matching nodes
    fn find_nodes_by_property(
        &self,
        label: &str,
        property_key: &str,
        property_value: &PropertyValue,
    ) -> Vec<NodeId>;
}

/// Write operations (only available in write transactions)
pub trait WriteOps: ReadOps {
    /// Create a new node with optional backdated valid_from time.
    ///
    /// # Arguments
    ///
    /// * `label` - Node label
    /// * `properties` - Node properties
    /// * `valid_from` - When the fact became valid (None = transaction time)
    ///
    /// # Bi-Temporal Semantics
    ///
    /// - If `valid_from` is None, `valid_time` starts at the **transaction start time**.
    /// - `transaction_time` always starts at the **commit time**.
    /// - This means by default, facts are considered valid from the moment the transaction began.
    /// - If `valid_from` is Some(ts), valid_time starts at `ts`.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, properties, api::transaction::WriteOps};
    /// # use aletheiadb::core::temporal::time;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let mut tx = db.write_transaction()?;
    /// // Backdate a fact to 1 hour ago
    /// let one_hour_ago = time::now().wallclock() - 3_600_000_000;
    /// let valid_from = time::from_secs(one_hour_ago / 1_000_000);
    ///
    /// let node_id = tx.create_node_with_valid_time(
    ///     "Person",
    ///     properties! { "name" => "Alice" },
    ///     Some(valid_from)
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    fn create_node_with_valid_time(
        &mut self,
        label: &str,
        properties: PropertyMap,
        valid_from: Option<Timestamp>,
    ) -> Result<NodeId>;

    /// Create a new node.
    ///
    /// This is a convenience method that sets `valid_from` to the **transaction start time**.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, properties, api::transaction::WriteOps};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let mut tx = db.write_transaction()?;
    /// let node_id = tx.create_node(
    ///     "Person",
    ///     properties! { "name" => "Alice", "age" => 30 }
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    fn create_node(&mut self, label: &str, properties: PropertyMap) -> Result<NodeId> {
        self.create_node_with_valid_time(label, properties, None)
    }

    /// Create a new edge with optional backdated valid_from time.
    ///
    /// Use this when loading historical data where relationships formed in the past.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, properties, core::NodeId, api::transaction::WriteOps};
    /// # use aletheiadb::core::temporal::time;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let mut tx = db.write_transaction()?;
    /// # let alice = NodeId::new(1)?;
    /// # let bob = NodeId::new(2)?;
    /// let past_time = time::from_secs(1609459200); // 2021-01-01
    ///
    /// let edge_id = tx.create_edge_with_valid_time(
    ///     alice,
    ///     bob,
    ///     "KNOWS",
    ///     properties! { "since" => 2021 },
    ///     Some(past_time)
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    fn create_edge_with_valid_time(
        &mut self,
        source: NodeId,
        target: NodeId,
        label: &str,
        properties: PropertyMap,
        valid_from: Option<Timestamp>,
    ) -> Result<EdgeId>;

    /// Create a new edge.
    ///
    /// This is a convenience method that sets `valid_from` to the **transaction start time**.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, properties, core::NodeId, api::transaction::WriteOps};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let mut tx = db.write_transaction()?;
    /// # let alice_id = NodeId::new(1)?;
    /// # let bob_id = NodeId::new(2)?;
    /// let edge_id = tx.create_edge(
    ///     alice_id,
    ///     bob_id,
    ///     "KNOWS",
    ///     properties! { "since" => 2024 }
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    fn create_edge(
        &mut self,
        source: NodeId,
        target: NodeId,
        label: &str,
        properties: PropertyMap,
    ) -> Result<EdgeId> {
        self.create_edge_with_valid_time(source, target, label, properties, None)
    }

    /// Update a node's properties with optional backdated valid_from time.
    ///
    /// This merges the new properties with existing ones (PATCH semantics).
    /// Existing properties not in the map are preserved.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, properties, core::NodeId, api::transaction::WriteOps};
    /// # use aletheiadb::core::temporal::time;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let mut tx = db.write_transaction()?;
    /// # let alice = NodeId::new(1)?;
    /// // Update address effective from yesterday
    /// let yesterday = time::now().wallclock() - 86_400_000_000;
    /// let valid_from = time::from_secs(yesterday / 1_000_000);
    ///
    /// tx.update_node_with_valid_time(
    ///     alice,
    ///     properties! { "city" => "London" },
    ///     Some(valid_from)
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    fn update_node_with_valid_time(
        &mut self,
        node_id: NodeId,
        properties: PropertyMap,
        valid_from: Option<Timestamp>,
    ) -> Result<()>;

    /// Update a node's properties.
    ///
    /// This performs a PATCH update: only the specified properties are updated;
    /// others are preserved. To delete a property, set it to `PropertyValue::Null` (future feature)
    /// or explicit delete (not yet implemented).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, properties, core::NodeId, api::transaction::WriteOps};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let mut tx = db.write_transaction()?;
    /// # let node_id = NodeId::new(1)?;
    /// // Only updates "age", preserves "name"
    /// tx.update_node(
    ///     node_id,
    ///     properties! { "age" => 31 }
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    fn update_node(&mut self, node_id: NodeId, properties: PropertyMap) -> Result<()> {
        self.update_node_with_valid_time(node_id, properties, None)
    }

    /// Update an edge's properties with optional backdated valid_from time.
    ///
    /// This merges the new properties with existing ones (PATCH semantics).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, properties, core::EdgeId, api::transaction::WriteOps};
    /// # use aletheiadb::core::temporal::time;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let mut tx = db.write_transaction()?;
    /// # let edge_id = EdgeId::new(1)?;
    /// // Retroactively increase relationship strength
    /// let past_time = time::from_secs(1609459200);
    ///
    /// tx.update_edge_with_valid_time(
    ///     edge_id,
    ///     properties! { "strength" => 0.8 },
    ///     Some(past_time)
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    fn update_edge_with_valid_time(
        &mut self,
        edge_id: EdgeId,
        properties: PropertyMap,
        valid_from: Option<Timestamp>,
    ) -> Result<()>;

    /// Update an edge's properties.
    ///
    /// This performs a PATCH update: only the specified properties are updated;
    /// others are preserved.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, properties, core::EdgeId, api::transaction::WriteOps};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let mut tx = db.write_transaction()?;
    /// # let edge_id = EdgeId::new(1)?;
    /// tx.update_edge(
    ///     edge_id,
    ///     properties! { "strength" => 0.95 }
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    fn update_edge(&mut self, edge_id: EdgeId, properties: PropertyMap) -> Result<()> {
        self.update_edge_with_valid_time(edge_id, properties, None)
    }

    /// Delete a node with optional backdated valid_from time (without deleting connected edges).
    ///
    /// # Warning
    ///
    /// This method does NOT delete edges connected to the node, which may leave
    /// orphaned edges in the graph. For most use cases, prefer
    /// [`delete_node_cascade`](Self::delete_node_cascade) which automatically
    /// removes all connected edges to maintain referential integrity.
    ///
    /// Only use this method if you explicitly need to preserve edges for some
    /// specialized use case.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, core::NodeId, api::transaction::WriteOps};
    /// # use aletheiadb::core::temporal::time;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let mut tx = db.write_transaction()?;
    /// # let alice = NodeId::new(1)?;
    /// // Mark node as deleted effective from 1 hour ago
    /// let one_hour_ago = time::now().wallclock() - 3_600_000_000;
    /// let valid_from = time::from_secs(one_hour_ago / 1_000_000);
    ///
    /// tx.delete_node_with_valid_time(alice, Some(valid_from))?;
    /// # Ok(())
    /// # }
    /// ```
    fn delete_node_with_valid_time(
        &mut self,
        node_id: NodeId,
        valid_from: Option<Timestamp>,
    ) -> Result<()>;

    /// Delete a node (leaves connected edges).
    ///
    /// **Warning**: This leaves orphaned edges. Use [`delete_node_cascade`](Self::delete_node_cascade)
    /// for safe deletion.
    ///
    /// ## Examples
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, PropertyMapBuilder, properties};
    /// # use aletheiadb::api::transaction::WriteOps;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let db = AletheiaDB::new()?;
    /// let mut tx = db.write_transaction()?;
    ///
    /// let alice = tx.create_node("Person", properties! { "name" => "Alice" })?;
    ///
    /// // Delete the node
    /// tx.delete_node(alice)?;
    ///
    /// tx.commit()?;
    /// # Ok(())
    /// # }
    /// ```
    fn delete_node(&mut self, node_id: NodeId) -> Result<()> {
        self.delete_node_with_valid_time(node_id, None)
    }

    /// Delete a node and all connected edges (cascade delete).
    ///
    /// This method deletes both the node and all edges where the node
    /// appears as either the source or target. This prevents orphaned edges
    /// and maintains referential integrity in the graph.
    ///
    /// # Performance
    ///
    /// The cascade delete operation is efficient even for highly-connected nodes:
    /// - O(degree) complexity where degree is the number of connected edges
    /// - All edge deletions are buffered and applied atomically on commit
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, properties};
    /// # use aletheiadb::api::transaction::WriteOps;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let properties = properties! { "name" => "DeleteMe" };
    /// let mut tx = db.write_transaction()?;
    /// let node_id = tx.create_node("Person", properties)?;
    /// // ... create edges ...
    /// tx.delete_node_cascade(node_id)?; // Deletes node and all connected edges
    /// tx.commit()?;
    /// # Ok(())
    /// # }
    /// ```
    fn delete_node_cascade(&mut self, node_id: NodeId) -> Result<()>;

    /// Delete an edge with optional backdated valid_from time
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, core::EdgeId, api::transaction::WriteOps};
    /// # use aletheiadb::core::temporal::time;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let db = AletheiaDB::new()?;
    /// # let mut tx = db.write_transaction()?;
    /// # let edge_id = EdgeId::new(1)?;
    /// // Mark edge as deleted in the past
    /// let past_time = time::from_secs(1609459200);
    ///
    /// tx.delete_edge_with_valid_time(edge_id, Some(past_time))?;
    /// # Ok(())
    /// # }
    /// ```
    fn delete_edge_with_valid_time(
        &mut self,
        edge_id: EdgeId,
        valid_from: Option<Timestamp>,
    ) -> Result<()>;

    /// Delete an edge (delegates to `delete_edge_with_valid_time` with `None`).
    ///
    /// ## Examples
    ///
    /// ```rust,no_run
    /// # use aletheiadb::{AletheiaDB, PropertyMapBuilder, properties};
    /// # use aletheiadb::api::transaction::WriteOps;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let db = AletheiaDB::new()?;
    /// let mut tx = db.write_transaction()?;
    ///
    /// let alice = tx.create_node("Person", properties! { "name" => "Alice" })?;
    /// let bob = tx.create_node("Person", properties! { "name" => "Bob" })?;
    /// let edge_id = tx.create_edge(alice, bob, "KNOWS", properties! {})?;
    ///
    /// // Delete the edge
    /// tx.delete_edge(edge_id)?;
    ///
    /// tx.commit()?;
    /// # Ok(())
    /// # }
    /// ```
    fn delete_edge(&mut self, edge_id: EdgeId) -> Result<()> {
        self.delete_edge_with_valid_time(edge_id, None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::AletheiaDB;
    use crate::core::property::PropertyMapBuilder;
    use crate::core::temporal::time;

    #[test]
    fn test_create_node_with_valid_time_trait_method_exists() {
        // This test verifies the trait method signature compiles
        fn assert_write_ops<T: WriteOps>(_tx: &mut T) {
            // Trait bound check - if this compiles, the method exists
        }

        let db = AletheiaDB::new().unwrap();
        let mut tx = db.write_transaction().unwrap();
        assert_write_ops(&mut tx);
    }

    #[test]
    fn test_create_node_default_delegates_to_with_valid_time() {
        let db = AletheiaDB::new().unwrap();
        let mut tx = db.write_transaction().unwrap();

        // Both should work identically when valid_from is None
        let props1 = PropertyMapBuilder::new().insert("name", "Test1").build();
        let props2 = PropertyMapBuilder::new().insert("name", "Test2").build();

        // Both should succeed
        let result1 = tx.create_node("Test", props1);
        assert!(result1.is_ok(), "create_node failed: {:?}", result1.err());
        let id1 = result1.unwrap();

        let result2 = tx.create_node_with_valid_time("Test", props2, None);
        assert!(
            result2.is_ok(),
            "create_node_with_valid_time failed: {:?}",
            result2.err()
        );
        let id2 = result2.unwrap();

        // IDs should be different (sequential generation)
        assert_ne!(id1, id2, "IDs should be unique");

        // Both methods should work - IDs are generated successfully
        // Note: First ID may be 0 due to IdGenerator starting at 0 (known issue)
        assert!(id1.as_u64() < id2.as_u64(), "IDs should increment");
    }

    #[test]
    fn test_create_node_with_backdated_valid_time() {
        let db = AletheiaDB::new().unwrap();
        let mut tx = db.write_transaction().unwrap();

        // Create node with valid_time = 1 hour ago
        let one_hour_ago = time::now().wallclock() - 3_600_000_000;
        let valid_from = crate::core::hlc::HybridTimestamp::new(one_hour_ago, 0).unwrap();

        let props = PropertyMapBuilder::new().insert("name", "Alice").build();
        let node_id = tx
            .create_node_with_valid_time("Person", props, Some(valid_from))
            .unwrap();

        // Verify node was created with a valid ID (0 is valid!)
        assert!(node_id.as_u64() <= MAX_VALID_ID);
    }

    #[test]
    fn test_create_edge_with_valid_time_trait_method_exists() {
        fn assert_write_ops<T: WriteOps>(_tx: &mut T) {
            // Trait bound check
        }

        let db = AletheiaDB::new().unwrap();
        let mut tx = db.write_transaction().unwrap();
        assert_write_ops(&mut tx);
    }

    #[test]
    fn test_update_node_with_valid_time_trait_method_exists() {
        fn assert_write_ops<T: WriteOps>(_tx: &mut T) {
            // Trait bound check
        }

        let db = AletheiaDB::new().unwrap();
        let mut tx = db.write_transaction().unwrap();
        assert_write_ops(&mut tx);
    }

    #[test]
    fn test_delete_node_with_valid_time_trait_method_exists() {
        fn assert_write_ops<T: WriteOps>(_tx: &mut T) {
            // Trait bound check
        }

        let db = AletheiaDB::new().unwrap();
        let mut tx = db.write_transaction().unwrap();
        assert_write_ops(&mut tx);
    }
}