Skip to main content

zeph_memory/graph/
community.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use std::collections::HashMap;
5use std::sync::Arc;
6#[allow(unused_imports)]
7use zeph_db::sql;
8
9use futures::TryStreamExt as _;
10use petgraph::Graph;
11use petgraph::graph::NodeIndex;
12use tokio::sync::Semaphore;
13use tokio::task::JoinSet;
14use zeph_llm::LlmProvider as _;
15use zeph_llm::any::AnyProvider;
16use zeph_llm::provider::{Message, Role};
17
18use crate::error::MemoryError;
19
20use super::store::GraphStore;
21use super::types::Entity;
22
23const MAX_LABEL_PROPAGATION_ITERATIONS: usize = 50;
24
25/// Strip control characters, Unicode bidi overrides, and zero-width characters from `s`
26/// to prevent prompt injection via entity names or edge facts sourced from untrusted text.
27///
28/// Filtered categories:
29/// - All Unicode control characters (`Cc` category, covers ASCII controls and more)
30/// - Bidi control characters: U+202A–U+202E, U+2066–U+2069
31/// - Zero-width and invisible characters: U+200B–U+200F (includes U+200C, U+200D)
32/// - Byte-order mark: U+FEFF
33fn scrub_content(s: &str) -> String {
34    s.chars()
35        .filter(|c| {
36            !c.is_control()
37                && !matches!(*c as u32,
38                    0x200B..=0x200F | 0x202A..=0x202E | 0x2066..=0x2069 | 0xFEFF
39                )
40        })
41        .collect()
42}
43
44/// Stats returned from graph eviction.
45#[derive(Debug, Default)]
46pub struct GraphEvictionStats {
47    pub expired_edges_deleted: usize,
48    pub orphan_entities_deleted: usize,
49    pub capped_entities_deleted: usize,
50}
51
52/// Truncate `prompt` to at most `max_bytes` at a UTF-8 boundary, appending `"..."`
53/// if truncation occurred.
54///
55/// If `max_bytes` is 0, returns an empty string immediately (disables community summaries).
56/// Otherwise clamps the boundary to the nearest valid UTF-8 char boundary and appends `"..."`.
57fn truncate_prompt(prompt: String, max_bytes: usize) -> String {
58    if max_bytes == 0 {
59        return String::new();
60    }
61    if prompt.len() <= max_bytes {
62        return prompt;
63    }
64    let boundary = prompt.floor_char_boundary(max_bytes);
65    format!("{}...", &prompt[..boundary])
66}
67
68/// Compute a BLAKE3 fingerprint for a community partition.
69///
70/// The fingerprint is derived from sorted entity IDs and sorted intra-community edge IDs,
71/// ensuring both membership and edge mutations trigger re-summarization.
72/// BLAKE3 is used (not `DefaultHasher`) to guarantee determinism across process restarts.
73fn compute_partition_fingerprint(entity_ids: &[i64], intra_edge_ids: &[i64]) -> String {
74    let mut hasher = blake3::Hasher::new();
75    let mut sorted_entities = entity_ids.to_vec();
76    sorted_entities.sort_unstable();
77    hasher.update(b"entities");
78    for id in &sorted_entities {
79        hasher.update(&id.to_le_bytes());
80    }
81    let mut sorted_edges = intra_edge_ids.to_vec();
82    sorted_edges.sort_unstable();
83    hasher.update(b"edges");
84    for id in &sorted_edges {
85        hasher.update(&id.to_le_bytes());
86    }
87    hasher.finalize().to_hex().to_string()
88}
89
90/// Per-community data collected before spawning LLM summarization tasks.
91struct CommunityData {
92    entity_ids: Vec<i64>,
93    entity_names: Vec<String>,
94    intra_facts: Vec<String>,
95    fingerprint: String,
96    name: String,
97}
98
99type UndirectedGraph = Graph<i64, (), petgraph::Undirected>;
100
101async fn build_entity_graph_and_maps(
102    store: &GraphStore,
103    entities: &[Entity],
104    edge_chunk_size: usize,
105) -> Result<
106    (
107        UndirectedGraph,
108        HashMap<(i64, i64), Vec<String>>,
109        HashMap<(i64, i64), Vec<i64>>,
110    ),
111    MemoryError,
112> {
113    let mut graph = UndirectedGraph::new_undirected();
114    let mut node_map: HashMap<i64, NodeIndex> = HashMap::new();
115
116    for entity in entities {
117        let idx = graph.add_node(entity.id);
118        node_map.insert(entity.id, idx);
119    }
120
121    let mut edge_facts_map: HashMap<(i64, i64), Vec<String>> = HashMap::new();
122    let mut edge_id_map: HashMap<(i64, i64), Vec<i64>> = HashMap::new();
123
124    if edge_chunk_size == 0 {
125        let edges: Vec<_> = store.all_active_edges_stream().try_collect().await?;
126        for edge in &edges {
127            if let (Some(&src_idx), Some(&tgt_idx)) = (
128                node_map.get(&edge.source_entity_id),
129                node_map.get(&edge.target_entity_id),
130            ) {
131                graph.add_edge(src_idx, tgt_idx, ());
132            }
133            let key = (edge.source_entity_id, edge.target_entity_id);
134            edge_facts_map
135                .entry(key)
136                .or_default()
137                .push(edge.fact.clone());
138            edge_id_map.entry(key).or_default().push(edge.id);
139        }
140    } else {
141        let limit = i64::try_from(edge_chunk_size).unwrap_or(i64::MAX);
142        let mut last_id: i64 = 0;
143        loop {
144            let chunk = store.edges_after_id(last_id, limit).await?;
145            if chunk.is_empty() {
146                break;
147            }
148            last_id = chunk.last().expect("non-empty chunk has a last element").id;
149            for edge in &chunk {
150                if let (Some(&src_idx), Some(&tgt_idx)) = (
151                    node_map.get(&edge.source_entity_id),
152                    node_map.get(&edge.target_entity_id),
153                ) {
154                    graph.add_edge(src_idx, tgt_idx, ());
155                }
156                let key = (edge.source_entity_id, edge.target_entity_id);
157                edge_facts_map
158                    .entry(key)
159                    .or_default()
160                    .push(edge.fact.clone());
161                edge_id_map.entry(key).or_default().push(edge.id);
162            }
163        }
164    }
165
166    Ok((graph, edge_facts_map, edge_id_map))
167}
168
169fn run_label_propagation(graph: &UndirectedGraph) -> HashMap<usize, Vec<i64>> {
170    let mut labels: Vec<usize> = (0..graph.node_count()).collect();
171
172    for _ in 0..MAX_LABEL_PROPAGATION_ITERATIONS {
173        let mut changed = false;
174        for node_idx in graph.node_indices() {
175            let neighbors: Vec<NodeIndex> = graph.neighbors(node_idx).collect();
176            if neighbors.is_empty() {
177                continue;
178            }
179            let mut freq: HashMap<usize, usize> = HashMap::new();
180            for &nbr in &neighbors {
181                *freq.entry(labels[nbr.index()]).or_insert(0) += 1;
182            }
183            let max_count = *freq.values().max().unwrap_or(&0);
184            let best_label = freq
185                .iter()
186                .filter(|&(_, count)| *count == max_count)
187                .map(|(&label, _)| label)
188                .min()
189                .unwrap_or(labels[node_idx.index()]);
190            if labels[node_idx.index()] != best_label {
191                labels[node_idx.index()] = best_label;
192                changed = true;
193            }
194        }
195        if !changed {
196            break;
197        }
198    }
199
200    let mut communities: HashMap<usize, Vec<i64>> = HashMap::new();
201    for node_idx in graph.node_indices() {
202        let entity_id = graph[node_idx];
203        communities
204            .entry(labels[node_idx.index()])
205            .or_default()
206            .push(entity_id);
207    }
208    communities.retain(|_, members| members.len() >= 2);
209    communities
210}
211
212struct ClassifyResult {
213    to_summarize: Vec<CommunityData>,
214    unchanged_count: usize,
215    new_fingerprints: std::collections::HashSet<String>,
216}
217
218fn classify_communities(
219    communities: &HashMap<usize, Vec<i64>>,
220    edge_facts_map: &HashMap<(i64, i64), Vec<String>>,
221    edge_id_map: &HashMap<(i64, i64), Vec<i64>>,
222    entity_name_map: &HashMap<i64, &str>,
223    stored_fingerprints: &HashMap<String, i64>,
224    sorted_labels: &[usize],
225) -> ClassifyResult {
226    let mut to_summarize: Vec<CommunityData> = Vec::new();
227    let mut unchanged_count = 0usize;
228    let mut new_fingerprints: std::collections::HashSet<String> = std::collections::HashSet::new();
229
230    for (label_index, &label) in sorted_labels.iter().enumerate() {
231        let entity_ids = communities[&label].as_slice();
232        let member_set: std::collections::HashSet<i64> = entity_ids.iter().copied().collect();
233
234        let mut intra_facts: Vec<String> = Vec::new();
235        let mut intra_edge_ids: Vec<i64> = Vec::new();
236        for (&(src, tgt), facts) in edge_facts_map {
237            if member_set.contains(&src) && member_set.contains(&tgt) {
238                intra_facts.extend(facts.iter().map(|f| scrub_content(f)));
239                if let Some(ids) = edge_id_map.get(&(src, tgt)) {
240                    intra_edge_ids.extend_from_slice(ids);
241                }
242            }
243        }
244
245        let fingerprint = compute_partition_fingerprint(entity_ids, &intra_edge_ids);
246        new_fingerprints.insert(fingerprint.clone());
247
248        if stored_fingerprints.contains_key(&fingerprint) {
249            unchanged_count += 1;
250            continue;
251        }
252
253        let entity_names: Vec<String> = entity_ids
254            .iter()
255            .filter_map(|id| entity_name_map.get(id).map(|&s| scrub_content(s)))
256            .collect();
257
258        // Append label_index to prevent ON CONFLICT(name) collisions when two communities
259        // share the same top-3 entity names across detect_communities runs (IC-SIG-02).
260        let base_name = entity_names
261            .iter()
262            .take(3)
263            .cloned()
264            .collect::<Vec<_>>()
265            .join(", ");
266        let name = format!("{base_name} [{label_index}]");
267
268        to_summarize.push(CommunityData {
269            entity_ids: entity_ids.to_vec(),
270            entity_names,
271            intra_facts,
272            fingerprint,
273            name,
274        });
275    }
276
277    ClassifyResult {
278        to_summarize,
279        unchanged_count,
280        new_fingerprints,
281    }
282}
283
284async fn summarize_and_upsert_communities(
285    store: &GraphStore,
286    provider: &AnyProvider,
287    to_summarize: Vec<CommunityData>,
288    concurrency: usize,
289    community_summary_max_prompt_bytes: usize,
290) -> Result<usize, MemoryError> {
291    let semaphore = Arc::new(Semaphore::new(concurrency.max(1)));
292    let mut join_set: JoinSet<(String, String, Vec<i64>, String)> = JoinSet::new();
293
294    for data in to_summarize {
295        let provider = provider.clone();
296        let sem = Arc::clone(&semaphore);
297        let max_bytes = community_summary_max_prompt_bytes;
298        join_set.spawn(async move {
299            let _permit = sem.acquire().await.expect("semaphore is never closed");
300            let summary = match generate_community_summary(
301                &provider,
302                &data.entity_names,
303                &data.intra_facts,
304                max_bytes,
305            )
306            .await
307            {
308                Ok(text) => text,
309                Err(e) => {
310                    tracing::warn!(community = %data.name, "community summary generation failed: {e:#}");
311                    String::new()
312                }
313            };
314            (data.name, summary, data.entity_ids, data.fingerprint)
315        });
316    }
317
318    // Collect results — handle task panics explicitly (HIGH-01 fix).
319    let mut results: Vec<(String, String, Vec<i64>, String)> = Vec::new();
320    while let Some(outcome) = join_set.join_next().await {
321        match outcome {
322            Ok(tuple) => results.push(tuple),
323            Err(e) => {
324                tracing::error!(
325                    panicked = e.is_panic(),
326                    cancelled = e.is_cancelled(),
327                    "community summary task failed"
328                );
329            }
330        }
331    }
332
333    results.sort_unstable_by(|a, b| a.0.cmp(&b.0));
334
335    let mut count = 0usize;
336    for (name, summary, entity_ids, fingerprint) in results {
337        store
338            .upsert_community(&name, &summary, &entity_ids, Some(&fingerprint))
339            .await?;
340        count += 1;
341    }
342
343    Ok(count)
344}
345
346/// Run label propagation on the full entity graph, generate community summaries via LLM,
347/// and upsert results to `SQLite`.
348///
349/// Returns the number of communities detected (with `>= 2` entities).
350///
351/// Unchanged communities (same entity membership and intra-community edges) are skipped —
352/// their existing summaries are preserved without LLM calls (incremental detection, #1262).
353/// LLM calls for changed communities are parallelized via a `JoinSet` bounded by a
354/// semaphore with `concurrency` permits (#1260).
355///
356/// # Panics
357///
358/// Does not panic in normal operation. The `semaphore.acquire().await.expect(...)` call is
359/// infallible because the semaphore is never closed during the lifetime of this function.
360///
361/// # Errors
362///
363/// Returns an error if `SQLite` queries or LLM calls fail.
364pub async fn detect_communities(
365    store: &GraphStore,
366    provider: &AnyProvider,
367    community_summary_max_prompt_bytes: usize,
368    concurrency: usize,
369    edge_chunk_size: usize,
370) -> Result<usize, MemoryError> {
371    let edge_chunk_size = if edge_chunk_size == 0 {
372        tracing::warn!(
373            "edge_chunk_size is 0, which would load all edges into memory; \
374             using safe default of 10_000"
375        );
376        10_000_usize
377    } else {
378        edge_chunk_size
379    };
380
381    let entities = store.all_entities().await?;
382    if entities.len() < 2 {
383        return Ok(0);
384    }
385
386    let (graph, edge_facts_map, edge_id_map) =
387        build_entity_graph_and_maps(store, &entities, edge_chunk_size).await?;
388
389    let communities = run_label_propagation(&graph);
390
391    let entity_name_map: HashMap<i64, &str> =
392        entities.iter().map(|e| (e.id, e.name.as_str())).collect();
393    let stored_fingerprints = store.community_fingerprints().await?;
394
395    let mut sorted_labels: Vec<usize> = communities.keys().copied().collect();
396    sorted_labels.sort_unstable();
397
398    let ClassifyResult {
399        to_summarize,
400        unchanged_count,
401        new_fingerprints,
402    } = classify_communities(
403        &communities,
404        &edge_facts_map,
405        &edge_id_map,
406        &entity_name_map,
407        &stored_fingerprints,
408        &sorted_labels,
409    );
410
411    tracing::debug!(
412        total = sorted_labels.len(),
413        unchanged = unchanged_count,
414        to_summarize = to_summarize.len(),
415        "community detection: partition classification complete"
416    );
417
418    // Delete dissolved communities (fingerprints no longer in new partition set).
419    for (stored_fp, community_id) in &stored_fingerprints {
420        if !new_fingerprints.contains(stored_fp.as_str()) {
421            store.delete_community_by_id(*community_id).await?;
422        }
423    }
424
425    let new_count = summarize_and_upsert_communities(
426        store,
427        provider,
428        to_summarize,
429        concurrency,
430        community_summary_max_prompt_bytes,
431    )
432    .await?;
433
434    Ok(unchanged_count + new_count)
435}
436
437/// Assign a single entity to an existing community via neighbor majority vote.
438///
439/// Returns `Some(community_id)` if assigned, `None` if no neighbors have communities.
440///
441/// When an entity is added, the stored fingerprint is cleared (`NULL`) so the next
442/// `detect_communities` run will re-summarize the affected community (CRIT-02 fix).
443///
444/// # Errors
445///
446/// Returns an error if `SQLite` queries fail.
447pub async fn assign_to_community(
448    store: &GraphStore,
449    entity_id: i64,
450) -> Result<Option<i64>, MemoryError> {
451    let edges = store.edges_for_entity(entity_id).await?;
452    if edges.is_empty() {
453        return Ok(None);
454    }
455
456    let neighbor_ids: Vec<i64> = edges
457        .iter()
458        .map(|e| {
459            if e.source_entity_id == entity_id {
460                e.target_entity_id
461            } else {
462                e.source_entity_id
463            }
464        })
465        .collect();
466
467    let mut community_votes: HashMap<i64, usize> = HashMap::new();
468    for &nbr_id in &neighbor_ids {
469        if let Some(community) = store.community_for_entity(nbr_id).await? {
470            *community_votes.entry(community.id).or_insert(0) += 1;
471        }
472    }
473
474    if community_votes.is_empty() {
475        return Ok(None);
476    }
477
478    // Majority vote — tie-break by smallest community_id.
479    // community_votes is non-empty (checked above), so max_by always returns Some.
480    let Some((&best_community_id, _)) =
481        community_votes
482            .iter()
483            .max_by(|&(&id_a, &count_a), &(&id_b, &count_b)| {
484                count_a.cmp(&count_b).then(id_b.cmp(&id_a))
485            })
486    else {
487        return Ok(None);
488    };
489
490    if let Some(mut target) = store.find_community_by_id(best_community_id).await? {
491        if !target.entity_ids.contains(&entity_id) {
492            target.entity_ids.push(entity_id);
493            store
494                .upsert_community(&target.name, &target.summary, &target.entity_ids, None)
495                .await?;
496            // Clear fingerprint to invalidate cache — next detect_communities will re-summarize.
497            store.clear_community_fingerprint(best_community_id).await?;
498        }
499        return Ok(Some(best_community_id));
500    }
501
502    Ok(None)
503}
504
505/// Remove `Qdrant` points for entities that no longer exist in `SQLite`.
506///
507/// Returns the number of stale points deleted.
508///
509/// # Errors
510///
511/// Returns an error if `Qdrant` operations fail.
512pub async fn cleanup_stale_entity_embeddings(
513    _store: &GraphStore,
514    _embeddings: &crate::embedding_store::EmbeddingStore,
515) -> Result<usize, MemoryError> {
516    // TODO: implement when EmbeddingStore exposes a scroll_all API
517    // (follow-up: add pub async fn scroll_all(&self, collection, key_field) delegating to
518    // self.ops.scroll_all). Then enumerate Qdrant points, collect IDs where entity_id is
519    // not in SQLite, and delete stale points.
520    Ok(0)
521}
522
523/// Run graph eviction: clean expired edges, orphan entities, and cap entity count.
524///
525/// # Errors
526///
527/// Returns an error if `SQLite` queries fail.
528pub async fn run_graph_eviction(
529    store: &GraphStore,
530    expired_edge_retention_days: u32,
531    max_entities: usize,
532) -> Result<GraphEvictionStats, MemoryError> {
533    let expired_edges_deleted = store
534        .delete_expired_edges(expired_edge_retention_days)
535        .await?;
536    let orphan_entities_deleted = store
537        .delete_orphan_entities(expired_edge_retention_days)
538        .await?;
539    let capped_entities_deleted = if max_entities > 0 {
540        store.cap_entities(max_entities).await?
541    } else {
542        0
543    };
544
545    Ok(GraphEvictionStats {
546        expired_edges_deleted,
547        orphan_entities_deleted,
548        capped_entities_deleted,
549    })
550}
551
552async fn generate_community_summary(
553    provider: &AnyProvider,
554    entity_names: &[String],
555    edge_facts: &[String],
556    max_prompt_bytes: usize,
557) -> Result<String, MemoryError> {
558    let entities_str = entity_names.join(", ");
559    // Cap facts at 20 to bound prompt size; data is already scrubbed upstream.
560    let facts_str = edge_facts
561        .iter()
562        .take(20)
563        .map(|f| format!("- {f}"))
564        .collect::<Vec<_>>()
565        .join("\n");
566
567    let raw_prompt = format!(
568        "Summarize the following group of related entities and their relationships \
569         into a single paragraph (2-3 sentences). Focus on the theme that connects \
570         them and the key relationships.\n\nEntities: {entities_str}\n\
571         Relationships:\n{facts_str}\n\nSummary:"
572    );
573
574    let original_bytes = raw_prompt.len();
575    let truncated = raw_prompt.len() > max_prompt_bytes;
576    let prompt = truncate_prompt(raw_prompt, max_prompt_bytes);
577    if prompt.is_empty() {
578        return Ok(String::new());
579    }
580    if truncated {
581        tracing::warn!(
582            entity_count = entity_names.len(),
583            original_bytes,
584            truncated_bytes = prompt.len(),
585            "community summary prompt truncated"
586        );
587    }
588
589    let messages = [Message::from_legacy(Role::User, prompt)];
590    let response: String = provider.chat(&messages).await.map_err(MemoryError::Llm)?;
591    Ok(response)
592}
593
594#[cfg(test)]
595mod tests {
596    use std::sync::{Arc, Mutex};
597
598    use super::*;
599    use crate::graph::types::EntityType;
600    use crate::store::SqliteStore;
601
602    async fn setup() -> GraphStore {
603        let store = SqliteStore::new(":memory:").await.unwrap();
604        GraphStore::new(store.pool().clone())
605    }
606
607    fn mock_provider() -> AnyProvider {
608        AnyProvider::Mock(zeph_llm::mock::MockProvider::default())
609    }
610
611    fn recording_provider() -> (
612        AnyProvider,
613        Arc<Mutex<Vec<Vec<zeph_llm::provider::Message>>>>,
614    ) {
615        let (mock, buf) = zeph_llm::mock::MockProvider::default().with_recording();
616        (AnyProvider::Mock(mock), buf)
617    }
618
619    #[tokio::test]
620    async fn test_detect_communities_empty_graph() {
621        let store = setup().await;
622        let provider = mock_provider();
623        let count = detect_communities(&store, &provider, usize::MAX, 4, 0)
624            .await
625            .unwrap();
626        assert_eq!(count, 0);
627    }
628
629    #[tokio::test]
630    async fn test_detect_communities_single_entity() {
631        let store = setup().await;
632        let provider = mock_provider();
633        store
634            .upsert_entity("Solo", "Solo", EntityType::Concept, None)
635            .await
636            .unwrap();
637        let count = detect_communities(&store, &provider, usize::MAX, 4, 0)
638            .await
639            .unwrap();
640        assert_eq!(count, 0, "single isolated entity must not form a community");
641    }
642
643    #[tokio::test]
644    async fn test_single_entity_community_filtered() {
645        let store = setup().await;
646        let provider = mock_provider();
647
648        // Create 3 connected entities (cluster A) and 1 isolated entity.
649        let a = store
650            .upsert_entity("A", "A", EntityType::Concept, None)
651            .await
652            .unwrap();
653        let b = store
654            .upsert_entity("B", "B", EntityType::Concept, None)
655            .await
656            .unwrap();
657        let c = store
658            .upsert_entity("C", "C", EntityType::Concept, None)
659            .await
660            .unwrap();
661        let iso = store
662            .upsert_entity("Isolated", "Isolated", EntityType::Concept, None)
663            .await
664            .unwrap();
665
666        store
667            .insert_edge(a, b, "r", "A relates B", 1.0, None)
668            .await
669            .unwrap();
670        store
671            .insert_edge(b, c, "r", "B relates C", 1.0, None)
672            .await
673            .unwrap();
674
675        let count = detect_communities(&store, &provider, usize::MAX, 4, 0)
676            .await
677            .unwrap();
678        // Isolated entity has no edges — must NOT be persisted as a community.
679        assert_eq!(count, 1, "only the 3-entity cluster should be detected");
680
681        let communities = store.all_communities().await.unwrap();
682        assert_eq!(communities.len(), 1);
683        assert!(
684            !communities[0].entity_ids.contains(&iso),
685            "isolated entity must not be in any community"
686        );
687    }
688
689    #[tokio::test]
690    async fn test_label_propagation_basic() {
691        let store = setup().await;
692        let provider = mock_provider();
693
694        // Create 4 clusters of 3 entities each (12 entities total), fully isolated.
695        let mut cluster_ids: Vec<Vec<i64>> = Vec::new();
696        for cluster in 0..4_i64 {
697            let mut ids = Vec::new();
698            for node in 0..3_i64 {
699                let name = format!("c{cluster}_n{node}");
700                let id = store
701                    .upsert_entity(&name, &name, EntityType::Concept, None)
702                    .await
703                    .unwrap();
704                ids.push(id);
705            }
706            // Connect nodes within cluster (chain: 0-1-2).
707            store
708                .insert_edge(ids[0], ids[1], "r", "f", 1.0, None)
709                .await
710                .unwrap();
711            store
712                .insert_edge(ids[1], ids[2], "r", "f", 1.0, None)
713                .await
714                .unwrap();
715            cluster_ids.push(ids);
716        }
717
718        let count = detect_communities(&store, &provider, usize::MAX, 4, 0)
719            .await
720            .unwrap();
721        assert_eq!(count, 4, "expected 4 communities, one per cluster");
722
723        let communities = store.all_communities().await.unwrap();
724        assert_eq!(communities.len(), 4);
725
726        // Each cluster's entity IDs must appear in exactly one community.
727        for ids in &cluster_ids {
728            let found = communities
729                .iter()
730                .filter(|c| ids.iter().any(|id| c.entity_ids.contains(id)))
731                .count();
732            assert_eq!(
733                found, 1,
734                "all nodes of a cluster must be in the same community"
735            );
736        }
737    }
738
739    #[tokio::test]
740    async fn test_all_isolated_nodes() {
741        let store = setup().await;
742        let provider = mock_provider();
743
744        // Insert 5 entities with no edges at all.
745        for i in 0..5_i64 {
746            store
747                .upsert_entity(
748                    &format!("iso_{i}"),
749                    &format!("iso_{i}"),
750                    EntityType::Concept,
751                    None,
752                )
753                .await
754                .unwrap();
755        }
756
757        let count = detect_communities(&store, &provider, usize::MAX, 4, 0)
758            .await
759            .unwrap();
760        assert_eq!(count, 0, "zero-edge graph must produce no communities");
761        assert_eq!(store.community_count().await.unwrap(), 0);
762    }
763
764    #[tokio::test]
765    async fn test_eviction_expired_edges() {
766        let store = setup().await;
767
768        let a = store
769            .upsert_entity("EA", "EA", EntityType::Concept, None)
770            .await
771            .unwrap();
772        let b = store
773            .upsert_entity("EB", "EB", EntityType::Concept, None)
774            .await
775            .unwrap();
776        let edge_id = store.insert_edge(a, b, "r", "f", 1.0, None).await.unwrap();
777        store.invalidate_edge(edge_id).await.unwrap();
778
779        // Manually set expired_at to a date far in the past to trigger deletion.
780        zeph_db::query(sql!(
781            "UPDATE graph_edges SET expired_at = datetime('now', '-200 days') WHERE id = ?1"
782        ))
783        .bind(edge_id)
784        .execute(store.pool())
785        .await
786        .unwrap();
787
788        let stats = run_graph_eviction(&store, 90, 0).await.unwrap();
789        assert_eq!(stats.expired_edges_deleted, 1);
790    }
791
792    #[tokio::test]
793    async fn test_eviction_orphan_entities() {
794        let store = setup().await;
795
796        let iso = store
797            .upsert_entity("Orphan", "Orphan", EntityType::Concept, None)
798            .await
799            .unwrap();
800
801        // Set last_seen_at to far in the past.
802        zeph_db::query(sql!(
803            "UPDATE graph_entities SET last_seen_at = datetime('now', '-200 days') WHERE id = ?1"
804        ))
805        .bind(iso)
806        .execute(store.pool())
807        .await
808        .unwrap();
809
810        let stats = run_graph_eviction(&store, 90, 0).await.unwrap();
811        assert_eq!(stats.orphan_entities_deleted, 1);
812    }
813
814    #[tokio::test]
815    async fn test_eviction_entity_cap() {
816        let store = setup().await;
817
818        // Insert 5 entities with no edges (so they can be capped).
819        for i in 0..5_i64 {
820            let name = format!("cap_entity_{i}");
821            store
822                .upsert_entity(&name, &name, EntityType::Concept, None)
823                .await
824                .unwrap();
825        }
826
827        let stats = run_graph_eviction(&store, 90, 3).await.unwrap();
828        assert_eq!(
829            stats.capped_entities_deleted, 2,
830            "should delete 5-3=2 entities"
831        );
832        assert_eq!(store.entity_count().await.unwrap(), 3);
833    }
834
835    #[tokio::test]
836    async fn test_assign_to_community_no_neighbors() {
837        let store = setup().await;
838        let entity_id = store
839            .upsert_entity("Loner", "Loner", EntityType::Concept, None)
840            .await
841            .unwrap();
842
843        let result = assign_to_community(&store, entity_id).await.unwrap();
844        assert!(result.is_none());
845    }
846
847    #[tokio::test]
848    async fn test_extraction_count_persistence() {
849        use tempfile::NamedTempFile;
850        // Create a real on-disk SQLite DB to verify persistence across store instances.
851        let tmp = NamedTempFile::new().unwrap();
852        let path = tmp.path().to_str().unwrap().to_owned();
853
854        let store1 = {
855            let s = crate::store::SqliteStore::new(&path).await.unwrap();
856            GraphStore::new(s.pool().clone())
857        };
858
859        store1.set_metadata("extraction_count", "0").await.unwrap();
860        for i in 1..=5_i64 {
861            store1
862                .set_metadata("extraction_count", &i.to_string())
863                .await
864                .unwrap();
865        }
866
867        // Open a second handle to the same file and verify the value persists.
868        let store2 = {
869            let s = crate::store::SqliteStore::new(&path).await.unwrap();
870            GraphStore::new(s.pool().clone())
871        };
872        assert_eq!(store2.extraction_count().await.unwrap(), 5);
873    }
874
875    #[test]
876    fn test_scrub_content_ascii_control() {
877        // Newline, carriage return, null byte, tab (all ASCII control chars) must be stripped.
878        let input = "hello\nworld\r\x00\x01\x09end";
879        assert_eq!(scrub_content(input), "helloworldend");
880    }
881
882    #[test]
883    fn test_scrub_content_bidi_overrides() {
884        // U+202A LEFT-TO-RIGHT EMBEDDING, U+202E RIGHT-TO-LEFT OVERRIDE,
885        // U+2066 LEFT-TO-RIGHT ISOLATE, U+2069 POP DIRECTIONAL ISOLATE.
886        let input = "safe\u{202A}inject\u{202E}end\u{2066}iso\u{2069}done".to_string();
887        assert_eq!(scrub_content(&input), "safeinjectendisodone");
888    }
889
890    #[test]
891    fn test_scrub_content_zero_width() {
892        // U+200B ZERO WIDTH SPACE, U+200C ZERO WIDTH NON-JOINER, U+200D ZERO WIDTH JOINER,
893        // U+200F RIGHT-TO-LEFT MARK.
894        let input = "a\u{200B}b\u{200C}c\u{200D}d\u{200F}e".to_string();
895        assert_eq!(scrub_content(&input), "abcde");
896    }
897
898    #[test]
899    fn test_scrub_content_bom() {
900        // U+FEFF BYTE ORDER MARK must be stripped.
901        let input = "\u{FEFF}hello".to_string();
902        assert_eq!(scrub_content(&input), "hello");
903    }
904
905    #[test]
906    fn test_scrub_content_clean_string_unchanged() {
907        let input = "Hello, World! 123 — normal text.";
908        assert_eq!(scrub_content(input), input);
909    }
910
911    #[test]
912    fn test_truncate_prompt_within_limit() {
913        let result = truncate_prompt("short".into(), 100);
914        assert_eq!(result, "short");
915    }
916
917    #[test]
918    fn test_truncate_prompt_zero_max_bytes() {
919        let result = truncate_prompt("hello".into(), 0);
920        assert_eq!(result, "");
921    }
922
923    #[test]
924    fn test_truncate_prompt_long_facts() {
925        let facts: Vec<String> = (0..20)
926            .map(|i| format!("fact_{i}_{}", "x".repeat(20)))
927            .collect();
928        let prompt = facts.join("\n");
929        let result = truncate_prompt(prompt, 200);
930        assert!(
931            result.ends_with("..."),
932            "truncated prompt must end with '...'"
933        );
934        // byte length must be at most max_bytes + 3 (the "..." suffix)
935        assert!(result.len() <= 203);
936        assert!(std::str::from_utf8(result.as_bytes()).is_ok());
937    }
938
939    #[test]
940    fn test_truncate_prompt_utf8_boundary() {
941        // Each '🔥' is 4 bytes; 100 emojis = 400 bytes.
942        let prompt = "🔥".repeat(100);
943        let result = truncate_prompt(prompt, 10);
944        assert!(
945            result.ends_with("..."),
946            "truncated prompt must end with '...'"
947        );
948        // floor_char_boundary(10) for 4-byte chars lands at 8 (2 full emojis = 8 bytes)
949        assert_eq!(result.len(), 8 + 3, "2 emojis (8 bytes) + '...' (3 bytes)");
950        assert!(std::str::from_utf8(result.as_bytes()).is_ok());
951    }
952
953    #[tokio::test]
954    async fn test_assign_to_community_majority_vote() {
955        let store = setup().await;
956
957        // Setup: community C1 with members [A, B], then add D with edges to both A and B.
958        let a = store
959            .upsert_entity("AA", "AA", EntityType::Concept, None)
960            .await
961            .unwrap();
962        let b = store
963            .upsert_entity("BB", "BB", EntityType::Concept, None)
964            .await
965            .unwrap();
966        let d = store
967            .upsert_entity("DD", "DD", EntityType::Concept, None)
968            .await
969            .unwrap();
970
971        store
972            .upsert_community("test_community", "summary", &[a, b], None)
973            .await
974            .unwrap();
975
976        store.insert_edge(d, a, "r", "f", 1.0, None).await.unwrap();
977        store.insert_edge(d, b, "r", "f", 1.0, None).await.unwrap();
978
979        let result = assign_to_community(&store, d).await.unwrap();
980        assert!(result.is_some());
981
982        // The returned ID must be valid for subsequent lookups (HIGH-IC-01 regression test).
983        let returned_id = result.unwrap();
984        let community = store
985            .find_community_by_id(returned_id)
986            .await
987            .unwrap()
988            .expect("returned community_id must reference an existing row");
989        assert!(
990            community.entity_ids.contains(&d),
991            "D should be added to the community"
992        );
993        // Fingerprint must be NULL after assign (cache invalidated for next detect run).
994        assert!(
995            community.fingerprint.is_none(),
996            "fingerprint must be cleared after assign_to_community"
997        );
998    }
999
1000    /// #1262: Second `detect_communities` call with no graph changes must produce 0 LLM calls.
1001    #[tokio::test]
1002    async fn test_incremental_detection_no_changes_skips_llm() {
1003        let store = setup().await;
1004        let (provider, call_buf) = recording_provider();
1005
1006        let a = store
1007            .upsert_entity("X", "X", EntityType::Concept, None)
1008            .await
1009            .unwrap();
1010        let b = store
1011            .upsert_entity("Y", "Y", EntityType::Concept, None)
1012            .await
1013            .unwrap();
1014        store
1015            .insert_edge(a, b, "r", "X relates Y", 1.0, None)
1016            .await
1017            .unwrap();
1018
1019        // First run: LLM called once to summarize the community.
1020        detect_communities(&store, &provider, usize::MAX, 4, 0)
1021            .await
1022            .unwrap();
1023        let first_calls = call_buf.lock().unwrap().len();
1024        assert_eq!(first_calls, 1, "first run must produce exactly 1 LLM call");
1025
1026        // Second run: graph unchanged — 0 LLM calls.
1027        detect_communities(&store, &provider, usize::MAX, 4, 0)
1028            .await
1029            .unwrap();
1030        let second_calls = call_buf.lock().unwrap().len();
1031        assert_eq!(
1032            second_calls, first_calls,
1033            "second run with no graph changes must produce 0 additional LLM calls"
1034        );
1035    }
1036
1037    /// #1262: Adding an edge changes the fingerprint — LLM must be called again.
1038    #[tokio::test]
1039    async fn test_incremental_detection_edge_change_triggers_resummary() {
1040        let store = setup().await;
1041        let (provider, call_buf) = recording_provider();
1042
1043        let a = store
1044            .upsert_entity("P", "P", EntityType::Concept, None)
1045            .await
1046            .unwrap();
1047        let b = store
1048            .upsert_entity("Q", "Q", EntityType::Concept, None)
1049            .await
1050            .unwrap();
1051        store
1052            .insert_edge(a, b, "r", "P relates Q", 1.0, None)
1053            .await
1054            .unwrap();
1055
1056        detect_communities(&store, &provider, usize::MAX, 4, 0)
1057            .await
1058            .unwrap();
1059        let after_first = call_buf.lock().unwrap().len();
1060        assert_eq!(after_first, 1);
1061
1062        // Add a new edge within the community to change its fingerprint.
1063        store
1064            .insert_edge(b, a, "r2", "Q also relates P", 1.0, None)
1065            .await
1066            .unwrap();
1067
1068        detect_communities(&store, &provider, usize::MAX, 4, 0)
1069            .await
1070            .unwrap();
1071        let after_second = call_buf.lock().unwrap().len();
1072        assert_eq!(
1073            after_second, 2,
1074            "edge change must trigger one additional LLM call"
1075        );
1076    }
1077
1078    /// #1262: Communities whose fingerprints vanish are deleted on refresh.
1079    #[tokio::test]
1080    async fn test_incremental_detection_dissolved_community_deleted() {
1081        let store = setup().await;
1082        let provider = mock_provider();
1083
1084        let a = store
1085            .upsert_entity("M1", "M1", EntityType::Concept, None)
1086            .await
1087            .unwrap();
1088        let b = store
1089            .upsert_entity("M2", "M2", EntityType::Concept, None)
1090            .await
1091            .unwrap();
1092        let edge_id = store
1093            .insert_edge(a, b, "r", "M1 relates M2", 1.0, None)
1094            .await
1095            .unwrap();
1096
1097        detect_communities(&store, &provider, usize::MAX, 4, 0)
1098            .await
1099            .unwrap();
1100        assert_eq!(store.community_count().await.unwrap(), 1);
1101
1102        // Invalidate the edge — community dissolves.
1103        store.invalidate_edge(edge_id).await.unwrap();
1104
1105        detect_communities(&store, &provider, usize::MAX, 4, 0)
1106            .await
1107            .unwrap();
1108        assert_eq!(
1109            store.community_count().await.unwrap(),
1110            0,
1111            "dissolved community must be deleted on next refresh"
1112        );
1113    }
1114
1115    /// #1260: Sequential fallback (concurrency=1) produces correct results.
1116    #[tokio::test]
1117    async fn test_detect_communities_concurrency_one() {
1118        let store = setup().await;
1119        let provider = mock_provider();
1120
1121        let a = store
1122            .upsert_entity("C1A", "C1A", EntityType::Concept, None)
1123            .await
1124            .unwrap();
1125        let b = store
1126            .upsert_entity("C1B", "C1B", EntityType::Concept, None)
1127            .await
1128            .unwrap();
1129        store.insert_edge(a, b, "r", "f", 1.0, None).await.unwrap();
1130
1131        let count = detect_communities(&store, &provider, usize::MAX, 1, 0)
1132            .await
1133            .unwrap();
1134        assert_eq!(count, 1, "concurrency=1 must still detect the community");
1135        assert_eq!(store.community_count().await.unwrap(), 1);
1136    }
1137
1138    #[test]
1139    fn test_compute_fingerprint_deterministic() {
1140        let fp1 = compute_partition_fingerprint(&[1, 2, 3], &[10, 20]);
1141        let fp2 = compute_partition_fingerprint(&[3, 1, 2], &[20, 10]);
1142        assert_eq!(fp1, fp2, "fingerprint must be order-independent");
1143
1144        let fp3 = compute_partition_fingerprint(&[1, 2, 3], &[10, 30]);
1145        assert_ne!(
1146            fp1, fp3,
1147            "different edge IDs must produce different fingerprint"
1148        );
1149
1150        let fp4 = compute_partition_fingerprint(&[1, 2, 4], &[10, 20]);
1151        assert_ne!(
1152            fp1, fp4,
1153            "different entity IDs must produce different fingerprint"
1154        );
1155    }
1156
1157    /// Domain separator test: entity/edge sequences with same raw bytes must not collide.
1158    ///
1159    /// Without domain separators, entities=[1,2] edges=[3] would hash identically to
1160    /// entities=[1] edges=[2,3] (same concatenated `le_bytes`). With separators they differ.
1161    #[test]
1162    fn test_compute_fingerprint_domain_separation() {
1163        let fp_a = compute_partition_fingerprint(&[1, 2], &[3]);
1164        let fp_b = compute_partition_fingerprint(&[1], &[2, 3]);
1165        assert_ne!(
1166            fp_a, fp_b,
1167            "entity/edge sequences with same raw bytes must produce different fingerprints"
1168        );
1169    }
1170
1171    /// Chunked loading with `chunk_size=1` must produce correct community assignments.
1172    ///
1173    /// Verifies: (a) community count is correct, (b) `edge_facts_map` and `edge_id_map` are fully
1174    /// populated (checked via community membership — all edges contribute to fingerprints),
1175    /// (c) the loop executes multiple iterations by using a tiny chunk size on a 3-edge graph.
1176    #[tokio::test]
1177    async fn test_detect_communities_chunked_correct_membership() {
1178        let store = setup().await;
1179        let provider = mock_provider();
1180
1181        // Build two isolated clusters: A-B-C and D-E.
1182        let node_alpha = store
1183            .upsert_entity("CA", "CA", EntityType::Concept, None)
1184            .await
1185            .unwrap();
1186        let node_beta = store
1187            .upsert_entity("CB", "CB", EntityType::Concept, None)
1188            .await
1189            .unwrap();
1190        let node_gamma = store
1191            .upsert_entity("CC", "CC", EntityType::Concept, None)
1192            .await
1193            .unwrap();
1194        let node_delta = store
1195            .upsert_entity("CD", "CD", EntityType::Concept, None)
1196            .await
1197            .unwrap();
1198        let node_epsilon = store
1199            .upsert_entity("CE", "CE", EntityType::Concept, None)
1200            .await
1201            .unwrap();
1202
1203        store
1204            .insert_edge(node_alpha, node_beta, "r", "A-B fact", 1.0, None)
1205            .await
1206            .unwrap();
1207        store
1208            .insert_edge(node_beta, node_gamma, "r", "B-C fact", 1.0, None)
1209            .await
1210            .unwrap();
1211        store
1212            .insert_edge(node_delta, node_epsilon, "r", "D-E fact", 1.0, None)
1213            .await
1214            .unwrap();
1215
1216        // chunk_size=1: each edge is fetched individually — loop must execute 3 times.
1217        let count_chunked = detect_communities(&store, &provider, usize::MAX, 4, 1)
1218            .await
1219            .unwrap();
1220        assert_eq!(
1221            count_chunked, 2,
1222            "chunked loading must detect both communities"
1223        );
1224
1225        // Verify communities contain the correct members.
1226        let communities = store.all_communities().await.unwrap();
1227        assert_eq!(communities.len(), 2);
1228
1229        let abc_ids = [node_alpha, node_beta, node_gamma];
1230        let de_ids = [node_delta, node_epsilon];
1231        let has_abc = communities
1232            .iter()
1233            .any(|comm| abc_ids.iter().all(|id| comm.entity_ids.contains(id)));
1234        let has_de = communities
1235            .iter()
1236            .any(|comm| de_ids.iter().all(|id| comm.entity_ids.contains(id)));
1237        assert!(has_abc, "cluster A-B-C must form a community");
1238        assert!(has_de, "cluster D-E must form a community");
1239    }
1240
1241    /// `chunk_size=usize::MAX` must load all edges in a single query and produce correct results.
1242    #[tokio::test]
1243    async fn test_detect_communities_chunk_size_max() {
1244        let store = setup().await;
1245        let provider = mock_provider();
1246
1247        let x = store
1248            .upsert_entity("MX", "MX", EntityType::Concept, None)
1249            .await
1250            .unwrap();
1251        let y = store
1252            .upsert_entity("MY", "MY", EntityType::Concept, None)
1253            .await
1254            .unwrap();
1255        store
1256            .insert_edge(x, y, "r", "X-Y fact", 1.0, None)
1257            .await
1258            .unwrap();
1259
1260        let count = detect_communities(&store, &provider, usize::MAX, 4, usize::MAX)
1261            .await
1262            .unwrap();
1263        assert_eq!(count, 1, "chunk_size=usize::MAX must detect the community");
1264    }
1265
1266    /// `chunk_size=0` falls back to the stream path without panicking.
1267    #[tokio::test]
1268    async fn test_detect_communities_chunk_size_zero_fallback() {
1269        let store = setup().await;
1270        let provider = mock_provider();
1271
1272        let p = store
1273            .upsert_entity("ZP", "ZP", EntityType::Concept, None)
1274            .await
1275            .unwrap();
1276        let q = store
1277            .upsert_entity("ZQ", "ZQ", EntityType::Concept, None)
1278            .await
1279            .unwrap();
1280        store
1281            .insert_edge(p, q, "r", "P-Q fact", 1.0, None)
1282            .await
1283            .unwrap();
1284
1285        let count = detect_communities(&store, &provider, usize::MAX, 4, 0)
1286            .await
1287            .unwrap();
1288        assert_eq!(
1289            count, 1,
1290            "chunk_size=0 must detect the community via stream fallback"
1291        );
1292    }
1293
1294    /// Verifies that `edge_facts_map` is fully populated during chunked loading by checking
1295    /// that the community fingerprint changes when a new edge is added (fingerprint includes
1296    /// edge IDs, so any missed edges would produce a different or stale fingerprint).
1297    #[tokio::test]
1298    async fn test_detect_communities_chunked_edge_map_complete() {
1299        let store = setup().await;
1300        let (provider, call_buf) = recording_provider();
1301
1302        let a = store
1303            .upsert_entity("FA", "FA", EntityType::Concept, None)
1304            .await
1305            .unwrap();
1306        let b = store
1307            .upsert_entity("FB", "FB", EntityType::Concept, None)
1308            .await
1309            .unwrap();
1310        store
1311            .insert_edge(a, b, "r", "edge1 fact", 1.0, None)
1312            .await
1313            .unwrap();
1314
1315        // First detection with chunk_size=1.
1316        detect_communities(&store, &provider, usize::MAX, 4, 1)
1317            .await
1318            .unwrap();
1319        let calls_after_first = call_buf.lock().unwrap().len();
1320        assert_eq!(calls_after_first, 1, "first run must trigger 1 LLM call");
1321
1322        // Add another edge — fingerprint must change, triggering a second LLM call.
1323        store
1324            .insert_edge(b, a, "r2", "edge2 fact", 1.0, None)
1325            .await
1326            .unwrap();
1327
1328        detect_communities(&store, &provider, usize::MAX, 4, 1)
1329            .await
1330            .unwrap();
1331        let calls_after_second = call_buf.lock().unwrap().len();
1332        assert_eq!(
1333            calls_after_second, 2,
1334            "adding an edge must change fingerprint and trigger re-summarization"
1335        );
1336    }
1337}