Skip to main content

qualia_core_db/services/
daemon_graph.rs

1//! In-process graph backing store for the loopback daemon `/query` route.
2//!
3//! The live daemon graph is a fixed-capacity, zero-heap store backed by a
4//! caller-invisible `[NQuin; MAX_GRAPH_QUINS]` buffer. Cold-path ontology and
5//! file ingestion may still allocate while parsing, but the resident graph used
6//! by `/query` no longer relies on `Vec` or `HashSet`.
7
8use crate::{q_hash, NQuin};
9use std::collections::{HashMap, HashSet};
10use std::ops::Index;
11use std::path::Path;
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::sync::{OnceLock, RwLock};
14use tokio::sync::broadcast;
15
16/// Bench datasets (Schema.org ~18K quins) must fit for browser/native parity.
17pub const MAX_GRAPH_QUINS: usize = 65_536;
18
19#[derive(Debug)]
20pub struct DaemonGraphStore {
21    quins: [NQuin; MAX_GRAPH_QUINS],
22    len: usize,
23}
24
25impl DaemonGraphStore {
26    /// Creates a default `DaemonGraphStore`.
27    pub const fn new() -> Self {
28        Self {
29            quins: [NQuin {
30                subject: 0,
31                predicate: 0,
32                object: 0,
33                context: 0,
34                metadata: 0,
35                parity: 0,
36            }; MAX_GRAPH_QUINS],
37            len: 0,
38        }
39    }
40
41    #[inline]
42    /// Quin count.
43    pub fn len(&self) -> usize {
44        self.len
45    }
46
47    #[inline]
48    /// `true` when empty.
49    pub fn is_empty(&self) -> bool {
50        self.len == 0
51    }
52
53    #[inline]
54    /// Quin slice.
55    pub fn as_slice(&self) -> &[NQuin] {
56        &self.quins[..self.len]
57    }
58
59    #[inline]
60    /// Clears the store.
61    pub fn clear(&mut self) {
62        for quin in &mut self.quins[..self.len] {
63            *quin = NQuin::default();
64        }
65        self.len = 0;
66    }
67
68    #[inline]
69    /// Pushes a quin; `false` at capacity.
70    pub fn push(&mut self, quin: NQuin) -> bool {
71        if self.len >= MAX_GRAPH_QUINS {
72            return false;
73        }
74        self.quins[self.len] = quin;
75        self.len += 1;
76        true
77    }
78
79    #[inline]
80    /// Extends from `quins`; returns accepted count.
81    pub fn extend_from_slice(&mut self, quins: &[NQuin]) -> usize {
82        let remaining = MAX_GRAPH_QUINS.saturating_sub(self.len);
83        let to_copy = quins.len().min(remaining);
84        if to_copy == 0 {
85            return 0;
86        }
87        self.quins[self.len..self.len + to_copy].copy_from_slice(&quins[..to_copy]);
88        self.len += to_copy;
89        to_copy
90    }
91
92    #[inline]
93    fn contains_subject_predicate_context(
94        &self,
95        subject: u64,
96        predicate: u64,
97        context: u64,
98    ) -> bool {
99        self.as_slice()
100            .iter()
101            .any(|q| q.subject == subject && q.predicate == predicate && q.context == context)
102    }
103
104    fn push_unique(&mut self, quin: NQuin) -> bool {
105        if self.contains_subject_predicate_context(quin.subject, quin.predicate, quin.context) {
106            return false;
107        }
108        self.push(quin)
109    }
110}
111
112impl Default for DaemonGraphStore {
113    fn default() -> Self {
114        Self::new()
115    }
116}
117
118impl Index<usize> for DaemonGraphStore {
119    type Output = NQuin;
120
121    fn index(&self, index: usize) -> &Self::Output {
122        &self.as_slice()[index]
123    }
124}
125
126static GRAPH: RwLock<DaemonGraphStore> = RwLock::new(DaemonGraphStore::new());
127static GRAPH_REVISION: AtomicU64 = AtomicU64::new(0);
128static REVISION_TX: OnceLock<broadcast::Sender<u64>> = OnceLock::new();
129
130fn graph_lock() -> &'static RwLock<DaemonGraphStore> {
131    &GRAPH
132}
133
134fn revision_tx() -> &'static broadcast::Sender<u64> {
135    REVISION_TX.get_or_init(|| {
136        let (tx, _) = broadcast::channel(64);
137        tx
138    })
139}
140
141/// Monotonic Lamport-style revision counter for daemon graph mutations.
142#[inline]
143pub fn graph_revision() -> u64 {
144    GRAPH_REVISION.load(Ordering::Acquire)
145}
146
147/// Subscribe to graph revision bumps (used by `GET /tensor/events` SSE).
148pub fn subscribe_graph_revisions() -> broadcast::Receiver<u64> {
149    revision_tx().subscribe()
150}
151
152/// Increment revision and notify SSE subscribers (Release ordering).
153pub fn bump_graph_revision() -> u64 {
154    let rev = GRAPH_REVISION.fetch_add(1, Ordering::Release) + 1;
155    let _ = revision_tx().send(rev);
156    rev
157}
158
159#[inline]
160fn triple_quin(subject: &str, predicate: &str, object: &str, context: &str) -> NQuin {
161    let subject = q_hash(subject);
162    let predicate = q_hash(predicate);
163    let object = q_hash(object);
164    let context = q_hash(context) & 0x00FF_FFFF_FFFF_FFFF;
165    NQuin {
166        subject,
167        predicate,
168        object,
169        context,
170        metadata: 0,
171        parity: subject ^ predicate ^ object ^ context,
172    }
173}
174
175fn push_quin(store: &mut DaemonGraphStore, quin: NQuin) {
176    let _ = store.push(quin);
177}
178
179/// Seed representative health-condition triples for Anatomy app development.
180fn seed_anatomy_health_graph(store: &mut DaemonGraphStore) {
181    const BIO: &str = "https://qualia.anatomy.example/ontology/bio#";
182    const ORGAN: &str = "https://qualia.anatomy.example/ontology/organ#";
183    const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
184    const HAS_PRIMARY: &str =
185        "https://qualia.anatomy.example/ontology/impact#hasPrimaryImpactSystem";
186    const IMPACTS: &str = "https://qualia.anatomy.example/ontology/impact#Impacts";
187    const USER_CTX: &str = "did:qualia:user:local-health-graph";
188
189    let seeds: [(&str, &str); 8] = [
190        ("Type2Diabetes", "organ:EndocrineSystem"),
191        ("Hypertension", "organ:CirculatorySystem"),
192        ("ChronicKidneyDisease", "organ:UrinarySystem"),
193        ("HeartFailure", "organ:CirculatorySystem"),
194        ("COPD", "organ:RespiratorySystem"),
195        ("Obesity", "organ:EndocrineSystem"),
196        ("AtrialFibrillation", "organ:CirculatorySystem"),
197        ("Depression", "organ:NervousSystem"),
198    ];
199
200    for (local_name, primary_system) in seeds {
201        let condition = format!("{BIO}{local_name}");
202        push_quin(
203            store,
204            triple_quin(&condition, RDF_TYPE, &format!("{BIO}Condition"), USER_CTX),
205        );
206        push_quin(
207            store,
208            triple_quin(
209                &condition,
210                HAS_PRIMARY,
211                &format!("{ORGAN}{}", primary_system.trim_start_matches("organ:")),
212                USER_CTX,
213            ),
214        );
215        push_quin(
216            store,
217            triple_quin(
218                &condition,
219                IMPACTS,
220                &format!("{ORGAN}{}", primary_system.trim_start_matches("organ:")),
221                USER_CTX,
222            ),
223        );
224    }
225}
226
227/// Merged literal lexicon (`hash -> text`) for the resident graph, built from
228/// the `.q42` volumes' lexicon segments at load. Lets the SPARQL evaluator
229/// resolve ingested literal *text* (for `geof:*`/text extension functions and
230/// correct literal serialisation) rather than only opaque hashes.
231static GRAPH_LEXICON: RwLock<Option<HashMap<u64, String>>> = RwLock::new(None);
232
233fn reset_graph_lexicon() {
234    if let Ok(mut g) = GRAPH_LEXICON.write() {
235        *g = Some(HashMap::new());
236    }
237}
238
239fn merge_graph_lexicon(entries: HashMap<u64, String>) {
240    if let Ok(mut g) = GRAPH_LEXICON.write() {
241        let map = g.get_or_insert_with(HashMap::new);
242        for (k, v) in entries {
243            map.entry(k).or_insert(v);
244        }
245    }
246}
247
248/// Resolve a term hash to its literal text via the resident graph's lexicon.
249/// Used by the query path as the ingested-data resolver for `TextResolver`.
250pub fn graph_lexicon_lookup(hash: u64) -> Option<String> {
251    GRAPH_LEXICON
252        .read()
253        .ok()
254        .and_then(|g| g.as_ref().and_then(|m| m.get(&hash).cloned()))
255}
256
257/// Load and merge the lexicon segments of all `.q42` volumes under
258/// `{storage_path}/Index` into the resident graph lexicon.
259fn load_graph_lexicon_from_index(storage_path: &str) {
260    let index = Path::new(storage_path).join("Index");
261    let Ok(entries) = std::fs::read_dir(&index) else {
262        return;
263    };
264    for entry in entries.filter_map(Result::ok) {
265        let path = entry.path();
266        if path.extension().and_then(|e| e.to_str()) != Some("q42") {
267            continue;
268        }
269        if path
270            .file_name()
271            .map(|n| n.to_string_lossy().contains(".meta."))
272            .unwrap_or(false)
273        {
274            continue;
275        }
276        if let Ok(lex) = crate::q42_lex::Q42Lexicon::load_for_q42(&path) {
277            merge_graph_lexicon(lex.entries);
278        }
279    }
280}
281
282fn try_load_index_dir(store: &mut DaemonGraphStore, storage_path: &str) {
283    let index = Path::new(storage_path).join("Index");
284    let Ok(entries) = std::fs::read_dir(&index) else {
285        return;
286    };
287    let paths: Vec<_> = entries
288        .filter_map(Result::ok)
289        .map(|entry| entry.path())
290        .filter(|path| {
291            path.extension().and_then(|e| e.to_str()) == Some("q42")
292                && !path
293                    .file_name()
294                    .map(|n| n.to_string_lossy().contains(".meta."))
295                    .unwrap_or(false)
296        })
297        .collect();
298    let mut child_paths = HashSet::new();
299    for path in &paths {
300        let Ok(root) = crate::q42_volume::Q42Volume::open(path) else {
301            continue;
302        };
303        let Ok(Some(manifest)) = root.volume_manifest() else {
304            continue;
305        };
306        let parent = path.parent().unwrap_or_else(|| Path::new("."));
307        for segment in manifest.segments {
308            child_paths.insert(parent.join(segment.locator));
309        }
310    }
311    for path in paths {
312        if child_paths.contains(&path) {
313            continue;
314        }
315        if let Ok(quins) = crate::q42_reader::read_q42_quins(&path) {
316            store.extend_from_slice(&quins);
317        }
318    }
319}
320
321/// Controls which resident graph layers are seeded at daemon boot.
322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323pub struct InitGraphOptions {
324    /// Seed the built-in anatomy/health demo triples.
325    pub seed_defaults: bool,
326    /// Load `.q42` volumes from `{storage_path}/Index`.
327    pub load_index: bool,
328}
329
330impl Default for InitGraphOptions {
331    fn default() -> Self {
332        Self {
333            seed_defaults: true,
334            load_index: true,
335        }
336    }
337}
338
339/// Initialise or refresh the daemon graph from storage path.
340pub fn init_daemon_graph(storage_path: &str) {
341    init_daemon_graph_with_options(storage_path, InitGraphOptions::default());
342}
343
344/// Initialise or refresh the daemon graph with explicit seeding policy.
345pub fn init_daemon_graph_with_options(storage_path: &str, opts: InitGraphOptions) {
346    // Always (re)load the literal lexicon from the Index volumes so the query
347    // path can resolve ingested literal text — independent of whether the quins
348    // come from the snapshot or a fresh seed below.
349    reset_graph_lexicon();
350    load_graph_lexicon_from_index(storage_path);
351
352    // A durable snapshot (written after each committed SPARQL Update) is the
353    // authoritative last full state — prefer it so updates survive a restart.
354    if let Ok(n) = load_graph_snapshot(storage_path) {
355        if n > 0 {
356            bump_graph_revision();
357            return;
358        }
359    }
360    let lock = graph_lock();
361    if let Ok(mut guard) = lock.write() {
362        guard.clear();
363        if opts.seed_defaults {
364            seed_anatomy_health_graph(&mut guard);
365        }
366        if opts.load_index {
367            try_load_index_dir(&mut guard, storage_path);
368        }
369    }
370    bump_graph_revision();
371}
372
373/// Number of Quins currently available to `/query`.
374pub fn graph_quin_count() -> usize {
375    graph_lock().read().map(|g| g.len()).unwrap_or(0)
376}
377
378/// Read guard over the live graph (lock is process-static via `OnceLock`).
379pub fn graph_read_guard() -> std::sync::RwLockReadGuard<'static, DaemonGraphStore> {
380    graph_lock().read().expect("daemon graph poisoned")
381}
382
383/// Outcome of applying a SPARQL Update to the daemon graph.
384#[derive(Debug, Clone, Copy, PartialEq, Eq)]
385pub struct UpdateOutcome {
386    /// Number of quins added to the graph.
387    pub inserted: u64,
388    /// Number of quins removed from the graph.
389    pub deleted: u64,
390    /// Whether the change was signed and persisted to the WAL (true only when a
391    /// real signer callback was supplied). `false` = ephemeral, in-memory only.
392    pub persisted: bool,
393}
394
395/// Apply a parsed SPARQL Update to the resident daemon graph.
396///
397/// The mutation is applied under a single write guard (copy → run
398/// `UpdateExecutor` → write back), then the graph revision is bumped so
399/// subscribers (e.g. WebSocket sessions) are notified.
400///
401/// `on_change`, if supplied, receives the `(inserted, deleted)` quin sets so the
402/// caller can sign and persist them to the WAL with a **real** key (see
403/// `wal::commit_semantic_mutation`); `persisted` is then `true`. If it is
404/// `None`, the change is applied in memory only (ephemeral) and `persisted` is
405/// `false`. A signature is **never fabricated here** — durable, signed mutation
406/// requires the caller to supply a real signer, so an irreversible delete can
407/// never be committed under a placeholder key.
408pub fn apply_sparql_update(
409    op: &crate::sparql_library::sparql_update::UpdateOperation,
410    ctx: &crate::sparql_ast::SparqlQueryContext,
411    on_change: Option<&mut dyn FnMut(&[NQuin], &[NQuin]) -> Result<(), String>>,
412) -> Result<UpdateOutcome, String> {
413    use crate::sparql_library::sparql_update::UpdateExecutor;
414
415    let lock = graph_lock();
416    let mut guard = lock
417        .write()
418        .map_err(|_| "daemon graph poisoned".to_string())?;
419
420    let before: Vec<NQuin> = guard.as_slice().to_vec();
421    let mut working = before.clone();
422    UpdateExecutor::new(&mut working).execute(op, ctx)?;
423
424    // Delta by semantic identity (subject/predicate/object/context), ignoring
425    // parity/metadata noise.
426    let same = |a: &NQuin, b: &NQuin| {
427        a.subject == b.subject
428            && a.predicate == b.predicate
429            && a.object == b.object
430            && a.context == b.context
431    };
432    let inserted: Vec<NQuin> = working
433        .iter()
434        .filter(|w| !before.iter().any(|b| same(w, b)))
435        .copied()
436        .collect();
437    let deleted: Vec<NQuin> = before
438        .iter()
439        .filter(|b| !working.iter().any(|w| same(w, b)))
440        .copied()
441        .collect();
442
443    guard.clear();
444    guard.extend_from_slice(&working);
445    drop(guard);
446    bump_graph_revision();
447
448    let persisted = if let Some(cb) = on_change {
449        // The graph is already updated; the callback makes it durable. If it
450        // fails, the in-memory change stands but is reported as not persisted.
451        cb(&inserted, &deleted).map_err(|e| format!("persist failed: {e}"))?;
452        true
453    } else {
454        false
455    };
456
457    Ok(UpdateOutcome {
458        inserted: inserted.len() as u64,
459        deleted: deleted.len() as u64,
460        persisted,
461    })
462}
463
464/// Path of the durable full-state snapshot under a storage directory.
465fn snapshot_path(storage_path: &str) -> std::path::PathBuf {
466    Path::new(storage_path).join("daemon_graph.snapshot")
467}
468
469/// Write the current full graph state to a flat-quin snapshot file. Called after
470/// a persisted SPARQL Update so the change survives a restart. Returns the quin
471/// count written.
472pub fn persist_graph_snapshot(storage_path: &str) -> std::io::Result<usize> {
473    let lock = graph_lock();
474    let guard = lock
475        .read()
476        .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "daemon graph poisoned"))?;
477    let bytes: &[u8] = bytemuck::cast_slice(guard.as_slice());
478    let path = snapshot_path(storage_path);
479    if let Some(parent) = path.parent() {
480        let _ = std::fs::create_dir_all(parent);
481    }
482    std::fs::write(&path, bytes)?;
483    Ok(guard.len())
484}
485
486/// Load the durable snapshot into the graph, if present. Returns the quin count
487/// loaded (0 if there is no snapshot). This is the authoritative last full state
488/// (defaults + index + committed updates) when it exists.
489pub fn load_graph_snapshot(storage_path: &str) -> std::io::Result<usize> {
490    let path = snapshot_path(storage_path);
491    if !path.exists() {
492        return Ok(0);
493    }
494    let bytes = std::fs::read(&path)?;
495    if bytes.is_empty() {
496        return Ok(0);
497    }
498    replace_graph_from_flat_bytes(&bytes)
499        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
500}
501
502/// Apply a SPARQL Update **durably and signed**: each net change is stamped and
503/// signed to the WAL (the append-only audit trail) with the caller's **real**
504/// ed25519 key, then the full graph state is snapshotted for restart durability.
505/// This is the production write path; the key must come from the identity /
506/// key-vault layer — never a placeholder.
507#[allow(clippy::too_many_arguments)]
508pub fn apply_sparql_update_durable(
509    op: &crate::sparql_library::sparql_update::UpdateOperation,
510    ctx: &crate::sparql_ast::SparqlQueryContext,
511    signing_key: &ed25519_dalek::SigningKey,
512    principal_did_hash: u64,
513    agent_did_hash: u64,
514    wal_path: &str,
515    storage_path: &str,
516) -> Result<UpdateOutcome, String> {
517    let mut wal = crate::wal::WriteAheadLog::open(wal_path).map_err(|e| e.to_string())?;
518    let mut suspended = crate::crdt::SuspendedTransactionQueue::new();
519    let mut cb = |inserted: &[NQuin], deleted: &[NQuin]| -> Result<(), String> {
520        // Record every mutation (insert and delete) as a signed WAL entry — the
521        // tamper-evident audit trail. Restart state comes from the snapshot.
522        for q in inserted.iter().chain(deleted.iter()) {
523            let mut qm = *q;
524            crate::wal::commit_semantic_mutation(
525                &mut wal,
526                &mut qm,
527                principal_did_hash,
528                agent_did_hash,
529                signing_key,
530                &mut suspended,
531            )
532            .map_err(|e| e.to_string())?;
533        }
534        Ok(())
535    };
536    let outcome = apply_sparql_update(op, ctx, Some(&mut cb))?;
537    persist_graph_snapshot(storage_path).map_err(|e| e.to_string())?;
538    Ok(outcome)
539}
540
541/// Extend the live graph with ontology quins from `qualia-core-db::ontology_loader`.
542pub fn extend_with_ontology_quins(quins: Vec<crate::NQuin>) {
543    extend_with_ontology_quins_slice(&quins);
544}
545
546/// Zero-heap resident update path for ontology insertion.
547pub fn extend_with_ontology_quins_slice(quins: &[crate::NQuin]) {
548    if quins.is_empty() {
549        return;
550    }
551    let lock = graph_lock();
552    if let Ok(mut guard) = lock.write() {
553        let before = guard.len();
554        for &q in quins {
555            let _ = guard.push_unique(q);
556        }
557        if guard.len() > before {
558            bump_graph_revision();
559        }
560    }
561}
562
563/// Replace the in-memory graph with flat 48-byte NQuin bytes (browser bench_load).
564pub fn replace_graph_from_flat_bytes(bytes: &[u8]) -> Result<usize, &'static str> {
565    let lock = graph_lock();
566    let mut guard = lock.write().map_err(|_| "daemon graph poisoned")?;
567    if bytes.is_empty() {
568        guard.clear();
569        return Ok(0);
570    }
571    if bytes.len() % 48 != 0 {
572        return Err("db_bytes length must be a multiple of 48");
573    }
574    let quin_count = bytes.len() / 48;
575    if quin_count > MAX_GRAPH_QUINS {
576        return Err("graph exceeds daemon MAX_GRAPH_QUINS");
577    }
578    let quins: &[NQuin] = bytemuck::cast_slice(bytes);
579    guard.clear();
580    guard.extend_from_slice(quins);
581    bump_graph_revision();
582    Ok(quin_count)
583}
584
585/// Known condition subject hashes for Anatomy graph -> label mapping.
586pub fn condition_label_for_subject_hash(subject: u64) -> Option<&'static str> {
587    const BIO: &str = "https://qualia.anatomy.example/ontology/bio#";
588    const TABLE: [(&str, &str); 8] = [
589        ("Type2Diabetes", "Type 2 Diabetes Mellitus"),
590        ("Hypertension", "Hypertension"),
591        ("ChronicKidneyDisease", "Chronic Kidney Disease (CKD)"),
592        ("HeartFailure", "Heart Failure"),
593        ("COPD", "Chronic Obstructive Pulmonary Disease (COPD)"),
594        ("Obesity", "Obesity"),
595        ("AtrialFibrillation", "Atrial Fibrillation"),
596        ("Depression", "Major Depressive Disorder"),
597    ];
598
599    for (local, label) in TABLE {
600        if q_hash(&format!("{BIO}{local}")) == subject {
601            return Some(label);
602        }
603    }
604    None
605}
606
607#[cfg(test)]
608mod tests {
609    use super::*;
610    use serial_test::serial;
611
612    fn reset_graph_for_test() {
613        let lock = graph_lock();
614        let mut guard = lock.write().expect("daemon graph poisoned");
615        guard.clear();
616    }
617
618    #[test]
619    #[serial]
620    fn seed_graph_has_health_quins() {
621        reset_graph_for_test();
622        init_daemon_graph("/tmp/qualia-test-graph");
623        assert!(graph_quin_count() >= 8);
624        reset_graph_for_test();
625    }
626
627    #[test]
628    #[serial]
629    fn replace_graph_from_flat_bytes_round_trip() {
630        reset_graph_for_test();
631        let quin = triple_quin(
632            "http://q.test/s/0",
633            "http://q.test/p/0",
634            "http://q.test/o/0",
635            "did:qualia:test",
636        );
637        let bytes = bytemuck::bytes_of(&quin);
638        let count = replace_graph_from_flat_bytes(bytes).expect("load flat quin");
639        assert_eq!(count, 1);
640        assert_eq!(graph_quin_count(), 1);
641        reset_graph_for_test();
642    }
643
644    #[test]
645    #[serial]
646    fn extend_with_ontology_quins_deduplicates_within_single_batch() {
647        reset_graph_for_test();
648        let quin = triple_quin(
649            "http://q.test/s/duplicate",
650            "http://q.test/p/duplicate",
651            "http://q.test/o/first",
652            "did:qualia:test",
653        );
654
655        extend_with_ontology_quins_slice(&[quin, quin]);
656
657        let guard = graph_read_guard();
658        assert_eq!(guard.len(), 1);
659        assert_eq!(guard[0], quin);
660        drop(guard);
661        reset_graph_for_test();
662    }
663
664    #[test]
665    #[serial]
666    fn init_daemon_graph_bumps_revision() {
667        reset_graph_for_test();
668        let before = graph_revision();
669        init_daemon_graph("/tmp/qualia-test-graph");
670        assert!(graph_revision() > before);
671        reset_graph_for_test();
672    }
673
674    #[test]
675    #[serial]
676    fn extend_with_ontology_quins_bumps_revision_only_when_added() {
677        reset_graph_for_test();
678        let quin = triple_quin(
679            "http://q.test/s/rev",
680            "http://q.test/p/rev",
681            "http://q.test/o/rev",
682            "did:qualia:test",
683        );
684        let before = graph_revision();
685        extend_with_ontology_quins_slice(&[quin]);
686        assert!(graph_revision() > before);
687
688        let unchanged = graph_revision();
689        extend_with_ontology_quins_slice(&[quin]);
690        assert_eq!(graph_revision(), unchanged);
691        reset_graph_for_test();
692    }
693
694    #[test]
695    #[serial]
696    fn replace_graph_from_flat_bytes_bumps_revision() {
697        reset_graph_for_test();
698        let quin = triple_quin(
699            "http://q.test/s/replace",
700            "http://q.test/p/replace",
701            "http://q.test/o/replace",
702            "did:qualia:test",
703        );
704        let before = graph_revision();
705        let bytes = bytemuck::bytes_of(&quin);
706        replace_graph_from_flat_bytes(bytes).expect("load flat quin");
707        assert!(graph_revision() > before);
708        reset_graph_for_test();
709    }
710
711    fn parse_upd(
712        src: &str,
713    ) -> (
714        crate::sparql_ast::SparqlQueryContext,
715        crate::sparql_library::sparql_update::UpdateOperation,
716    ) {
717        let mut ctx = crate::sparql_ast::SparqlQueryContext::new();
718        let op = crate::sparql_library::sparql_grammar::parse_update(
719            src,
720            &mut ctx,
721            &std::collections::HashMap::new(),
722        )
723        .unwrap();
724        (ctx, op)
725    }
726
727    #[test]
728    #[serial]
729    fn apply_update_insert_grows_graph_ephemeral() {
730        reset_graph_for_test();
731        let (ctx, op) =
732            parse_upd("INSERT DATA { <http://q.test/s1> <http://q.test/p1> <http://q.test/o1> }");
733        let before = graph_quin_count();
734        let rev_before = graph_revision();
735        let out = apply_sparql_update(&op, &ctx, None).unwrap();
736        assert_eq!(out.inserted, 1);
737        assert!(
738            !out.persisted,
739            "no signer callback → ephemeral, not persisted"
740        );
741        assert_eq!(graph_quin_count(), before + 1);
742        assert!(
743            graph_revision() > rev_before,
744            "revision bumped for subscribers"
745        );
746        reset_graph_for_test();
747    }
748
749    #[test]
750    #[serial]
751    fn graph_lexicon_merge_and_lookup() {
752        // The resident graph lexicon (merged from .q42 volumes) is what the query
753        // path hands the geo/text resolver for ingested-data literal text.
754        reset_graph_lexicon();
755        let mut m = std::collections::HashMap::new();
756        m.insert(42u64, "POINT(1 2)".to_string());
757        merge_graph_lexicon(m);
758        assert_eq!(graph_lexicon_lookup(42), Some("POINT(1 2)".to_string()));
759        assert_eq!(graph_lexicon_lookup(999), None);
760        reset_graph_lexicon();
761    }
762
763    #[test]
764    #[serial]
765    fn update_snapshot_survives_reinit() {
766        reset_graph_for_test();
767        let dir = std::env::temp_dir().join(format!("qdb_snap_{}", std::process::id()));
768        let _ = std::fs::create_dir_all(&dir);
769        let storage = dir.to_string_lossy().to_string();
770        let _ = std::fs::remove_file(snapshot_path(&storage));
771
772        // Apply an update and snapshot the full state.
773        let (ctx, op) = parse_upd(
774            "INSERT DATA { <http://q.test/durable> <http://q.test/p> <http://q.test/o> }",
775        );
776        apply_sparql_update(&op, &ctx, None).unwrap();
777        let count = graph_quin_count();
778        assert!(count > 0);
779        persist_graph_snapshot(&storage).unwrap();
780
781        // Wipe the in-memory graph, then re-init — the snapshot must restore it.
782        reset_graph_for_test();
783        assert_eq!(graph_quin_count(), 0);
784        init_daemon_graph_with_options(&storage, InitGraphOptions::default());
785        assert_eq!(
786            graph_quin_count(),
787            count,
788            "the durable snapshot must restore the updated graph on restart"
789        );
790
791        let _ = std::fs::remove_file(snapshot_path(&storage));
792        reset_graph_for_test();
793    }
794
795    #[test]
796    #[serial]
797    fn apply_update_delete_removes_and_signer_sees_delta() {
798        reset_graph_for_test();
799        let (ictx, iop) =
800            parse_upd("INSERT DATA { <http://q.test/s2> <http://q.test/p2> <http://q.test/o2> }");
801        apply_sparql_update(&iop, &ictx, None).unwrap();
802        let seeded = graph_quin_count();
803
804        let (dctx, dop) =
805            parse_upd("DELETE DATA { <http://q.test/s2> <http://q.test/p2> <http://q.test/o2> }");
806        let mut captured_deleted = 0usize;
807        let mut cb = |_ins: &[NQuin], del: &[NQuin]| -> Result<(), String> {
808            captured_deleted = del.len();
809            Ok(())
810        };
811        let out = apply_sparql_update(&dop, &dctx, Some(&mut cb)).unwrap();
812        assert_eq!(out.deleted, 1);
813        assert!(out.persisted, "signer callback supplied → persisted");
814        assert_eq!(captured_deleted, 1, "callback received the deleted quin");
815        assert_eq!(graph_quin_count(), seeded - 1);
816        reset_graph_for_test();
817    }
818}