feat(embedding): explicit OpenAI-compatible semantic channel

- add a transport client for one current backend protocol with loopback http,
  TLS-only remote endpoints, explicit remote consent, disabled redirects,
  bounded timeout/batch/payload/response/dimension and no credential in URLs
- validate responses strictly (count, index order, dimension, finite values,
  non-zero norm, mixed-model rejection) and abort publication when any vector
  is missing so a mixed index is never stored
- embed search units in the same transaction that writes the projection, with
  content-digest/model-digest guarded reuse for incremental compiles; the
  build metadata records endpoint/model/revision/dimension/distance/chunking
- add the semantic query channel behind explicit --semantic using an exact
  cosine scan with a bounded vector budget; default queries stay completely
  offline even when vectors exist
- add a local mock-server integration test proving protocol handling,
  cross-vocabulary recall, offline default behaviour, remote consent rules and
  all-or-nothing failure; real-model quality remains NOT RUN and is not claimed
This commit is contained in:
marqdo-knowledge committed 2026-11-26 02:26:37 +08:00
1 parent 514d9fbd4c
commit 87b9c132aa
20 files changed
+2882 -106

No files matched your search

+139 -44
View File
@@ -7,6 +7,7 @@
//! 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;
@@ -24,11 +25,13 @@ const MAX_BODY_GRAMS: usize = 2048;
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,
}
@@ -74,63 +77,142 @@ pub fn build_index(
graph: &Graph,
doc_ids: &HashMap<&str, i64>,
node_ids: &HashMap<&str, i64>,
) -> Result<IndexStats, rusqlite::Error> {
embeddings: Option<&crate::embedding::EmbeddingVectors>,
) -> Result<IndexStats, KnowledgeError> {
let mut stats = IndexStats::default();
let mut seen: HashSet<(String, u64)> = HashSet::new();
for facts in &graph.facts {
let Some(doc_id) = doc_ids.get(facts.rel_path.as_str()).copied() else {
for spec in unit_specs(graph) {
let Some(doc_id) = doc_ids.get(spec.doc_path.as_str()).copied() else {
continue;
};
let specs = unit_specs(facts, graph);
for spec in specs {
let Some(node_id) = node_ids.get(spec.node_key.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",
));
};
// One search unit per (node, span chunk): never duplicate text.
if !seen.insert((spec.node_key.clone(), spec.span.start)) {
continue;
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 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),
],
)?;
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)",
"INSERT INTO embeddings (search_unit_id, content_digest, model_digest, dimension, vector)
VALUES (?1, ?2, ?3, ?4, ?5)",
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),
digest,
embeddings.model_digest,
embeddings.dimension as i64,
blob,
],
)?;
stats.search_units += 1;
stats.grams += insert_grams(tx, unit_id, &spec.fields)?;
)
.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<Vec<crate::embedding::EmbeddingSource>, 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,
@@ -179,7 +261,15 @@ fn insert_grams(
/// Generate deterministic search-unit specs for one document, chunked on block
/// boundaries with a hard byte budget.
fn unit_specs(facts: &DocumentFacts, graph: &Graph) -> Vec<UnitSpec> {
fn unit_specs(graph: &Graph) -> Vec<UnitSpec> {
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<UnitSpec> {
let mut specs = Vec::new();
let node_by_key: HashMap<&str, &Node> = graph
.nodes
@@ -218,6 +308,7 @@ fn unit_specs(facts: &DocumentFacts, graph: &Graph) -> Vec<UnitSpec> {
};
specs.push(UnitSpec {
node_key,
doc_path: facts.rel_path.clone(),
span,
fields: base,
});
@@ -235,7 +326,8 @@ fn unit_specs(facts: &DocumentFacts, graph: &Graph) -> Vec<UnitSpec> {
first: bool,
specs: &mut Vec<UnitSpec>,
base: &SearchFields,
node_key: &str| {
node_key: &str,
doc_path: &str| {
if fields.byte_len() == 0 && !first {
return;
}
@@ -247,6 +339,7 @@ fn unit_specs(facts: &DocumentFacts, graph: &Graph) -> Vec<UnitSpec> {
}
specs.push(UnitSpec {
node_key: node_key.to_string(),
doc_path: doc_path.to_string(),
span: Span::new(start, end),
fields: merged,
});
@@ -263,6 +356,7 @@ fn unit_specs(facts: &DocumentFacts, graph: &Graph) -> Vec<UnitSpec> {
&mut specs,
&base,
&node_key,
&facts.rel_path,
);
first = false;
chunk_start = block.span.start;
@@ -278,6 +372,7 @@ fn unit_specs(facts: &DocumentFacts, graph: &Graph) -> Vec<UnitSpec> {
&mut specs,
&base,
&node_key,
&facts.rel_path,
);
}
let _ = node_by_key;