//! Derived search-index construction. //! //! Search units are generated only from source structure: heading scopes, //! extracted blocks, function interface metadata and front-matter metadata. //! Texts are segmented with [`crate::text`] before entering FTS5 so two-character //! Chinese queries do not depend on a trigram tokenizer. Gram rows support the //! bounded fuzzy channel. Nothing here generates facts or rewrites source. use crate::document::{BlockFact, DocumentFacts, UnitKind}; use crate::error::KnowledgeError; use crate::graph::identity; use crate::graph::{Graph, Node}; use crate::model::Span; use crate::text; use rusqlite::Transaction; use std::collections::{HashMap, HashSet}; /// Maximum source bytes in one search unit chunk. const MAX_CHUNK_BYTES: usize = 4096; /// Per-field gram caps keep the fuzzy index bounded for large documents. const MAX_GRAMS_PER_FIELD: usize = 2048; const MAX_BODY_GRAMS: usize = 2048; #[derive(Debug, Clone, Default)] pub struct IndexStats { pub search_units: u64, pub grams: u64, pub embeddings: u64, } #[derive(Debug, Clone)] struct UnitSpec { node_key: String, doc_path: String, span: Span, fields: SearchFields, } #[derive(Debug, Clone, Default)] struct SearchFields { title: String, body: String, symbols: String, metadata: String, formula: String, tabular: String, links: String, } impl SearchFields { fn append_block(&mut self, block: &BlockFact) { push_field(&mut self.body, &block.text); push_field(&mut self.formula, &block.formula); push_field(&mut self.tabular, &block.table); push_field(&mut self.links, &block.links); } fn byte_len(&self) -> usize { self.body.len() + self.formula.len() + self.tabular.len() + self.links.len() } } fn push_field(field: &mut String, value: &str) { if value.is_empty() { return; } if !field.is_empty() { field.push('\n'); } field.push_str(value); } /// Build search units and gram rows for the whole graph inside the publish /// transaction. pub fn build_index( tx: &Transaction<'_>, graph: &Graph, doc_ids: &HashMap<&str, i64>, node_ids: &HashMap<&str, i64>, embeddings: Option<&crate::embedding::EmbeddingVectors>, ) -> Result { let mut stats = IndexStats::default(); let mut seen: HashSet<(String, u64)> = HashSet::new(); for spec in unit_specs(graph) { let Some(doc_id) = doc_ids.get(spec.doc_path.as_str()).copied() else { continue; }; let Some(node_id) = node_ids.get(spec.node_key.as_str()).copied() else { continue; }; if !seen.insert((spec.node_key.clone(), spec.span.start)) { continue; } tx.execute( "INSERT INTO search_units (node_id, doc_id, span_start, span_end, title, body, symbols, metadata, formula, tabular, links) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", rusqlite::params![ node_id, doc_id, spec.span.start as i64, spec.span.end as i64, text::segment(&spec.fields.title), text::segment(&spec.fields.body), text::segment(&spec.fields.symbols), text::segment(&spec.fields.metadata), text::segment(&spec.fields.formula), text::segment(&spec.fields.tabular), text::segment(&spec.fields.links), ], ) .map_err(storage_error)?; let unit_id = tx.last_insert_rowid(); tx.execute( "INSERT INTO search_fts(rowid, title, body, symbols, metadata, formula, tabular, links) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", rusqlite::params![ unit_id, text::segment(&spec.fields.title), text::segment(&spec.fields.body), text::segment(&spec.fields.symbols), text::segment(&spec.fields.metadata), text::segment(&spec.fields.formula), text::segment(&spec.fields.tabular), text::segment(&spec.fields.links), ], ) .map_err(storage_error)?; stats.search_units += 1; stats.grams += insert_grams(tx, unit_id, &spec.fields).map_err(storage_error)?; if let Some(embeddings) = embeddings { let embedded_text = unit_embedding_text(&spec.fields); let digest = crate::embedding::embedding_content_digest(&embedded_text); let key = (spec.node_key.clone(), spec.span.start, digest.clone()); let Some(vector) = embeddings.vectors.get(&key) else { return Err(KnowledgeError::environment( crate::diagnostic::code::EMBEDDING_INVALID_RESPONSE, "missing embedding vector for a search unit; the semantic index would be incomplete", )); }; if vector.len() != embeddings.dimension { return Err(KnowledgeError::environment( crate::diagnostic::code::EMBEDDING_INVALID_RESPONSE, "embedding dimension differs from the published dimension", )); } let mut blob = Vec::with_capacity(vector.len() * 4); for value in vector { blob.extend_from_slice(&value.to_le_bytes()); } tx.execute( "INSERT INTO embeddings (search_unit_id, content_digest, model_digest, dimension, vector) VALUES (?1, ?2, ?3, ?4, ?5)", rusqlite::params![ unit_id, digest, embeddings.model_digest, embeddings.dimension as i64, blob, ], ) .map_err(storage_error)?; stats.embeddings += 1; } } if embeddings.is_some() && stats.embeddings != stats.search_units { return Err(KnowledgeError::environment( crate::diagnostic::code::EMBEDDING_INVALID_RESPONSE, "semantic index would contain missing vectors; publication was aborted", )); } Ok(stats) } fn storage_error(error: rusqlite::Error) -> KnowledgeError { KnowledgeError::environment( crate::diagnostic::code::DATABASE_CORRUPT, format!("search index write failed: {error}"), ) } /// Exact text embedded for one search unit (same function used by index and /// source planning). fn unit_embedding_text(fields: &SearchFields) -> String { crate::embedding::embedding_text(&fields.title, &fields.body, &fields.formula) } /// Plan the texts that must be embedded for this graph. pub fn embedding_sources( graph: &Graph, ) -> Result, KnowledgeError> { let mut sources = Vec::new(); for spec in unit_specs(graph) { let text = unit_embedding_text(&spec.fields); sources.push(crate::embedding::EmbeddingSource { node_key: spec.node_key, span_start: spec.span.start, content_digest: crate::embedding::embedding_content_digest(&text), text, }); } if sources.len() > crate::embedding::MAX_UNITS { return Err(KnowledgeError::environment( crate::diagnostic::code::BUDGET_EXCEEDED, format!( "{} search units exceed the {} embedding unit budget", sources.len(), crate::embedding::MAX_UNITS ), )); } Ok(sources) } fn insert_grams( tx: &Transaction<'_>, unit_id: i64, fields: &SearchFields, ) -> Result { let mut count = 0u64; let mut seen: HashSet<(String, &'static str)> = HashSet::new(); for (field_name, text_value) in [ ("title", fields.title.as_str()), ("symbols", fields.symbols.as_str()), ("metadata", fields.metadata.as_str()), ] { let mut grams = text::grams(text_value); grams.truncate(MAX_GRAMS_PER_FIELD); for gram in grams { if !seen.insert((gram.clone(), field_name)) { continue; } tx.execute( "INSERT OR IGNORE INTO grams (norm_gram, search_unit_id, field) VALUES (?1, ?2, ?3)", rusqlite::params![gram, unit_id, field_name], )?; count += 1; } } let mut body_grams: Vec = text::grams(&fields.body) .into_iter() .filter(|gram| { let chars: Vec = gram.chars().collect(); chars.len() == 2 && chars.iter().all(|ch| text::is_cjk(*ch)) }) .collect(); body_grams.truncate(MAX_BODY_GRAMS); for gram in body_grams { if !seen.insert((gram.clone(), "body")) { continue; } tx.execute( "INSERT OR IGNORE INTO grams (norm_gram, search_unit_id, field) VALUES (?1, ?2, ?3)", rusqlite::params![gram, unit_id, "body"], )?; count += 1; } Ok(count) } /// Generate deterministic search-unit specs for one document, chunked on block /// boundaries with a hard byte budget. fn unit_specs(graph: &Graph) -> Vec { let mut specs = Vec::new(); for facts in &graph.facts { specs.extend(unit_specs_for_document(facts, graph)); } specs } fn unit_specs_for_document(facts: &DocumentFacts, graph: &Graph) -> Vec { let mut specs = Vec::new(); let node_by_key: HashMap<&str, &Node> = graph .nodes .iter() .map(|node| (node.key.as_str(), node)) .collect(); let mut blocks_by_unit: HashMap> = HashMap::new(); for block in &facts.blocks { blocks_by_unit.entry(block.unit).or_default().push(block); } for (unit_index, unit) in facts.units.iter().enumerate() { let node_key = if unit_index == 0 { identity::document_key(&facts.rel_path) } else { identity::unit_key(&facts.rel_path, unit.occurrence, &unit.path) }; let node_key = node_key.as_str().to_string(); let Some(node) = node_by_key.get(node_key.as_str()) else { continue; }; if !node.is_searchable() { continue; } let base = SearchFields { title: node.title.clone(), symbols: symbols_for(facts, unit_index), metadata: metadata_for(facts, unit_index, node), ..SearchFields::default() }; let blocks = blocks_by_unit.get(&unit_index).cloned().unwrap_or_default(); if blocks.is_empty() { let span = if unit_index == 0 { Span::new(0, source_len(facts)) } else { unit.span }; specs.push(UnitSpec { node_key, doc_path: facts.rel_path.clone(), span, fields: base, }); continue; } // Chunk on block boundaries. Title/symbols/metadata are emitted only in // the first chunk so a long document cannot multiply title matches. let mut current_fields = SearchFields::default(); let mut chunk_start = blocks[0].span.start; let mut chunk_end = blocks[0].span.end; let mut first = true; let flush = |fields: SearchFields, start: u64, end: u64, first: bool, specs: &mut Vec, base: &SearchFields, node_key: &str, doc_path: &str| { if fields.byte_len() == 0 && !first { return; } let mut merged = fields; if first { merged.title = base.title.clone(); merged.symbols = base.symbols.clone(); merged.metadata = base.metadata.clone(); } specs.push(UnitSpec { node_key: node_key.to_string(), doc_path: doc_path.to_string(), span: Span::new(start, end), fields: merged, }); }; for block in blocks { let block_len = block.text.len() + block.formula.len() + block.table.len() + block.links.len(); if !first && current_fields.byte_len() + block_len > MAX_CHUNK_BYTES { flush( std::mem::take(&mut current_fields), chunk_start, chunk_end, first, &mut specs, &base, &node_key, &facts.rel_path, ); first = false; chunk_start = block.span.start; } current_fields.append_block(block); chunk_end = block.span.end; } flush( current_fields, chunk_start, chunk_end, first, &mut specs, &base, &node_key, &facts.rel_path, ); } let _ = node_by_key; specs } fn source_len(facts: &DocumentFacts) -> u64 { facts .units .first() .map(|unit| unit.span.end) .unwrap_or_else(|| facts.ast.span.end) } fn symbols_for(facts: &DocumentFacts, unit_index: usize) -> String { let mut symbols = String::new(); if facts.units[unit_index].kind == UnitKind::Function { if let Some(function) = facts .functions .iter() .find(|function| function.unit == unit_index) { push_field(&mut symbols, &function.local_name); push_field(&mut symbols, &function.function_id); if let Some(namespace) = &function.namespace { push_field(&mut symbols, namespace); } if let Some(params) = function .signature .get("params") .and_then(|params| params.as_array()) { for param in params { if let Some(name) = param.get("name").and_then(|name| name.as_str()) { push_field(&mut symbols, name); } if let Some(type_name) = param.get("type").and_then(|type_name| type_name.as_str()) { push_field(&mut symbols, type_name); } } } } } push_field(&mut symbols, &facts.units[unit_index].path.join(" ")); if let Some(unit_id) = &facts.units[unit_index].unit_id { push_field(&mut symbols, unit_id); } symbols } fn metadata_for(facts: &DocumentFacts, unit_index: usize, node: &Node) -> String { let mut metadata = String::new(); if unit_index == 0 { if let Some(front_matter) = &facts.front_matter { if let Some(value) = &front_matter.value { let mut flat = String::new(); flatten_json(value, &mut flat, 0); push_field(&mut metadata, &flat); } } } if let Some(analysis) = &facts.analysis { push_field(&mut metadata, &analysis.module_id); push_field(&mut metadata, &analysis.entry_module_id); push_field(&mut metadata, &analysis.root_id); } if let Some(signature) = node.metadata.get("signature") { if let Ok(serialized) = serde_json::to_string(signature) { push_field(&mut metadata, &serialized); } } metadata } fn flatten_json(value: &serde_json::Value, out: &mut String, depth: usize) { if depth > 8 { return; } match value { serde_json::Value::Object(object) => { for (key, value) in object { push_field(out, key); flatten_json(value, out, depth + 1); } } serde_json::Value::Array(items) => { for item in items { flatten_json(item, out, depth + 1); } } serde_json::Value::String(text) => push_field(out, text), serde_json::Value::Number(number) => push_field(out, &number.to_string()), serde_json::Value::Bool(boolean) => { push_field(out, if *boolean { "true" } else { "false" }) } serde_json::Value::Null => {} } } #[cfg(test)] mod tests { use super::*; #[test] fn field_append_keeps_lines_separate() { let mut fields = SearchFields::default(); fields.append_block(&BlockFact { kind: crate::document::BlockKind::Paragraph, span: Span::new(0, 1), unit: 0, text: "a".into(), formula: "f".into(), table: "t".into(), links: "l".into(), code: String::new(), }); fields.append_block(&BlockFact { kind: crate::document::BlockKind::Paragraph, span: Span::new(1, 2), unit: 0, text: "b".into(), formula: String::new(), table: String::new(), links: String::new(), code: String::new(), }); assert_eq!(fields.body, "a\nb"); assert_eq!(fields.formula, "f"); assert_eq!(fields.byte_len(), 6); } #[test] fn flatten_json_preserves_keys_and_scalars() { let value = serde_json::json!({"type": "Theory", "tags": ["physics"], "n": 3}); let mut out = String::new(); flatten_json(&value, &mut out, 0); assert!(out.contains("type")); assert!(out.contains("Theory")); assert!(out.contains("physics")); assert!(out.contains('3')); } }