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:
1 parent
514d9fbd4c
commit
87b9c132aa
20 files changed
+2882
-106
No files matched your search
+166
-14
@@ -47,6 +47,7 @@ pub fn compile(args: &CompileArgs, marqdo_bin: Option<&Path>) -> Result<Output,
|
||||
"edges": outcome.stats.edges,
|
||||
"search_units": outcome.stats.search_units,
|
||||
"grams": outcome.stats.grams,
|
||||
"embeddings": outcome.stats.embeddings,
|
||||
"rebuild_generation": outcome.stats.rebuild_generation,
|
||||
"errors": outcome.diagnostics.error_count(),
|
||||
"warnings": outcome.diagnostics.warning_count(),
|
||||
@@ -96,13 +97,6 @@ fn compile_inner(
|
||||
})?)
|
||||
};
|
||||
check_launch_context(core.as_ref(), mq_entries.is_empty())?;
|
||||
if args.embedding.embedding_url.is_some() {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::EMBEDDING_UNAVAILABLE,
|
||||
"semantic indexing is not available in this build",
|
||||
)
|
||||
.with_hint("compile without embedding options for the offline index"));
|
||||
}
|
||||
|
||||
let previous_ref = previous.as_ref();
|
||||
let reuse = plan_reuse(previous_ref, &snapshot, core.as_ref());
|
||||
@@ -240,12 +234,136 @@ fn compile_inner(
|
||||
.iter()
|
||||
.map(|file| (file.rel_path.as_str(), file.text.as_str()))
|
||||
.collect();
|
||||
let graph = graph::build(facts, &sources, &snapshot.assets, &missing_paths);
|
||||
let graph = graph::build(facts, &sources, &snapshot.assets, &missing_paths, false);
|
||||
diagnostics.merge(graph.diagnostics.clone());
|
||||
if graph.diagnostics.has_errors() {
|
||||
return Err(fatal_from_diagnostics(&diagnostics));
|
||||
}
|
||||
|
||||
// Semantic index preparation (explicit opt-in only). All vectors must be
|
||||
// ready and complete before the transaction starts; any failure aborts the
|
||||
// whole compile and publishes nothing.
|
||||
let mut embedding_meta: Option<serde_json::Value> = None;
|
||||
let mut embedding_vectors: Option<crate::embedding::EmbeddingVectors> = None;
|
||||
if let Some(url) = &args.embedding.embedding_url {
|
||||
let model = args
|
||||
.embedding
|
||||
.embedding_model
|
||||
.clone()
|
||||
.ok_or_else(|| KnowledgeError::usage("--embedding-model is required"))?;
|
||||
let revision = args
|
||||
.embedding
|
||||
.embedding_revision
|
||||
.clone()
|
||||
.ok_or_else(|| KnowledgeError::usage("--embedding-revision is required"))?;
|
||||
let config = crate::embedding::EmbeddingConfig::new(
|
||||
url,
|
||||
&model,
|
||||
&revision,
|
||||
args.embedding.allow_remote_embedding,
|
||||
)?;
|
||||
let client = crate::embedding::EmbeddingClient::new(&config)?;
|
||||
let sources = storage::index::embedding_sources(&graph)?;
|
||||
if sources.is_empty() {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::EMBEDDING_UNAVAILABLE,
|
||||
"there are no search units to embed in this root",
|
||||
));
|
||||
}
|
||||
let mut reused: HashMap<String, Vec<f32>> = HashMap::new();
|
||||
let mut dimension = 0usize;
|
||||
let mut stored_digest: Option<String> = None;
|
||||
if let Some(previous) = previous_ref {
|
||||
if let Some(stored) = &previous.meta.embedding {
|
||||
let stored_endpoint = stored.get("endpoint").and_then(|value| value.as_str());
|
||||
let stored_model = stored.get("model").and_then(|value| value.as_str());
|
||||
let stored_revision = stored.get("revision").and_then(|value| value.as_str());
|
||||
if stored_endpoint == Some(client.endpoint())
|
||||
&& stored_model == Some(model.as_str())
|
||||
&& stored_revision == Some(revision.as_str())
|
||||
{
|
||||
dimension = stored
|
||||
.get("dimension")
|
||||
.and_then(|value| value.as_u64())
|
||||
.unwrap_or(0) as usize;
|
||||
stored_digest = stored
|
||||
.get("model_digest")
|
||||
.and_then(|value| value.as_str())
|
||||
.map(str::to_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
if dimension > 0 {
|
||||
let digest = config.model_digest(dimension)?;
|
||||
if stored_digest.as_deref() == Some(digest.as_str()) {
|
||||
reused = previous_ref
|
||||
.map(|previous| previous.embedding_vectors.clone())
|
||||
.unwrap_or_default();
|
||||
}
|
||||
}
|
||||
let mut vectors: HashMap<(String, u64, String), Vec<f32>> = HashMap::new();
|
||||
let mut missing: Vec<&crate::embedding::EmbeddingSource> = Vec::new();
|
||||
for source in &sources {
|
||||
match reused.get(&source.content_digest) {
|
||||
Some(vector) => {
|
||||
vectors.insert(
|
||||
(
|
||||
source.node_key.clone(),
|
||||
source.span_start,
|
||||
source.content_digest.clone(),
|
||||
),
|
||||
vector.clone(),
|
||||
);
|
||||
}
|
||||
None => missing.push(source),
|
||||
}
|
||||
}
|
||||
if !missing.is_empty() {
|
||||
let texts: Vec<String> = missing.iter().map(|source| source.text.clone()).collect();
|
||||
let (new_vectors, new_dimension) = client.embed(&texts)?;
|
||||
if dimension == 0 {
|
||||
dimension = new_dimension;
|
||||
} else if dimension != new_dimension {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::EMBEDDING_CONFIG_MISMATCH,
|
||||
"embedding model returned a different dimension than the existing index",
|
||||
));
|
||||
}
|
||||
for (source, vector) in missing.iter().zip(new_vectors) {
|
||||
vectors.insert(
|
||||
(
|
||||
source.node_key.clone(),
|
||||
source.span_start,
|
||||
source.content_digest.clone(),
|
||||
),
|
||||
vector,
|
||||
);
|
||||
}
|
||||
}
|
||||
if dimension == 0 {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::EMBEDDING_INVALID_RESPONSE,
|
||||
"embedding endpoint returned no dimension",
|
||||
));
|
||||
}
|
||||
let model_digest = config.model_digest(dimension)?;
|
||||
embedding_meta = Some(serde_json::json!(crate::embedding::EmbeddingMeta {
|
||||
endpoint: config.endpoint()?,
|
||||
model,
|
||||
revision,
|
||||
dimension,
|
||||
distance: crate::embedding::DISTANCE.to_string(),
|
||||
model_digest: model_digest.clone(),
|
||||
chunking: crate::embedding::CHUNKING.to_string(),
|
||||
max_input_chars: crate::embedding::MAX_INPUT_CHARS,
|
||||
}));
|
||||
embedding_vectors = Some(crate::embedding::EmbeddingVectors {
|
||||
model_digest,
|
||||
dimension,
|
||||
vectors,
|
||||
});
|
||||
}
|
||||
|
||||
// Source recheck immediately before publishing: never mix snapshots.
|
||||
let changed = snapshot.verify_unchanged();
|
||||
if changed.has_errors() {
|
||||
@@ -271,6 +389,11 @@ fn compile_inner(
|
||||
edges,
|
||||
search_units: previous.meta.search_units,
|
||||
grams: 0,
|
||||
embeddings: previous
|
||||
.meta
|
||||
.embedding
|
||||
.as_ref()
|
||||
.map_or(0, |_| previous.meta.search_units),
|
||||
rebuild_generation: previous.meta.rebuild_generation,
|
||||
};
|
||||
return Ok(CompileOutcome {
|
||||
@@ -300,7 +423,7 @@ fn compile_inner(
|
||||
.unwrap_or_else(|| "native-only".into());
|
||||
meta.facts_cache_version = crate::document::facts_cache_version();
|
||||
meta.rebuild_generation = generation;
|
||||
meta.embedding = None;
|
||||
meta.embedding = embedding_meta;
|
||||
if contexts.is_empty() {
|
||||
if let Some(previous) = previous_ref {
|
||||
contexts = previous.contexts.clone();
|
||||
@@ -325,6 +448,7 @@ fn compile_inner(
|
||||
graph: &graph,
|
||||
snapshot: &snapshot,
|
||||
contexts: &contexts,
|
||||
embeddings: embedding_vectors.as_ref(),
|
||||
})?;
|
||||
Ok(CompileOutcome {
|
||||
mode: stats.mode.clone(),
|
||||
@@ -406,7 +530,7 @@ pub fn check(args: &CheckArgs, marqdo_bin: Option<&Path>) -> Result<Output, Know
|
||||
.iter()
|
||||
.map(|file| (file.rel_path.as_str(), file.text.as_str()))
|
||||
.collect();
|
||||
let graph = graph::build(facts, &sources, &snapshot.assets, &missing_paths);
|
||||
let graph = graph::build(facts, &sources, &snapshot.assets, &missing_paths, args.okf);
|
||||
diagnostics.merge(graph.diagnostics.clone());
|
||||
|
||||
// OKF structural validation is a separate, explicit mode.
|
||||
@@ -455,9 +579,13 @@ pub fn check(args: &CheckArgs, marqdo_bin: Option<&Path>) -> Result<Output, Know
|
||||
}
|
||||
|
||||
diagnostics.sorted();
|
||||
let definite_broken = diagnostics
|
||||
.iter()
|
||||
.any(|diagnostic| DEFINITE_BROKEN_REFERENCE.contains(&diagnostic.code.as_str()));
|
||||
// A plain check fails on a definite broken link. In explicit OKF mode the
|
||||
// OKF conformance rules tolerate broken links (they are reported as
|
||||
// notices), so only structural/metadata errors fail the bundle check.
|
||||
let definite_broken = !args.okf
|
||||
&& diagnostics
|
||||
.iter()
|
||||
.any(|diagnostic| DEFINITE_BROKEN_REFERENCE.contains(&diagnostic.code.as_str()));
|
||||
let failed = diagnostics.has_errors() || definite_broken || database_state == "stale";
|
||||
let payload = serde_json::json!({
|
||||
"documents": snapshot.files.len(),
|
||||
@@ -510,6 +638,7 @@ struct PreviousState {
|
||||
contexts: Vec<ProjectContext>,
|
||||
inputs: HashMap<String, String>,
|
||||
cache: HashMap<String, CachedFacts>,
|
||||
embedding_vectors: HashMap<String, Vec<f32>>,
|
||||
}
|
||||
|
||||
struct PreviousMeta {
|
||||
@@ -524,6 +653,7 @@ struct PreviousMeta {
|
||||
nodes: u64,
|
||||
edges: u64,
|
||||
search_units: u64,
|
||||
embedding: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl PreviousMeta {
|
||||
@@ -560,6 +690,7 @@ fn load_previous_state(
|
||||
nodes,
|
||||
edges,
|
||||
search_units: store.search_unit_count()?,
|
||||
embedding: meta.embedding.clone(),
|
||||
},
|
||||
contexts: store.contexts()?,
|
||||
inputs: store
|
||||
@@ -568,6 +699,7 @@ fn load_previous_state(
|
||||
.map(|input| (input.path, input.digest))
|
||||
.collect(),
|
||||
cache: HashMap::new(),
|
||||
embedding_vectors: HashMap::new(),
|
||||
}));
|
||||
}
|
||||
Err(error) if error.code == code::DATABASE_OLD_SCHEMA => {
|
||||
@@ -584,10 +716,12 @@ fn load_previous_state(
|
||||
nodes: 0,
|
||||
edges: 0,
|
||||
search_units: 0,
|
||||
embedding: None,
|
||||
},
|
||||
contexts: Vec::new(),
|
||||
inputs: HashMap::new(),
|
||||
cache: HashMap::new(),
|
||||
embedding_vectors: HashMap::new(),
|
||||
}));
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
@@ -598,6 +732,15 @@ fn load_previous_state(
|
||||
let meta = store.build_meta()?;
|
||||
let (documents, nodes, edges) = store.counts()?;
|
||||
let search_units = store.search_unit_count()?;
|
||||
let embedding_vectors = match meta
|
||||
.embedding
|
||||
.as_ref()
|
||||
.and_then(|embedding| embedding.get("model_digest"))
|
||||
.and_then(|digest| digest.as_str())
|
||||
{
|
||||
Some(model_digest) => store.all_embeddings_by_digest(model_digest)?,
|
||||
None => HashMap::new(),
|
||||
};
|
||||
let mut cache = HashMap::new();
|
||||
if meta.facts_cache_version == crate::document::facts_cache_version() {
|
||||
for document in store.documents()? {
|
||||
@@ -621,6 +764,7 @@ fn load_previous_state(
|
||||
nodes,
|
||||
edges,
|
||||
search_units,
|
||||
embedding: meta.embedding.clone(),
|
||||
},
|
||||
contexts: store.contexts()?,
|
||||
inputs: store
|
||||
@@ -629,6 +773,7 @@ fn load_previous_state(
|
||||
.map(|input| (input.path, input.digest))
|
||||
.collect(),
|
||||
cache,
|
||||
embedding_vectors,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -729,7 +874,7 @@ fn fatal_from_diagnostics(diagnostics: &DiagnosticSet) -> KnowledgeError {
|
||||
// Referenced assets and known-missing paths
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn collect_assets(
|
||||
pub(crate) fn collect_assets(
|
||||
scope: &crate::document::Scope,
|
||||
snapshot: &SourceSnapshot,
|
||||
facts_by_path: &HashMap<String, DocumentFacts>,
|
||||
@@ -741,6 +886,13 @@ fn collect_assets(
|
||||
.collect();
|
||||
let mut candidates: Vec<String> = Vec::new();
|
||||
for facts in facts_by_path.values() {
|
||||
// OKF `resource` is an explicit path field and participates in the
|
||||
// snapshot as a referenced asset.
|
||||
if let Some(resource) = facts.okf.resource_is_relative_path() {
|
||||
if let Ok(rel) = discovery::resolve_link_path(&facts.rel_path, resource) {
|
||||
candidates.push(rel);
|
||||
}
|
||||
}
|
||||
for reference in &facts.references {
|
||||
if let Some(analysis) = &reference.analysis {
|
||||
let package_matches = analysis
|
||||
|
||||
Reference in new issue
Block a user