nusy-arrow-core 0.15.2

Arrow-native neurosymbolic graph store — triple storage, SPARQL-like queries, namespace partitioning, and Parquet persistence
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
//! KgStore — full-featured Arrow-native knowledge graph store.
//!
//! Replacement for Python `brain/reasoning/kg_store.py`.
//! Adds namespace prefix management, keyword search, knowledge gap tracking,
//! and bulk operations on top of [`ArrowGraphStore`].
//!
//! # Quick Start
//!
//! ```rust
//! use nusy_arrow_core::kg_store::KgStore;
//!
//! let mut store = KgStore::new();
//! store.bind_prefix("nusy", "https://nusy.dev/");
//! store.bind_prefix("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
//!
//! store.add_triple("nusy:Alice", "rdf:type", "nusy:Person", None, 1.0).unwrap();
//!
//! let results = store.search_by_keywords(&["Alice"]);
//! assert_eq!(results.len(), 1);
//! ```

use crate::namespace::Namespace;
use crate::schema::col;
use crate::store::{ArrowGraphStore, QuerySpec, StoreError, Triple};
use crate::triple_store::{StoredTriple, batches_to_stored_triples};
use crate::y_layer::YLayer;

use arrow::array::StringArray;
use std::collections::HashMap;

/// Default namespace prefixes (matching Python KGStore).
fn default_prefixes() -> HashMap<String, String> {
    let mut m = HashMap::new();
    m.insert(
        "rdf".into(),
        "http://www.w3.org/1999/02/22-rdf-syntax-ns#".into(),
    );
    m.insert(
        "rdfs".into(),
        "http://www.w3.org/2000/01/rdf-schema#".into(),
    );
    m.insert("owl".into(), "http://www.w3.org/2002/07/owl#".into());
    m.insert("xsd".into(), "http://www.w3.org/2001/XMLSchema#".into());
    m.insert("foaf".into(), "http://xmlns.com/foaf/0.1/".into());
    m.insert("prov".into(), "http://www.w3.org/ns/prov#".into());
    m.insert("santiago".into(), "https://nusy.dev/santiago/".into());
    m.insert("ethics".into(), "https://nusy.dev/ethics/".into());
    m.insert("pm".into(), "https://nusy.dev/pm/".into());
    m.insert("dev".into(), "https://nusy.dev/dev/".into());
    m.insert("nusy".into(), "https://nusy.dev/".into());
    m
}

/// A knowledge gap — something the being doesn't know.
#[derive(Debug, Clone)]
pub struct KnowledgeGap {
    pub question: String,
    pub keywords: Vec<String>,
    pub confidence: f64,
    pub missing_concepts: Vec<String>,
    pub resolved: bool,
}

/// Statistics about the knowledge graph.
#[derive(Debug, Clone)]
pub struct KgStats {
    pub total_triples: usize,
    pub unique_subjects: usize,
    pub unique_predicates: usize,
    pub unique_objects: usize,
    pub namespace_count: usize,
}

/// Full-featured Arrow-native knowledge graph store.
///
/// Provides:
/// - Namespace prefix management (expand/compact URIs)
/// - Pattern-based triple queries
/// - Keyword search (case-insensitive substring matching)
/// - Knowledge gap tracking
/// - Bulk add operations
pub struct KgStore {
    inner: ArrowGraphStore,
    prefixes: HashMap<String, String>,
    gaps: Vec<KnowledgeGap>,
    default_namespace: Namespace,
    default_y_layer: YLayer,
}

impl KgStore {
    /// Create a new store with default NuSy prefixes.
    pub fn new() -> Self {
        Self {
            inner: ArrowGraphStore::new(),
            prefixes: default_prefixes(),
            gaps: Vec::new(),
            default_namespace: Namespace::World,
            default_y_layer: YLayer::Semantic,
        }
    }

    /// Create with custom defaults.
    pub fn with_defaults(namespace: Namespace, y_layer: YLayer) -> Self {
        Self {
            inner: ArrowGraphStore::new(),
            prefixes: default_prefixes(),
            gaps: Vec::new(),
            default_namespace: namespace,
            default_y_layer: y_layer,
        }
    }

    // ── Prefix management ─────────────────────────────────────────────

    /// Bind a namespace prefix (e.g., "rdf" → "http://www.w3.org/...").
    pub fn bind_prefix(&mut self, prefix: &str, uri: &str) {
        self.prefixes.insert(prefix.to_string(), uri.to_string());
    }

    /// Expand a prefixed URI (e.g., "rdf:type" → "http://www.w3.org/.../type").
    /// Returns the original string if no prefix matches.
    pub fn expand_uri(&self, value: &str) -> String {
        if let Some(idx) = value.find(':') {
            let prefix = &value[..idx];
            let local = &value[idx + 1..];
            if let Some(ns_uri) = self.prefixes.get(prefix) {
                return format!("{ns_uri}{local}");
            }
        }
        value.to_string()
    }

    /// Compact a full URI to prefixed form (e.g., "http://www.w3.org/.../type" → "rdf:type").
    /// Returns the original string if no prefix matches.
    /// Matches longest prefix first to avoid ambiguity (e.g., "santiago:" before "nusy:").
    pub fn compact_uri(&self, uri: &str) -> String {
        // Sort by URI length descending so longest prefix matches first
        let mut sorted: Vec<_> = self.prefixes.iter().collect();
        sorted.sort_by(|a, b| b.1.len().cmp(&a.1.len()));

        for (prefix, ns_uri) in sorted {
            if let Some(local) = uri.strip_prefix(ns_uri.as_str()) {
                return format!("{prefix}:{local}");
            }
        }
        uri.to_string()
    }

    /// Get all bound prefixes.
    pub fn prefixes(&self) -> &HashMap<String, String> {
        &self.prefixes
    }

    // ── Triple operations ─────────────────────────────────────────────

    /// Add a triple with optional namespace expansion.
    pub fn add_triple(
        &mut self,
        subject: &str,
        predicate: &str,
        object: &str,
        source: Option<&str>,
        confidence: f64,
    ) -> Result<String, StoreError> {
        let triple = Triple {
            subject: self.expand_uri(subject),
            predicate: self.expand_uri(predicate),
            object: self.expand_uri(object),
            graph: None,
            confidence: Some(confidence),
            source_document: source.map(|s| s.to_string()),
            source_chunk_id: None,
            extracted_by: source.map(|s| s.to_string()),
            caused_by: None,
            derived_from: None,
            consolidated_at: None,
            certifiability_class: None,
        };
        self.inner
            .add_triple(&triple, self.default_namespace, self.default_y_layer)
    }

    /// Add multiple triples in batch.
    pub fn add_triples(
        &mut self,
        triples: &[(&str, &str, &str, f64)],
        source: Option<&str>,
    ) -> Result<Vec<String>, StoreError> {
        let ts: Vec<Triple> = triples
            .iter()
            .map(|(s, p, o, conf)| Triple {
                subject: self.expand_uri(s),
                predicate: self.expand_uri(p),
                object: self.expand_uri(o),
                graph: None,
                confidence: Some(*conf),
                source_document: source.map(|s| s.to_string()),
                source_chunk_id: None,
                extracted_by: source.map(|s| s.to_string()),
                caused_by: None,
                derived_from: None,
                consolidated_at: None,
                certifiability_class: None,
            })
            .collect();
        self.inner
            .add_batch(&ts, self.default_namespace, self.default_y_layer)
    }

    /// Query by (s, p, o) pattern. None means wildcard. URIs are expanded.
    pub fn query(
        &self,
        subject: Option<&str>,
        predicate: Option<&str>,
        object: Option<&str>,
    ) -> Result<Vec<StoredTriple>, StoreError> {
        let spec = QuerySpec {
            subject: subject.map(|s| self.expand_uri(s)),
            predicate: predicate.map(|s| self.expand_uri(s)),
            object: object.map(|s| self.expand_uri(s)),
            ..Default::default()
        };
        let batches = self.inner.query(&spec)?;
        Ok(batches_to_stored_triples(&batches))
    }

    /// Search by keywords (case-insensitive substring match on s/p/o).
    /// Returns matching triples with the matched keyword noted.
    pub fn search_by_keywords(&self, keywords: &[&str]) -> Vec<(StoredTriple, String)> {
        let spec = QuerySpec::default();
        let batches = self.inner.query(&spec).unwrap_or_default();
        let mut results = Vec::new();

        for batch in &batches {
            let subjects = batch
                .column(col::SUBJECT)
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("subject column");
            let predicates = batch
                .column(col::PREDICATE)
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("predicate column");
            let objects = batch
                .column(col::OBJECT)
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("object column");

            for i in 0..batch.num_rows() {
                let s = subjects.value(i).to_lowercase();
                let p = predicates.value(i).to_lowercase();
                let o = objects.value(i).to_lowercase();

                for kw in keywords {
                    let kw_lower = kw.to_lowercase();
                    if s.contains(&kw_lower) || p.contains(&kw_lower) || o.contains(&kw_lower) {
                        results.push((
                            crate::triple_store::extract_stored_triple(batch, i),
                            kw.to_string(),
                        ));
                        break; // Don't duplicate for multiple keyword matches
                    }
                }
            }
        }
        results
    }

    /// Clear all triples.
    pub fn clear(&mut self) {
        self.inner.clear();
    }

    // ── Knowledge gap tracking ────────────────────────────────────────

    /// Record a knowledge gap.
    pub fn record_knowledge_gap(
        &mut self,
        question: &str,
        keywords: &[&str],
        confidence: f64,
        missing_concepts: &[&str],
    ) -> usize {
        let gap = KnowledgeGap {
            question: question.to_string(),
            keywords: keywords.iter().map(|s| s.to_string()).collect(),
            confidence,
            missing_concepts: missing_concepts.iter().map(|s| s.to_string()).collect(),
            resolved: false,
        };
        self.gaps.push(gap);
        self.gaps.len() - 1
    }

    /// Get unresolved knowledge gaps.
    pub fn unresolved_gaps(&self) -> Vec<&KnowledgeGap> {
        self.gaps.iter().filter(|g| !g.resolved).collect()
    }

    /// Resolve a knowledge gap by index.
    pub fn resolve_gap(&mut self, index: usize) -> bool {
        if let Some(gap) = self.gaps.get_mut(index) {
            gap.resolved = true;
            true
        } else {
            false
        }
    }

    // ── Statistics ────────────────────────────────────────────────────

    /// Get store statistics.
    pub fn statistics(&self) -> KgStats {
        let spec = QuerySpec::default();
        let batches = self.inner.query(&spec).unwrap_or_default();
        let triples = batches_to_stored_triples(&batches);

        let mut subjects = std::collections::HashSet::new();
        let mut predicates = std::collections::HashSet::new();
        let mut objects = std::collections::HashSet::new();

        for t in &triples {
            subjects.insert(t.subject.clone());
            predicates.insert(t.predicate.clone());
            objects.insert(t.object.clone());
        }

        KgStats {
            total_triples: triples.len(),
            unique_subjects: subjects.len(),
            unique_predicates: predicates.len(),
            unique_objects: objects.len(),
            namespace_count: self.prefixes.len(),
        }
    }

    /// Total triple count.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Whether empty.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Get reference to underlying ArrowGraphStore.
    pub fn inner(&self) -> &ArrowGraphStore {
        &self.inner
    }

    /// Get mutable reference to underlying ArrowGraphStore.
    pub fn inner_mut(&mut self) -> &mut ArrowGraphStore {
        &mut self.inner
    }
}

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

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

    #[test]
    fn test_prefix_expand() {
        let store = KgStore::new();
        assert_eq!(
            store.expand_uri("rdf:type"),
            "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"
        );
        assert_eq!(
            store.expand_uri("santiago:Alice"),
            "https://nusy.dev/santiago/Alice"
        );
        assert_eq!(store.expand_uri("no_prefix"), "no_prefix");
    }

    #[test]
    fn test_prefix_compact() {
        let store = KgStore::new();
        assert_eq!(
            store.compact_uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
            "rdf:type"
        );
        assert_eq!(
            store.compact_uri("https://nusy.dev/santiago/Alice"),
            "santiago:Alice"
        );
        assert_eq!(
            store.compact_uri("http://unknown/foo"),
            "http://unknown/foo"
        );
    }

    #[test]
    fn test_add_with_prefix_expansion() {
        let mut store = KgStore::new();
        store
            .add_triple("santiago:Alice", "rdf:type", "santiago:Person", None, 1.0)
            .unwrap();

        // Query with expanded URI
        let results = store
            .query(Some("https://nusy.dev/santiago/Alice"), None, None)
            .unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(
            results[0].predicate,
            "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"
        );
    }

    #[test]
    fn test_query_with_prefix() {
        let mut store = KgStore::new();
        store
            .add_triple("santiago:Alice", "rdf:type", "santiago:Person", None, 1.0)
            .unwrap();

        // Query with prefixed URI (auto-expanded)
        let results = store.query(Some("santiago:Alice"), None, None).unwrap();
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_keyword_search() {
        let mut store = KgStore::new();
        store
            .add_triple(
                "santiago:Alice",
                "santiago:knows",
                "santiago:Bob",
                None,
                1.0,
            )
            .unwrap();
        store
            .add_triple(
                "santiago:Carol",
                "santiago:likes",
                "santiago:Dave",
                None,
                1.0,
            )
            .unwrap();

        let results = store.search_by_keywords(&["Alice"]);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].1, "Alice");

        let results = store.search_by_keywords(&["santiago"]);
        assert_eq!(results.len(), 2); // Both triples contain "santiago"
    }

    #[test]
    fn test_keyword_search_case_insensitive() {
        let mut store = KgStore::new();
        store
            .add_triple("Alice", "knows", "Bob", None, 1.0)
            .unwrap();

        let results = store.search_by_keywords(&["alice"]);
        assert_eq!(results.len(), 1);

        let results = store.search_by_keywords(&["ALICE"]);
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_knowledge_gaps() {
        let mut store = KgStore::new();
        let idx = store.record_knowledge_gap(
            "What is photosynthesis?",
            &["photosynthesis", "plants"],
            0.3,
            &["chloroplast", "light_reaction"],
        );

        assert_eq!(store.unresolved_gaps().len(), 1);
        assert_eq!(
            store.unresolved_gaps()[0].question,
            "What is photosynthesis?"
        );

        assert!(store.resolve_gap(idx));
        assert_eq!(store.unresolved_gaps().len(), 0);
    }

    #[test]
    fn test_bulk_add() {
        let mut store = KgStore::new();
        let ids = store
            .add_triples(
                &[
                    ("santiago:A", "rdf:type", "santiago:Person", 1.0),
                    ("santiago:B", "rdf:type", "santiago:Person", 1.0),
                    ("santiago:C", "rdf:type", "santiago:Person", 1.0),
                ],
                Some("bulk_import"),
            )
            .unwrap();
        assert_eq!(ids.len(), 3);
        assert_eq!(store.len(), 3);
    }

    #[test]
    fn test_custom_prefix() {
        let mut store = KgStore::new();
        store.bind_prefix("med", "https://nusy.dev/medical/");
        store
            .add_triple("med:Aspirin", "rdf:type", "med:Drug", None, 1.0)
            .unwrap();

        let results = store.query(Some("med:Aspirin"), None, None).unwrap();
        assert_eq!(results.len(), 1);
        assert!(results[0].subject.starts_with("https://nusy.dev/medical/"));
    }

    #[test]
    fn test_statistics() {
        let mut store = KgStore::new();
        store.add_triple("s1", "p1", "o1", None, 1.0).unwrap();
        store.add_triple("s2", "p1", "o2", None, 1.0).unwrap();

        let stats = store.statistics();
        assert_eq!(stats.total_triples, 2);
        assert_eq!(stats.unique_subjects, 2);
        assert_eq!(stats.unique_predicates, 1);
        assert!(stats.namespace_count >= 11); // Default prefixes
    }

    #[test]
    fn test_clear() {
        let mut store = KgStore::new();
        store.add_triple("s", "p", "o", None, 1.0).unwrap();
        assert_eq!(store.len(), 1);

        store.clear();
        assert_eq!(store.len(), 0);
    }
}