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;
+13 -3
View File
@@ -77,6 +77,7 @@ pub struct PublishStats {
pub edges: u64,
pub search_units: u64,
pub grams: u64,
pub embeddings: u64,
pub rebuild_generation: u64,
}
@@ -87,6 +88,7 @@ pub struct PublishRequest<'a> {
pub graph: &'a Graph,
pub snapshot: &'a SourceSnapshot,
pub contexts: &'a [ProjectContext],
pub embeddings: Option<&'a crate::embedding::EmbeddingVectors>,
}
/// Open a connection with the mandatory safety pragmas.
@@ -461,7 +463,7 @@ fn write_rows(
(path, format, source_digest, source, title, front_matter_json,
document_role, okf_json, analysis_context_id, module_id,
facts_json, facts_digest, facts_cache_version, diagnostic_status)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'native', NULL, ?7, ?8, ?9, ?10, ?11, ?12)",
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
rusqlite::params![
facts.rel_path,
facts.format.as_str(),
@@ -469,6 +471,8 @@ fn write_rows(
file.text.as_bytes(),
facts.document_title,
front_matter,
facts.okf.role.as_str(),
serde_json::to_string(&facts.okf).unwrap_or_else(|_| "null".into()),
facts
.analysis
.as_ref()
@@ -668,10 +672,16 @@ fn write_rows(
insert_diagnostic(transaction, diagnostic)?;
}
let index_stats = index::build_index(transaction, request.graph, &doc_ids, &node_ids)
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
let index_stats = index::build_index(
transaction,
request.graph,
&doc_ids,
&node_ids,
request.embeddings,
)?;
stats.search_units = index_stats.search_units;
stats.grams = index_stats.grams;
stats.embeddings = index_stats.embeddings;
Ok(stats)
}
+39
View File
@@ -672,6 +672,45 @@ impl ReadStore {
Ok(out)
}
/// All stored vectors for reuse during an incremental compile, keyed by the
/// embedded-text digest. Reuse is only valid for the same model digest.
pub fn all_embeddings_by_digest(
&self,
model_digest: &str,
) -> Result<HashMap<String, Vec<f32>>, KnowledgeError> {
let mut statement = self
.conn
.prepare(
"SELECT content_digest, dimension, vector FROM embeddings
WHERE model_digest = ?1 ORDER BY search_unit_id",
)
.map_err(db)?;
let rows = statement
.query_map([model_digest], |row| {
let blob: Vec<u8> = row.get(2)?;
Ok((row.get::<_, String>(0)?, blob))
})
.map_err(db)?;
let mut out = HashMap::new();
for row in rows {
let (digest, blob) = row.map_err(db)?;
if blob.len() % 4 != 0 {
continue;
}
let mut vector = Vec::with_capacity(blob.len() / 4);
for index in (0..blob.len()).step_by(4) {
vector.push(f32::from_le_bytes([
blob[index],
blob[index + 1],
blob[index + 2],
blob[index + 3],
]));
}
out.insert(digest, vector);
}
Ok(out)
}
pub fn embeddings(
&self,
model_digest: &str,
+1 -1
View File
@@ -70,7 +70,7 @@ CREATE TABLE nodes (
metadata_json TEXT NOT NULL,
CHECK ((span_start IS NULL) = (span_end IS NULL)),
CHECK (span_start IS NULL OR (span_start >= 0 AND span_end >= span_start)),
CHECK (kind = 'external' OR doc_id IS NOT NULL)
CHECK (kind IN ('external', 'resource') OR doc_id IS NOT NULL)
);
CREATE INDEX nodes_doc ON nodes(doc_id);