aingle_graph 0.7.1

Native GraphDB for AIngle - Semantic triple store with SPO indexes
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
// Copyright 2019-2026 Apilium Technologies OÜ. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR Commercial

//! Semantic triples, the core data structure of the graph.
//!
//! A `Triple` represents a single fact in the form of a `(Subject, Predicate, Object)`
//! statement. Triples are the fundamental unit of data in the semantic graph.
//!
//! # Example
//!
//! ```text
//! [Subject] --[Predicate]--> [Object]
//!
//! [user:alice] --[has_title]--> "Doctor"
//! ```

use crate::{NodeId, Predicate, Value};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fmt;

/// A unique, content-based identifier for a [`Triple`].
///
/// The ID is generated by hashing the triple's subject, predicate, and object
/// using the BLAKE3 cryptographic hash function. This ensures that identical
/// triples will always have the same ID.
///
/// # Examples
///
/// ```
/// use aingle_graph::{Triple, TripleId, NodeId, Predicate, Value};
///
/// let triple = Triple::new(
///     NodeId::named("user:alice"),
///     Predicate::named("has_name"),
///     Value::literal("Alice"),
/// );
///
/// let id = triple.id();
/// let hex_repr = id.to_hex();
/// println!("Triple ID: {}", id);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TripleId(pub [u8; 32]);

impl TripleId {
    /// Creates a new `TripleId` from a 32-byte array.
    ///
    /// # Examples
    ///
    /// ```
    /// use aingle_graph::TripleId;
    ///
    /// let bytes = [0u8; 32];
    /// let id = TripleId::new(bytes);
    /// ```
    pub fn new(bytes: [u8; 32]) -> Self {
        Self(bytes)
    }

    /// Generates a `TripleId` by hashing the content of a [`Triple`].
    ///
    /// Uses BLAKE3 to hash the concatenation of the subject, predicate, and object.
    /// Identical triples will always produce the same ID.
    ///
    /// # Examples
    ///
    /// ```
    /// use aingle_graph::{Triple, TripleId, NodeId, Predicate, Value};
    ///
    /// let triple1 = Triple::new(
    ///     NodeId::named("alice"),
    ///     Predicate::named("knows"),
    ///     Value::Node(NodeId::named("bob")),
    /// );
    ///
    /// let triple2 = Triple::new(
    ///     NodeId::named("alice"),
    ///     Predicate::named("knows"),
    ///     Value::Node(NodeId::named("bob")),
    /// );
    ///
    /// assert_eq!(TripleId::from_triple(&triple1), TripleId::from_triple(&triple2));
    /// ```
    pub fn from_triple(triple: &Triple) -> Self {
        let mut hasher = blake3::Hasher::new();
        hasher.update(&triple.subject.to_bytes());
        hasher.update(&triple.predicate.to_bytes());
        hasher.update(&triple.object.to_bytes());
        Self(*hasher.finalize().as_bytes())
    }

    /// Returns the raw byte representation of the ID.
    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// Returns a hexadecimal string representation of the ID.
    pub fn to_hex(&self) -> String {
        self.0.iter().map(|b| format!("{:02x}", b)).collect()
    }

    /// Creates a `TripleId` from a hexadecimal string.
    pub fn from_hex(hex: &str) -> Option<Self> {
        if hex.len() != 64 {
            return None;
        }
        let mut bytes = [0u8; 32];
        for (i, chunk) in hex.as_bytes().chunks(2).enumerate() {
            let s = std::str::from_utf8(chunk).ok()?;
            bytes[i] = u8::from_str_radix(s, 16).ok()?;
        }
        Some(Self(bytes))
    }
}

impl fmt::Display for TripleId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", &self.to_hex()[..16])
    }
}

impl From<[u8; 32]> for TripleId {
    fn from(bytes: [u8; 32]) -> Self {
        Self(bytes)
    }
}

/// Metadata associated with a [`Triple`], providing provenance and context.
///
/// Metadata allows you to track information about where a triple came from,
/// who created it, when it was created, and how confident you are in its validity.
///
/// # Examples
///
/// ```
/// use aingle_graph::{TripleMeta, NodeId};
///
/// let meta = TripleMeta::new()
///     .with_author(NodeId::named("user:alice"))
///     .with_source("manual_entry")
///     .with_confidence(0.95)
///     .validated();
///
/// assert!(meta.validated);
/// assert_eq!(meta.confidence, Some(0.95));
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TripleMeta {
    /// The timestamp of when the triple was created.
    pub created_at: DateTime<Utc>,
    /// The `NodeId` of the author who created the triple.
    pub author: Option<NodeId>,
    /// An optional cryptographic signature for the triple.
    pub signature: Option<Vec<u8>>,
    /// A string indicating the source of the triple (e.g., "import", "user", "inference").
    pub source: Option<String>,
    /// A confidence score (0.0 to 1.0), typically used for inferred triples.
    pub confidence: Option<f64>,
    /// A flag indicating whether this triple has been validated.
    pub validated: bool,
    /// A map for storing arbitrary custom properties.
    pub properties: std::collections::HashMap<String, String>,
}

impl Default for TripleMeta {
    fn default() -> Self {
        Self {
            created_at: Utc::now(),
            author: None,
            signature: None,
            source: None,
            confidence: None,
            validated: false,
            properties: std::collections::HashMap::new(),
        }
    }
}

impl TripleMeta {
    /// Creates a new `TripleMeta` with the current timestamp.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the author for the metadata.
    pub fn with_author(mut self, author: NodeId) -> Self {
        self.author = Some(author);
        self
    }

    /// Sets the source for the metadata.
    pub fn with_source(mut self, source: impl Into<String>) -> Self {
        self.source = Some(source.into());
        self
    }

    /// Sets the confidence score for the metadata.
    pub fn with_confidence(mut self, confidence: f64) -> Self {
        self.confidence = Some(confidence.clamp(0.0, 1.0));
        self
    }

    /// Marks the triple as validated.
    pub fn validated(mut self) -> Self {
        self.validated = true;
        self
    }

    /// Adds a custom property to the metadata.
    pub fn with_property(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.properties.insert(key.into(), value.into());
        self
    }
}

/// A semantic triple, representing a single fact as a `(Subject, Predicate, Object)` statement.
///
/// A triple is the fundamental unit of data in the graph database. It represents
/// a relationship between a subject and an object through a predicate.
///
/// # Examples
///
/// Creating a triple with a literal value:
///
/// ```
/// use aingle_graph::{Triple, NodeId, Predicate, Value};
///
/// let triple = Triple::new(
///     NodeId::named("user:alice"),
///     Predicate::named("has_age"),
///     Value::integer(30),
/// );
/// ```
///
/// Creating a triple that links two nodes:
///
/// ```
/// use aingle_graph::{Triple, NodeId, Predicate};
///
/// let triple = Triple::link(
///     NodeId::named("user:alice"),
///     Predicate::named("knows"),
///     NodeId::named("user:bob"),
/// );
/// ```
///
/// Creating a triple with metadata:
///
/// ```
/// use aingle_graph::{Triple, TripleMeta, NodeId, Predicate, Value};
///
/// let meta = TripleMeta::new()
///     .with_author(NodeId::named("system"))
///     .with_source("import");
///
/// let triple = Triple::with_meta(
///     NodeId::named("user:alice"),
///     Predicate::named("has_name"),
///     Value::literal("Alice"),
///     meta,
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Triple {
    /// The subject of the triple (the "thing" being described).
    pub subject: NodeId,
    /// The predicate (the relationship type).
    pub predicate: Predicate,
    /// The object (the value or related node).
    pub object: Value,
    /// Associated metadata, providing context and provenance for the triple.
    pub meta: TripleMeta,
}

impl Triple {
    /// Creates a new [`Triple`] with default metadata.
    ///
    /// # Examples
    ///
    /// ```
    /// use aingle_graph::{Triple, NodeId, Predicate, Value};
    ///
    /// let triple = Triple::new(
    ///     NodeId::named("user:alice"),
    ///     Predicate::named("has_email"),
    ///     Value::literal("alice@example.com"),
    /// );
    /// ```
    pub fn new(subject: NodeId, predicate: Predicate, object: Value) -> Self {
        Self {
            subject,
            predicate,
            object,
            meta: TripleMeta::default(),
        }
    }

    /// Creates a new `Triple` with the specified metadata.
    pub fn with_meta(
        subject: NodeId,
        predicate: Predicate,
        object: Value,
        meta: TripleMeta,
    ) -> Self {
        Self {
            subject,
            predicate,
            object,
            meta,
        }
    }

    /// A convenience method to create a triple with a literal string object.
    ///
    /// # Examples
    ///
    /// ```
    /// use aingle_graph::{Triple, NodeId};
    ///
    /// let triple = Triple::literal("user:alice", "has_name", "Alice Smith");
    /// assert_eq!(triple.object.as_string(), Some("Alice Smith"));
    /// ```
    pub fn literal(
        subject: impl Into<NodeId>,
        predicate: impl Into<Predicate>,
        value: impl Into<String>,
    ) -> Self
    where
        NodeId: From<String>,
    {
        Self::new(subject.into(), predicate.into(), Value::literal(value))
    }

    /// A convenience method to create a triple that links two nodes.
    ///
    /// This creates a relationship between two nodes in the graph.
    ///
    /// # Examples
    ///
    /// ```
    /// use aingle_graph::{Triple, NodeId};
    ///
    /// let triple = Triple::link(
    ///     NodeId::named("user:alice"),
    ///     "knows",
    ///     NodeId::named("user:bob"),
    /// );
    ///
    /// assert!(triple.is_link());
    /// assert_eq!(triple.object_node(), Some(&NodeId::named("user:bob")));
    /// ```
    pub fn link(
        subject: impl Into<NodeId>,
        predicate: impl Into<Predicate>,
        object: impl Into<NodeId>,
    ) -> Self {
        Self::new(subject.into(), predicate.into(), Value::Node(object.into()))
    }

    /// Generates the unique, content-based ID for this triple.
    ///
    /// The ID is deterministic - identical triples will always produce the same ID.
    ///
    /// # Examples
    ///
    /// ```
    /// use aingle_graph::{Triple, NodeId, Predicate, Value};
    ///
    /// let triple = Triple::new(
    ///     NodeId::named("alice"),
    ///     Predicate::named("age"),
    ///     Value::integer(30),
    /// );
    ///
    /// let id = triple.id();
    /// println!("Triple ID: {}", id);
    /// ```
    pub fn id(&self) -> TripleId {
        TripleId::from_triple(self)
    }

    /// Returns `true` if the triple's object is a reference to another node.
    pub fn is_link(&self) -> bool {
        self.object.is_node()
    }

    /// Returns `true` if the triple's object is a literal value.
    pub fn is_literal(&self) -> bool {
        self.object.is_literal()
    }

    /// Returns the object as a `NodeId` if it is a node reference.
    pub fn object_node(&self) -> Option<&NodeId> {
        self.object.as_node()
    }

    /// Returns the object as a string slice if it is a string-like literal.
    pub fn object_string(&self) -> Option<&str> {
        self.object.as_string()
    }

    /// Formats the triple into the N-Triples standard string format.
    pub fn to_ntriples(&self) -> String {
        format!("{} {} {} .", self.subject, self.predicate, self.object)
    }

    /// Serializes the `Triple` to a byte vector for storage.
    pub fn to_bytes(&self) -> Vec<u8> {
        bincode::serde::encode_to_vec(self, bincode::config::standard()).unwrap_or_default()
    }

    /// Deserializes a `Triple` from a byte slice.
    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
        bincode::serde::decode_from_slice(bytes, bincode::config::standard())
            .map(|(v, _)| v)
            .ok()
    }

    /// Creates a set of pre-computed, lexicographically sortable keys for database indexing.
    pub fn index_keys(&self) -> TripleIndexKeys {
        let s = self.subject.to_bytes();
        let p = self.predicate.to_bytes();
        let o = self.object.sort_key();

        // SPO key: subject + predicate + object
        let mut spo = Vec::with_capacity(s.len() + p.len() + o.len() + 2);
        spo.extend(&s);
        spo.push(0);
        spo.extend(&p);
        spo.push(0);
        spo.extend(&o);

        // POS key: predicate + object + subject
        let mut pos = Vec::with_capacity(s.len() + p.len() + o.len() + 2);
        pos.extend(&p);
        pos.push(0);
        pos.extend(&o);
        pos.push(0);
        pos.extend(&s);

        // OSP key: object + subject + predicate
        let mut osp = Vec::with_capacity(s.len() + p.len() + o.len() + 2);
        osp.extend(&o);
        osp.push(0);
        osp.extend(&s);
        osp.push(0);
        osp.extend(&p);

        TripleIndexKeys { spo, pos, osp }
    }
}

/// A container for the pre-computed index keys for a [`Triple`].
///
/// These keys are designed to be lexicographically sortable and are used
/// by the storage backend to create efficient indexes for different query patterns.
///
/// The three index types (SPO, POS, OSP) allow efficient lookups based on
/// different combinations of subject, predicate, and object.
pub struct TripleIndexKeys {
    /// The key for the Subject-Predicate-Object index.
    pub spo: Vec<u8>,
    /// The key for the Predicate-Object-Subject index.
    pub pos: Vec<u8>,
    /// The key for the Object-Subject-Predicate index.
    pub osp: Vec<u8>,
}

impl fmt::Display for Triple {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {} {}", self.subject, self.predicate, self.object)
    }
}

/// A builder for creating [`Triple`]s using a fluent API.
///
/// # Examples
///
/// ```
/// use aingle_graph::{TripleBuilder, NodeId, Value};
///
/// let triple = TripleBuilder::new()
///     .subject(NodeId::named("user:alice"))
///     .predicate("has_age")
///     .object(Value::integer(30))
///     .author("system")
///     .source("import")
///     .build()
///     .unwrap();
///
/// assert_eq!(triple.subject, NodeId::named("user:alice"));
/// assert_eq!(triple.meta.source, Some("import".to_string()));
/// ```
pub struct TripleBuilder {
    subject: Option<NodeId>,
    predicate: Option<Predicate>,
    object: Option<Value>,
    meta: TripleMeta,
}

impl TripleBuilder {
    /// Starts building a new triple.
    pub fn new() -> Self {
        Self {
            subject: None,
            predicate: None,
            object: None,
            meta: TripleMeta::default(),
        }
    }

    /// Sets the subject of the triple.
    pub fn subject(mut self, subject: impl Into<NodeId>) -> Self {
        self.subject = Some(subject.into());
        self
    }

    /// Sets the predicate of the triple.
    pub fn predicate(mut self, predicate: impl Into<Predicate>) -> Self {
        self.predicate = Some(predicate.into());
        self
    }

    /// Sets the object of the triple.
    pub fn object(mut self, object: impl Into<Value>) -> Self {
        self.object = Some(object.into());
        self
    }

    /// A convenience method to set the object as a `Node` reference.
    pub fn object_node(mut self, node: impl Into<NodeId>) -> Self {
        self.object = Some(Value::Node(node.into()));
        self
    }

    /// Sets the author in the triple's metadata.
    pub fn author(mut self, author: impl Into<NodeId>) -> Self {
        self.meta.author = Some(author.into());
        self
    }

    /// Sets the source in the triple's metadata.
    pub fn source(mut self, source: impl Into<String>) -> Self {
        self.meta.source = Some(source.into());
        self
    }

    /// Builds the `Triple`.
    ///
    /// # Returns
    ///
    /// `Some(Triple)` if all components (subject, predicate, object) have been set,
    /// `None` otherwise.
    pub fn build(self) -> Option<Triple> {
        Some(Triple {
            subject: self.subject?,
            predicate: self.predicate?,
            object: self.object?,
            meta: self.meta,
        })
    }
}

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

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

    #[test]
    fn test_create_triple() {
        let triple = Triple::new(
            NodeId::named("user:alice"),
            Predicate::named("has_name"),
            Value::literal("Alice"),
        );

        assert_eq!(triple.subject.as_name(), Some("user:alice"));
        assert_eq!(triple.predicate.as_str(), "has_name");
        assert_eq!(triple.object.as_string(), Some("Alice"));
    }

    #[test]
    fn test_triple_id() {
        let t1 = Triple::new(
            NodeId::named("a"),
            Predicate::named("b"),
            Value::literal("c"),
        );
        let t2 = Triple::new(
            NodeId::named("a"),
            Predicate::named("b"),
            Value::literal("c"),
        );
        let t3 = Triple::new(
            NodeId::named("a"),
            Predicate::named("b"),
            Value::literal("d"),
        );

        assert_eq!(t1.id(), t2.id()); // Same content = same ID
        assert_ne!(t1.id(), t3.id()); // Different content = different ID
    }

    #[test]
    fn test_triple_link() {
        let triple = Triple::link(
            NodeId::named("user:alice"),
            Predicate::named("knows"),
            NodeId::named("user:bob"),
        );

        assert!(triple.is_link());
        assert!(!triple.is_literal());
        assert_eq!(triple.object_node(), Some(&NodeId::named("user:bob")));
    }

    #[test]
    fn test_triple_builder() {
        let triple = TripleBuilder::new()
            .subject("user:alice")
            .predicate("has_age")
            .object(Value::integer(30))
            .author("system")
            .source("import")
            .build()
            .unwrap();

        assert_eq!(triple.object.as_integer(), Some(30));
        assert_eq!(triple.meta.source, Some("import".to_string()));
    }

    #[test]
    fn test_to_ntriples() {
        let triple = Triple::new(
            NodeId::named("user:alice"),
            Predicate::named("has_name"),
            Value::literal("Alice"),
        );

        let nt = triple.to_ntriples();
        assert!(nt.contains("user:alice"));
        assert!(nt.contains("has_name"));
        assert!(nt.contains("Alice"));
    }

    #[test]
    fn test_index_keys() {
        let triple = Triple::new(
            NodeId::named("s"),
            Predicate::named("p"),
            Value::literal("o"),
        );

        let keys = triple.index_keys();
        assert!(!keys.spo.is_empty());
        assert!(!keys.pos.is_empty());
        assert!(!keys.osp.is_empty());

        // Keys should be different
        assert_ne!(keys.spo, keys.pos);
        assert_ne!(keys.pos, keys.osp);
    }

    #[test]
    fn test_serialization() {
        let triple = Triple::new(
            NodeId::named("test:s"),
            Predicate::named("test:p"),
            Value::literal("test:o"),
        );

        let bytes = triple.to_bytes();
        let restored = Triple::from_bytes(&bytes).unwrap();

        assert_eq!(triple.subject, restored.subject);
        assert_eq!(triple.predicate, restored.predicate);
        assert_eq!(triple.object, restored.object);
    }

    #[test]
    fn test_triple_id_hex() {
        let triple = Triple::new(
            NodeId::named("a"),
            Predicate::named("b"),
            Value::literal("c"),
        );
        let id = triple.id();
        let hex = id.to_hex();
        let restored = TripleId::from_hex(&hex).unwrap();
        assert_eq!(id, restored);
    }
}