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
//! Temporal query operations for bi-temporal data.
//!
//! Methods for querying historical states of the graph using valid and transaction times.
use crate::core::error::{Result, ResultExt};
use crate::core::graph::{Edge, Node};
use crate::core::id::{EdgeId, NodeId, VersionId};
use crate::core::temporal::{Timestamp, time};
use crate::db::AletheiaDB;
use crate::query::{EntityHistory, VersionDiff};
impl AletheiaDB {
/// Get outgoing edges from a node at a specific point in time.
///
/// This method uses the temporal adjacency index to efficiently find all
/// edges that were valid at the specified time, including edges that have
/// been deleted in current storage.
///
/// # Arguments
///
/// * `source` - The source node ID
/// * `valid_time` - The valid time to query
/// * `tx_time` - The transaction time to query
///
/// # Returns
///
/// A vector of edge IDs that were valid at the specified time. Returns an
/// empty vector if no temporal adjacency index is configured.
///
/// # Example
///
/// ```ignore
/// use aletheiadb::AletheiaDB;
/// use aletheiadb::core::temporal::time;
///
/// let db = AletheiaDB::new().unwrap();
/// // ... create and delete edges ...
/// let edges = db.get_outgoing_edges_at_time(node_id, valid_time, tx_time);
/// ```
pub fn get_outgoing_edges_at_time(
&self,
source: NodeId,
valid_time: Timestamp,
tx_time: Timestamp,
) -> Vec<EdgeId> {
self.historical
.read()
.get_outgoing_edges_at_time(source, valid_time, tx_time)
}
/// Get incoming edges to a node at a specific point in time.
///
/// This method uses the temporal adjacency index to efficiently find all
/// edges that were valid at the specified time, including edges that have
/// been deleted in current storage.
///
/// # Arguments
///
/// * `target` - The target node ID
/// * `valid_time` - The valid time to query
/// * `tx_time` - The transaction time to query
///
/// # Returns
///
/// A vector of edge IDs that were valid at the specified time. Returns an
/// empty vector if no temporal adjacency index is configured.
///
/// # Example
///
/// ```ignore
/// use aletheiadb::AletheiaDB;
/// use aletheiadb::core::temporal::time;
///
/// let db = AletheiaDB::new().unwrap();
/// // ... create and delete edges ...
/// let edges = db.get_incoming_edges_at_time(node_id, valid_time, tx_time);
/// ```
pub fn get_incoming_edges_at_time(
&self,
target: NodeId,
valid_time: Timestamp,
tx_time: Timestamp,
) -> Vec<EdgeId> {
self.historical
.read()
.get_incoming_edges_at_time(target, valid_time, tx_time)
}
/// Get a node as it existed at a specific point in bi-temporal space.
///
/// Uses the temporal index for O(log n) candidate lookup, then verifies
/// visibility with historical storage (handles closed intervals from deletions).
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_node_at_time(
&self,
node_id: NodeId,
valid_time: Timestamp,
transaction_time: Timestamp,
) -> Result<Node> {
#[cfg(feature = "observability")]
let _span = crate::observability::temporal_query_span("get_node_at_time").entered();
self.historical
.read()
.get_node_at_time(node_id, valid_time, transaction_time)
.record_error_metric()
}
/// Get an edge as it existed at a specific point in bi-temporal space.
///
/// Uses the temporal index for O(log n) candidate lookup, then verifies
/// visibility with historical storage (handles closed intervals from deletions).
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_edge_at_time(
&self,
edge_id: EdgeId,
valid_time: Timestamp,
transaction_time: Timestamp,
) -> Result<Edge> {
#[cfg(feature = "observability")]
let _span = crate::observability::temporal_query_span("get_edge_at_time").entered();
self.historical
.read()
.get_edge_at_time(edge_id, valid_time, transaction_time)
.record_error_metric()
}
/// Get multiple nodes as they existed at a specific point in bi-temporal space.
///
/// This is more efficient than calling `get_node_at_time` in a loop because it
/// acquires the historical storage lock only once for all queries.
///
/// **Note**: This implementation is similar to `get_edges_at_time()`. While the
/// duplication could be eliminated with a generic helper function, we keep them
/// separate for clarity and maintainability, as the type-specific operations
/// (Node vs Edge construction) would require complex trait bounds.
///
/// # Arguments
///
/// * `node_ids` - Slice of node IDs to query
/// * `valid_time` - The valid time to query
/// * `transaction_time` - The transaction time to query
///
/// # Returns
///
/// A vector of (NodeId, `Option<Node>`) pairs, where None indicates the node
/// did not exist at the specified time. Results are returned in the same
/// order as the input node_ids.
///
/// # Error Handling
///
/// Unlike `get_node_at_time()` which returns an error when a node is not found,
/// this batch API returns `None` for individual nodes that don't exist at the
/// specified time. This allows partial results when querying multiple nodes.
/// The method only returns `Err` for systemic failures (lock poisoning, storage
/// corruption, property reconstruction failures).
///
/// # Duplicate Handling
///
/// If `node_ids` contains duplicate IDs, each will be processed independently
/// and appear in the results. No deduplication is performed. The caller is
/// responsible for deduplication if needed.
///
/// # Performance Characteristics
///
/// The current implementation holds a read lock on historical storage for the
/// entire batch processing duration, including property reconstruction. This
/// design prioritizes simplicity and correctness for the initial implementation.
///
/// For very large batches (1000+ entities), consider:
/// - Breaking the batch into smaller chunks
/// - Using this method when temporal consistency across the batch is required
///
/// Future optimization: A two-phase approach (gather version IDs, then reconstruct)
/// could reduce lock hold time for better concurrency, at the cost of additional
/// lock acquisitions.
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::AletheiaDB;
/// # use aletheiadb::core::NodeId;
/// # use aletheiadb::core::temporal::Timestamp;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// # let node1 = NodeId::new(1)?;
/// # let valid_time = Timestamp::from(0);
/// # let tx_time = Timestamp::from(0);
/// // Query 100 nodes at a historical point with single lock acquisition
/// let node_ids = vec![node1];
/// let results = db.get_nodes_at_time(&node_ids, valid_time, tx_time)?;
///
/// for (node_id, node_opt) in results {
/// if let Some(node) = node_opt {
/// println!("Node {} existed with properties: {:?}", node_id, node.properties);
/// } else {
/// println!("Node {} did not exist at this time", node_id);
/// }
/// }
/// # Ok(())
/// # }
/// ```
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_nodes_at_time(
&self,
node_ids: &[NodeId],
valid_time: Timestamp,
transaction_time: Timestamp,
) -> Result<Vec<(NodeId, Option<Node>)>> {
#[cfg(feature = "observability")]
let _span = crate::observability::temporal_query_span("get_nodes_at_time").entered();
self.historical
.read()
.get_nodes_at_time(node_ids, valid_time, transaction_time)
.record_error_metric()
}
/// Get multiple edges as they existed at a specific point in bi-temporal space.
///
/// This is more efficient than calling `get_edge_at_time` in a loop because it
/// acquires the historical storage lock only once for all queries.
///
/// # Arguments
///
/// * `edge_ids` - Slice of edge IDs to query
/// * `valid_time` - The valid time to query
/// * `transaction_time` - The transaction time to query
///
/// # Returns
///
/// A vector of (EdgeId, `Option<Edge>`) pairs, where None indicates the edge
/// did not exist at the specified time. Results are returned in the same
/// order as the input edge_ids.
///
/// # Error Handling
///
/// Unlike `get_edge_at_time()` which returns an error when an edge is not found,
/// this batch API returns `None` for individual edges that don't exist at the
/// specified time. This allows partial results when querying multiple edges.
/// The method only returns `Err` for systemic failures (lock poisoning, storage
/// corruption, property reconstruction failures).
///
/// # Duplicate Handling
///
/// If `edge_ids` contains duplicate IDs, each will be processed independently
/// and appear in the results. No deduplication is performed. The caller is
/// responsible for deduplication if needed.
///
/// # Performance Characteristics
///
/// The current implementation holds a read lock on historical storage for the
/// entire batch processing duration, including property reconstruction. This
/// design prioritizes simplicity and correctness for the initial implementation.
///
/// For very large batches (1000+ entities), consider:
/// - Breaking the batch into smaller chunks
/// - Using this method when temporal consistency across the batch is required
///
/// Future optimization: A two-phase approach (gather version IDs, then reconstruct)
/// could reduce lock hold time for better concurrency, at the cost of additional
/// lock acquisitions.
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::AletheiaDB;
/// # use aletheiadb::core::EdgeId;
/// # use aletheiadb::core::temporal::Timestamp;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// # let edge1 = EdgeId::new(1)?;
/// # let valid_time = Timestamp::from(0);
/// # let tx_time = Timestamp::from(0);
/// // Query multiple edges at a historical point with single lock acquisition
/// let edge_ids = vec![edge1];
/// let results = db.get_edges_at_time(&edge_ids, valid_time, tx_time)?;
///
/// for (edge_id, edge_opt) in results {
/// if let Some(edge) = edge_opt {
/// println!("Edge {} existed: {} -> {}", edge_id, edge.source, edge.target);
/// } else {
/// println!("Edge {} did not exist at this time", edge_id);
/// }
/// }
/// # Ok(())
/// # }
/// ```
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_edges_at_time(
&self,
edge_ids: &[EdgeId],
valid_time: Timestamp,
transaction_time: Timestamp,
) -> Result<Vec<(EdgeId, Option<Edge>)>> {
#[cfg(feature = "observability")]
let _span = crate::observability::temporal_query_span("get_edges_at_time").entered();
self.historical
.read()
.get_edges_at_time(edge_ids, valid_time, transaction_time)
.record_error_metric()
}
// ========================================================================
// History & Version API (Phase 9: True Bi-Temporal)
// ========================================================================
/// Get a node as it was valid at a specific valid time.
///
/// Transaction time defaults to "now" - queries what was valid at the given time,
/// based on the latest knowledge.
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::AletheiaDB;
/// # use aletheiadb::core::NodeId;
/// # use aletheiadb::core::temporal::Timestamp;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// # let alice_id = NodeId::new(1)?;
/// # let jan_15 = Timestamp::from(0);
/// // "What were Alice's properties on January 15th?"
/// let node = db.get_node_at_valid_time(alice_id, jan_15)?;
/// # Ok(())
/// # }
/// ```
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_node_at_valid_time(&self, node_id: NodeId, valid_time: Timestamp) -> Result<Node> {
let tx_time = time::now();
self.get_node_at_time(node_id, valid_time, tx_time)
}
/// Get a node as it was recorded at a specific transaction time.
///
/// Valid time defaults to "now" - queries what we knew at the given time,
/// regardless of when facts were valid.
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::AletheiaDB;
/// # use aletheiadb::core::NodeId;
/// # use aletheiadb::core::temporal::Timestamp;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// # let alice_id = NodeId::new(1)?;
/// # let feb_1 = Timestamp::from(0);
/// // "What did we know about Alice on February 1st?"
/// let node = db.get_node_at_transaction_time(alice_id, feb_1)?;
/// # Ok(())
/// # }
/// ```
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_node_at_transaction_time(
&self,
node_id: NodeId,
transaction_time: Timestamp,
) -> Result<Node> {
let valid_time = time::now();
self.get_node_at_time(node_id, valid_time, transaction_time)
}
/// Get the complete version history of a node.
///
/// Returns all versions in chronological order (oldest first).
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::AletheiaDB;
/// # use aletheiadb::core::NodeId;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// # let alice_id = NodeId::new(1)?;
/// let history = db.get_node_history(alice_id)?;
/// println!("Alice has {} versions", history.version_count());
/// # Ok(())
/// # }
/// ```
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_node_history(&self, node_id: NodeId) -> Result<EntityHistory> {
self.historical
.read()
.get_node_history(node_id)
.record_error_metric()
}
/// Get a node at a specific logical version number.
///
/// Version numbers are 1-indexed (1 = first version, 2 = second version, etc.).
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::AletheiaDB;
/// # use aletheiadb::core::NodeId;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// # let alice_id = NodeId::new(1)?;
/// let v1 = db.get_node_at_version(alice_id, 1)?; // Original version
/// let v2 = db.get_node_at_version(alice_id, 2)?; // After first update
/// # Ok(())
/// # }
/// ```
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_node_at_version(&self, node_id: NodeId, version_number: u64) -> Result<Node> {
self.historical
.read()
.get_node_at_version(node_id, version_number)
.record_error_metric()
}
/// Compute the difference between two versions of a node.
///
/// Shows which properties were added, removed, or modified.
///
/// # Example
///
/// ```rust,no_run
/// # use aletheiadb::AletheiaDB;
/// # use aletheiadb::core::NodeId;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let db = AletheiaDB::new()?;
/// # let alice_id = NodeId::new(1)?;
/// let history = db.get_node_history(alice_id)?;
/// let v1 = history.first_version().unwrap().version_id;
/// let v2 = history.current_version().unwrap().version_id;
///
/// let diff = db.diff_node_versions(alice_id, v1, v2)?;
/// if diff.has_changes() {
/// println!("Properties changed: {}", diff.change_count());
/// }
/// # Ok(())
/// # }
/// ```
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn diff_node_versions(
&self,
node_id: NodeId,
from_version: VersionId,
to_version: VersionId,
) -> Result<VersionDiff> {
self.historical
.read()
.diff_node_versions(node_id, from_version, to_version)
.record_error_metric()
}
/// Get an edge at a specific valid time.
///
/// Query by valid time only (transaction time defaults to now).
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_edge_at_valid_time(&self, edge_id: EdgeId, valid_time: Timestamp) -> Result<Edge> {
let transaction_time = time::now();
self.get_edge_at_time(edge_id, valid_time, transaction_time)
}
/// Get an edge at a specific transaction time.
///
/// Query by transaction time only (valid time defaults to now).
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_edge_at_transaction_time(
&self,
edge_id: EdgeId,
transaction_time: Timestamp,
) -> Result<Edge> {
let valid_time = time::now();
self.get_edge_at_time(edge_id, valid_time, transaction_time)
}
/// Get the complete version history of an edge.
///
/// Returns all versions in chronological order (oldest first).
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn get_edge_history(&self, edge_id: EdgeId) -> Result<EntityHistory> {
self.historical
.read()
.get_edge_history(edge_id)
.record_error_metric()
}
/// Compute the difference between two versions of an edge.
///
/// Shows which properties were added, removed, or modified.
#[must_use = "this Result must be used; ignoring errors can lead to silent failures"]
pub fn diff_edge_versions(
&self,
edge_id: EdgeId,
from_version: VersionId,
to_version: VersionId,
) -> Result<VersionDiff> {
self.historical
.read()
.diff_edge_versions(edge_id, from_version, to_version)
.record_error_metric()
}
}