Skip to main content

mcp_memory/
kg.rs

1use rustc_hash::FxHashMap;
2use std::collections::{HashSet, VecDeque};
3use std::num::NonZeroUsize;
4use std::path::Path;
5use std::sync::atomic::{AtomicI64, AtomicUsize, Ordering};
6use std::time::{Duration, SystemTime, UNIX_EPOCH};
7
8use lru::LruCache;
9use parking_lot::{Mutex, MutexGuard};
10use rusqlite::{params, types::ToSql, Connection, OpenFlags};
11
12use crate::config::{Durability, SqliteTuning};
13use crate::errors::{MCSError, Result};
14use crate::types::{Entity, Relation};
15
16fn sqlite_err(e: rusqlite::Error) -> MCSError {
17    MCSError::IoError(std::io::Error::other(e))
18}
19
20const fn is_not_found(e: &rusqlite::Error) -> bool {
21    matches!(e, rusqlite::Error::QueryReturnedNoRows)
22}
23
24#[inline(always)]
25fn now_us() -> i64 {
26    SystemTime::now()
27        .duration_since(UNIX_EPOCH)
28        .unwrap_or_default()
29        .as_micros() as i64
30}
31
32#[inline(always)]
33pub(crate) fn name_hash(name: &str) -> i64 {
34    let mut h: u64 = 0xcbf29ce484222325;
35    for b in name.bytes() {
36        h ^= u64::from(b);
37        h = h.wrapping_mul(0x100000001b3);
38    }
39    h as i64
40}
41
42fn load_observations(conn: &Connection, entity_id: i64) -> Result<Vec<String>> {
43    let mut stmt = conn
44        .prepare_cached("SELECT body FROM observation WHERE entity_id = ?1 ORDER BY idx")
45        .map_err(sqlite_err)?;
46    let rows = stmt
47        .query_map(params![entity_id], |row| row.get::<_, String>(0))
48        .map_err(sqlite_err)?
49        .filter_map(|r| r.ok())
50        .collect::<Vec<_>>();
51    Ok(rows)
52}
53
54fn load_observations_opt(conn: &Connection, entity_id: i64) -> Vec<String> {
55    load_observations(conn, entity_id).unwrap_or_default()
56}
57
58fn entity_name_lookup(conn: &Connection, name: &str) -> Result<Option<i64>> {
59    let h = name_hash(name);
60    let mut stmt = conn
61        .prepare_cached(
62            "SELECT id FROM entity WHERE name_hash = ?1 AND name = ?2 AND flags = 0",
63        )
64        .map_err(sqlite_err)?;
65    match stmt.query_row(params![h, name], |row| row.get::<_, i64>(0)) {
66        Ok(id) => Ok(Some(id)),
67        Err(e) if is_not_found(&e) => Ok(None),
68        Err(e) => Err(sqlite_err(e)),
69    }
70}
71
72fn get_type_id(conn: &Connection, type_name: &str, kind: i64) -> Result<i64> {
73    let mut sel = conn
74        .prepare_cached("SELECT id FROM type_dict WHERE kind = ?1 AND name = ?2")
75        .map_err(sqlite_err)?;
76    if let Ok(id) = sel.query_row(params![kind, type_name], |row| row.get::<_, i64>(0)) {
77        return Ok(id);
78    }
79    conn.execute(
80        "INSERT INTO type_dict (kind, name, count) VALUES (?1, ?2, 0)",
81        params![kind, type_name],
82    )
83    .map_err(sqlite_err)?;
84    Ok(conn.last_insert_rowid())
85}
86
87/// Read-only type lookup. Unlike [`get_type_id`] this never inserts, so it is
88/// safe to call on a `query_only` reader connection. Returns `None` when the
89/// type does not exist.
90fn lookup_type_id(conn: &Connection, type_name: &str, kind: i64) -> Option<i64> {
91    conn.prepare_cached("SELECT id FROM type_dict WHERE kind = ?1 AND name = ?2")
92        .ok()?
93        .query_row(params![kind, type_name], |row| row.get::<_, i64>(0))
94        .ok()
95}
96
97fn inc_type_count(conn: &Connection, type_id: i64, delta: i64) -> Result<()> {
98    conn.execute(
99        "UPDATE type_dict SET count = count + ?1 WHERE id = ?2",
100        params![delta, type_id],
101    )
102    .map_err(sqlite_err)?;
103    Ok(())
104}
105
106fn inc_graph_stat(conn: &Connection, key: &str, delta: i64) -> Result<()> {
107    conn.execute(
108        "UPDATE graph_stat SET value = value + ?1 WHERE key = ?2",
109        params![delta, key],
110    )
111    .map_err(sqlite_err)?;
112    Ok(())
113}
114
115fn read_graph_stat(conn: &Connection, key: &str) -> Result<i64> {
116    conn.query_row(
117        "SELECT value FROM graph_stat WHERE key = ?1",
118        params![key],
119        |row| row.get(0),
120    )
121    .map_err(sqlite_err)
122}
123
124fn name_of_type(conn: &Connection, type_id: i64) -> Result<String> {
125    conn.query_row(
126        "SELECT name FROM type_dict WHERE id = ?1",
127        params![type_id],
128        |row| row.get(0),
129    )
130    .map_err(sqlite_err)
131}
132
133fn select_all_types(conn: &Connection, kind: i64) -> Result<Vec<(String, usize)>> {
134    let mut stmt = conn
135        .prepare_cached(
136            "SELECT name, count FROM type_dict WHERE kind = ?1 AND count > 0 ORDER BY count DESC",
137        )
138        .map_err(sqlite_err)?;
139    let rows = stmt
140        .query_map(params![kind], |row| {
141            Ok((
142                row.get::<_, String>(0)?,
143                row.get::<_, i64>(1)? as usize,
144            ))
145        })
146        .map_err(sqlite_err)?
147        .filter_map(|r| r.ok())
148        .collect();
149    Ok(rows)
150}
151
152fn entity_by_id(conn: &Connection, id: i64) -> Result<Entity> {
153    let mut stmt = conn
154        .prepare_cached(
155            "SELECT e.name, t.name,
156               COALESCE((SELECT json_group_array(o.body ORDER BY o.idx) FROM observation o WHERE o.entity_id = e.id), '[]')
157             FROM entity e JOIN type_dict t ON t.id = e.type_id WHERE e.id = ?1 AND e.flags = 0",
158        )
159        .map_err(sqlite_err)?;
160    let (name, etype, obs_json): (String, String, String) = stmt
161        .query_row(params![id], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
162        .map_err(sqlite_err)?;
163    let observations: Vec<String> = serde_json::from_str(&obs_json).unwrap_or_default();
164    Ok(Entity {
165        name,
166        entity_type: etype,
167        observations,
168    })
169}
170
171/// Direction of relation traversal.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub enum Direction {
174    Outgoing,
175    Incoming,
176    Both,
177}
178
179impl Direction {
180    pub fn parse(s: Option<&str>) -> Self {
181        match s {
182            Some("OUTGOING") => Direction::Outgoing,
183            Some("INCOMING") => Direction::Incoming,
184            _ => Direction::Both,
185        }
186    }
187}
188
189/// Escape a string for embedding in JSON, writing directly into the given buffer.
190/// Avoids allocating a temporary `serde_json::Value` for the JSON-RPC wrapper.
191pub fn push_json_str(buf: &mut String, raw: &str) {
192    buf.push('"');
193    let mut start = 0;
194    let bytes = raw.as_bytes();
195    for (i, &b) in bytes.iter().enumerate() {
196        let esc: u8 = match b {
197            b'"' => b'"',
198            b'\\' => b'\\',
199            b'\n' => b'n',
200            b'\r' => b'r',
201            b'\t' => b't',
202            0x08 => b'b',
203            0x0C => b'f',
204            0x00..=0x07 | 0x0B | 0x0E..=0x1F => continue, // escaped below
205            _ => continue,
206        };
207        buf.push_str(&raw[start..i]);
208        buf.push('\\');
209        buf.push(esc as char);
210        start = i + 1;
211    }
212    // Control chars 0x00-0x1F not handled above: escape as \u00XX
213    for (i, &b) in bytes.iter().enumerate().skip(start) {
214        if b <= 0x07 || b == 0x0B || (0x0E..=0x1F).contains(&b) {
215            buf.push_str(&raw[start..i]);
216            write_escape_unicode(buf, b);
217            start = i + 1;
218        }
219    }
220    buf.push_str(&raw[start..]);
221    buf.push('"');
222}
223
224#[inline(never)]
225fn write_escape_unicode(buf: &mut String, b: u8) {
226    use std::fmt::Write;
227    write!(buf, "\\u{:04x}", b).unwrap();
228}
229
230// ── MetaCache ────────────────────────────────────────────────────────────
231
232#[derive(Copy, Clone)]
233struct EntityMeta {
234    id: i64,
235    type_id: i64,
236    obs_count: i64,
237    out_deg: i64,
238    in_deg: i64,
239}
240
241// ── Transaction guard (RAII rollback on error) ─────────────────────────
242
243struct TxGuard<'a> {
244    conn: &'a Connection,
245    done: bool,
246}
247
248impl<'a> TxGuard<'a> {
249    fn begin(conn: &'a Connection) -> Result<Self> {
250        // BEGIN IMMEDIATE acquires the WAL write lock up front rather than
251        // lazily on the first write. This makes the busy-timeout apply to lock
252        // acquisition deterministically and avoids `SQLITE_BUSY_SNAPSHOT`
253        // surprises when readers are concurrently active.
254        conn.execute_batch("BEGIN IMMEDIATE").map_err(sqlite_err)?;
255        Ok(Self { conn, done: false })
256    }
257
258    fn commit(mut self) -> Result<()> {
259        self.done = true;
260        self.conn.execute_batch("COMMIT").map_err(sqlite_err)
261    }
262}
263
264impl Drop for TxGuard<'_> {
265    fn drop(&mut self) {
266        if !self.done {
267            let _ = self.conn.execute_batch("ROLLBACK");
268        }
269    }
270}
271
272// ── Reader pool ───────────────────────────────────────────────────────────
273
274/// A small fixed pool of `query_only` SQLite connections used for read
275/// operations. WAL mode permits any number of concurrent readers alongside the
276/// single writer, so spreading reads across several connections lets them run
277/// in parallel instead of serializing on the writer's mutex.
278struct ReaderPool {
279    conns: Vec<Mutex<Connection>>,
280    next: AtomicUsize,
281}
282
283impl ReaderPool {
284    /// Acquire a reader connection. Fast path: grab the first idle one. If every
285    /// connection is busy, block on a round-robin pick so callers still make
286    /// progress (and never spin).
287    fn get(&self) -> MutexGuard<'_, Connection> {
288        for c in &self.conns {
289            if let Some(g) = c.try_lock() {
290                return g;
291            }
292        }
293        let i = self.next.fetch_add(1, Ordering::Relaxed) % self.conns.len();
294        self.conns[i].lock()
295    }
296}
297
298// ── GraphHandle ──────────────────────────────────────────────────────────
299
300pub struct GraphHandle {
301    /// The single read-write connection. SQLite allows only one writer, so all
302    /// mutations serialize here.
303    writer: Mutex<Connection>,
304    /// Pool of `query_only` connections for concurrent reads (WAL).
305    readers: ReaderPool,
306    seq_entity: AtomicI64,
307    seq_obs: AtomicI64,
308    cache: Mutex<LruCache<String, EntityMeta>>,
309}
310
311/// Open one `query_only` reader connection against an existing WAL database.
312///
313/// The connection is opened read-write at the OS level (so it can attach to the
314/// `-shm` wal-index — SQLite cannot read a WAL database through a pure
315/// `SQLITE_OPEN_READ_ONLY` handle) and then locked to reads with
316/// `PRAGMA query_only = ON`, which makes any accidental write error out.
317fn open_reader(path: &Path, tuning: &SqliteTuning) -> Result<Connection> {
318    let conn = Connection::open_with_flags(
319        path,
320        OpenFlags::SQLITE_OPEN_READ_WRITE
321            | OpenFlags::SQLITE_OPEN_NO_MUTEX
322            | OpenFlags::SQLITE_OPEN_URI,
323    )
324    .map_err(sqlite_err)?;
325    conn.busy_timeout(Duration::from_millis(tuning.busy_timeout_ms))
326        .map_err(sqlite_err)?;
327    conn.execute_batch(&format!(
328        "PRAGMA query_only   = ON;
329         PRAGMA cache_size   = -{};
330         PRAGMA temp_store   = MEMORY;
331         PRAGMA mmap_size    = {};",
332        tuning.cache_size_kb, tuning.mmap_size
333    ))
334    .map_err(sqlite_err)?;
335    Ok(conn)
336}
337
338impl GraphHandle {
339    pub fn new(
340        path: &Path,
341        durability: Durability,
342        tuning: SqliteTuning,
343        lru_cache_size: NonZeroUsize,
344        read_pool_size: usize,
345    ) -> Result<Self> {
346        let conn = Connection::open(path).map_err(sqlite_err)?;
347        // Apply the busy handler through the API so it is in force for every
348        // subsequent statement (including schema creation and BEGIN IMMEDIATE).
349        conn.busy_timeout(Duration::from_millis(tuning.busy_timeout_ms))
350            .map_err(sqlite_err)?;
351
352        // `page_size` and `auto_vacuum` are fixed when the database first gets
353        // content, and `page_size` additionally must precede `journal_mode=WAL`.
354        // Set both up front on this connection, before any table is created, so
355        // they take effect on a fresh database. On an existing database they are
356        // silently ignored (would require VACUUM to change).
357        conn.execute_batch(&format!(
358            "PRAGMA page_size    = {};
359             PRAGMA auto_vacuum  = INCREMENTAL;",
360            tuning.page_size
361        ))
362        .map_err(sqlite_err)?;
363
364        conn.execute_batch(&format!(
365             "PRAGMA journal_mode = WAL;
366             PRAGMA foreign_keys = OFF;
367             PRAGMA cache_size    = -{};
368             PRAGMA temp_store    = MEMORY;
369             PRAGMA busy_timeout  = {};
370             PRAGMA synchronous   = NORMAL;
371             PRAGMA journal_size_limit = {};",
372            tuning.cache_size_kb, tuning.busy_timeout_ms, tuning.journal_size_limit
373        ))
374        .map_err(sqlite_err)?;
375
376        conn.execute_batch(
377             "CREATE TABLE IF NOT EXISTS entity (
378                 id          INTEGER PRIMARY KEY,
379                 name_hash   INTEGER NOT NULL,
380                 name        TEXT    NOT NULL,
381                 type_id     INTEGER NOT NULL,
382                 obs_count   INTEGER NOT NULL DEFAULT 0,
383                 out_deg     INTEGER NOT NULL DEFAULT 0,
384                 in_deg      INTEGER NOT NULL DEFAULT 0,
385                 created_us  INTEGER NOT NULL,
386                 updated_us  INTEGER NOT NULL,
387                 flags       INTEGER NOT NULL DEFAULT 0
388             ) STRICT;
389
390             CREATE INDEX IF NOT EXISTS entity_by_hash
391                 ON entity(name_hash, type_id, obs_count, out_deg, in_deg)
392                 WHERE flags = 0;
393
394             CREATE INDEX IF NOT EXISTS entity_name_ci
395                 ON entity(lower(name))
396                 WHERE flags = 0;
397
398             CREATE TABLE IF NOT EXISTS observation (
399                 id          INTEGER PRIMARY KEY,
400                 entity_id   INTEGER NOT NULL,
401                 idx         INTEGER NOT NULL,
402                 body        TEXT    NOT NULL,
403                 created_us  INTEGER NOT NULL
404             ) STRICT;
405
406             CREATE INDEX IF NOT EXISTS obs_by_entity
407                 ON observation(entity_id, idx);
408
409             CREATE TABLE IF NOT EXISTS relation (
410                 from_id     INTEGER NOT NULL,
411                 to_id       INTEGER NOT NULL,
412                 type_id     INTEGER NOT NULL,
413                 created_us  INTEGER NOT NULL
414             ) STRICT;
415
416             CREATE INDEX IF NOT EXISTS rel_out
417                 ON relation(from_id, type_id, to_id);
418
419             CREATE INDEX IF NOT EXISTS rel_in
420                 ON relation(to_id, type_id, from_id);
421
422             CREATE VIRTUAL TABLE IF NOT EXISTS name_fts
423                 USING fts5(name, content='entity', content_rowid='id',
424                            tokenize='unicode61 remove_diacritics 2');
425
426             CREATE VIRTUAL TABLE IF NOT EXISTS obs_fts
427                 USING fts5(body, content='observation', content_rowid='id',
428                            tokenize='unicode61 remove_diacritics 2');
429
430             CREATE TRIGGER IF NOT EXISTS obs_fts_ai AFTER INSERT ON observation BEGIN
431               INSERT INTO obs_fts(rowid, body) VALUES (new.id, new.body);
432             END;
433
434             CREATE TRIGGER IF NOT EXISTS obs_fts_bd BEFORE DELETE ON observation BEGIN
435               INSERT INTO obs_fts(obs_fts, rowid, body) VALUES ('delete', old.id, '');
436             END;
437
438             CREATE TABLE IF NOT EXISTS type_dict (
439                 id     INTEGER PRIMARY KEY,
440                 kind   INTEGER NOT NULL,
441                 name   TEXT    NOT NULL,
442                 count  INTEGER NOT NULL DEFAULT 0
443             ) STRICT;
444
445             CREATE INDEX IF NOT EXISTS type_by_name
446                 ON type_dict(kind, name);
447
448             CREATE TABLE IF NOT EXISTS graph_stat (
449                 key    TEXT NOT NULL PRIMARY KEY,
450                 value  INTEGER NOT NULL
451             ) STRICT, WITHOUT ROWID;
452
453             CREATE TABLE IF NOT EXISTS hub_degree (
454                 entity_id INTEGER PRIMARY KEY,
455                 out_deg   INTEGER NOT NULL,
456                 in_deg    INTEGER NOT NULL
457             ) STRICT;
458
459             CREATE TABLE IF NOT EXISTS partition_map (
460                 table_name TEXT NOT NULL PRIMARY KEY,
461                 role       INTEGER NOT NULL,
462                 type_id    INTEGER,
463                 row_count  INTEGER NOT NULL DEFAULT 0
464             ) STRICT, WITHOUT ROWID;",
465        )
466        .map_err(sqlite_err)?;
467
468        conn.execute_batch(&format!("PRAGMA mmap_size = {};", tuning.mmap_size))
469            .map_err(sqlite_err)?;
470
471        let sync_pragma = match durability {
472            Durability::Sync => "PRAGMA synchronous = FULL",
473            Durability::Async => "PRAGMA synchronous = NORMAL",
474        };
475        conn.execute_batch(sync_pragma).map_err(sqlite_err)?;
476
477        // Bound the cost of `PRAGMA optimize` (here and in maintenance) so a
478        // large database cannot stall startup/maintenance analyzing every index.
479        conn.execute_batch("PRAGMA analysis_limit = 400;")
480            .map_err(sqlite_err)?;
481
482        let has_stat: bool = conn
483            .query_row("SELECT 1 FROM graph_stat LIMIT 1", [], |_| Ok(()))
484            .is_ok();
485        if !has_stat {
486            conn.execute_batch(
487                "INSERT INTO graph_stat(key, value) VALUES
488                 ('entities', 0), ('relations', 0), ('observations', 0),
489                 ('entity_seq', 0), ('obs_seq', 0);",
490            )
491            .map_err(sqlite_err)?;
492        }
493
494        conn.execute_batch("PRAGMA optimize;").map_err(sqlite_err)?;
495
496        let seq_entity = read_graph_stat(&conn, "entity_seq").unwrap_or(0);
497        let seq_obs = read_graph_stat(&conn, "obs_seq").unwrap_or(0);
498
499        // Open the reader pool against the now-initialized database. At least one
500        // reader is always created.
501        let pool_size = read_pool_size.max(1);
502        let mut conns = Vec::with_capacity(pool_size);
503        for _ in 0..pool_size {
504            conns.push(Mutex::new(open_reader(path, &tuning)?));
505        }
506        let readers = ReaderPool {
507            conns,
508            next: AtomicUsize::new(0),
509        };
510
511        Ok(Self {
512            writer: Mutex::new(conn),
513            readers,
514            seq_entity: AtomicI64::new(seq_entity),
515            seq_obs: AtomicI64::new(seq_obs),
516            cache: Mutex::new(LruCache::new(lru_cache_size)),
517        })
518    }
519
520    fn next_entity_id(&self) -> i64 {
521        self.seq_entity.fetch_add(1, Ordering::Relaxed) + 1
522    }
523
524    fn next_obs_id(&self) -> i64 {
525        self.seq_obs.fetch_add(1, Ordering::Relaxed) + 1
526    }
527
528    fn meta_get(&self, name: &str) -> Option<EntityMeta> {
529        self.cache.lock().get(name).copied()
530    }
531
532    fn meta_set(&self, name: &str, m: EntityMeta) {
533        self.cache.lock().put(name.to_string(), m);
534    }
535
536    fn meta_remove(&self, name: &str) {
537        self.cache.lock().pop(name);
538    }
539
540    fn meta_update(&self, name: &str, f: impl FnOnce(&mut EntityMeta)) {
541        let mut cache = self.cache.lock();
542        if let Some(m) = cache.get_mut(name) {
543            f(m);
544        }
545    }
546
547    fn get_entity_id(&self, conn: &Connection, name: &str) -> Result<Option<(i64, i64, i64, i64)>> {
548        if let Some(m) = self.meta_get(name) {
549            return Ok(Some((m.id, m.type_id, m.out_deg, m.in_deg)));
550        }
551        let h = name_hash(name);
552        let mut stmt = conn
553            .prepare_cached(
554                "SELECT id, type_id, obs_count, out_deg, in_deg
555                 FROM entity WHERE name_hash = ?1 AND name = ?2 AND flags = 0",
556            )
557            .map_err(sqlite_err)?;
558        match stmt.query_row(params![h, name], |row| {
559            Ok(EntityMeta {
560                id: row.get(0)?,
561                type_id: row.get(1)?,
562                obs_count: row.get(2)?,
563                out_deg: row.get(3)?,
564                in_deg: row.get(4)?,
565            })
566        }) {
567            Ok(m) => {
568                self.meta_set(name, m);
569                Ok(Some((m.id, m.type_id, m.out_deg, m.in_deg)))
570            }
571            Err(e) if is_not_found(&e) => Ok(None),
572            Err(e) => Err(sqlite_err(e)),
573        }
574    }
575
576    fn sync_seqs(&self, conn: &Connection) -> Result<()> {
577        let seq_e = self.seq_entity.load(Ordering::Relaxed);
578        let seq_o = self.seq_obs.load(Ordering::Relaxed);
579        conn.execute(
580            "UPDATE graph_stat SET value = CASE key WHEN 'entity_seq' THEN ?1 WHEN 'obs_seq' THEN ?2 ELSE value END
581             WHERE key IN ('entity_seq', 'obs_seq')",
582            params![seq_e, seq_o],
583        )
584        .map_err(sqlite_err)?;
585        Ok(())
586    }
587
588    // ── Public API ──────────────────────────────────────────────────────
589
590    pub fn get_entity(&self, name: &str) -> Result<Option<Entity>> {
591        if name.is_empty() {
592            return Ok(None);
593        }
594
595        if let Some(m) = self.meta_get(name) {
596            let conn = self.readers.get();
597            let etype = name_of_type(&conn, m.type_id).unwrap_or_default();
598            let observations = load_observations_opt(&conn, m.id);
599            return Ok(Some(Entity {
600                name: name.to_string(),
601                entity_type: etype,
602                observations,
603            }));
604        }
605
606        let conn = self.readers.get();
607        let h = name_hash(name);
608        let mut stmt = conn
609            .prepare_cached(
610                "SELECT e.id, e.type_id, e.name, t.name,
611                        e.obs_count, e.out_deg, e.in_deg
612                 FROM entity e
613                 JOIN type_dict t ON t.id = e.type_id
614                 WHERE e.name_hash = ?1 AND e.name = ?2 AND e.flags = 0",
615            )
616            .map_err(sqlite_err)?;
617        match stmt.query_row(params![h, name], |row| {
618            let id: i64 = row.get(0)?;
619            let type_id: i64 = row.get(1)?;
620            let ename: String = row.get(2)?;
621            let etype: String = row.get(3)?;
622            let obs_count: i64 = row.get(4)?;
623            let out_deg: i64 = row.get(5)?;
624            let in_deg: i64 = row.get(6)?;
625            Ok((id, type_id, ename, etype, obs_count, out_deg, in_deg))
626        }) {
627            Ok((id, type_id, ename, etype, obs_count, out_deg, in_deg)) => {
628                let observations = load_observations_opt(&conn, id);
629                drop(stmt);
630                drop(conn);
631                self.meta_set(&ename, EntityMeta { id, type_id, obs_count, out_deg, in_deg });
632                Ok(Some(Entity {
633                    name: ename,
634                    entity_type: etype,
635                    observations,
636                }))
637            }
638            Err(e) if is_not_found(&e) => Ok(None),
639            Err(e) => Err(sqlite_err(e)),
640        }
641    }
642
643    pub fn create_entities(&self, entities: &[Entity]) -> Result<Vec<Entity>> {
644        let conn = self.writer.lock();
645        let tx = TxGuard::begin(&conn)?;
646
647        let mut ins_ent = conn
648            .prepare_cached(
649                "INSERT INTO entity (id, name_hash, name, type_id, obs_count, out_deg, in_deg, created_us, updated_us, flags)
650                 SELECT ?1, ?2, ?3, ?4, ?5, 0, 0, ?6, ?6, 0
651                 WHERE NOT EXISTS (SELECT 1 FROM entity WHERE name_hash = ?2 AND name = ?3 AND flags = 0)",
652            )
653            .map_err(sqlite_err)?;
654
655        let mut ins_fts = conn
656            .prepare_cached("INSERT INTO name_fts (rowid, name) VALUES (?1, ?2)")
657            .map_err(sqlite_err)?;
658
659        let batch_ts = now_us();
660        let mut type_cache: FxHashMap<String, i64> = FxHashMap::default();
661        let mut type_deltas: FxHashMap<i64, i64> = FxHashMap::default();
662        let mut total_entities: i64 = 0;
663        let mut total_obs: i64 = 0;
664        let mut created = Vec::new();
665        let mut created_metas: Vec<(String, EntityMeta)> = Vec::new();
666        let mut obs_sql = String::new();
667
668        for entity in entities {
669            if entity.name.is_empty() {
670                continue;
671            }
672            let h = name_hash(&entity.name);
673            let id = self.next_entity_id();
674            let type_id = match type_cache.get(entity.entity_type.as_str()) {
675                Some(t) => *t,
676                None => {
677                    let t = get_type_id(&conn, &entity.entity_type, 0)?;
678                    type_cache.insert(entity.entity_type.clone(), t);
679                    t
680                }
681            };
682            let obs_count = entity.observations.len() as i64;
683
684            let changed = ins_ent
685                .execute(params![id, h, entity.name, type_id, obs_count, batch_ts])
686                .map_err(sqlite_err)?;
687            if changed == 0 {
688                continue;
689            }
690
691            let n = entity.observations.len();
692            if n > 0 {
693                obs_sql.clear();
694
695                let mut oids = Vec::with_capacity(n);
696                let mut idxs = Vec::with_capacity(n);
697                for _ in 0..n {
698                    oids.push(self.next_obs_id());
699                }
700                for i in 0..n as i64 {
701                    idxs.push(i);
702                }
703
704                obs_sql.push_str("INSERT INTO observation (id,entity_id,idx,body,created_us) VALUES");
705                for i in 0..n {
706                    if i > 0 { obs_sql.push(','); }
707                    obs_sql.push_str("(?,?,?,?,?)");
708                }
709
710                let mut obs_params: Vec<&dyn ToSql> = Vec::with_capacity(n * 5);
711                for (i, obs) in entity.observations.iter().enumerate() {
712                    obs_params.push(&oids[i]);
713                    obs_params.push(&id);
714                    obs_params.push(&idxs[i]);
715                    obs_params.push(obs);
716                    obs_params.push(&batch_ts);
717                }
718
719                conn.execute(&obs_sql, obs_params.as_slice())
720                    .map_err(sqlite_err)?;
721            }
722
723            ins_fts
724                .execute(params![id, entity.name])
725                .map_err(sqlite_err)?;
726
727            *type_deltas.entry(type_id).or_insert(0) += 1;
728            total_entities += 1;
729            total_obs += obs_count;
730
731            created.push(entity.clone());
732            created_metas.push((entity.name.clone(), EntityMeta {
733                id,
734                type_id,
735                obs_count,
736                out_deg: 0,
737                in_deg: 0,
738            }));
739        }
740
741        if total_entities > 0 {
742            for (type_id, delta) in &type_deltas {
743                inc_type_count(&conn, *type_id, *delta)?;
744            }
745            inc_graph_stat(&conn, "entities", total_entities)?;
746            inc_graph_stat(&conn, "observations", total_obs)?;
747            self.sync_seqs(&conn)?;
748        }
749
750        tx.commit()?;
751
752        // Note: `PRAGMA optimize` is intentionally *not* run here. It analyzes
753        // indexes and writes to internal stat tables — pure overhead on the
754        // write hot path. The periodic `run_maintenance` task covers it.
755
756        if !created_metas.is_empty() {
757            let mut cache = self.cache.lock();
758            for (name, meta) in &created_metas {
759                cache.put(name.clone(), *meta);
760            }
761        }
762
763        Ok(created)
764    }
765
766    pub fn delete_entities(&self, names: &[String]) -> Result<()> {
767        if names.is_empty() {
768            return Ok(());
769        }
770        let conn = self.writer.lock();
771
772        // Phase 1: Resolve all names to (id, type_id).
773        let mut resolved: Vec<(i64, i64, String)> = Vec::with_capacity(names.len());
774        let mut sel = conn
775            .prepare_cached(
776                "SELECT id, type_id FROM entity WHERE name_hash = ?1 AND name = ?2 AND flags = 0",
777            )
778            .map_err(sqlite_err)?;
779        for name in names {
780            let h = name_hash(name);
781            let (id, type_id) = match sel.query_row(params![h, name], |row| {
782                Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?))
783            }) {
784                Ok(v) => v,
785                Err(e) if is_not_found(&e) => continue,
786                Err(e) => return Err(sqlite_err(e)),
787            };
788            resolved.push((id, type_id, name.clone()));
789        }
790
791        if resolved.is_empty() {
792            return Ok(());
793        }
794
795        let ids: Vec<i64> = resolved.iter().map(|(id, _, _)| *id).collect();
796        let n = ids.len();
797
798        // Phase 2: Batch DELETE observations.
799        let obs_p: Vec<String> = (0..n).map(|i| format!("?{}", i + 1)).collect();
800        let obs_sql = format!(
801            "DELETE FROM observation WHERE entity_id IN ({})",
802            obs_p.join(",")
803        );
804        let obs_refs: Vec<&dyn ToSql> = ids.iter().map(|id| id as &dyn ToSql).collect();
805        let obs_deleted = conn
806            .execute(&obs_sql, obs_refs.as_slice())
807            .map_err(sqlite_err)? as i64;
808
809        // Phase 3: Batch DELETE relations.
810        let rel_sql = format!(
811            "DELETE FROM relation WHERE from_id IN ({}) OR to_id IN ({})",
812            obs_p.join(","),
813            obs_p.join(",")
814        );
815        let rel_refs: Vec<&dyn ToSql> = ids.iter().map(|id| id as &dyn ToSql).collect();
816        let rel_deleted = conn
817            .execute(&rel_sql, rel_refs.as_slice())
818            .map_err(sqlite_err)? as i64;
819
820        // Phase 4: Batch FTS deletes.
821        let fts_values: Vec<String> = (0..n)
822            .map(|_| "('delete', ?, '')".to_string())
823            .collect();
824        let fts_sql = format!(
825            "INSERT INTO name_fts(name_fts, rowid, name) VALUES {}",
826            fts_values.join(", ")
827        );
828        conn.execute(&fts_sql, rusqlite::params_from_iter(&ids))
829            .map_err(sqlite_err)?;
830
831        // Aggregate type count deltas.
832        let mut type_deltas: FxHashMap<i64, i64> = FxHashMap::default();
833        for &(_, type_id, _) in &resolved {
834            *type_deltas.entry(type_id).or_insert(0) += 1;
835        }
836
837        // Phase 5: Batch type count decrements.
838        if !type_deltas.is_empty() {
839            let m = type_deltas.len();
840            let type_keys: Vec<i64> = type_deltas.keys().cloned().collect();
841            let type_vals: Vec<i64> = type_deltas.values().map(|v| -*v).collect();
842            let mut case_parts: Vec<String> = Vec::with_capacity(m);
843            let mut id_parts: Vec<String> = Vec::with_capacity(m);
844            for i in 0..m {
845                case_parts.push(format!("WHEN ?{} THEN ?{}", i + 1, m + i + 1));
846                id_parts.push(format!("?{}", i + 1));
847            }
848            let sql = format!(
849                "UPDATE type_dict SET count = MAX(0, count + CASE id {} ELSE 0 END) WHERE id IN ({})",
850                case_parts.join(" "),
851                id_parts.join(","),
852            );
853            let mut params: Vec<Box<dyn ToSql>> = Vec::with_capacity(2 * m);
854            for id in &type_keys {
855                params.push(Box::new(*id));
856            }
857            for delta in &type_vals {
858                params.push(Box::new(*delta));
859            }
860            let param_refs: Vec<&dyn ToSql> = params.iter().map(|p| p.as_ref()).collect();
861            conn.execute(&sql, param_refs.as_slice()).map_err(sqlite_err)?;
862        }
863
864        // Phase 6: Batch DELETE entities.
865        conn.execute(
866            &format!("DELETE FROM entity WHERE id IN ({})", obs_p.join(",")),
867            ids.iter().map(|id| id as &dyn ToSql).collect::<Vec<_>>().as_slice(),
868        )
869        .map_err(sqlite_err)?;
870
871        // Phase 7: Update stats.
872        inc_graph_stat(&conn, "entities", -(n as i64))?;
873        inc_graph_stat(&conn, "observations", -obs_deleted)?;
874        inc_graph_stat(&conn, "relations", -rel_deleted)?;
875
876        // Phase 8: Remove from cache.
877        for (_, _, name) in &resolved {
878            self.meta_remove(name);
879        }
880
881        Ok(())
882    }
883
884    pub fn create_relations(&self, relations: &[Relation]) -> Result<Vec<Relation>> {
885        let conn = self.writer.lock();
886        let tx = TxGuard::begin(&conn)?;
887
888        let mut ins = conn
889            .prepare_cached(
890                "INSERT INTO relation (from_id, to_id, type_id, created_us)
891                 SELECT ?1, ?2, ?3, ?4
892                 WHERE NOT EXISTS (SELECT 1 FROM relation WHERE from_id = ?1 AND to_id = ?2 AND type_id = ?3)",
893            )
894            .map_err(sqlite_err)?;
895
896        let ts = now_us();
897        let mut type_cache: FxHashMap<String, i64> = FxHashMap::default();
898        let mut type_deltas: FxHashMap<i64, i64> = FxHashMap::default();
899        let mut out_deltas: FxHashMap<i64, i64> = FxHashMap::default();
900        let mut in_deltas: FxHashMap<i64, i64> = FxHashMap::default();
901        let mut total_relations: i64 = 0;
902        let mut created = Vec::new();
903
904        for rel in relations {
905            let (from_id, _, _, _) = match self.get_entity_id(&conn, &rel.from)? {
906                Some(v) => v,
907                None => continue,
908            };
909            let (to_id, _, _, _) = match self.get_entity_id(&conn, &rel.to)? {
910                Some(v) => v,
911                None => continue,
912            };
913            let type_id = match type_cache.get(rel.relation_type.as_str()) {
914                Some(t) => *t,
915                None => {
916                    let t = get_type_id(&conn, &rel.relation_type, 1)?;
917                    type_cache.insert(rel.relation_type.clone(), t);
918                    t
919                }
920            };
921
922            let changed = ins
923                .execute(params![from_id, to_id, type_id, ts])
924                .map_err(sqlite_err)?;
925            if changed == 0 {
926                continue;
927            }
928
929            *out_deltas.entry(from_id).or_insert(0) += 1;
930            *in_deltas.entry(to_id).or_insert(0) += 1;
931            *type_deltas.entry(type_id).or_insert(0) += 1;
932            total_relations += 1;
933
934            created.push(rel.clone());
935        }
936
937        if total_relations > 0 {
938            for (id, delta) in &out_deltas {
939                conn.execute(
940                    "UPDATE entity SET out_deg = out_deg + ?1 WHERE id = ?2",
941                    params![delta, id],
942                )
943                .map_err(sqlite_err)?;
944            }
945            for (id, delta) in in_deltas {
946                conn.execute(
947                    "UPDATE entity SET in_deg = in_deg + ?1 WHERE id = ?2",
948                    params![delta, id],
949                )
950                .map_err(sqlite_err)?;
951            }
952            for (type_id, delta) in &type_deltas {
953                inc_type_count(&conn, *type_id, *delta)?;
954            }
955            inc_graph_stat(&conn, "relations", total_relations)?;
956        }
957
958        tx.commit()?;
959
960        // See `create_entities`: `PRAGMA optimize` is deferred to maintenance.
961
962        if !created.is_empty() {
963            let mut cache = self.cache.lock();
964            for rel in &created {
965                if let Some(m) = cache.get_mut(&rel.from) {
966                    m.out_deg += 1;
967                }
968                if let Some(m) = cache.get_mut(&rel.to) {
969                    m.in_deg += 1;
970                }
971            }
972        }
973
974        Ok(created)
975    }
976
977    pub fn delete_relations(&self, relations: &[Relation]) -> Result<()> {
978        if relations.is_empty() {
979            return Ok(());
980        }
981        let conn = self.writer.lock();
982
983        // Resolve names to IDs and collect valid triples.
984        let mut triples: Vec<(i64, i64, i64)> = Vec::with_capacity(relations.len());
985        let mut names: Vec<(String, String)> = Vec::with_capacity(relations.len());
986        for rel in relations {
987            let (from_id, _, _, _) = match self.get_entity_id(&conn, &rel.from)? {
988                Some(v) => v,
989                None => continue,
990            };
991            let (to_id, _, _, _) = match self.get_entity_id(&conn, &rel.to)? {
992                Some(v) => v,
993                None => continue,
994            };
995            let type_id = match get_type_id(&conn, &rel.relation_type, 1) {
996                Ok(id) => id,
997                Err(_) => continue,
998            };
999            triples.push((from_id, to_id, type_id));
1000            names.push((rel.from.clone(), rel.to.clone()));
1001        }
1002
1003        if triples.is_empty() {
1004            return Ok(());
1005        }
1006
1007        // Batch DELETE using VALUES subquery.
1008        let mut sql = String::from(
1009            "DELETE FROM relation WHERE (from_id, to_id, type_id) IN (",
1010        );
1011        for (i, _) in triples.iter().enumerate() {
1012            if i > 0 {
1013                sql.push_str(", ");
1014            }
1015            let base = (i * 3) + 1;
1016            sql.push_str(&format!("SELECT ?{b}, ?{bp1}, ?{bp2}", b = base, bp1 = base + 1, bp2 = base + 2));
1017        }
1018        sql.push(')');
1019
1020        let mut param_values: Vec<Box<dyn ToSql>> = Vec::with_capacity(triples.len() * 3);
1021        for &(f, t, tp) in &triples {
1022            param_values.push(Box::new(f));
1023            param_values.push(Box::new(t));
1024            param_values.push(Box::new(tp));
1025        }
1026        let param_refs: Vec<&dyn ToSql> = param_values.iter().map(|p| p.as_ref()).collect();
1027        let total = conn.execute(&sql, param_refs.as_slice()).map_err(sqlite_err)?;
1028        if total == 0 {
1029            return Ok(());
1030        }
1031
1032        // Aggregate degree and type deltas.
1033        let mut out_deltas: FxHashMap<i64, i64> = FxHashMap::default();
1034        let mut in_deltas: FxHashMap<i64, i64> = FxHashMap::default();
1035        let mut type_deltas: FxHashMap<i64, i64> = FxHashMap::default();
1036        for &(from_id, to_id, type_id) in &triples {
1037            *out_deltas.entry(from_id).or_insert(0) += 1;
1038            *in_deltas.entry(to_id).or_insert(0) += 1;
1039            *type_deltas.entry(type_id).or_insert(0) += 1;
1040        }
1041
1042        // Batch out_deg updates.
1043        let out_keys: Vec<i64> = out_deltas.keys().cloned().collect();
1044        let out_vals: Vec<i64> = out_deltas.values().cloned().collect();
1045        if !out_keys.is_empty() {
1046            let m = out_keys.len();
1047            let mut case_parts: Vec<String> = Vec::with_capacity(m);
1048            let mut id_parts: Vec<String> = Vec::with_capacity(m);
1049            for i in 0..m {
1050                case_parts.push(format!("WHEN ?{} THEN ?{}", i + 1, m + i + 1));
1051                id_parts.push(format!("?{}", i + 1));
1052            }
1053            let sql = format!(
1054                "UPDATE entity SET out_deg = MAX(0, out_deg - CASE id {} ELSE 0 END) WHERE id IN ({})",
1055                case_parts.join(" "),
1056                id_parts.join(","),
1057            );
1058            let mut params: Vec<Box<dyn ToSql>> = Vec::with_capacity(2 * m);
1059            for id in &out_keys {
1060                params.push(Box::new(*id));
1061            }
1062            for delta in &out_vals {
1063                params.push(Box::new(*delta));
1064            }
1065            let param_refs: Vec<&dyn ToSql> = params.iter().map(|p| p.as_ref()).collect();
1066            conn.execute(&sql, param_refs.as_slice()).map_err(sqlite_err)?;
1067        }
1068
1069        // Batch in_deg updates.
1070        let in_keys: Vec<i64> = in_deltas.keys().cloned().collect();
1071        let in_vals: Vec<i64> = in_deltas.values().cloned().collect();
1072        if !in_keys.is_empty() {
1073            let m = in_keys.len();
1074            let mut case_parts: Vec<String> = Vec::with_capacity(m);
1075            let mut id_parts: Vec<String> = Vec::with_capacity(m);
1076            for i in 0..m {
1077                case_parts.push(format!("WHEN ?{} THEN ?{}", i + 1, m + i + 1));
1078                id_parts.push(format!("?{}", i + 1));
1079            }
1080            let sql = format!(
1081                "UPDATE entity SET in_deg = MAX(0, in_deg - CASE id {} ELSE 0 END) WHERE id IN ({})",
1082                case_parts.join(" "),
1083                id_parts.join(","),
1084            );
1085            let mut params: Vec<Box<dyn ToSql>> = Vec::with_capacity(2 * m);
1086            for id in &in_keys {
1087                params.push(Box::new(*id));
1088            }
1089            for delta in &in_vals {
1090                params.push(Box::new(*delta));
1091            }
1092            let param_refs: Vec<&dyn ToSql> = params.iter().map(|p| p.as_ref()).collect();
1093            conn.execute(&sql, param_refs.as_slice()).map_err(sqlite_err)?;
1094        }
1095
1096        // Batch type_dict updates.
1097        let type_keys: Vec<i64> = type_deltas.keys().cloned().collect();
1098        let type_vals: Vec<i64> = type_deltas.values().cloned().collect();
1099        if !type_keys.is_empty() {
1100            let m = type_keys.len();
1101            let mut case_parts: Vec<String> = Vec::with_capacity(m);
1102            let mut id_parts: Vec<String> = Vec::with_capacity(m);
1103            for i in 0..m {
1104                case_parts.push(format!("WHEN ?{} THEN ?{}", i + 1, m + i + 1));
1105                id_parts.push(format!("?{}", i + 1));
1106            }
1107            let sql = format!(
1108                "UPDATE type_dict SET count = MAX(0, count - CASE id {} ELSE 0 END) WHERE id IN ({})",
1109                case_parts.join(" "),
1110                id_parts.join(","),
1111            );
1112            let mut params: Vec<Box<dyn ToSql>> = Vec::with_capacity(2 * m);
1113            for id in &type_keys {
1114                params.push(Box::new(*id));
1115            }
1116            for delta in &type_vals {
1117                params.push(Box::new(*delta));
1118            }
1119            let param_refs: Vec<&dyn ToSql> = params.iter().map(|p| p.as_ref()).collect();
1120            conn.execute(&sql, param_refs.as_slice()).map_err(sqlite_err)?;
1121        }
1122
1123        inc_graph_stat(&conn, "relations", -(total as i64))?;
1124
1125        // Update cache for resolved triples (self-heals on next reload if
1126        // a triple happened to not match).
1127        for (from, to) in &names {
1128            self.meta_update(from, |m| m.out_deg = m.out_deg.saturating_sub(1));
1129            self.meta_update(to, |m| m.in_deg = m.in_deg.saturating_sub(1));
1130        }
1131
1132        Ok(())
1133    }
1134
1135    pub fn add_observations(&self, entity_name: &str, contents: &[String]) -> Result<Vec<String>> {
1136        let conn = self.writer.lock();
1137        let (id, _type_id, _, _) = match self.get_entity_id(&conn, entity_name)? {
1138            Some(v) => v,
1139            None => {
1140                return Err(MCSError::InvalidParams(format!(
1141                    "Entity '{entity_name}' not found"
1142                )))
1143            }
1144        };
1145
1146        let mut max_idx: i64 = conn
1147            .query_row(
1148                "SELECT COALESCE(MAX(idx), -1) FROM observation WHERE entity_id = ?1",
1149                params![id],
1150                |row| row.get(0),
1151            )
1152            .map_err(sqlite_err)?;
1153
1154        let ts = now_us();
1155        let mut ins_obs = conn
1156            .prepare_cached(
1157                "INSERT INTO observation (id, entity_id, idx, body, created_us) VALUES (?1, ?2, ?3, ?4, ?5)",
1158            )
1159            .map_err(sqlite_err)?;
1160
1161        for content in contents {
1162            max_idx += 1;
1163            let oid = self.next_obs_id();
1164            ins_obs
1165                .execute(params![oid, id, max_idx, content, ts])
1166                .map_err(sqlite_err)?;
1167        }
1168        let added = contents.to_vec();
1169
1170        let count: i64 = contents.len() as i64;
1171        conn.execute(
1172            "UPDATE entity SET obs_count = obs_count + ?1, updated_us = ?2 WHERE id = ?3",
1173            params![count, ts, id],
1174        )
1175        .map_err(sqlite_err)?;
1176
1177        inc_graph_stat(&conn, "observations", count)?;
1178        self.sync_seqs(&conn)?;
1179
1180        self.meta_update(entity_name, |m| m.obs_count += count);
1181
1182        Ok(added)
1183    }
1184
1185    pub fn delete_observations(&self, entity_name: &str, observations: &[String]) -> Result<()> {
1186        if observations.is_empty() {
1187            return Ok(());
1188        }
1189        let conn = self.writer.lock();
1190        let (id, _, _, _) = match self.get_entity_id(&conn, entity_name)? {
1191            Some(v) => v,
1192            None => {
1193                return Err(MCSError::InvalidParams(format!(
1194                    "Entity '{entity_name}' not found"
1195                )))
1196            }
1197        };
1198
1199        let placeholders: Vec<String> = (0..observations.len())
1200            .map(|i| format!("?{}", i + 2))
1201            .collect();
1202        let sql = format!(
1203            "DELETE FROM observation WHERE entity_id = ?1 AND body IN ({})",
1204            placeholders.join(",")
1205        );
1206
1207        let mut param_values: Vec<Box<dyn ToSql>> = Vec::with_capacity(1 + observations.len());
1208        param_values.push(Box::new(id));
1209        for obs in observations {
1210            param_values.push(Box::new(obs.as_str()));
1211        }
1212        let param_refs: Vec<&dyn ToSql> = param_values.iter().map(|p| p.as_ref()).collect();
1213        let removed = conn.execute(&sql, param_refs.as_slice()).map_err(sqlite_err)? as i64;
1214
1215        if removed > 0 {
1216            conn.execute(
1217                "UPDATE entity SET obs_count = MAX(0, obs_count - ?1), updated_us = ?2 WHERE id = ?3",
1218                params![removed, now_us(), id],
1219            )
1220            .map_err(sqlite_err)?;
1221            inc_graph_stat(&conn, "observations", -removed)?;
1222
1223            self.meta_update(entity_name, |m| m.obs_count = m.obs_count.saturating_sub(removed));
1224        }
1225
1226        Ok(())
1227    }
1228
1229    pub fn upsert_entities(&self, entities: &[Entity]) -> Result<Vec<Entity>> {
1230        let mut results = Vec::new();
1231        for entity in entities {
1232            if let Some(existing) = self.get_entity(&entity.name)? {
1233                // Update type if different.
1234                if existing.entity_type != entity.entity_type {
1235                    let conn = self.writer.lock();
1236                    let old_type_id = conn
1237                        .query_row(
1238                            "SELECT type_id FROM entity WHERE name_hash = ?1 AND name = ?2 AND flags = 0",
1239                            params![name_hash(&entity.name), entity.name],
1240                            |row| row.get::<_, i64>(0),
1241                        )
1242                        .map_err(sqlite_err)?;
1243                    let new_type_id = get_type_id(&conn, &entity.entity_type, 0)?;
1244                    inc_type_count(&conn, old_type_id, -1)?;
1245                    inc_type_count(&conn, new_type_id, 1)?;
1246                    conn.execute(
1247                        "UPDATE entity SET type_id = ?1, updated_us = ?2 WHERE name_hash = ?3 AND name = ?4",
1248                        params![new_type_id, now_us(), name_hash(&entity.name), entity.name],
1249                    )
1250                    .map_err(sqlite_err)?;
1251                    // Invalidate cache so subsequent get_entity reloads meta.
1252                    self.meta_remove(&entity.name);
1253                }
1254                // Merge observations (append new ones not already present).
1255                let existing_set: HashSet<&str> =
1256                    existing.observations.iter().map(|s| s.as_str()).collect();
1257                let to_add: Vec<String> = entity
1258                    .observations
1259                    .iter()
1260                    .filter(|o| !existing_set.contains(o.as_str()))
1261                    .cloned()
1262                    .collect();
1263                if !to_add.is_empty() {
1264                    self.add_observations(&entity.name, &to_add)?;
1265                }
1266                let updated = self
1267                    .get_entity(&entity.name)?
1268                    .unwrap_or(entity.clone());
1269                results.push(updated);
1270            } else {
1271                let c = self.create_entities(std::slice::from_ref(entity))?;
1272                if let Some(e) = c.into_iter().next() {
1273                    results.push(e);
1274                }
1275            }
1276        }
1277        Ok(results)
1278    }
1279
1280    pub fn merge_entities(&self, source: &str, target: &str) -> Result<Entity> {
1281        let conn = self.writer.lock();
1282        let (src_id, _, _, _) = match self.get_entity_id(&conn, source)? {
1283            Some(v) => v,
1284            None => {
1285                return Err(MCSError::InvalidParams(format!(
1286                    "Source entity '{source}' not found"
1287                )))
1288            }
1289        };
1290        let (tgt_id, _, _, _) = match self.get_entity_id(&conn, target)? {
1291            Some(v) => v,
1292            None => {
1293                return Err(MCSError::InvalidParams(format!(
1294                    "Target entity '{target}' not found"
1295                )))
1296            }
1297        };
1298
1299        if src_id == tgt_id {
1300            return self.get_entity(target)?.ok_or_else(|| {
1301                MCSError::InvalidParams("Target entity not found after merge".into())
1302            });
1303        }
1304
1305        // Move observations from source to target.
1306        let mut obs_count: i64 = 0;
1307        {
1308            let mut max_idx: i64 = conn
1309                .query_row(
1310                    "SELECT COALESCE(MAX(idx), -1) FROM observation WHERE entity_id = ?1",
1311                    params![tgt_id],
1312                    |row| row.get(0),
1313                )
1314                .map_err(sqlite_err)?;
1315            let mut sel_obs = conn
1316                .prepare_cached(
1317                    "SELECT id, body FROM observation WHERE entity_id = ?1 ORDER BY idx",
1318                )
1319                .map_err(sqlite_err)?;
1320            let mut upd_obs = conn
1321                .prepare_cached("UPDATE observation SET entity_id = ?1, idx = ?2 WHERE id = ?3")
1322                .map_err(sqlite_err)?;
1323            let rows: Vec<(i64, String)> = sel_obs
1324                .query_map(params![src_id], |row| {
1325                    Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
1326                })
1327                .map_err(sqlite_err)?
1328                .filter_map(|r| r.ok())
1329                .collect();
1330            for (oid, _body) in &rows {
1331                max_idx += 1;
1332                upd_obs
1333                    .execute(params![tgt_id, max_idx, oid])
1334                    .map_err(sqlite_err)?;
1335                obs_count += 1;
1336            }
1337        }
1338
1339        // Move relations from source to target.
1340        conn.execute(
1341            "UPDATE OR IGNORE relation SET from_id = ?1 WHERE from_id = ?2",
1342            params![tgt_id, src_id],
1343        )
1344        .map_err(sqlite_err)?;
1345        conn.execute(
1346            "UPDATE OR IGNORE relation SET to_id = ?1 WHERE to_id = ?2",
1347            params![tgt_id, src_id],
1348        )
1349        .map_err(sqlite_err)?;
1350        // Delete orphaned relations that were updated by the above (the "OR IGNORE"
1351        // keeps the first, but we still have the original row with the old id? No —
1352        // UPDATE OR IGNORE won't remove. So we must delete any that still reference src_id.)
1353        conn.execute("DELETE FROM relation WHERE from_id = ?1", params![src_id])
1354            .map_err(sqlite_err)?;
1355        conn.execute("DELETE FROM relation WHERE to_id = ?1", params![src_id])
1356            .map_err(sqlite_err)?;
1357
1358        // Update degrees on target.
1359        let out_add: i64 = conn
1360            .query_row(
1361                "SELECT COUNT(*) FROM relation WHERE from_id = ?1",
1362                params![tgt_id],
1363                |row| row.get(0),
1364            )
1365            .map_err(sqlite_err)?;
1366        let in_add: i64 = conn
1367            .query_row(
1368                "SELECT COUNT(*) FROM relation WHERE to_id = ?1",
1369                params![tgt_id],
1370                |row| row.get(0),
1371            )
1372            .map_err(sqlite_err)?;
1373        conn.execute(
1374            "UPDATE entity SET out_deg = ?1, in_deg = ?2, obs_count = obs_count + ?3, updated_us = ?4 WHERE id = ?5",
1375            params![out_add, in_add, obs_count, now_us(), tgt_id],
1376        )
1377        .map_err(sqlite_err)?;
1378
1379        // Delete source entity.
1380        conn.execute(
1381            "INSERT INTO name_fts(name_fts, rowid, name) VALUES ('delete', ?1, '')",
1382            params![src_id],
1383        )
1384        .map_err(sqlite_err)?;
1385        conn.execute("DELETE FROM entity WHERE id = ?1", params![src_id])
1386            .map_err(sqlite_err)?;
1387
1388        inc_graph_stat(&conn, "entities", -1)?;
1389        self.meta_remove(source);
1390
1391        // Reload target into cache.
1392        if let Ok(meta) = conn.query_row(
1393            "SELECT id, type_id, obs_count, out_deg, in_deg FROM entity WHERE id = ?1",
1394            params![tgt_id],
1395            |row| {
1396                Ok(EntityMeta {
1397                    id: row.get(0)?,
1398                    type_id: row.get(1)?,
1399                    obs_count: row.get(2)?,
1400                    out_deg: row.get(3)?,
1401                    in_deg: row.get(4)?,
1402                })
1403            },
1404        ) {
1405            self.meta_set(target, meta);
1406        }
1407
1408        let (name, etype): (String, String) = conn
1409            .query_row(
1410                "SELECT e.name, t.name FROM entity e JOIN type_dict t ON t.id = e.type_id WHERE e.id = ?1",
1411                params![tgt_id],
1412                |row| Ok((row.get(0)?, row.get(1)?)),
1413            )
1414            .map_err(sqlite_err)?;
1415        let observations = load_observations_opt(&conn, tgt_id);
1416
1417        Ok(Entity {
1418            name,
1419            entity_type: etype,
1420            observations,
1421        })
1422    }
1423
1424    pub fn search_nodes_filtered(
1425        &self,
1426        query: &str,
1427        filter_type: Option<&str>,
1428        offset: usize,
1429        limit: usize,
1430    ) -> Vec<Entity> {
1431        if query.is_empty() {
1432            return Vec::new();
1433        }
1434        let conn = self.readers.get();
1435
1436        // Single pass: collect IDs from name_fts then obs_fts, deduping with a set.
1437        let mut entity_ids: Vec<i64> = Vec::new();
1438        let mut seen: HashSet<i64> = HashSet::new();
1439
1440        if let Ok(mut stmt) = conn.prepare(
1441            "SELECT rowid FROM name_fts WHERE name_fts MATCH ?1 ORDER BY rank LIMIT ?2",
1442        ) {
1443            let limit_i64 = (limit + offset) as i64;
1444            if let Ok(rows) = stmt.query_map(params![query, limit_i64], |row| {
1445                row.get::<_, i64>(0)
1446            }) {
1447                for row in rows.flatten() {
1448                    if seen.insert(row) {
1449                        entity_ids.push(row);
1450                    }
1451                }
1452            }
1453        }
1454
1455        if let Ok(mut stmt) = conn.prepare(
1456            "SELECT entity_id FROM obs_fts JOIN observation ON obs_fts.rowid = observation.id
1457             WHERE obs_fts MATCH ?1
1458             GROUP BY entity_id
1459             LIMIT ?2",
1460        ) {
1461            let limit_i64 = (limit + offset) as i64;
1462            if let Ok(rows) = stmt.query_map(params![query, limit_i64], |row| {
1463                row.get::<_, i64>(0)
1464            }) {
1465                for row in rows.flatten() {
1466                    if seen.insert(row) {
1467                        entity_ids.push(row);
1468                    }
1469                }
1470            }
1471        }
1472
1473        // Apply filter_type, offset, limit.
1474        let mut results = Vec::new();
1475        let mut count: usize = 0;
1476        for eid in entity_ids {
1477            if let Ok(entity) = entity_by_id(&conn, eid) {
1478                if let Some(ft) = filter_type
1479                    && !ft.is_empty() && entity.entity_type != ft {
1480                        continue;
1481                    }
1482                if count < offset {
1483                    count += 1;
1484                    continue;
1485                }
1486                if results.len() >= limit {
1487                    break;
1488                }
1489                results.push(entity);
1490                count += 1;
1491            }
1492        }
1493
1494        results
1495    }
1496
1497    pub fn read_graph_filtered(
1498        &self,
1499        filter_type: Option<&str>,
1500        offset: usize,
1501        limit: usize,
1502    ) -> Result<String> {
1503        let conn = self.readers.get();
1504
1505        let limit_sql: i64 = if limit == usize::MAX {
1506            -1
1507        } else {
1508            limit.min(i64::MAX as usize) as i64
1509        };
1510        let offset_sql: i64 = offset as i64;
1511
1512        // Resolve the requested page of entity ids first. Relations are then
1513        // scoped to edges whose *both* endpoints fall inside this page, which
1514        // keeps the response self-consistent (no dangling references to
1515        // entities that were paged out) and bounds the relation payload by the
1516        // page size instead of dumping every relation in the graph.
1517        let filter = filter_type.filter(|ft| !ft.is_empty());
1518        let ids: Vec<i64> = if let Some(ft) = filter {
1519            let mut stmt = conn
1520                .prepare_cached(
1521                    "SELECT e.id FROM entity e
1522                     WHERE e.type_id = (SELECT id FROM type_dict WHERE kind = 0 AND name = ?1)
1523                       AND e.flags = 0
1524                     ORDER BY e.id LIMIT ?2 OFFSET ?3",
1525                )
1526                .map_err(sqlite_err)?;
1527            stmt.query_map(params![ft, limit_sql, offset_sql], |r| r.get::<_, i64>(0))
1528                .map_err(sqlite_err)?
1529                .filter_map(|r| r.ok())
1530                .collect()
1531        } else {
1532            let mut stmt = conn
1533                .prepare_cached(
1534                    "SELECT e.id FROM entity e WHERE e.flags = 0
1535                     ORDER BY e.id LIMIT ?1 OFFSET ?2",
1536                )
1537                .map_err(sqlite_err)?;
1538            stmt.query_map(params![limit_sql, offset_sql], |r| r.get::<_, i64>(0))
1539                .map_err(sqlite_err)?
1540                .filter_map(|r| r.ok())
1541                .collect()
1542        };
1543
1544        if ids.is_empty() {
1545            return Ok(r#"{"entities":[],"relations":[]}"#.to_string());
1546        }
1547
1548        let placeholders = ids.iter().map(|_| "?").collect::<Vec<_>>().join(",");
1549
1550        let entities_json: String = {
1551            let sql = format!(
1552                "SELECT COALESCE(json_group_array(json_object(
1553                    'name', e.name,
1554                    'entityType', t.name,
1555                    'observations', COALESCE((
1556                        SELECT json_group_array(o.body ORDER BY o.idx)
1557                        FROM observation o WHERE o.entity_id = e.id
1558                    ), json('[]'))
1559                ) ORDER BY e.id), json('[]'))
1560                FROM entity e
1561                JOIN type_dict t ON t.id = e.type_id
1562                WHERE e.id IN ({placeholders}) AND e.flags = 0"
1563            );
1564            conn.query_row(&sql, rusqlite::params_from_iter(&ids), |row| {
1565                row.get::<_, String>(0)
1566            })
1567            .map_err(sqlite_err)?
1568        };
1569
1570        let relations_json: String = {
1571            let sql = format!(
1572                "SELECT COALESCE(json_group_array(json_object(
1573                    'from', e1.name,
1574                    'to', e2.name,
1575                    'relationType', t.name
1576                )), json('[]'))
1577                FROM relation r
1578                JOIN entity e1 ON e1.id = r.from_id
1579                JOIN entity e2 ON e2.id = r.to_id
1580                JOIN type_dict t ON t.id = r.type_id
1581                WHERE r.from_id IN ({placeholders}) AND r.to_id IN ({placeholders})
1582                  AND e1.flags = 0 AND e2.flags = 0"
1583            );
1584            let all_params: Vec<&dyn ToSql> = ids
1585                .iter()
1586                .map(|id| id as &dyn ToSql)
1587                .chain(ids.iter().map(|id| id as &dyn ToSql))
1588                .collect();
1589            conn.query_row(&sql, all_params.as_slice(), |row| row.get::<_, String>(0))
1590                .map_err(sqlite_err)?
1591        };
1592
1593        let mut out = String::with_capacity(32 + entities_json.len() + relations_json.len());
1594        out.push_str("{\"entities\":");
1595        out.push_str(&entities_json);
1596        out.push_str(",\"relations\":");
1597        out.push_str(&relations_json);
1598        out.push('}');
1599        Ok(out)
1600    }
1601
1602    pub fn open_nodes(&self, names: &[String]) -> String {
1603        let conn = self.readers.get();
1604        let mut entity_ids: Vec<i64> = Vec::new();
1605
1606        for name in names {
1607            let h = name_hash(name);
1608            if let Ok(Some(id)) = conn
1609                .query_row(
1610                    "SELECT id FROM entity WHERE name_hash = ?1 AND name = ?2 AND flags = 0",
1611                    params![h, name],
1612                    |row| row.get::<_, i64>(0),
1613                )
1614                .map(Some)
1615                .or_else(|e| if is_not_found(&e) { Ok(None) } else { Err(sqlite_err(e)) })
1616            {
1617                entity_ids.push(id);
1618            }
1619        }
1620
1621        if entity_ids.is_empty() {
1622            return r#"{"entities":[],"relations":[]}"#.to_string();
1623        }
1624
1625        let placeholders: Vec<String> = entity_ids.iter().map(|_| "?".to_string()).collect();
1626        let ids_str = placeholders.join(",");
1627
1628        let entities_json: String = {
1629            let sql = format!(
1630                "SELECT COALESCE(json_group_array(json_object(
1631                    'name', e.name,
1632                    'entityType', t.name,
1633                    'observations', COALESCE((
1634                        SELECT json_group_array(o.body ORDER BY o.idx)
1635                        FROM observation o WHERE o.entity_id = e.id
1636                    ), json('[]'))
1637                ) ORDER BY e.id), json('[]'))
1638                FROM entity e
1639                JOIN type_dict t ON t.id = e.type_id
1640                WHERE e.id IN ({ids_str}) AND e.flags = 0"
1641            );
1642            conn.query_row(&sql, rusqlite::params_from_iter(&entity_ids), |row| {
1643                row.get::<_, String>(0)
1644            })
1645            .unwrap_or_else(|_| "[]".to_string())
1646        };
1647
1648        let relations_json: String = {
1649            let sql = format!(
1650                "SELECT COALESCE(json_group_array(json_object(
1651                    'from', e1.name,
1652                    'to', e2.name,
1653                    'relationType', t.name
1654                )), json('[]'))
1655                FROM relation r
1656                JOIN entity e1 ON e1.id = r.from_id
1657                JOIN entity e2 ON e2.id = r.to_id
1658                JOIN type_dict t ON t.id = r.type_id
1659                WHERE (r.from_id IN ({ids_str}) OR r.to_id IN ({ids_str}))
1660                  AND e1.flags = 0 AND e2.flags = 0"
1661            );
1662            let all_params: Vec<&dyn rusqlite::types::ToSql> = entity_ids
1663                .iter()
1664                .map(|id| id as &dyn rusqlite::types::ToSql)
1665                .chain(entity_ids.iter().map(|id| id as &dyn rusqlite::types::ToSql))
1666                .collect();
1667            let mut stmt = conn.prepare(&sql).unwrap();
1668            stmt.query_row(all_params.as_slice(), |row| row.get::<_, String>(0))
1669                .unwrap_or_else(|_| "[]".to_string())
1670        };
1671
1672        let mut out = String::with_capacity(32 + entities_json.len() + relations_json.len());
1673        out.push_str("{\"entities\":");
1674        out.push_str(&entities_json);
1675        out.push_str(",\"relations\":");
1676        out.push_str(&relations_json);
1677        out.push('}');
1678        out
1679    }
1680
1681    pub fn entities_exist(&self, names: &[String]) -> Result<Vec<bool>> {
1682        let conn = self.readers.get();
1683        let mut results = Vec::with_capacity(names.len());
1684        for name in names {
1685            let h = name_hash(name);
1686            let exists: bool = conn
1687                .query_row(
1688                    "SELECT 1 FROM entity WHERE name_hash = ?1 AND name = ?2 AND flags = 0",
1689                    params![h, name],
1690                    |_| Ok(()),
1691                )
1692                .is_ok();
1693            results.push(exists);
1694        }
1695        Ok(results)
1696    }
1697
1698    pub fn degree(&self, name: &str, direction: Direction) -> Result<usize> {
1699        let conn = self.readers.get();
1700        let (_, _, out_d, in_d) = match self.get_entity_id(&conn, name)? {
1701            Some(v) => v,
1702            None => {
1703                return Err(MCSError::InvalidParams(format!(
1704                    "Entity '{name}' not found"
1705                )))
1706            }
1707        };
1708        Ok(match direction {
1709            Direction::Outgoing => out_d as usize,
1710            Direction::Incoming => in_d as usize,
1711            Direction::Both => (out_d + in_d) as usize,
1712        })
1713    }
1714
1715    pub fn get_entity_count(&self) -> Result<usize> {
1716        let conn = self.readers.get();
1717        read_graph_stat(&conn, "entities")
1718            .map(|v| v as usize)
1719            .map_err(|_| MCSError::MemoryError("Failed to read entity count".into()))
1720    }
1721
1722    pub fn get_relation_count(&self) -> Result<usize> {
1723        let conn = self.readers.get();
1724        read_graph_stat(&conn, "relations")
1725            .map(|v| v as usize)
1726            .map_err(|_| MCSError::MemoryError("Failed to read relation count".into()))
1727    }
1728
1729    pub fn search_relations(
1730        &self,
1731        from: Option<&str>,
1732        to: Option<&str>,
1733        rtype: Option<&str>,
1734    ) -> Vec<Relation> {
1735        let conn = self.readers.get();
1736        let mut results = Vec::new();
1737
1738        // A filter that is supplied but resolves to nothing uses the sentinel
1739        // id -1 (which matches no row), so the query returns empty rather than
1740        // silently dropping the filter and matching every relation. The lookups
1741        // are read-only — `get_type_id` would *insert* a phantom type, which is
1742        // both wrong and impossible on a `query_only` reader connection.
1743        let from_id = from
1744            .filter(|f| !f.is_empty())
1745            .map(|f| entity_name_lookup(&conn, f).ok().flatten().unwrap_or(-1));
1746        let to_id = to
1747            .filter(|t| !t.is_empty())
1748            .map(|t| entity_name_lookup(&conn, t).ok().flatten().unwrap_or(-1));
1749        let type_id = rtype
1750            .filter(|rt| !rt.is_empty())
1751            .map(|rt| lookup_type_id(&conn, rt, 1).unwrap_or(-1));
1752
1753        match (from_id, to_id, type_id) {
1754            (Some(fid), Some(tid), Some(tpid)) => {
1755                if let Ok(mut stmt) = conn.prepare_cached(
1756                    "SELECT e1.name, e2.name, t.name
1757                     FROM relation r
1758                     JOIN entity e1 ON e1.id = r.from_id
1759                     JOIN entity e2 ON e2.id = r.to_id
1760                     JOIN type_dict t ON t.id = r.type_id
1761                     WHERE r.from_id = ?1 AND r.to_id = ?2 AND r.type_id = ?3
1762                       AND e1.flags = 0 AND e2.flags = 0
1763                     ORDER BY r.from_id, r.to_id"
1764                )
1765                    && let Ok(rows) = stmt.query_map(params![fid, tid, tpid], |row| {
1766                        Ok(Relation { from: row.get(0)?, to: row.get(1)?, relation_type: row.get(2)? })
1767                    }) {
1768                        for row in rows.flatten() { results.push(row); }
1769                    }
1770            }
1771            (Some(fid), Some(tid), None) => {
1772                if let Ok(mut stmt) = conn.prepare_cached(
1773                    "SELECT e1.name, e2.name, t.name
1774                     FROM relation r
1775                     JOIN entity e1 ON e1.id = r.from_id
1776                     JOIN entity e2 ON e2.id = r.to_id
1777                     JOIN type_dict t ON t.id = r.type_id
1778                     WHERE r.from_id = ?1 AND r.to_id = ?2
1779                       AND e1.flags = 0 AND e2.flags = 0
1780                     ORDER BY r.from_id, r.to_id"
1781                )
1782                    && let Ok(rows) = stmt.query_map(params![fid, tid], |row| {
1783                        Ok(Relation { from: row.get(0)?, to: row.get(1)?, relation_type: row.get(2)? })
1784                    }) {
1785                        for row in rows.flatten() { results.push(row); }
1786                    }
1787            }
1788            (Some(fid), None, Some(tpid)) => {
1789                if let Ok(mut stmt) = conn.prepare_cached(
1790                    "SELECT e1.name, e2.name, t.name
1791                     FROM relation r
1792                     JOIN entity e1 ON e1.id = r.from_id
1793                     JOIN entity e2 ON e2.id = r.to_id
1794                     JOIN type_dict t ON t.id = r.type_id
1795                     WHERE r.from_id = ?1 AND r.type_id = ?2
1796                       AND e1.flags = 0 AND e2.flags = 0
1797                     ORDER BY r.from_id, r.to_id"
1798                )
1799                    && let Ok(rows) = stmt.query_map(params![fid, tpid], |row| {
1800                        Ok(Relation { from: row.get(0)?, to: row.get(1)?, relation_type: row.get(2)? })
1801                    }) {
1802                        for row in rows.flatten() { results.push(row); }
1803                    }
1804            }
1805            (None, Some(tid), Some(tpid)) => {
1806                if let Ok(mut stmt) = conn.prepare_cached(
1807                    "SELECT e1.name, e2.name, t.name
1808                     FROM relation r
1809                     JOIN entity e1 ON e1.id = r.from_id
1810                     JOIN entity e2 ON e2.id = r.to_id
1811                     JOIN type_dict t ON t.id = r.type_id
1812                     WHERE r.to_id = ?1 AND r.type_id = ?2
1813                       AND e1.flags = 0 AND e2.flags = 0
1814                     ORDER BY r.from_id, r.to_id"
1815                )
1816                    && let Ok(rows) = stmt.query_map(params![tid, tpid], |row| {
1817                        Ok(Relation { from: row.get(0)?, to: row.get(1)?, relation_type: row.get(2)? })
1818                    }) {
1819                        for row in rows.flatten() { results.push(row); }
1820                    }
1821            }
1822            (Some(fid), None, None) => {
1823                if let Ok(mut stmt) = conn.prepare_cached(
1824                    "SELECT e1.name, e2.name, t.name
1825                     FROM relation r
1826                     JOIN entity e1 ON e1.id = r.from_id
1827                     JOIN entity e2 ON e2.id = r.to_id
1828                     JOIN type_dict t ON t.id = r.type_id
1829                     WHERE r.from_id = ?1
1830                       AND e1.flags = 0 AND e2.flags = 0
1831                     ORDER BY r.from_id, r.to_id"
1832                )
1833                    && let Ok(rows) = stmt.query_map(params![fid], |row| {
1834                        Ok(Relation { from: row.get(0)?, to: row.get(1)?, relation_type: row.get(2)? })
1835                    }) {
1836                        for row in rows.flatten() { results.push(row); }
1837                    }
1838            }
1839            (None, Some(tid), None) => {
1840                if let Ok(mut stmt) = conn.prepare_cached(
1841                    "SELECT e1.name, e2.name, t.name
1842                     FROM relation r
1843                     JOIN entity e1 ON e1.id = r.from_id
1844                     JOIN entity e2 ON e2.id = r.to_id
1845                     JOIN type_dict t ON t.id = r.type_id
1846                     WHERE r.to_id = ?1
1847                       AND e1.flags = 0 AND e2.flags = 0
1848                     ORDER BY r.from_id, r.to_id"
1849                )
1850                    && let Ok(rows) = stmt.query_map(params![tid], |row| {
1851                        Ok(Relation { from: row.get(0)?, to: row.get(1)?, relation_type: row.get(2)? })
1852                    }) {
1853                        for row in rows.flatten() { results.push(row); }
1854                    }
1855            }
1856            (None, None, Some(tpid)) => {
1857                if let Ok(mut stmt) = conn.prepare_cached(
1858                    "SELECT e1.name, e2.name, t.name
1859                     FROM relation r
1860                     JOIN entity e1 ON e1.id = r.from_id
1861                     JOIN entity e2 ON e2.id = r.to_id
1862                     JOIN type_dict t ON t.id = r.type_id
1863                     WHERE r.type_id = ?1
1864                       AND e1.flags = 0 AND e2.flags = 0
1865                     ORDER BY r.from_id, r.to_id"
1866                )
1867                    && let Ok(rows) = stmt.query_map(params![tpid], |row| {
1868                        Ok(Relation { from: row.get(0)?, to: row.get(1)?, relation_type: row.get(2)? })
1869                    }) {
1870                        for row in rows.flatten() { results.push(row); }
1871                    }
1872            }
1873            (None, None, None) => {
1874                if let Ok(mut stmt) = conn.prepare_cached(
1875                    "SELECT e1.name, e2.name, t.name
1876                     FROM relation r
1877                     JOIN entity e1 ON e1.id = r.from_id
1878                     JOIN entity e2 ON e2.id = r.to_id
1879                     JOIN type_dict t ON t.id = r.type_id
1880                     WHERE e1.flags = 0 AND e2.flags = 0
1881                     ORDER BY r.from_id, r.to_id"
1882                )
1883                    && let Ok(rows) = stmt.query_map([], |row| {
1884                        Ok(Relation { from: row.get(0)?, to: row.get(1)?, relation_type: row.get(2)? })
1885                    }) {
1886                        for row in rows.flatten() { results.push(row); }
1887                    }
1888            }
1889        }
1890        results
1891    }
1892
1893    pub fn find_path(&self, from: &str, to: &str) -> Result<Option<Vec<String>>> {
1894        let conn = self.readers.get();
1895        let (from_id, _, _, _) = match self.get_entity_id(&conn, from)? {
1896            Some(v) => v,
1897            None => {
1898                return Err(MCSError::InvalidParams(format!(
1899                    "Source entity '{from}' not found"
1900                )))
1901            }
1902        };
1903        let (to_id, _, _, _) = match self.get_entity_id(&conn, to)? {
1904            Some(v) => v,
1905            None => {
1906                return Err(MCSError::InvalidParams(format!(
1907                    "Target entity '{to}' not found"
1908                )))
1909            }
1910        };
1911
1912        if from_id == to_id {
1913            return Ok(Some(vec![from.to_string()]));
1914        }
1915
1916        // BFS with adjacency from relation table.
1917        let mut visited = HashSet::new();
1918        let mut parent: FxHashMap<i64, i64> = FxHashMap::default();
1919        let mut queue = VecDeque::new();
1920        visited.insert(from_id);
1921        queue.push_back(from_id);
1922
1923        while let Some(cur) = queue.pop_front() {
1924            if cur == to_id {
1925                break;
1926            }
1927            // Fetch out-neighbors.
1928            if let Ok(mut stmt) =
1929                conn.prepare_cached("SELECT to_id FROM relation WHERE from_id = ?1")
1930                && let Ok(rows) = stmt.query_map(params![cur], |row| row.get::<_, i64>(0)) {
1931                    for row in rows.flatten() {
1932                        if visited.insert(row) {
1933                            parent.insert(row, cur);
1934                            queue.push_back(row);
1935                        }
1936                    }
1937                }
1938            // Also check in-neighbors (undirected traversal).
1939            if let Ok(mut stmt) =
1940                conn.prepare_cached("SELECT from_id FROM relation WHERE to_id = ?1")
1941                && let Ok(rows) = stmt.query_map(params![cur], |row| row.get::<_, i64>(0)) {
1942                    for row in rows.flatten() {
1943                        if visited.insert(row) {
1944                            parent.insert(row, cur);
1945                            queue.push_back(row);
1946                        }
1947                    }
1948                }
1949        }
1950
1951        if !parent.contains_key(&to_id) && to_id != from_id {
1952            return Ok(None);
1953        }
1954
1955        let mut path = Vec::new();
1956        let mut cur = to_id;
1957        path.push(cur);
1958        while let Some(&p) = parent.get(&cur) {
1959            path.push(p);
1960            cur = p;
1961            if cur == from_id {
1962                break;
1963            }
1964        }
1965        path.reverse();
1966
1967        let mut name_path = Vec::with_capacity(path.len());
1968        for id in path {
1969            if let Ok(name) = conn.query_row(
1970                "SELECT name FROM entity WHERE id = ?1",
1971                params![id],
1972                |row| row.get::<_, String>(0),
1973            ) {
1974                name_path.push(name);
1975            }
1976        }
1977
1978        Ok(Some(name_path))
1979    }
1980
1981    pub fn compact(&self) -> Result<()> {
1982        let conn = self.writer.lock();
1983        conn.execute_batch("PRAGMA incremental_vacuum;").map_err(sqlite_err)?;
1984        Ok(())
1985    }
1986
1987    pub fn neighbors(
1988        &self,
1989        name: &str,
1990        direction: Direction,
1991        rtype: Option<&str>,
1992        depth: u32,
1993    ) -> Result<String> {
1994        self._traverse(name, direction, rtype, depth, true)
1995    }
1996
1997    pub fn extract_subgraph(
1998        &self,
1999        names: &[String],
2000        depth: u32,
2001    ) -> Result<String> {
2002        if names.is_empty() {
2003            return Ok(r#"{"entities":[],"relations":[]}"#.to_string());
2004        }
2005
2006        let conn = self.readers.get();
2007        let mut all_entity_ids: HashSet<i64> = HashSet::new();
2008        let mut frontier: HashSet<i64> = HashSet::new();
2009        let mut all_rel_pairs: HashSet<(i64, i64, i64)> = HashSet::new();
2010
2011        // Resolve seed entities.
2012        for name in names {
2013            let h = name_hash(name);
2014            if let Ok(Some(id)) = conn
2015                .query_row(
2016                    "SELECT id FROM entity WHERE name_hash = ?1 AND name = ?2 AND flags = 0",
2017                    params![h, name],
2018                    |row| row.get::<_, i64>(0),
2019                )
2020                .map(Some)
2021                .or_else(|e| if is_not_found(&e) { Ok(None) } else { Err(sqlite_err(e)) })
2022            {
2023                all_entity_ids.insert(id);
2024                frontier.insert(id);
2025            }
2026        }
2027
2028        let mut current_depth = 0u32;
2029        while current_depth < depth && !frontier.is_empty() {
2030            let mut next_frontier: HashSet<i64> = HashSet::new();
2031
2032            // Collect relations for current frontier.
2033            for fid in &frontier {
2034                if let Ok(mut stmt) = conn.prepare_cached(
2035                    "SELECT from_id, to_id, type_id FROM relation WHERE from_id = ?1",
2036                )
2037                    && let Ok(rows) =
2038                        stmt.query_map(params![fid], |row| {
2039                            Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?, row.get::<_, i64>(2)?))
2040                        })
2041                    {
2042                        for row in rows.flatten() {
2043                            let (from_id, to_id, type_id) = row;
2044                            all_rel_pairs.insert((from_id, to_id, type_id));
2045                            if all_entity_ids.insert(to_id) {
2046                                next_frontier.insert(to_id);
2047                            }
2048                        }
2049                    }
2050                if let Ok(mut stmt) = conn.prepare_cached(
2051                    "SELECT from_id, to_id, type_id FROM relation WHERE to_id = ?1",
2052                )
2053                    && let Ok(rows) =
2054                        stmt.query_map(params![fid], |row| {
2055                            Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?, row.get::<_, i64>(2)?))
2056                        })
2057                    {
2058                        for row in rows.flatten() {
2059                            let (from_id, to_id, type_id) = row;
2060                            all_rel_pairs.insert((from_id, to_id, type_id));
2061                            if all_entity_ids.insert(from_id) {
2062                                next_frontier.insert(from_id);
2063                            }
2064                        }
2065                    }
2066            }
2067            frontier = next_frontier;
2068            current_depth += 1;
2069        }
2070
2071        let entities_json: String = {
2072            if all_entity_ids.is_empty() {
2073                "[]".to_string()
2074            } else {
2075                let ids: Vec<i64> = all_entity_ids.iter().copied().collect();
2076                let placeholders: Vec<String> = ids.iter().map(|_| "?".to_string()).collect();
2077                let sql = format!(
2078                    "SELECT COALESCE(json_group_array(json_object(
2079                        'name', e.name,
2080                        'entityType', t.name,
2081                        'observations', COALESCE((
2082                            SELECT json_group_array(o.body ORDER BY o.idx)
2083                            FROM observation o WHERE o.entity_id = e.id
2084                        ), json('[]'))
2085                    ) ORDER BY e.id), json('[]'))
2086                    FROM entity e
2087                    JOIN type_dict t ON t.id = e.type_id
2088                    WHERE e.id IN ({}) AND e.flags = 0",
2089                    placeholders.join(",")
2090                );
2091                conn.query_row(&sql, rusqlite::params_from_iter(&ids), |row| {
2092                    row.get::<_, String>(0)
2093                })
2094                .unwrap_or_else(|_| "[]".to_string())
2095            }
2096        };
2097
2098        let relations_json: String = {
2099            if all_rel_pairs.is_empty() {
2100                "[]".to_string()
2101            } else {
2102                let vals: Vec<String> = all_rel_pairs.iter().map(|_| "(?, ?, ?)".to_string()).collect();
2103                let sql = format!(
2104                    "WITH r(from_id, to_id, type_id) AS (VALUES {})
2105                    SELECT COALESCE(json_group_array(json_object(
2106                        'from', e1.name,
2107                        'to', e2.name,
2108                        'relationType', t.name
2109                    )), json('[]'))
2110                    FROM r
2111                    JOIN entity e1 ON e1.id = r.from_id
2112                    JOIN entity e2 ON e2.id = r.to_id
2113                    JOIN type_dict t ON t.id = r.type_id
2114                    WHERE e1.flags = 0 AND e2.flags = 0",
2115                    vals.join(", ")
2116                );
2117                let params: Vec<&dyn ToSql> = all_rel_pairs.iter()
2118                    .flat_map(|(f, t, tp)| {
2119                        vec![f as &dyn ToSql, t as &dyn ToSql, tp as &dyn ToSql]
2120                    })
2121                    .collect();
2122                let mut stmt = conn.prepare(&sql).map_err(sqlite_err)?;
2123                stmt.query_row(params.as_slice(), |row| row.get::<_, String>(0))
2124                    .unwrap_or_else(|_| "[]".to_string())
2125            }
2126        };
2127
2128        let mut out = String::with_capacity(32 + entities_json.len() + relations_json.len());
2129        out.push_str("{\"entities\":");
2130        out.push_str(&entities_json);
2131        out.push_str(",\"relations\":");
2132        out.push_str(&relations_json);
2133        out.push('}');
2134        Ok(out)
2135    }
2136
2137    pub fn describe_entity(&self, name: &str) -> Result<Entity> {
2138        self.get_entity(name)?
2139            .ok_or_else(|| MCSError::InvalidParams(format!("Entity '{name}' not found")))
2140    }
2141
2142    pub fn entity_type_counts(&self) -> Vec<(String, usize)> {
2143        let conn = self.readers.get();
2144        select_all_types(&conn, 0).unwrap_or_default()
2145    }
2146
2147    pub fn relation_type_counts(&self) -> Vec<(String, usize)> {
2148        let conn = self.readers.get();
2149        select_all_types(&conn, 1).unwrap_or_default()
2150    }
2151
2152    pub fn batch_get_entities(&self, names: &[String]) -> Vec<Option<Entity>> {
2153        names
2154            .iter()
2155            .map(|n| self.get_entity(n).unwrap_or(None))
2156            .collect()
2157    }
2158
2159    pub fn find_all_paths(
2160        &self,
2161        from: &str,
2162        to: &str,
2163        max_depth: usize,
2164        max_paths: usize,
2165    ) -> Result<Vec<Vec<String>>> {
2166        let conn = self.readers.get();
2167        let (from_id, _, _, _) = match self.get_entity_id(&conn, from)? {
2168            Some(v) => v,
2169            None => {
2170                return Err(MCSError::InvalidParams(format!(
2171                    "Source entity '{from}' not found"
2172                )))
2173            }
2174        };
2175        let (to_id, _, _, _) = match self.get_entity_id(&conn, to)? {
2176            Some(v) => v,
2177            None => {
2178                return Err(MCSError::InvalidParams(format!(
2179                    "Target entity '{to}' not found"
2180                )))
2181            }
2182        };
2183
2184        if from_id == to_id {
2185            return Ok(vec![vec![from.to_string()]]);
2186        }
2187
2188        // BFS enumerating all paths up to max_depth.
2189        let mut all_paths: Vec<Vec<i64>> = Vec::new();
2190        let mut queue: VecDeque<(i64, Vec<i64>)> = VecDeque::new();
2191        queue.push_back((from_id, vec![from_id]));
2192
2193        const MAX_QUEUE_SIZE: usize = 10_000_000;
2194
2195        while let Some((cur, path)) = queue.pop_front() {
2196            if all_paths.len() >= max_paths {
2197                break;
2198            }
2199            if path.len() > max_depth {
2200                continue;
2201            }
2202
2203            // Out-neighbors.
2204            if let Ok(mut stmt) =
2205                conn.prepare_cached("SELECT to_id FROM relation WHERE from_id = ?1")
2206                && let Ok(rows) = stmt.query_map(params![cur], |row| row.get::<_, i64>(0)) {
2207                    for next_id in rows.flatten() {
2208                        if next_id == to_id {
2209                            let mut full_path = path.clone();
2210                            full_path.push(next_id);
2211                            all_paths.push(full_path);
2212                            if all_paths.len() >= max_paths {
2213                                break;
2214                            }
2215                        } else if !path.contains(&next_id) && path.len() < max_depth {
2216                            if queue.len() >= MAX_QUEUE_SIZE {
2217                                return Err(MCSError::InvalidParams(
2218                                    "Path exploration queue exceeded limit (too many paths on highly connected graph)".to_string()
2219                                ));
2220                            }
2221                            let mut new_path = path.clone();
2222                            new_path.push(next_id);
2223                            queue.push_back((next_id, new_path));
2224                        }
2225                    }
2226                }
2227
2228            // In-neighbors (undirected).
2229            if let Ok(mut stmt) =
2230                conn.prepare_cached("SELECT from_id FROM relation WHERE to_id = ?1")
2231                && let Ok(rows) = stmt.query_map(params![cur], |row| row.get::<_, i64>(0)) {
2232                    for next_id in rows.flatten() {
2233                        if next_id == to_id {
2234                            let mut full_path = path.clone();
2235                            full_path.push(next_id);
2236                            all_paths.push(full_path);
2237                            if all_paths.len() >= max_paths {
2238                                break;
2239                            }
2240                        } else if !path.contains(&next_id) && path.len() < max_depth {
2241                            if queue.len() >= MAX_QUEUE_SIZE {
2242                                return Err(MCSError::InvalidParams(
2243                                    "Path exploration queue exceeded limit (too many paths on highly connected graph)".to_string()
2244                                ));
2245                            }
2246                            let mut new_path = path.clone();
2247                            new_path.push(next_id);
2248                            queue.push_back((next_id, new_path));
2249                        }
2250                    }
2251                }
2252        }
2253
2254        // Convert ids to names.
2255        let mut named_paths: Vec<Vec<String>> = Vec::new();
2256        for path_ids in all_paths {
2257            let mut named = Vec::with_capacity(path_ids.len());
2258            for id in path_ids {
2259                if let Ok(name) = conn.query_row(
2260                    "SELECT name FROM entity WHERE id = ?1",
2261                    params![id],
2262                    |row| row.get::<_, String>(0),
2263                ) {
2264                    named.push(name);
2265                }
2266            }
2267            named_paths.push(named);
2268        }
2269
2270        Ok(named_paths)
2271    }
2272
2273    /// Export the whole graph as a JSON string. `max_rows` caps both the entity
2274    /// and relation arrays so a pathologically large graph cannot be coerced
2275    /// into an unbounded in-memory string (DoS guard); callers pass a generous
2276    /// constant. A negative value means "no limit".
2277    pub fn export(&self, _format: &str, max_rows: i64) -> Result<String> {
2278        let conn = self.readers.get();
2279        // Only JSON is supported; the format argument is accepted for forward
2280        // compatibility.
2281        conn.query_row(
2282            "SELECT json_object(
2283                'entities', COALESCE((
2284                    SELECT json_group_array(json_object(
2285                        'name', e.name,
2286                        'entityType', t.name,
2287                        'observations', COALESCE((
2288                            SELECT json_group_array(o.body ORDER BY o.idx)
2289                            FROM observation o WHERE o.entity_id = e.id
2290                        ), json('[]'))
2291                    ) ORDER BY e.id)
2292                    FROM (
2293                        SELECT id, name, type_id FROM entity
2294                        WHERE flags = 0 ORDER BY id LIMIT ?1
2295                    ) e
2296                    JOIN type_dict t ON t.id = e.type_id
2297                ), json('[]')),
2298                'relations', COALESCE((
2299                    SELECT json_group_array(json_object(
2300                        'from', e1.name,
2301                        'to', e2.name,
2302                        'relationType', t.name
2303                    ))
2304                    FROM (
2305                        SELECT from_id, to_id, type_id FROM relation LIMIT ?1
2306                    ) r
2307                    JOIN entity e1 ON e1.id = r.from_id
2308                    JOIN entity e2 ON e2.id = r.to_id
2309                    JOIN type_dict t ON t.id = r.type_id
2310                    WHERE e1.flags = 0 AND e2.flags = 0
2311                ), json('[]'))
2312            )",
2313            params![max_rows],
2314            |row| row.get::<_, String>(0),
2315        )
2316        .map_err(sqlite_err)
2317    }
2318
2319    pub fn wipe(&self) -> Result<()> {
2320        let conn = self.writer.lock();
2321        // `name_fts`/`obs_fts` are external-content FTS5 tables; the supported
2322        // way to empty them is the special `'delete-all'` command, not a bare
2323        // `DELETE FROM` (which is invalid for external-content tables and can
2324        // leave the index inconsistent). Run it after clearing the content rows.
2325        conn.execute_batch(
2326            "DELETE FROM observation;
2327             DELETE FROM relation;
2328             DELETE FROM entity;
2329             DELETE FROM type_dict;
2330             INSERT INTO name_fts(name_fts) VALUES('delete-all');
2331             INSERT INTO obs_fts(obs_fts) VALUES('delete-all');
2332             UPDATE graph_stat SET value = 0 WHERE key IN ('entities', 'relations', 'observations');
2333             UPDATE graph_stat SET value = 0 WHERE key IN ('entity_seq', 'obs_seq');",
2334        )
2335        .map_err(sqlite_err)?;
2336        self.seq_entity.store(0, Ordering::Relaxed);
2337        self.seq_obs.store(0, Ordering::Relaxed);
2338        self.cache.lock().clear();
2339        Ok(())
2340    }
2341
2342    /// Periodic database maintenance: WAL checkpoint, query planner analysis,
2343    /// and FTS index optimization. Call from a background timer.
2344    pub fn run_maintenance(&self) -> Result<()> {
2345        let conn = self.writer.lock();
2346
2347        conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")
2348            .map_err(sqlite_err)?;
2349
2350        conn.execute_batch("PRAGMA optimize(0x10000);")
2351            .map_err(sqlite_err)?;
2352
2353        conn.execute_batch(
2354            "INSERT INTO name_fts(name_fts) VALUES('optimize');
2355             INSERT INTO obs_fts(obs_fts) VALUES('optimize');",
2356        )
2357        .map_err(sqlite_err)?;
2358
2359        Ok(())
2360    }
2361
2362    /// Run a non-blocking `wal_checkpoint(PASSIVE)` to fsync committed WAL frames
2363    /// without stalling readers or writers. Call from a short-interval timer to
2364    /// bound the durability window in `async` mode.
2365    pub fn checkpoint_passive(&self) -> Result<()> {
2366        let conn = self.writer.lock();
2367        conn.execute_batch("PRAGMA wal_checkpoint(PASSIVE);")
2368            .map_err(sqlite_err)?;
2369        Ok(())
2370    }
2371
2372    fn _traverse(
2373        &self,
2374        name: &str,
2375        direction: Direction,
2376        rtype: Option<&str>,
2377        depth: u32,
2378        // unused — we always include relations; the caller controls via depth
2379        _include_relations: bool,
2380    ) -> Result<String> {
2381        let conn = self.readers.get();
2382        let (start_id, _, _, _) = match self.get_entity_id(&conn, name)? {
2383            Some(v) => v,
2384            None => {
2385                return Err(MCSError::InvalidParams(format!(
2386                    "Entity '{name}' not found"
2387                )))
2388            }
2389        };
2390
2391        let mut all_ids: HashSet<i64> = HashSet::new();
2392        let mut all_rels: HashSet<(i64, i64, i64)> = HashSet::new();
2393        let mut frontier: HashSet<i64> = HashSet::new();
2394        all_ids.insert(start_id);
2395        frontier.insert(start_id);
2396
2397        // Read-only type resolution. A requested-but-missing type uses the
2398        // sentinel id -1 (matches no edge), so traversal yields just the start
2399        // entity instead of falling back to "no type filter" and walking every
2400        // edge. `get_type_id` is avoided here: it inserts and cannot run on the
2401        // `query_only` reader connection.
2402        let type_filter: Option<i64> = rtype
2403            .filter(|rt| !rt.is_empty())
2404            .map(|rt| lookup_type_id(&conn, rt, 1).unwrap_or(-1));
2405
2406        // Pre-compile all four possible queries outside the loop.
2407        let mut q_out_t = conn.prepare_cached(
2408            "SELECT to_id, type_id FROM relation WHERE from_id = ?1 AND type_id = ?2");
2409        let mut q_out   = conn.prepare_cached(
2410            "SELECT to_id, type_id FROM relation WHERE from_id = ?1");
2411        let mut q_in_t  = conn.prepare_cached(
2412            "SELECT from_id, type_id FROM relation WHERE to_id = ?1 AND type_id = ?2");
2413        let mut q_in    = conn.prepare_cached(
2414            "SELECT from_id, type_id FROM relation WHERE to_id = ?1");
2415
2416        let mut cur_depth = 0u32;
2417        while cur_depth < depth && !frontier.is_empty() {
2418            let mut next_frontier: HashSet<i64> = HashSet::new();
2419
2420            for &fid in &frontier {
2421                if direction == Direction::Outgoing || direction == Direction::Both {
2422                    if let Some(tid) = type_filter {
2423                        if let Ok(ref mut stmt) = q_out_t
2424                            && let Ok(rows) = stmt.query_map(params![fid, tid], |row| {
2425                                Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?))
2426                            }) {
2427                                for row in rows.flatten() {
2428                                    let (to_id, t_id) = row;
2429                                    all_rels.insert((fid, to_id, t_id));
2430                                    if all_ids.insert(to_id) { next_frontier.insert(to_id); }
2431                                }
2432                            }
2433                    } else if let Ok(ref mut stmt) = q_out
2434                        && let Ok(rows) = stmt.query_map(params![fid], |row| {
2435                            Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?))
2436                        }) {
2437                            for row in rows.flatten() {
2438                                let (to_id, t_id) = row;
2439                                all_rels.insert((fid, to_id, t_id));
2440                                if all_ids.insert(to_id) { next_frontier.insert(to_id); }
2441                            }
2442                        }
2443                }
2444
2445                if direction == Direction::Incoming || direction == Direction::Both {
2446                    if let Some(tid) = type_filter {
2447                        if let Ok(ref mut stmt) = q_in_t
2448                            && let Ok(rows) = stmt.query_map(params![fid, tid], |row| {
2449                                Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?))
2450                            }) {
2451                                for row in rows.flatten() {
2452                                    let (from_id, t_id) = row;
2453                                    all_rels.insert((from_id, fid, t_id));
2454                                    if all_ids.insert(from_id) { next_frontier.insert(from_id); }
2455                                }
2456                            }
2457                    } else if let Ok(ref mut stmt) = q_in
2458                        && let Ok(rows) = stmt.query_map(params![fid], |row| {
2459                            Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?))
2460                        }) {
2461                            for row in rows.flatten() {
2462                                let (from_id, t_id) = row;
2463                                all_rels.insert((from_id, fid, t_id));
2464                                if all_ids.insert(from_id) { next_frontier.insert(from_id); }
2465                            }
2466                        }
2467                }
2468            }
2469
2470            frontier = next_frontier;
2471            cur_depth += 1;
2472        }
2473
2474        let entities_json: String = {
2475            if all_ids.is_empty() {
2476                "[]".to_string()
2477            } else {
2478                let ids: Vec<i64> = all_ids.iter().copied().collect();
2479                let placeholders: Vec<String> = ids.iter().map(|_| "?".to_string()).collect();
2480                let sql = format!(
2481                    "SELECT COALESCE(json_group_array(json_object(
2482                        'name', e.name,
2483                        'entityType', t.name,
2484                        'observations', COALESCE((
2485                            SELECT json_group_array(o.body ORDER BY o.idx)
2486                            FROM observation o WHERE o.entity_id = e.id
2487                        ), json('[]'))
2488                    ) ORDER BY e.id), json('[]'))
2489                    FROM entity e
2490                    JOIN type_dict t ON t.id = e.type_id
2491                    WHERE e.id IN ({}) AND e.flags = 0",
2492                    placeholders.join(",")
2493                );
2494                conn.query_row(&sql, rusqlite::params_from_iter(&ids), |row| {
2495                    row.get::<_, String>(0)
2496                })
2497                .unwrap_or_else(|_| "[]".to_string())
2498            }
2499        };
2500
2501        let relations_json: String = {
2502            if all_rels.is_empty() {
2503                "[]".to_string()
2504            } else {
2505                let vals: Vec<String> = all_rels.iter().map(|_| "(?, ?, ?)".to_string()).collect();
2506                let sql = format!(
2507                    "WITH r(from_id, to_id, type_id) AS (VALUES {})
2508                    SELECT COALESCE(json_group_array(json_object(
2509                        'from', e1.name,
2510                        'to', e2.name,
2511                        'relationType', t.name
2512                    )), json('[]'))
2513                    FROM r
2514                    JOIN entity e1 ON e1.id = r.from_id
2515                    JOIN entity e2 ON e2.id = r.to_id
2516                    JOIN type_dict t ON t.id = r.type_id
2517                    WHERE e1.flags = 0 AND e2.flags = 0",
2518                    vals.join(", ")
2519                );
2520                let params: Vec<&dyn ToSql> = all_rels.iter()
2521                    .flat_map(|(f, t, tp)| {
2522                        vec![f as &dyn ToSql, t as &dyn ToSql, tp as &dyn ToSql]
2523                    })
2524                    .collect();
2525                let mut stmt = conn.prepare(&sql).map_err(sqlite_err)?;
2526                stmt.query_row(params.as_slice(), |row| row.get::<_, String>(0))
2527                    .unwrap_or_else(|_| "[]".to_string())
2528            }
2529        };
2530
2531        let mut out = String::with_capacity(32 + entities_json.len() + relations_json.len());
2532        out.push_str("{\"entities\":");
2533        out.push_str(&entities_json);
2534        out.push_str(",\"relations\":");
2535        out.push_str(&relations_json);
2536        out.push('}');
2537        Ok(out)
2538    }
2539}
2540
2541// ── Tests ────────────────────────────────────────────────────────────────
2542
2543#[cfg(test)]
2544mod tests {
2545    use super::*;
2546    use serde_json::Value;
2547    use std::ops::Deref;
2548    use std::path::PathBuf;
2549
2550    struct TestKg(GraphHandle, PathBuf);
2551
2552    impl Deref for TestKg {
2553        type Target = GraphHandle;
2554        fn deref(&self) -> &GraphHandle {
2555            &self.0
2556        }
2557    }
2558
2559    impl Drop for TestKg {
2560        fn drop(&mut self) {
2561            cleanup_db(&self.1);
2562        }
2563    }
2564
2565    fn cleanup_db(path: &std::path::Path) {
2566        let _ = std::fs::remove_file(path);
2567        let _ = std::fs::remove_file(path.with_extension("db-wal"));
2568        let _ = std::fs::remove_file(path.with_extension("db-shm"));
2569    }
2570
2571    fn new_kg() -> TestKg {
2572        use std::sync::atomic::AtomicU64;
2573        use std::sync::atomic::Ordering;
2574        static COUNTER: AtomicU64 = AtomicU64::new(0);
2575        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
2576        let dir = std::env::temp_dir();
2577        let path = dir.join(format!("kg_test_{}_{}.db", std::process::id(), n));
2578        cleanup_db(&path);
2579        let kg = GraphHandle::new(&path, Durability::Async, SqliteTuning::default(), NonZeroUsize::new(10000).unwrap(), 4).expect("create KG");
2580        TestKg(kg, path)
2581    }
2582
2583    #[test]
2584    fn test_create_and_get_entity() {
2585        let kg = new_kg();
2586        let entities = vec![Entity {
2587            name: "test".into(),
2588            entity_type: "person".into(),
2589            observations: vec!["obs1".into(), "obs2".into()],
2590        }];
2591        let created = kg.create_entities(&entities).unwrap();
2592        assert_eq!(created.len(), 1);
2593
2594        let got = kg.get_entity("test").unwrap().unwrap();
2595        assert_eq!(got.name, "test");
2596        assert_eq!(got.entity_type, "person");
2597        assert_eq!(got.observations, vec!["obs1", "obs2"]);
2598    }
2599
2600    #[test]
2601    fn test_get_nonexistent() {
2602        let kg = new_kg();
2603        assert!(kg.get_entity("nonexistent").unwrap().is_none());
2604    }
2605
2606    #[test]
2607    fn test_delete_entity() {
2608        let kg = new_kg();
2609        kg.create_entities(&[Entity {
2610            name: "del".into(),
2611            entity_type: "t".into(),
2612            observations: vec![],
2613        }])
2614        .unwrap();
2615        assert!(kg.get_entity("del").unwrap().is_some());
2616        kg.delete_entities(&["del".to_string()]).unwrap();
2617        assert!(kg.get_entity("del").unwrap().is_none());
2618    }
2619
2620    #[test]
2621    fn test_add_and_delete_observations() {
2622        let kg = new_kg();
2623        kg.create_entities(&[Entity {
2624            name: "obs_test".into(),
2625            entity_type: "t".into(),
2626            observations: vec!["a".into()],
2627        }])
2628        .unwrap();
2629
2630        let added = kg.add_observations("obs_test", &["b".into(), "c".into()]).unwrap();
2631        assert_eq!(added.len(), 2);
2632
2633        let ent = kg.get_entity("obs_test").unwrap().unwrap();
2634        assert!(ent.observations.contains(&"b".into()));
2635        assert!(ent.observations.contains(&"c".into()));
2636
2637        kg.delete_observations("obs_test", &["b".into()]).unwrap();
2638        let ent = kg.get_entity("obs_test").unwrap().unwrap();
2639        assert!(!ent.observations.contains(&"b".into()));
2640        assert!(ent.observations.contains(&"c".into()));
2641        assert!(ent.observations.contains(&"a".into()));
2642    }
2643
2644    #[test]
2645    fn test_create_relations() {
2646        let kg = new_kg();
2647        kg.create_entities(&[
2648            Entity {
2649                name: "A".into(),
2650                entity_type: "node".into(),
2651                observations: vec![],
2652            },
2653            Entity {
2654                name: "B".into(),
2655                entity_type: "node".into(),
2656                observations: vec![],
2657            },
2658        ])
2659        .unwrap();
2660
2661        let rels = kg
2662            .create_relations(&[Relation {
2663                from: "A".into(),
2664                to: "B".into(),
2665                relation_type: "edge".into(),
2666            }])
2667            .unwrap();
2668        assert_eq!(rels.len(), 1);
2669
2670        assert_eq!(kg.get_entity_count().unwrap(), 2);
2671        assert_eq!(kg.get_relation_count().unwrap(), 1);
2672    }
2673
2674    #[test]
2675    fn test_search_nodes() {
2676        let kg = new_kg();
2677        kg.create_entities(&[Entity {
2678            name: "Einstein".into(),
2679            entity_type: "scientist".into(),
2680            observations: vec!["physics".into(), "relativity".into()],
2681        }])
2682        .unwrap();
2683
2684        let results = kg.search_nodes_filtered("physics", None, 0, 10);
2685        assert_eq!(results.len(), 1);
2686        assert_eq!(results[0].name, "Einstein");
2687
2688        let results = kg.search_nodes_filtered("physics", Some("scientist"), 0, 10);
2689        assert_eq!(results.len(), 1);
2690
2691        let results = kg.search_nodes_filtered("physics", Some("nonexistent"), 0, 10);
2692        assert_eq!(results.len(), 0);
2693    }
2694
2695    #[test]
2696    fn test_find_path() {
2697        let kg = new_kg();
2698        kg.create_entities(&[
2699            Entity { name: "A".into(), entity_type: "n".into(), observations: vec![] },
2700            Entity { name: "B".into(), entity_type: "n".into(), observations: vec![] },
2701            Entity { name: "C".into(), entity_type: "n".into(), observations: vec![] },
2702        ]).unwrap();
2703
2704        kg.create_relations(&[
2705            Relation { from: "A".into(), to: "B".into(), relation_type: "e".into() },
2706            Relation { from: "B".into(), to: "C".into(), relation_type: "e".into() },
2707        ]).unwrap();
2708
2709        let path = kg.find_path("A", "C").unwrap().unwrap();
2710        assert_eq!(path, vec!["A", "B", "C"]);
2711    }
2712
2713    #[test]
2714    fn test_degree() {
2715        let kg = new_kg();
2716        kg.create_entities(&[
2717            Entity { name: "A".into(), entity_type: "n".into(), observations: vec![] },
2718            Entity { name: "B".into(), entity_type: "n".into(), observations: vec![] },
2719            Entity { name: "C".into(), entity_type: "n".into(), observations: vec![] },
2720        ]).unwrap();
2721
2722        kg.create_relations(&[
2723            Relation { from: "A".into(), to: "B".into(), relation_type: "e".into() },
2724            Relation { from: "A".into(), to: "C".into(), relation_type: "e".into() },
2725        ]).unwrap();
2726
2727        assert_eq!(kg.degree("A", Direction::Outgoing).unwrap(), 2);
2728        assert_eq!(kg.degree("A", Direction::Incoming).unwrap(), 0);
2729        assert_eq!(kg.degree("B", Direction::Incoming).unwrap(), 1);
2730    }
2731
2732    #[test]
2733    fn test_neighbors() {
2734        let kg = new_kg();
2735        kg.create_entities(&[
2736            Entity { name: "A".into(), entity_type: "n".into(), observations: vec![] },
2737            Entity { name: "B".into(), entity_type: "n".into(), observations: vec![] },
2738        ]).unwrap();
2739
2740        kg.create_relations(&[Relation {
2741            from: "A".into(), to: "B".into(), relation_type: "e".into(),
2742        }]).unwrap();
2743
2744        let result = kg.neighbors("A", Direction::Outgoing, None, 1).unwrap();
2745        let v: Value = serde_json::from_str(&result).unwrap();
2746        assert_eq!(v["entities"].as_array().unwrap().len(), 2);
2747        assert_eq!(v["relations"].as_array().unwrap().len(), 1);
2748    }
2749
2750    #[test]
2751    fn test_open_nodes() {
2752        let kg = new_kg();
2753        kg.create_entities(&[
2754            Entity { name: "X".into(), entity_type: "n".into(), observations: vec!["obs_x".into()] },
2755            Entity { name: "Y".into(), entity_type: "n".into(), observations: vec!["obs_y".into()] },
2756        ]).unwrap();
2757
2758        kg.create_relations(&[Relation {
2759            from: "X".into(), to: "Y".into(), relation_type: "e".into(),
2760        }]).unwrap();
2761
2762        let result = kg.open_nodes(&["X".into()]);
2763        let v: Value = serde_json::from_str(&result).unwrap();
2764        assert_eq!(v["entities"].as_array().unwrap().len(), 1);
2765        assert_eq!(v["relations"].as_array().unwrap().len(), 1);
2766    }
2767
2768    #[test]
2769    fn test_entities_exist() {
2770        let kg = new_kg();
2771        kg.create_entities(&[Entity {
2772            name: "exists".into(), entity_type: "t".into(), observations: vec![],
2773        }]).unwrap();
2774
2775        let res = kg.entities_exist(&["exists".into(), "missing".into()]).unwrap();
2776        assert_eq!(res, vec![true, false]);
2777    }
2778
2779    #[test]
2780    fn test_describe_entity() {
2781        let kg = new_kg();
2782        kg.create_entities(&[Entity {
2783            name: "desc".into(), entity_type: "t".into(), observations: vec!["o".into()],
2784        }]).unwrap();
2785
2786        let entity = kg.describe_entity("desc").unwrap();
2787        assert_eq!(entity.name, "desc");
2788    }
2789
2790    #[test]
2791    fn test_entity_type_counts() {
2792        let kg = new_kg();
2793        kg.create_entities(&[
2794            Entity { name: "a".into(), entity_type: "person".into(), observations: vec![] },
2795            Entity { name: "b".into(), entity_type: "person".into(), observations: vec![] },
2796            Entity { name: "c".into(), entity_type: "place".into(), observations: vec![] },
2797        ]).unwrap();
2798
2799        let counts = kg.entity_type_counts();
2800        let map: FxHashMap<_, _> = counts.into_iter().collect();
2801        assert_eq!(map.get("person"), Some(&2));
2802        assert_eq!(map.get("place"), Some(&1));
2803    }
2804
2805    #[test]
2806    fn test_relation_type_counts() {
2807        let kg = new_kg();
2808        kg.create_entities(&[
2809            Entity { name: "a".into(), entity_type: "n".into(), observations: vec![] },
2810            Entity { name: "b".into(), entity_type: "n".into(), observations: vec![] },
2811            Entity { name: "c".into(), entity_type: "n".into(), observations: vec![] },
2812        ]).unwrap();
2813
2814        kg.create_relations(&[
2815            Relation { from: "a".into(), to: "b".into(), relation_type: "knows".into() },
2816            Relation { from: "a".into(), to: "c".into(), relation_type: "knows".into() },
2817        ]).unwrap();
2818
2819        let counts = kg.relation_type_counts();
2820        let map: FxHashMap<_, _> = counts.into_iter().collect();
2821        assert_eq!(map.get("knows"), Some(&2));
2822    }
2823
2824    #[test]
2825    fn test_upsert_entities() {
2826        let kg = new_kg();
2827        kg.create_entities(&[Entity {
2828            name: "u".into(), entity_type: "old".into(), observations: vec!["existing".into()],
2829        }]).unwrap();
2830
2831        // Upsert with new type and additional observation.
2832        kg.upsert_entities(&[Entity {
2833            name: "u".into(), entity_type: "new".into(), observations: vec!["existing".into(), "added".into()],
2834        }]).unwrap();
2835
2836        let ent = kg.get_entity("u").unwrap().unwrap();
2837        assert_eq!(ent.entity_type, "new");
2838        assert!(ent.observations.contains(&"added".into()));
2839        assert!(ent.observations.contains(&"existing".into()));
2840    }
2841
2842    #[test]
2843    fn test_merge_entities() {
2844        let kg = new_kg();
2845        kg.create_entities(&[
2846            Entity { name: "source".into(), entity_type: "t".into(), observations: vec!["src_obs".into()] },
2847            Entity { name: "target".into(), entity_type: "t".into(), observations: vec!["tgt_obs".into()] },
2848        ]).unwrap();
2849
2850        kg.create_relations(&[Relation {
2851            from: "source".into(), to: "target".into(), relation_type: "e".into(),
2852        }]).unwrap();
2853
2854        let merged = kg.merge_entities("source", "target").unwrap();
2855        assert_eq!(merged.name, "target");
2856        assert_eq!(kg.get_entity("source").unwrap().is_none(), true);
2857    }
2858
2859    #[test]
2860    fn test_find_all_paths() {
2861        let kg = new_kg();
2862        kg.create_entities(&[
2863            Entity { name: "A".into(), entity_type: "n".into(), observations: vec![] },
2864            Entity { name: "B".into(), entity_type: "n".into(), observations: vec![] },
2865            Entity { name: "C".into(), entity_type: "n".into(), observations: vec![] },
2866        ]).unwrap();
2867
2868        kg.create_relations(&[
2869            Relation { from: "A".into(), to: "B".into(), relation_type: "e".into() },
2870            Relation { from: "B".into(), to: "C".into(), relation_type: "e".into() },
2871            Relation { from: "A".into(), to: "C".into(), relation_type: "e".into() },
2872        ]).unwrap();
2873
2874        let paths = kg.find_all_paths("A", "C", 5, 10).unwrap();
2875        assert!(paths.len() >= 2);
2876    }
2877
2878    #[test]
2879    fn test_batch_get_entities() {
2880        let kg = new_kg();
2881        kg.create_entities(&[
2882            Entity { name: "a".into(), entity_type: "t".into(), observations: vec![] },
2883            Entity { name: "b".into(), entity_type: "t".into(), observations: vec![] },
2884        ]).unwrap();
2885
2886        let results = kg.batch_get_entities(&["a".into(), "missing".into(), "b".into()]);
2887        assert_eq!(results.len(), 3);
2888        assert!(results[0].is_some());
2889        assert!(results[1].is_none());
2890        assert!(results[2].is_some());
2891    }
2892
2893    #[test]
2894    fn test_export_graph() {
2895        let kg = new_kg();
2896        kg.create_entities(&[Entity {
2897            name: "exp".into(), entity_type: "t".into(), observations: vec!["o".into()],
2898        }]).unwrap();
2899
2900        let exported = kg.export("json", i64::MAX).unwrap();
2901        assert!(exported.contains("exp"));
2902        assert!(exported.contains("o"));
2903    }
2904
2905    #[test]
2906    fn test_graph_stats() {
2907        let kg = new_kg();
2908        assert_eq!(kg.get_entity_count().unwrap(), 0);
2909        assert_eq!(kg.get_relation_count().unwrap(), 0);
2910
2911        kg.create_entities(&[Entity {
2912            name: "s".into(), entity_type: "t".into(), observations: vec![],
2913        }]).unwrap();
2914
2915        assert_eq!(kg.get_entity_count().unwrap(), 1);
2916    }
2917
2918    #[test]
2919    fn test_read_graph_filtered() {
2920        let kg = new_kg();
2921        kg.create_entities(&[
2922            Entity { name: "p1".into(), entity_type: "person".into(), observations: vec![] },
2923            Entity { name: "p2".into(), entity_type: "place".into(), observations: vec![] },
2924        ]).unwrap();
2925
2926        let out = kg.read_graph_filtered(Some("person"), 0, 10).unwrap();
2927        let v: Value = serde_json::from_str(&out).unwrap();
2928        assert_eq!(v["entities"].as_array().unwrap().len(), 1);
2929        assert_eq!(v["entities"][0]["name"], "p1");
2930    }
2931
2932    #[test]
2933    fn test_wipe() {
2934        let kg = new_kg();
2935        kg.create_entities(&[Entity {
2936            name: "w".into(), entity_type: "t".into(), observations: vec!["o".into()],
2937        }]).unwrap();
2938        assert_eq!(kg.get_entity_count().unwrap(), 1);
2939
2940        kg.wipe().unwrap();
2941        assert_eq!(kg.get_entity_count().unwrap(), 0);
2942    }
2943
2944    #[test]
2945    fn test_push_json_str() {
2946        let mut buf = String::new();
2947        push_json_str(&mut buf, "hello");
2948        assert_eq!(buf, "\"hello\"");
2949        let mut buf = String::new();
2950        push_json_str(&mut buf, "he\"llo");
2951        assert_eq!(buf, "\"he\\\"llo\"");
2952    }
2953
2954    // ── create_entities edge cases ────────────────────────────────────
2955
2956    #[test]
2957    fn test_create_entities_empty_input() {
2958        let kg = new_kg();
2959        let created = kg.create_entities(&[]).unwrap();
2960        assert!(created.is_empty());
2961    }
2962
2963    #[test]
2964    fn test_create_entities_skip_empty_name() {
2965        let kg = new_kg();
2966        let created = kg.create_entities(&[Entity {
2967            name: "".into(),
2968            entity_type: "t".into(),
2969            observations: vec![],
2970        }])
2971        .unwrap();
2972        assert!(created.is_empty());
2973        assert_eq!(kg.get_entity_count().unwrap(), 0);
2974    }
2975
2976    #[test]
2977    fn test_create_entities_duplicate_names() {
2978        let kg = new_kg();
2979        let e = Entity {
2980            name: "dup".into(),
2981            entity_type: "t".into(),
2982            observations: vec!["obs".into()],
2983        };
2984        let first = kg.create_entities(&[e.clone()]).unwrap();
2985        assert_eq!(first.len(), 1);
2986        let second = kg.create_entities(&[e.clone()]).unwrap();
2987        assert!(second.is_empty());
2988        assert_eq!(kg.get_entity_count().unwrap(), 1);
2989    }
2990
2991    #[test]
2992    fn test_create_entities_partial_duplicates() {
2993        let kg = new_kg();
2994        let created = kg.create_entities(&[
2995            Entity { name: "a".into(), entity_type: "t".into(), observations: vec![] },
2996            Entity { name: "b".into(), entity_type: "t".into(), observations: vec![] },
2997        ]).unwrap();
2998        assert_eq!(created.len(), 2);
2999
3000        let second = kg.create_entities(&[
3001            Entity { name: "b".into(), entity_type: "t".into(), observations: vec![] },
3002            Entity { name: "c".into(), entity_type: "t".into(), observations: vec![] },
3003        ]).unwrap();
3004        assert_eq!(second.len(), 1); // only c created
3005        assert_eq!(second[0].name, "c");
3006        assert_eq!(kg.get_entity_count().unwrap(), 3);
3007    }
3008
3009    #[test]
3010    fn test_create_entities_mixed_empty_and_valid() {
3011        let kg = new_kg();
3012        let created = kg.create_entities(&[
3013            Entity { name: "".into(), entity_type: "t".into(), observations: vec![] },
3014            Entity { name: "valid".into(), entity_type: "t".into(), observations: vec![] },
3015            Entity { name: "".into(), entity_type: "t".into(), observations: vec![] },
3016        ]).unwrap();
3017        assert_eq!(created.len(), 1);
3018        assert_eq!(created[0].name, "valid");
3019        assert_eq!(kg.get_entity_count().unwrap(), 1);
3020    }
3021
3022    #[test]
3023    fn test_create_entities_same_name_in_batch() {
3024        let kg = new_kg();
3025        let created = kg.create_entities(&[
3026            Entity { name: "dup_in_batch".into(), entity_type: "t".into(), observations: vec![] },
3027            Entity { name: "dup_in_batch".into(), entity_type: "t".into(), observations: vec![] },
3028        ]).unwrap();
3029        assert_eq!(created.len(), 1);
3030        assert_eq!(kg.get_entity_count().unwrap(), 1);
3031    }
3032
3033    // ── create_relations edge cases ───────────────────────────────────
3034
3035    #[test]
3036    fn test_create_relations_empty_input() {
3037        let kg = new_kg();
3038        let rels = kg.create_relations(&[]).unwrap();
3039        assert!(rels.is_empty());
3040    }
3041
3042    #[test]
3043    fn test_create_relations_nonexistent_from() {
3044        let kg = new_kg();
3045        kg.create_entities(&[Entity {
3046            name: "B".into(), entity_type: "t".into(), observations: vec![],
3047        }]).unwrap();
3048
3049        let rels = kg.create_relations(&[Relation {
3050            from: "A".into(), to: "B".into(), relation_type: "e".into(),
3051        }]).unwrap();
3052        assert!(rels.is_empty());
3053        assert_eq!(kg.get_relation_count().unwrap(), 0);
3054    }
3055
3056    #[test]
3057    fn test_create_relations_nonexistent_to() {
3058        let kg = new_kg();
3059        kg.create_entities(&[Entity {
3060            name: "A".into(), entity_type: "t".into(), observations: vec![],
3061        }]).unwrap();
3062
3063        let rels = kg.create_relations(&[Relation {
3064            from: "A".into(), to: "B".into(), relation_type: "e".into(),
3065        }]).unwrap();
3066        assert!(rels.is_empty());
3067        assert_eq!(kg.get_relation_count().unwrap(), 0);
3068    }
3069
3070    #[test]
3071    fn test_create_relations_both_nonexistent() {
3072        let kg = new_kg();
3073        let rels = kg.create_relations(&[Relation {
3074            from: "A".into(), to: "B".into(), relation_type: "e".into(),
3075        }]).unwrap();
3076        assert!(rels.is_empty());
3077    }
3078
3079    #[test]
3080    fn test_create_relations_self_loop() {
3081        let kg = new_kg();
3082        kg.create_entities(&[Entity {
3083            name: "self".into(), entity_type: "t".into(), observations: vec![],
3084        }]).unwrap();
3085
3086        let rels = kg.create_relations(&[Relation {
3087            from: "self".into(), to: "self".into(), relation_type: "loop".into(),
3088        }]).unwrap();
3089        assert_eq!(rels.len(), 1);
3090        assert_eq!(kg.get_relation_count().unwrap(), 1);
3091        assert_eq!(kg.degree("self", Direction::Outgoing).unwrap(), 1);
3092        assert_eq!(kg.degree("self", Direction::Incoming).unwrap(), 1);
3093    }
3094
3095    #[test]
3096    fn test_create_relations_duplicate() {
3097        let kg = new_kg();
3098        kg.create_entities(&[
3099            Entity { name: "A".into(), entity_type: "t".into(), observations: vec![] },
3100            Entity { name: "B".into(), entity_type: "t".into(), observations: vec![] },
3101        ]).unwrap();
3102
3103        let r = Relation {
3104            from: "A".into(), to: "B".into(), relation_type: "e".into(),
3105        };
3106        let first = kg.create_relations(&[r.clone()]).unwrap();
3107        assert_eq!(first.len(), 1);
3108
3109        let second = kg.create_relations(&[r.clone()]).unwrap();
3110        assert!(second.is_empty());
3111        assert_eq!(kg.get_relation_count().unwrap(), 1);
3112    }
3113
3114    #[test]
3115    fn test_create_relations_new_type_auto_created() {
3116        let kg = new_kg();
3117        kg.create_entities(&[
3118            Entity { name: "A".into(), entity_type: "t".into(), observations: vec![] },
3119            Entity { name: "B".into(), entity_type: "t".into(), observations: vec![] },
3120        ]).unwrap();
3121
3122        let rels = kg.create_relations(&[Relation {
3123            from: "A".into(), to: "B".into(), relation_type: "brand_new_type".into(),
3124        }]).unwrap();
3125        assert_eq!(rels.len(), 1);
3126
3127        let counts = kg.relation_type_counts();
3128        let map: FxHashMap<_, _> = counts.into_iter().collect();
3129        assert_eq!(map.get("brand_new_type"), Some(&1));
3130    }
3131
3132    #[test]
3133    fn test_create_relations_degree_updates() {
3134        let kg = new_kg();
3135        kg.create_entities(&[
3136            Entity { name: "A".into(), entity_type: "t".into(), observations: vec![] },
3137            Entity { name: "B".into(), entity_type: "t".into(), observations: vec![] },
3138            Entity { name: "C".into(), entity_type: "t".into(), observations: vec![] },
3139        ]).unwrap();
3140
3141        kg.create_relations(&[
3142            Relation { from: "A".into(), to: "B".into(), relation_type: "e".into() },
3143            Relation { from: "A".into(), to: "C".into(), relation_type: "e".into() },
3144        ]).unwrap();
3145
3146        assert_eq!(kg.degree("A", Direction::Outgoing).unwrap(), 2);
3147        assert_eq!(kg.degree("A", Direction::Incoming).unwrap(), 0);
3148        assert_eq!(kg.degree("B", Direction::Incoming).unwrap(), 1);
3149        assert_eq!(kg.degree("C", Direction::Incoming).unwrap(), 1);
3150        assert_eq!(kg.degree("A", Direction::Both).unwrap(), 2);
3151    }
3152
3153    #[test]
3154    fn test_create_relations_delete_and_recreate() {
3155        let kg = new_kg();
3156        kg.create_entities(&[
3157            Entity { name: "A".into(), entity_type: "t".into(), observations: vec![] },
3158            Entity { name: "B".into(), entity_type: "t".into(), observations: vec![] },
3159        ]).unwrap();
3160
3161        let r = Relation {
3162            from: "A".into(), to: "B".into(), relation_type: "e".into(),
3163        };
3164        kg.create_relations(&[r.clone()]).unwrap();
3165        assert_eq!(kg.get_relation_count().unwrap(), 1);
3166
3167        kg.delete_relations(&[r.clone()]).unwrap();
3168        assert_eq!(kg.get_relation_count().unwrap(), 0);
3169
3170        // Recreate after delete
3171        let re = kg.create_relations(&[r.clone()]).unwrap();
3172        assert_eq!(re.len(), 1);
3173        assert_eq!(kg.get_relation_count().unwrap(), 1);
3174    }
3175
3176    // ── Integration edge cases ────────────────────────────────────────
3177
3178    #[test]
3179    fn test_create_entities_then_relations_then_delete_entity_with_relations() {
3180        let kg = new_kg();
3181        kg.create_entities(&[
3182            Entity { name: "A".into(), entity_type: "t".into(), observations: vec![] },
3183            Entity { name: "B".into(), entity_type: "t".into(), observations: vec![] },
3184        ]).unwrap();
3185        kg.create_relations(&[
3186            Relation { from: "A".into(), to: "B".into(), relation_type: "e".into() },
3187        ]).unwrap();
3188
3189        assert_eq!(kg.get_relation_count().unwrap(), 1);
3190
3191        // Deleting entity A should also delete the relation
3192        kg.delete_entities(&["A".into()]).unwrap();
3193        assert_eq!(kg.get_entity("A").unwrap().is_none(), true);
3194        assert_eq!(kg.get_relation_count().unwrap(), 0);
3195    }
3196
3197    #[test]
3198    fn test_graph_stats_after_entity_with_observations() {
3199        let kg = new_kg();
3200        kg.create_entities(&[Entity {
3201            name: "stat".into(), entity_type: "t".into(),
3202            observations: vec!["o1".into(), "o2".into(), "o3".into()],
3203        }]).unwrap();
3204
3205        let ecount = kg.get_entity_count().unwrap();
3206        // graph_stat for observations is tracked but there's no public getter for it
3207        assert_eq!(ecount, 1);
3208
3209        // delete reverts stats
3210        kg.delete_entities(&["stat".into()]).unwrap();
3211        assert_eq!(kg.get_entity_count().unwrap(), 0);
3212    }
3213
3214    // ── Helpers for the fix-specific suites ────────────────────────────────
3215
3216    fn new_kg_with_pool(read_pool_size: usize) -> TestKg {
3217        use std::sync::atomic::AtomicU64;
3218        static COUNTER: AtomicU64 = AtomicU64::new(1_000_000);
3219        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
3220        let path = std::env::temp_dir().join(format!("kg_pool_{}_{}.db", std::process::id(), n));
3221        cleanup_db(&path);
3222        let kg = GraphHandle::new(
3223            &path,
3224            Durability::Async,
3225            SqliteTuning::default(),
3226            NonZeroUsize::new(10_000).unwrap(),
3227            read_pool_size,
3228        )
3229        .expect("create KG");
3230        TestKg(kg, path)
3231    }
3232
3233    fn seed_line(kg: &GraphHandle, n: usize) {
3234        let entities: Vec<Entity> = (0..n)
3235            .map(|i| Entity {
3236                name: format!("n{i}"),
3237                entity_type: "node".into(),
3238                observations: vec![format!("obs of n{i}")],
3239            })
3240            .collect();
3241        kg.create_entities(&entities).unwrap();
3242        let rels: Vec<Relation> = (0..n.saturating_sub(1))
3243            .map(|i| Relation {
3244                from: format!("n{i}"),
3245                to: format!("n{}", i + 1),
3246                relation_type: "edge".into(),
3247            })
3248            .collect();
3249        if !rels.is_empty() {
3250            kg.create_relations(&rels).unwrap();
3251        }
3252    }
3253
3254    fn count_relations(graph_json: &str) -> usize {
3255        let v: Value = serde_json::from_str(graph_json).unwrap();
3256        v["relations"].as_array().unwrap().len()
3257    }
3258
3259    fn count_entities(graph_json: &str) -> usize {
3260        let v: Value = serde_json::from_str(graph_json).unwrap();
3261        v["entities"].as_array().unwrap().len()
3262    }
3263
3264    // ── Fix #1: reader pool / concurrency ──────────────────────────────────
3265
3266    #[test]
3267    fn test_pool_size_one_still_works() {
3268        let kg = new_kg_with_pool(1);
3269        seed_line(&kg, 5);
3270        assert_eq!(kg.get_entity_count().unwrap(), 5);
3271        assert!(kg.get_entity("n2").unwrap().is_some());
3272        let g = kg.read_graph_filtered(None, 0, usize::MAX).unwrap();
3273        assert_eq!(count_entities(&g), 5);
3274    }
3275
3276    #[test]
3277    fn test_reads_see_committed_writes() {
3278        // A read on a pool connection must observe a just-committed write made on
3279        // the writer connection (WAL visibility).
3280        let kg = new_kg_with_pool(4);
3281        kg.create_entities(&[Entity {
3282            name: "fresh".into(),
3283            entity_type: "t".into(),
3284            observations: vec!["v".into()],
3285        }])
3286        .unwrap();
3287        // get_entity goes through the reader pool.
3288        let got = kg.get_entity("fresh").unwrap().unwrap();
3289        assert_eq!(got.observations, vec!["v"]);
3290    }
3291
3292    #[test]
3293    fn test_concurrent_readers_consistent() {
3294        // Many readers hammering the pool while the writer mutates must never
3295        // panic, deadlock, or observe a torn graph. The final counts must match.
3296        let kg = new_kg_with_pool(4);
3297        seed_line(&kg, 50);
3298
3299        std::thread::scope(|s| {
3300            // 8 reader threads.
3301            for _ in 0..8 {
3302                s.spawn(|| {
3303                    for _ in 0..200 {
3304                        let _ = kg.get_entity("n10");
3305                        let _ = kg.search_nodes_filtered("obs", None, 0, 10);
3306                        let _ = kg.read_graph_filtered(None, 0, 100);
3307                        let _ = kg.get_entity_count();
3308                        let _ = kg.neighbors("n10", Direction::Both, None, 2);
3309                    }
3310                });
3311            }
3312            // 1 writer thread adding more entities concurrently.
3313            s.spawn(|| {
3314                for i in 100..160 {
3315                    kg.create_entities(&[Entity {
3316                        name: format!("w{i}"),
3317                        entity_type: "node".into(),
3318                        observations: vec![format!("w obs {i}")],
3319                    }])
3320                    .unwrap();
3321                }
3322            });
3323        });
3324
3325        // 50 seeded + 60 written.
3326        assert_eq!(kg.get_entity_count().unwrap(), 110);
3327        assert!(kg.get_entity("w159").unwrap().is_some());
3328    }
3329
3330    #[test]
3331    fn test_reader_pool_rejects_writes_internally() {
3332        // Sanity: query_only readers cannot mutate. We can't call a write through
3333        // the pool directly, but we can confirm a read method that *would* have
3334        // inserted (search_relations resolving a missing type) does not create a
3335        // phantom type — see the dedicated test below — and that reads under a
3336        // size-1 pool serialize correctly without deadlock.
3337        let kg = new_kg_with_pool(1);
3338        seed_line(&kg, 3);
3339        std::thread::scope(|s| {
3340            for _ in 0..4 {
3341                s.spawn(|| {
3342                    for _ in 0..100 {
3343                        let _ = kg.read_graph_filtered(None, 0, 10);
3344                    }
3345                });
3346            }
3347        });
3348        assert_eq!(kg.get_entity_count().unwrap(), 3);
3349    }
3350
3351    // ── Fix #6: read_graph relation scoping + export bound ─────────────────
3352
3353    #[test]
3354    fn test_read_graph_relations_scoped_to_page() {
3355        let kg = new_kg_with_pool(2);
3356        // n0 -> n1 -> n2 -> n3 (4 entities, 3 edges).
3357        seed_line(&kg, 4);
3358
3359        // Full page: all 3 edges present.
3360        let full = kg.read_graph_filtered(None, 0, usize::MAX).unwrap();
3361        assert_eq!(count_entities(&full), 4);
3362        assert_eq!(count_relations(&full), 3);
3363
3364        // Page of only the first entity (n0): its only edge n0->n1 has an
3365        // endpoint (n1) outside the page, so no relations are returned.
3366        let page1 = kg.read_graph_filtered(None, 0, 1).unwrap();
3367        assert_eq!(count_entities(&page1), 1);
3368        assert_eq!(count_relations(&page1), 0);
3369
3370        // Page of first two entities (n0, n1): edge n0->n1 fully inside, n1->n2
3371        // straddles the boundary and is excluded.
3372        let page2 = kg.read_graph_filtered(None, 0, 2).unwrap();
3373        assert_eq!(count_entities(&page2), 2);
3374        assert_eq!(count_relations(&page2), 1);
3375    }
3376
3377    #[test]
3378    fn test_read_graph_pagination_offset() {
3379        let kg = new_kg_with_pool(2);
3380        seed_line(&kg, 5);
3381        let g = kg.read_graph_filtered(None, 2, 2).unwrap();
3382        assert_eq!(count_entities(&g), 2);
3383        // Entities are ordered by id; offset 2 skips n0, n1.
3384        assert!(!g.contains("\"n0\""));
3385        assert!(!g.contains("\"n1\""));
3386        assert!(g.contains("\"n2\""));
3387        assert!(g.contains("\"n3\""));
3388    }
3389
3390    #[test]
3391    fn test_read_graph_empty() {
3392        let kg = new_kg_with_pool(2);
3393        let g = kg.read_graph_filtered(None, 0, usize::MAX).unwrap();
3394        assert_eq!(g, r#"{"entities":[],"relations":[]}"#);
3395    }
3396
3397    #[test]
3398    fn test_read_graph_filtered_by_type() {
3399        let kg = new_kg_with_pool(2);
3400        kg.create_entities(&[
3401            Entity { name: "p1".into(), entity_type: "person".into(), observations: vec![] },
3402            Entity { name: "q1".into(), entity_type: "place".into(), observations: vec![] },
3403            Entity { name: "p2".into(), entity_type: "person".into(), observations: vec![] },
3404        ])
3405        .unwrap();
3406        let g = kg.read_graph_filtered(Some("person"), 0, usize::MAX).unwrap();
3407        assert_eq!(count_entities(&g), 2);
3408        assert!(g.contains("\"p1\""));
3409        assert!(g.contains("\"p2\""));
3410        assert!(!g.contains("\"q1\""));
3411    }
3412
3413    #[test]
3414    fn test_export_respects_max_rows() {
3415        let kg = new_kg_with_pool(2);
3416        seed_line(&kg, 5);
3417
3418        // Unbounded export returns everything.
3419        let full = kg.export("json", i64::MAX).unwrap();
3420        assert_eq!(count_entities(&full), 5);
3421        assert_eq!(count_relations(&full), 4);
3422
3423        // Capped export truncates both arrays to the cap.
3424        let capped = kg.export("json", 2).unwrap();
3425        assert_eq!(count_entities(&capped), 2);
3426        assert_eq!(count_relations(&capped), 2);
3427    }
3428
3429    #[test]
3430    fn test_export_negative_max_rows_is_unbounded() {
3431        let kg = new_kg_with_pool(2);
3432        seed_line(&kg, 3);
3433        // SQLite treats a negative LIMIT as "no limit".
3434        let out = kg.export("json", -1).unwrap();
3435        assert_eq!(count_entities(&out), 3);
3436    }
3437
3438    // ── Fix #8: writes remain correct without the per-write PRAGMA optimize ─
3439
3440    #[test]
3441    fn test_many_small_write_batches_stay_consistent() {
3442        let kg = new_kg_with_pool(2);
3443        for i in 0..100 {
3444            kg.create_entities(&[Entity {
3445                name: format!("e{i}"),
3446                entity_type: "t".into(),
3447                observations: vec![format!("o{i}")],
3448            }])
3449            .unwrap();
3450        }
3451        assert_eq!(kg.get_entity_count().unwrap(), 100);
3452        // Search must still find a needle inserted across many tiny batches,
3453        // proving FTS stayed consistent without per-write optimization.
3454        let hits = kg.search_nodes_filtered("e57", None, 0, 10);
3455        assert!(hits.iter().any(|e| e.name == "e57"));
3456    }
3457
3458    // ── Fix #9: wipe fully resets the FTS indexes ──────────────────────────
3459
3460    #[test]
3461    fn test_wipe_clears_name_and_obs_fts() {
3462        let kg = new_kg_with_pool(2);
3463        kg.create_entities(&[Entity {
3464            name: "Einstein".into(),
3465            entity_type: "scientist".into(),
3466            observations: vec!["physics".into()],
3467        }])
3468        .unwrap();
3469
3470        // Both FTS indexes resolve before the wipe.
3471        assert_eq!(kg.search_nodes_filtered("Einstein", None, 0, 10).len(), 1);
3472        assert_eq!(kg.search_nodes_filtered("physics", None, 0, 10).len(), 1);
3473
3474        kg.wipe().unwrap();
3475
3476        // After wipe both indexes must be empty (a bare DELETE on an
3477        // external-content FTS5 table would have left stale rowids behind).
3478        assert_eq!(kg.get_entity_count().unwrap(), 0);
3479        assert!(kg.search_nodes_filtered("Einstein", None, 0, 10).is_empty());
3480        assert!(kg.search_nodes_filtered("physics", None, 0, 10).is_empty());
3481    }
3482
3483    #[test]
3484    fn test_wipe_then_recreate_search_works() {
3485        // Recreating the same names after a wipe must produce a clean, searchable
3486        // index — not a corrupted one or duplicate FTS rows.
3487        let kg = new_kg_with_pool(2);
3488        kg.create_entities(&[Entity {
3489            name: "Einstein".into(),
3490            entity_type: "scientist".into(),
3491            observations: vec!["physics".into()],
3492        }])
3493        .unwrap();
3494        kg.wipe().unwrap();
3495
3496        kg.create_entities(&[Entity {
3497            name: "Einstein".into(),
3498            entity_type: "scientist".into(),
3499            observations: vec!["physics".into(), "relativity".into()],
3500        }])
3501        .unwrap();
3502
3503        let by_name = kg.search_nodes_filtered("Einstein", None, 0, 10);
3504        assert_eq!(by_name.len(), 1, "exactly one Einstein after recreate");
3505        let by_obs = kg.search_nodes_filtered("relativity", None, 0, 10);
3506        assert_eq!(by_obs.len(), 1);
3507        assert_eq!(kg.get_entity_count().unwrap(), 1);
3508    }
3509
3510    // ── Read-only type/entity resolution (introduced by the reader pool) ───
3511
3512    #[test]
3513    fn test_search_relations_missing_type_returns_empty() {
3514        let kg = new_kg_with_pool(2);
3515        seed_line(&kg, 3); // edges of type "edge"
3516        // A filter for a relation type that does not exist must return nothing,
3517        // not every relation — and must not create a phantom type row.
3518        let r = kg.search_relations(None, None, Some("does_not_exist"));
3519        assert!(r.is_empty());
3520        // The phantom type must not have been inserted by the read.
3521        let types = kg.relation_type_counts();
3522        assert!(types.iter().all(|(t, _)| t != "does_not_exist"));
3523    }
3524
3525    #[test]
3526    fn test_search_relations_missing_from_returns_empty() {
3527        let kg = new_kg_with_pool(2);
3528        seed_line(&kg, 3);
3529        let r = kg.search_relations(Some("ghost"), None, None);
3530        assert!(r.is_empty(), "missing 'from' must not match every relation");
3531    }
3532
3533    #[test]
3534    fn test_search_relations_existing_filters_still_work() {
3535        let kg = new_kg_with_pool(2);
3536        seed_line(&kg, 3);
3537        let r = kg.search_relations(Some("n0"), None, Some("edge"));
3538        assert_eq!(r.len(), 1);
3539        assert_eq!(r[0].from, "n0");
3540        assert_eq!(r[0].to, "n1");
3541    }
3542
3543    #[test]
3544    fn test_neighbors_missing_type_returns_only_start() {
3545        let kg = new_kg_with_pool(2);
3546        seed_line(&kg, 3);
3547        let json = kg
3548            .neighbors("n0", Direction::Both, Some("nonexistent"), 2)
3549            .unwrap();
3550        // No edge matches the bogus type, so only the start node comes back.
3551        assert_eq!(count_entities(&json), 1);
3552        assert_eq!(count_relations(&json), 0);
3553    }
3554
3555    #[test]
3556    fn test_neighbors_existing_type_filters() {
3557        let kg = new_kg_with_pool(2);
3558        kg.create_entities(&[
3559            Entity { name: "a".into(), entity_type: "n".into(), observations: vec![] },
3560            Entity { name: "b".into(), entity_type: "n".into(), observations: vec![] },
3561            Entity { name: "c".into(), entity_type: "n".into(), observations: vec![] },
3562        ])
3563        .unwrap();
3564        kg.create_relations(&[
3565            Relation { from: "a".into(), to: "b".into(), relation_type: "knows".into() },
3566            Relation { from: "a".into(), to: "c".into(), relation_type: "likes".into() },
3567        ])
3568        .unwrap();
3569        let json = kg.neighbors("a", Direction::Outgoing, Some("knows"), 1).unwrap();
3570        assert!(json.contains("\"b\""));
3571        assert!(!json.contains("\"c\""));
3572        assert_eq!(count_relations(&json), 1);
3573    }
3574
3575    #[test]
3576    fn test_sqlite_tuning_applied_to_fresh_db() {
3577        use std::sync::atomic::AtomicU64;
3578        static COUNTER: AtomicU64 = AtomicU64::new(2_000_000);
3579        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
3580        let path = std::env::temp_dir().join(format!("kg_tuning_{}_{}.db", std::process::id(), n));
3581        cleanup_db(&path);
3582
3583        let tuning = SqliteTuning {
3584            page_size: 8192,
3585            ..SqliteTuning::default()
3586        };
3587        let kg = TestKg(
3588            GraphHandle::new(&path, Durability::Async, tuning, NonZeroUsize::new(64).unwrap(), 2)
3589                .expect("create KG"),
3590            path.clone(),
3591        );
3592        kg.create_entities(&[Entity {
3593            name: "a".into(),
3594            entity_type: "n".into(),
3595            observations: vec!["o".into()],
3596        }])
3597        .unwrap();
3598
3599        // page_size (fresh-DB only) and auto_vacuum=INCREMENTAL must have taken
3600        // effect, and journal_mode must be WAL.
3601        let probe = Connection::open(&path).unwrap();
3602        let page_size: i64 = probe.query_row("PRAGMA page_size", [], |r| r.get(0)).unwrap();
3603        assert_eq!(page_size, 8192);
3604        let auto_vacuum: i64 = probe.query_row("PRAGMA auto_vacuum", [], |r| r.get(0)).unwrap();
3605        assert_eq!(auto_vacuum, 2, "expected INCREMENTAL auto_vacuum");
3606        let journal: String = probe.query_row("PRAGMA journal_mode", [], |r| r.get(0)).unwrap();
3607        assert_eq!(journal.to_lowercase(), "wal");
3608    }
3609
3610    #[test]
3611    fn test_checkpoint_passive_is_noop_safe() {
3612        let kg = new_kg();
3613        // On an empty / freshly-written DB a passive checkpoint must succeed.
3614        kg.checkpoint_passive().unwrap();
3615        kg.create_entities(&[Entity {
3616            name: "a".into(),
3617            entity_type: "n".into(),
3618            observations: vec!["o".into()],
3619        }])
3620        .unwrap();
3621        // And after a write, repeatedly, without error or deadlock.
3622        kg.checkpoint_passive().unwrap();
3623        kg.checkpoint_passive().unwrap();
3624        // Data is still readable afterwards.
3625        assert!(kg.get_entity("a").unwrap().is_some());
3626    }
3627}