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
|
||||
|
||||
@@ -1951,6 +1951,7 @@ fn module_to_facts(
|
||||
let mut diagnostics = DiagnosticSet::new();
|
||||
let blocks = markdown::searchable_blocks(&module.document, &units);
|
||||
let front_matter = markdown::front_matter_fact(&module.document, &mut diagnostics, &path);
|
||||
let okf = super::okf::analyze(&path, front_matter.as_ref(), &mut diagnostics);
|
||||
let document_title = document_title(&units, &module.relative_path);
|
||||
|
||||
let stdlib_digest = artifact
|
||||
@@ -1990,6 +1991,7 @@ fn module_to_facts(
|
||||
resources,
|
||||
blocks,
|
||||
front_matter,
|
||||
okf,
|
||||
analysis: Some(analysis),
|
||||
diagnostics: all,
|
||||
})
|
||||
|
||||
@@ -50,6 +50,7 @@ pub fn parse_plain(file: &SourceFile) -> DocumentFacts {
|
||||
}
|
||||
|
||||
let front_matter = front_matter_fact(&ast, &mut diagnostics, &file.rel_path);
|
||||
let okf = super::okf::analyze(&file.rel_path, front_matter.as_ref(), &mut diagnostics);
|
||||
let mut units = build_units(&ast, file);
|
||||
fix_unit_spans(&mut units, source.len() as u64);
|
||||
let anchors = build_anchors(&units);
|
||||
@@ -73,6 +74,7 @@ pub fn parse_plain(file: &SourceFile) -> DocumentFacts {
|
||||
resources: Vec::new(),
|
||||
blocks,
|
||||
front_matter,
|
||||
okf,
|
||||
analysis: None::<AnalysisFacts>,
|
||||
diagnostics,
|
||||
}
|
||||
|
||||
+4
-2
@@ -521,6 +521,9 @@ pub struct DocumentFacts {
|
||||
pub resources: Vec<ResourceFact>,
|
||||
pub blocks: Vec<BlockFact>,
|
||||
pub front_matter: Option<FrontMatterFact>,
|
||||
/// OKF document-layer recognition. Metadata never changes program semantics.
|
||||
#[serde(default)]
|
||||
pub okf: okf::OkfInfo,
|
||||
pub analysis: Option<AnalysisFacts>,
|
||||
pub diagnostics: DiagnosticSet,
|
||||
}
|
||||
@@ -558,11 +561,10 @@ impl DocumentFacts {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)] // consumed by the incremental compiler milestone
|
||||
pub(crate) fn facts_cache_version() -> u32 {
|
||||
// Bump when the serialised DocumentFacts shape or extraction semantics
|
||||
// change. The cache is derived data; a mismatch forces re-extraction.
|
||||
1
|
||||
2
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+375
-14
@@ -1,25 +1,386 @@
|
||||
//! OKF v0.3 document-layer recognition and `check --okf` validation.
|
||||
//!
|
||||
//! OKF is an optional Markdown organisation convention, not a project type and
|
||||
//! not an additional knowledge format. Recognition only reads front-matter
|
||||
//! metadata and fixed file roles; it never executes an executor/attester and
|
||||
//! never changes program semantics.
|
||||
//! not an additional knowledge format. This module only reads front-matter
|
||||
//! metadata and fixed file roles:
|
||||
//!
|
||||
//! Implemented by the OKF milestone. Until then `--okf` reports an explicit
|
||||
//! unverified diagnostic instead of pretending to validate.
|
||||
//! * a bundle is a directory of UTF-8 `.md` files;
|
||||
//! * `index.md` and `log.md` are reserved navigation/history files at every
|
||||
//! level and are never concepts, whatever front matter they carry;
|
||||
//! * every other file is a concept and needs a non-empty YAML `type`;
|
||||
//! * `title`, `description`, `tags` and `resource` are recognised when present;
|
||||
//! * unknown types, unknown keys and unknown optional fields are preserved and
|
||||
//! tolerated; no executor or attester is ever run.
|
||||
//!
|
||||
//! OKF metadata never changes program semantics. Compile always recognises the
|
||||
//! metadata; OKF *link* semantics (bundle-root absolute paths) are only applied
|
||||
//! when the user explicitly requests an OKF check.
|
||||
|
||||
use super::FrontMatterFact;
|
||||
use crate::diagnostic::{code, Diagnostic, DiagnosticSet};
|
||||
use crate::document::{DocumentFacts, SourceSnapshot};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Validate the supported OKF surface for an explicitly requested bundle.
|
||||
pub fn validate_okf(_snapshot: &SourceSnapshot, _facts: &[DocumentFacts]) -> DiagnosticSet {
|
||||
/// OKF specification version this implementation targets.
|
||||
pub const OKF_VERSION: &str = "0.3";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OkfRole {
|
||||
Native,
|
||||
Concept,
|
||||
Index,
|
||||
Log,
|
||||
}
|
||||
|
||||
impl OkfRole {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
OkfRole::Native => "native",
|
||||
OkfRole::Concept => "concept",
|
||||
OkfRole::Index => "index",
|
||||
OkfRole::Log => "log",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_reserved(self) -> bool {
|
||||
matches!(self, OkfRole::Index | OkfRole::Log)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct OkfInfo {
|
||||
pub role: OkfRole,
|
||||
/// Concept id = bundle-relative path without `.md` (never fabricated for
|
||||
/// non-concepts).
|
||||
pub concept_id: Option<String>,
|
||||
/// Free-form concept type (unregistered, never validated against a list).
|
||||
pub concept_type: Option<String>,
|
||||
pub title: Option<String>,
|
||||
pub description: Option<String>,
|
||||
pub tags: Vec<String>,
|
||||
/// `resource` value as written; only recognised as a path when it has no URL
|
||||
/// scheme. Root-absolute bundle paths are OKF-only semantics.
|
||||
pub resource: Option<String>,
|
||||
/// Full parsed front-matter object, unknown keys preserved.
|
||||
pub metadata: serde_json::Value,
|
||||
/// Root `okf_version` when present.
|
||||
pub declared_version: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for OkfInfo {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
role: OkfRole::Native,
|
||||
concept_id: None,
|
||||
concept_type: None,
|
||||
title: None,
|
||||
description: None,
|
||||
tags: Vec::new(),
|
||||
resource: None,
|
||||
metadata: serde_json::Value::Null,
|
||||
declared_version: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl OkfInfo {
|
||||
pub fn resource_is_relative_path(&self) -> Option<&str> {
|
||||
let resource = self.resource.as_deref()?;
|
||||
if resource.is_empty()
|
||||
|| resource.contains("://")
|
||||
|| resource.starts_with("//")
|
||||
|| resource.split_once(':').is_some_and(|(scheme, _)| {
|
||||
!scheme.is_empty()
|
||||
&& scheme
|
||||
.chars()
|
||||
.next()
|
||||
.is_some_and(|c| c.is_ascii_alphabetic())
|
||||
&& scheme
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
|
||||
})
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(resource)
|
||||
}
|
||||
|
||||
/// Document role used by storage.
|
||||
pub fn role(&self) -> OkfRole {
|
||||
self.role
|
||||
}
|
||||
}
|
||||
|
||||
/// Recognise OKF metadata for one document.
|
||||
pub fn analyze(
|
||||
rel_path: &str,
|
||||
front_matter: Option<&FrontMatterFact>,
|
||||
diagnostics: &mut DiagnosticSet,
|
||||
) -> OkfInfo {
|
||||
let name = rel_path.rsplit('/').next().unwrap_or(rel_path);
|
||||
let stem = name.strip_suffix(".md").unwrap_or(name);
|
||||
let mut info = OkfInfo::default();
|
||||
let value = front_matter.and_then(|front_matter| front_matter.value.clone());
|
||||
if let Some(value) = &value {
|
||||
if let Some(object) = value.as_object() {
|
||||
if let Some(version) = object.get("okf_version").and_then(|value| value.as_str()) {
|
||||
info.declared_version = Some(version.to_string());
|
||||
}
|
||||
info.concept_type = object
|
||||
.get("type")
|
||||
.and_then(|value| value.as_str())
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(str::to_string);
|
||||
info.title = object
|
||||
.get("title")
|
||||
.and_then(|value| value.as_str())
|
||||
.map(str::to_string);
|
||||
info.description = object
|
||||
.get("description")
|
||||
.and_then(|value| value.as_str())
|
||||
.map(str::to_string);
|
||||
if let Some(tags) = object.get("tags").and_then(|value| value.as_array()) {
|
||||
info.tags = tags
|
||||
.iter()
|
||||
.filter_map(|tag| tag.as_str())
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
}
|
||||
info.resource = object
|
||||
.get("resource")
|
||||
.and_then(|value| value.as_str())
|
||||
.map(str::to_string);
|
||||
info.metadata = value.clone();
|
||||
}
|
||||
}
|
||||
if stem == "index" {
|
||||
info.role = OkfRole::Index;
|
||||
return info;
|
||||
}
|
||||
if stem == "log" {
|
||||
info.role = OkfRole::Log;
|
||||
return info;
|
||||
}
|
||||
if info.concept_type.is_some() {
|
||||
info.role = OkfRole::Concept;
|
||||
info.concept_id = Some(strip_markdown_suffix(rel_path));
|
||||
if info.title.is_none() {
|
||||
info.title = None;
|
||||
}
|
||||
} else if front_matter.is_some() {
|
||||
// Front matter without a type is not a concept. The front matter layer
|
||||
// already reported parse problems; do not invent one here.
|
||||
info.role = OkfRole::Native;
|
||||
let _ = diagnostics;
|
||||
}
|
||||
info
|
||||
}
|
||||
|
||||
fn strip_markdown_suffix(rel_path: &str) -> String {
|
||||
rel_path.strip_suffix(".md").unwrap_or(rel_path).to_string()
|
||||
}
|
||||
|
||||
/// `check --okf`: validate the supported conformance surface for an explicitly
|
||||
/// requested bundle. This is not an attestation verifier: unknown types and
|
||||
/// unknown keys are accepted, broken links are reported as notices, and nothing
|
||||
/// is executed.
|
||||
pub fn validate_okf(snapshot: &SourceSnapshot, facts: &[DocumentFacts]) -> DiagnosticSet {
|
||||
let mut diagnostics = DiagnosticSet::new();
|
||||
diagnostics.push(
|
||||
Diagnostic::warning(
|
||||
code::OKF_UNVERIFIED,
|
||||
"OKF v0.3 validation is not implemented in this build; no OKF claim is made",
|
||||
)
|
||||
.with_hint("see docs/STATUS.md for the current capability matrix"),
|
||||
);
|
||||
let by_path: std::collections::HashMap<&str, &DocumentFacts> = facts
|
||||
.iter()
|
||||
.map(|fact| (fact.rel_path.as_str(), fact))
|
||||
.collect();
|
||||
for file in &snapshot.files {
|
||||
let Some(fact) = by_path.get(file.rel_path.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
let info = &fact.okf;
|
||||
match info.role {
|
||||
OkfRole::Index => {
|
||||
if let Some(front_matter) = &fact.front_matter {
|
||||
if let Some(value) = &front_matter.value {
|
||||
if let Some(object) = value.as_object() {
|
||||
let unknown: Vec<&String> = object
|
||||
.keys()
|
||||
.filter(|key| key.as_str() != "okf_version")
|
||||
.collect();
|
||||
if !unknown.is_empty() {
|
||||
diagnostics.push(
|
||||
Diagnostic::warning(
|
||||
code::OKF_UNVERIFIED,
|
||||
format!(
|
||||
"reserved index file carries extra front-matter keys ({}) ; they are preserved but not interpreted",
|
||||
unknown
|
||||
.iter()
|
||||
.map(|key| key.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
),
|
||||
)
|
||||
.with_path(&file.rel_path)
|
||||
.with_span(front_matter.span),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
OkfRole::Log => {
|
||||
// Conformance does not require date headings; only report that
|
||||
// no history semantics were interpreted.
|
||||
}
|
||||
OkfRole::Concept => {}
|
||||
OkfRole::Native => {
|
||||
// Conformance §11: every non-reserved Markdown file in a bundle
|
||||
// needs parseable YAML front matter with a non-empty type.
|
||||
match &fact.front_matter {
|
||||
None => diagnostics.push(
|
||||
Diagnostic::error(
|
||||
code::OKF_INVALID,
|
||||
format!(
|
||||
"non-reserved file `{}` has no front matter; OKF concepts require a `type`",
|
||||
file.rel_path
|
||||
),
|
||||
)
|
||||
.with_path(&file.rel_path)
|
||||
.with_hint("add YAML front matter with a non-empty `type`, or exclude the file"),
|
||||
),
|
||||
Some(front_matter) => {
|
||||
if let Some(error) = &front_matter.error {
|
||||
diagnostics.push(
|
||||
Diagnostic::error(
|
||||
code::OKF_INVALID,
|
||||
format!("front matter is not valid OKF metadata: {error}"),
|
||||
)
|
||||
.with_path(&file.rel_path)
|
||||
.with_span(front_matter.span),
|
||||
);
|
||||
} else {
|
||||
diagnostics.push(
|
||||
Diagnostic::error(
|
||||
code::OKF_INVALID,
|
||||
format!(
|
||||
"non-reserved file `{}` has no non-empty `type`",
|
||||
file.rel_path
|
||||
),
|
||||
)
|
||||
.with_path(&file.rel_path)
|
||||
.with_span(front_matter.span),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Consumers must tolerate broken links; they are notices, not errors.
|
||||
for reference in &fact.references {
|
||||
if let Some(analysis) = &reference.analysis {
|
||||
if matches!(
|
||||
analysis.state,
|
||||
crate::model::EdgeState::Missing | crate::model::EdgeState::Ambiguous
|
||||
) {
|
||||
diagnostics.push(
|
||||
Diagnostic::warning(
|
||||
code::OKF_UNVERIFIED,
|
||||
format!("bundle link `{}` could not be verified", reference.url),
|
||||
)
|
||||
.with_path(&file.rel_path)
|
||||
.with_span(reference.span),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
diagnostics.sorted();
|
||||
diagnostics
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::document::FrontMatterFact;
|
||||
use crate::model::Span;
|
||||
|
||||
fn front(value: serde_json::Value) -> FrontMatterFact {
|
||||
FrontMatterFact {
|
||||
span: Span::new(0, 1),
|
||||
literal: String::new(),
|
||||
value: Some(value),
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_document_is_a_concept_with_preserved_metadata() {
|
||||
let mut diagnostics = DiagnosticSet::new();
|
||||
let info = analyze(
|
||||
"physics/mechanics.md",
|
||||
Some(&front(serde_json::json!({
|
||||
"type": "Theory",
|
||||
"title": "经典力学",
|
||||
"tags": ["physics", "mechanics"],
|
||||
"custom": {"a": 1}
|
||||
}))),
|
||||
&mut diagnostics,
|
||||
);
|
||||
assert_eq!(info.role, OkfRole::Concept);
|
||||
assert_eq!(info.concept_id.as_deref(), Some("physics/mechanics"));
|
||||
assert_eq!(info.concept_type.as_deref(), Some("Theory"));
|
||||
assert_eq!(info.tags, vec!["physics", "mechanics"]);
|
||||
assert_eq!(info.metadata["custom"]["a"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_files_are_never_concepts() {
|
||||
let mut diagnostics = DiagnosticSet::new();
|
||||
let value = front(serde_json::json!({"type": "Index"}));
|
||||
assert_eq!(
|
||||
analyze("index.md", Some(&value), &mut diagnostics).role,
|
||||
OkfRole::Index
|
||||
);
|
||||
assert_eq!(
|
||||
analyze("a/b/log.md", Some(&value), &mut diagnostics).role,
|
||||
OkfRole::Log
|
||||
);
|
||||
let info = analyze("a/b/index.md", Some(&value), &mut diagnostics);
|
||||
assert!(info.concept_id.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn untyped_document_stays_native() {
|
||||
let mut diagnostics = DiagnosticSet::new();
|
||||
let info = analyze(
|
||||
"notes.md",
|
||||
Some(&front(serde_json::json!({"title": "notes"}))),
|
||||
&mut diagnostics,
|
||||
);
|
||||
assert_eq!(info.role, OkfRole::Native);
|
||||
assert!(info.concept_id.is_none());
|
||||
assert!(analyze("plain.md", None, &mut diagnostics).role == OkfRole::Native);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_paths_are_separated_from_urls() {
|
||||
let mut diagnostics = DiagnosticSet::new();
|
||||
let info = analyze(
|
||||
"a.md",
|
||||
Some(&front(serde_json::json!({
|
||||
"type": "Dataset",
|
||||
"resource": "../data/table.csv"
|
||||
}))),
|
||||
&mut diagnostics,
|
||||
);
|
||||
assert_eq!(info.resource_is_relative_path(), Some("../data/table.csv"));
|
||||
let info = analyze(
|
||||
"a.md",
|
||||
Some(&front(serde_json::json!({
|
||||
"type": "Dataset",
|
||||
"resource": "https://example.com/x.csv"
|
||||
}))),
|
||||
&mut diagnostics,
|
||||
);
|
||||
assert_eq!(info.resource_is_relative_path(), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
//! OpenAI-compatible embeddings transport (one current backend protocol).
|
||||
//!
|
||||
//! Semantic indexing is explicit. The client sends only the selected snippets
|
||||
//! and the query, never the workspace, paths or unrelated metadata. The API key
|
||||
//! comes from the environment and is never stored, logged or printed.
|
||||
//!
|
||||
//! Safety rules:
|
||||
//! * no implicit network: construction only validates configuration;
|
||||
//! * remote endpoints require explicit consent, HTTPS and disabled redirects;
|
||||
//! * loopback HTTP is allowed for a locally deployed compatible service;
|
||||
//! * bounded timeout, batch size, response size and dimension;
|
||||
//! * strict response validation: count, order, dimension, finite values and
|
||||
//! non-zero norm; mixed models/dimensions are rejected.
|
||||
|
||||
use crate::error::KnowledgeError;
|
||||
use crate::model::sha256_prefixed;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
|
||||
pub const API_KEY_ENV: &str = "MARQDO_KNOWLEDGE_EMBEDDING_API_KEY";
|
||||
pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
pub const MAX_BATCH: usize = 64;
|
||||
pub const MAX_UNITS: usize = 20_000;
|
||||
pub const MAX_DIMENSION: usize = 8_192;
|
||||
pub const MAX_RESPONSE_BYTES: usize = 64 * 1024 * 1024;
|
||||
pub const MAX_INPUT_CHARS: usize = 2_000;
|
||||
pub const MAX_ATTEMPTS: usize = 2;
|
||||
pub const DISTANCE: &str = "cosine";
|
||||
pub const CHUNKING: &str = "search_unit_title_body";
|
||||
|
||||
/// User-supplied embedding options.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EmbeddingConfig {
|
||||
endpoint: String,
|
||||
model: String,
|
||||
revision: String,
|
||||
allow_remote: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct UrlParts {
|
||||
scheme: String,
|
||||
host: String,
|
||||
port: Option<u16>,
|
||||
path: String,
|
||||
}
|
||||
|
||||
impl EmbeddingConfig {
|
||||
pub fn new(
|
||||
url: &str,
|
||||
model: &str,
|
||||
revision: &str,
|
||||
allow_remote: bool,
|
||||
) -> Result<Self, KnowledgeError> {
|
||||
let config = Self {
|
||||
endpoint: url.trim().to_string(),
|
||||
model: model.trim().to_string(),
|
||||
revision: revision.trim().to_string(),
|
||||
allow_remote,
|
||||
};
|
||||
config.validate()?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub fn model(&self) -> &str {
|
||||
&self.model
|
||||
}
|
||||
|
||||
pub fn revision(&self) -> &str {
|
||||
&self.revision
|
||||
}
|
||||
|
||||
/// Sanitised endpoint without credentials, query or fragment.
|
||||
pub fn endpoint(&self) -> Result<String, KnowledgeError> {
|
||||
let parts = parse_url(&self.endpoint)?;
|
||||
Ok(format!(
|
||||
"{}://{}{}{}",
|
||||
parts.scheme,
|
||||
parts.host,
|
||||
parts
|
||||
.port
|
||||
.map(|port| format!(":{port}"))
|
||||
.unwrap_or_default(),
|
||||
parts.path
|
||||
))
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<(), KnowledgeError> {
|
||||
if self.model.is_empty() || self.revision.is_empty() {
|
||||
return Err(KnowledgeError::usage(
|
||||
"embedding model and revision must not be empty",
|
||||
));
|
||||
}
|
||||
let parts = parse_url(&self.endpoint)?;
|
||||
let loopback = is_loopback(&parts.host);
|
||||
if !loopback {
|
||||
if parts.scheme != "https" {
|
||||
return Err(KnowledgeError::environment(
|
||||
crate::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED,
|
||||
"remote embeddings require TLS (https); plain http is only allowed for loopback services",
|
||||
));
|
||||
}
|
||||
if !self.allow_remote {
|
||||
return Err(KnowledgeError::environment(
|
||||
crate::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED,
|
||||
"remote embeddings require explicit --allow-remote-embedding consent",
|
||||
)
|
||||
.with_hint("the query/index content would leave this machine"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stable digest of the index configuration (never includes the API key).
|
||||
pub fn model_digest(&self, dimension: usize) -> Result<String, KnowledgeError> {
|
||||
let endpoint = self.endpoint()?;
|
||||
let canonical = format!(
|
||||
"endpoint={endpoint}|model={}|revision={}|dimension={dimension}|distance={DISTANCE}|chunking={CHUNKING}",
|
||||
self.model, self.revision
|
||||
);
|
||||
Ok(sha256_prefixed(canonical.as_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_url(url: &str) -> Result<UrlParts, KnowledgeError> {
|
||||
let Some(scheme_end) = url.find("://") else {
|
||||
return Err(KnowledgeError::usage(
|
||||
"embedding endpoint must be an absolute http(s) URL",
|
||||
));
|
||||
};
|
||||
let scheme = url[..scheme_end].to_ascii_lowercase();
|
||||
if scheme != "http" && scheme != "https" {
|
||||
return Err(KnowledgeError::usage(
|
||||
"embedding endpoint scheme must be http or https",
|
||||
));
|
||||
}
|
||||
if url.contains('?') || url.contains('#') {
|
||||
return Err(KnowledgeError::usage(
|
||||
"embedding endpoint must not contain a query or fragment",
|
||||
));
|
||||
}
|
||||
let rest = &url[scheme_end + 3..];
|
||||
let (authority, path) = match rest.split_once('/') {
|
||||
Some((authority, path)) => (authority, format!("/{path}")),
|
||||
None => (rest, "/".to_string()),
|
||||
};
|
||||
if authority.is_empty() {
|
||||
return Err(KnowledgeError::usage("embedding endpoint has no host"));
|
||||
}
|
||||
if authority.contains('@') {
|
||||
return Err(KnowledgeError::usage(
|
||||
"credentials must not be embedded in the embedding endpoint URL",
|
||||
));
|
||||
}
|
||||
let (host, port) = if let Some(stripped) = authority.strip_prefix('[') {
|
||||
// IPv6 literal.
|
||||
let Some((host, rest)) = stripped.split_once(']') else {
|
||||
return Err(KnowledgeError::usage(
|
||||
"invalid IPv6 host in embedding endpoint",
|
||||
));
|
||||
};
|
||||
let port = match rest.strip_prefix(':') {
|
||||
Some(port) => Some(
|
||||
port.parse::<u16>()
|
||||
.map_err(|_| KnowledgeError::usage("invalid embedding endpoint port"))?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
(format!("[{host}]"), port)
|
||||
} else {
|
||||
match authority.rsplit_once(':') {
|
||||
Some((host, port)) if !host.contains(':') => (
|
||||
host.to_string(),
|
||||
Some(
|
||||
port.parse::<u16>()
|
||||
.map_err(|_| KnowledgeError::usage("invalid embedding endpoint port"))?,
|
||||
),
|
||||
),
|
||||
_ => (authority.to_string(), None),
|
||||
}
|
||||
};
|
||||
if host.is_empty() {
|
||||
return Err(KnowledgeError::usage("embedding endpoint has no host"));
|
||||
}
|
||||
Ok(UrlParts {
|
||||
scheme,
|
||||
host,
|
||||
port,
|
||||
path,
|
||||
})
|
||||
}
|
||||
|
||||
fn is_loopback(host: &str) -> bool {
|
||||
let host = host.trim_start_matches('[').trim_end_matches(']');
|
||||
matches!(host, "127.0.0.1" | "::1" | "localhost") || host.starts_with("127.")
|
||||
}
|
||||
|
||||
/// Index configuration persisted in build metadata.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct EmbeddingMeta {
|
||||
pub endpoint: String,
|
||||
pub model: String,
|
||||
pub revision: String,
|
||||
pub dimension: usize,
|
||||
pub distance: String,
|
||||
pub model_digest: String,
|
||||
pub chunking: String,
|
||||
pub max_input_chars: usize,
|
||||
}
|
||||
|
||||
/// Precomputed vectors for the publish transaction.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EmbeddingVectors {
|
||||
pub model_digest: String,
|
||||
pub dimension: usize,
|
||||
/// (node canonical key, unit span start, embedded-text digest) -> vector.
|
||||
pub vectors: std::collections::HashMap<(String, u64, String), Vec<f32>>,
|
||||
}
|
||||
|
||||
/// One text that must be embedded, keyed by its search-unit identity.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EmbeddingSource {
|
||||
pub node_key: String,
|
||||
pub span_start: u64,
|
||||
pub content_digest: String,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// Build the exact text used for chunk embeddings. Deterministic and bounded.
|
||||
pub fn embedding_text(title: &str, body: &str, formula: &str) -> String {
|
||||
let mut text = String::new();
|
||||
if !title.is_empty() {
|
||||
text.push_str(title);
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(body);
|
||||
if !formula.is_empty() {
|
||||
text.push('\n');
|
||||
text.push_str(formula);
|
||||
}
|
||||
let mut end = text.len().min(MAX_INPUT_CHARS * 4);
|
||||
while end > 0 && !text.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
text.truncate(end);
|
||||
text
|
||||
}
|
||||
|
||||
/// Digest of the exact embedded text, used for reuse and invalidation.
|
||||
pub fn embedding_content_digest(text: &str) -> String {
|
||||
sha256_prefixed(text.as_bytes())
|
||||
}
|
||||
|
||||
pub struct EmbeddingClient {
|
||||
agent: ureq::Agent,
|
||||
url: String,
|
||||
model: String,
|
||||
api_key: Option<String>,
|
||||
}
|
||||
|
||||
impl EmbeddingClient {
|
||||
pub fn new(config: &EmbeddingConfig) -> Result<Self, KnowledgeError> {
|
||||
config.validate()?;
|
||||
let url = config.endpoint()?;
|
||||
let agent_config = ureq::Agent::config_builder()
|
||||
.timeout_global(Some(REQUEST_TIMEOUT))
|
||||
.max_redirects(0)
|
||||
.build();
|
||||
let agent: ureq::Agent = agent_config.into();
|
||||
Ok(Self {
|
||||
agent,
|
||||
url,
|
||||
model: config.model.clone(),
|
||||
api_key: std::env::var(API_KEY_ENV)
|
||||
.ok()
|
||||
.filter(|key| !key.is_empty()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn endpoint(&self) -> &str {
|
||||
&self.url
|
||||
}
|
||||
|
||||
/// Embed bounded batches. Every batch is validated before being accepted.
|
||||
pub fn embed(&self, inputs: &[String]) -> Result<(Vec<Vec<f32>>, usize), KnowledgeError> {
|
||||
if inputs.is_empty() {
|
||||
return Err(KnowledgeError::environment(
|
||||
crate::diagnostic::code::EMBEDDING_UNAVAILABLE,
|
||||
"no search units to embed",
|
||||
));
|
||||
}
|
||||
if inputs.len() > MAX_UNITS {
|
||||
return Err(KnowledgeError::environment(
|
||||
crate::diagnostic::code::BUDGET_EXCEEDED,
|
||||
format!(
|
||||
"{} embedding inputs exceed the {MAX_UNITS} unit budget",
|
||||
inputs.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let mut vectors = Vec::with_capacity(inputs.len());
|
||||
let mut dimension = 0usize;
|
||||
for batch in inputs.chunks(MAX_BATCH) {
|
||||
let batch_vectors = self.embed_batch(batch)?;
|
||||
for vector in batch_vectors {
|
||||
if dimension == 0 {
|
||||
dimension = vector.len();
|
||||
} else if vector.len() != dimension {
|
||||
return Err(invalid_response(
|
||||
"embedding dimension changed between batches",
|
||||
));
|
||||
}
|
||||
vectors.push(vector);
|
||||
}
|
||||
}
|
||||
Ok((vectors, dimension))
|
||||
}
|
||||
|
||||
fn embed_batch(&self, inputs: &[String]) -> Result<Vec<Vec<f32>>, KnowledgeError> {
|
||||
let payload = serde_json::json!({"model": self.model, "input": inputs});
|
||||
let mut last_error = None;
|
||||
for attempt in 0..MAX_ATTEMPTS {
|
||||
match self.send(&payload) {
|
||||
Ok(response) => return validate_response(response, inputs.len()),
|
||||
Err(error)
|
||||
if error.code == crate::diagnostic::code::EMBEDDING_TRANSPORT
|
||||
&& attempt + 1 < MAX_ATTEMPTS =>
|
||||
{
|
||||
last_error = Some(error);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Err(last_error
|
||||
.unwrap_or_else(|| invalid_response("embedding request failed without a response")))
|
||||
}
|
||||
|
||||
fn send(&self, payload: &serde_json::Value) -> Result<serde_json::Value, KnowledgeError> {
|
||||
if payload.to_string().len() > MAX_RESPONSE_BYTES {
|
||||
return Err(KnowledgeError::environment(
|
||||
crate::diagnostic::code::BUDGET_EXCEEDED,
|
||||
"embedding request payload exceeds the size budget",
|
||||
));
|
||||
}
|
||||
let mut request = self
|
||||
.agent
|
||||
.post(&self.url)
|
||||
.header("content-type", "application/json");
|
||||
if let Some(key) = &self.api_key {
|
||||
request = request.header("authorization", format!("Bearer {key}"));
|
||||
}
|
||||
let mut response = request.send_json(payload).map_err(|error| {
|
||||
KnowledgeError::environment(
|
||||
crate::diagnostic::code::EMBEDDING_TRANSPORT,
|
||||
format!("embedding endpoint request failed: {error}"),
|
||||
)
|
||||
})?;
|
||||
let body = response.body_mut().read_to_string().map_err(|error| {
|
||||
KnowledgeError::environment(
|
||||
crate::diagnostic::code::EMBEDDING_TRANSPORT,
|
||||
format!("embedding response could not be read: {error}"),
|
||||
)
|
||||
})?;
|
||||
if body.len() > MAX_RESPONSE_BYTES {
|
||||
return Err(KnowledgeError::environment(
|
||||
crate::diagnostic::code::BUDGET_EXCEEDED,
|
||||
"embedding response exceeds the size budget",
|
||||
));
|
||||
}
|
||||
serde_json::from_str(&body).map_err(|error| {
|
||||
invalid_response(&format!("embedding response is not valid JSON: {error}"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid_response(message: &str) -> KnowledgeError {
|
||||
KnowledgeError::environment(
|
||||
crate::diagnostic::code::EMBEDDING_INVALID_RESPONSE,
|
||||
message.to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
fn validate_response(
|
||||
response: serde_json::Value,
|
||||
expected: usize,
|
||||
) -> Result<Vec<Vec<f32>>, KnowledgeError> {
|
||||
let Some(data) = response.get("data").and_then(|data| data.as_array()) else {
|
||||
return Err(invalid_response("embedding response has no `data` array"));
|
||||
};
|
||||
if data.len() != expected {
|
||||
return Err(invalid_response(&format!(
|
||||
"embedding response returned {} vector(s) for {expected} input(s)",
|
||||
data.len()
|
||||
)));
|
||||
}
|
||||
let mut vectors: Vec<Option<Vec<f32>>> = vec![None; expected];
|
||||
for item in data {
|
||||
let index = item
|
||||
.get("index")
|
||||
.and_then(|index| index.as_u64())
|
||||
.ok_or_else(|| invalid_response("embedding item has no integer `index`"))?
|
||||
as usize;
|
||||
if index >= expected {
|
||||
return Err(invalid_response("embedding item index is out of range"));
|
||||
}
|
||||
if vectors[index].is_some() {
|
||||
return Err(invalid_response("embedding response repeats an item index"));
|
||||
}
|
||||
let embedding = item
|
||||
.get("embedding")
|
||||
.and_then(|embedding| embedding.as_array())
|
||||
.ok_or_else(|| invalid_response("embedding item has no vector"))?;
|
||||
if embedding.is_empty() || embedding.len() > MAX_DIMENSION {
|
||||
return Err(invalid_response(
|
||||
"embedding dimension is empty or too large",
|
||||
));
|
||||
}
|
||||
let mut vector = Vec::with_capacity(embedding.len());
|
||||
let mut norm_squared = 0.0f64;
|
||||
for value in embedding {
|
||||
let value = value
|
||||
.as_f64()
|
||||
.ok_or_else(|| invalid_response("embedding value is not a finite number"))?;
|
||||
if !value.is_finite() {
|
||||
return Err(invalid_response("embedding value is not finite"));
|
||||
}
|
||||
vector.push(value as f32);
|
||||
norm_squared += value * value;
|
||||
}
|
||||
if norm_squared <= 1e-12 {
|
||||
return Err(invalid_response("embedding vector has zero norm"));
|
||||
}
|
||||
vectors[index] = Some(vector);
|
||||
}
|
||||
let mut out = Vec::with_capacity(expected);
|
||||
for vector in vectors {
|
||||
out.push(vector.ok_or_else(|| invalid_response("embedding response is missing an item"))?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Cosine similarity of two equal-length vectors. Returns `None` for invalid
|
||||
/// input; the caller never compares different dimensions.
|
||||
pub fn cosine(left: &[f32], right: &[f32]) -> Option<f64> {
|
||||
if left.len() != right.len() || left.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut dot = 0.0f64;
|
||||
let mut left_norm = 0.0f64;
|
||||
let mut right_norm = 0.0f64;
|
||||
for (a, b) in left.iter().zip(right.iter()) {
|
||||
let a = f64::from(*a);
|
||||
let b = f64::from(*b);
|
||||
if !a.is_finite() || !b.is_finite() {
|
||||
return None;
|
||||
}
|
||||
dot += a * b;
|
||||
left_norm += a * a;
|
||||
right_norm += b * b;
|
||||
}
|
||||
if left_norm <= 0.0 || right_norm <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
Some(dot / (left_norm.sqrt() * right_norm.sqrt()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn loopback_http_is_allowed_but_remote_http_is_not() {
|
||||
assert!(EmbeddingConfig::new("http://127.0.0.1:8080/v1", "m", "r", false).is_ok());
|
||||
assert!(EmbeddingConfig::new("http://localhost:8080/v1", "m", "r", false).is_ok());
|
||||
let error = EmbeddingConfig::new("http://example.com/v1", "m", "r", true).unwrap_err();
|
||||
assert_eq!(
|
||||
error.code,
|
||||
crate::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED
|
||||
);
|
||||
let error = EmbeddingConfig::new("https://example.com/v1", "m", "r", false).unwrap_err();
|
||||
assert_eq!(
|
||||
error.code,
|
||||
crate::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED
|
||||
);
|
||||
let error = EmbeddingConfig::new("https://example.com/v1?x=1", "m", "r", true).unwrap_err();
|
||||
assert!(error.message.contains("query") || error.message.contains("fragment"));
|
||||
assert!(EmbeddingConfig::new("https://user:pass@example.com/v1", "m", "r", true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_digest_is_stable_and_excludes_secrets() {
|
||||
let config =
|
||||
EmbeddingConfig::new("http://127.0.0.1:8080/v1/", "model", "r1", false).unwrap();
|
||||
let first = config.model_digest(3).unwrap();
|
||||
let second = config.model_digest(3).unwrap();
|
||||
assert_eq!(first, second);
|
||||
assert!(first.starts_with("sha256:"));
|
||||
let other = config.model_digest(4).unwrap();
|
||||
assert_ne!(first, other);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_validation_rejects_bad_shapes() {
|
||||
let good = serde_json::json!({"data": [
|
||||
{"index": 0, "embedding": [1.0, 0.0]},
|
||||
{"index": 1, "embedding": [0.0, 1.0]}
|
||||
]});
|
||||
assert_eq!(validate_response(good, 2).unwrap().len(), 2);
|
||||
let wrong_count = serde_json::json!({"data": [{"index": 0, "embedding": [1.0]}]});
|
||||
assert!(validate_response(wrong_count, 2).is_err());
|
||||
let zero = serde_json::json!({"data": [{"index": 0, "embedding": [0.0, 0.0]}]});
|
||||
assert!(validate_response(zero, 1).is_err());
|
||||
let duplicate = serde_json::json!({"data": [
|
||||
{"index": 0, "embedding": [1.0]},
|
||||
{"index": 0, "embedding": [1.0]}
|
||||
]});
|
||||
assert!(validate_response(duplicate, 2).is_err());
|
||||
let huge = serde_json::json!({"data": [{"index": 0, "embedding": [1e300]}]});
|
||||
assert!(validate_response(huge, 1).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cosine_is_bounded_and_rejects_mismatch() {
|
||||
assert!(cosine(&[1.0, 0.0], &[1.0, 0.0]).unwrap() > 0.999);
|
||||
assert!(cosine(&[1.0, 0.0], &[0.0, 1.0]).unwrap() < 0.001);
|
||||
assert!(cosine(&[1.0], &[1.0, 2.0]).is_none());
|
||||
assert!(cosine(&[0.0, 0.0], &[1.0, 0.0]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedding_text_is_bounded_on_char_boundaries() {
|
||||
let long = "量子".repeat(10_000);
|
||||
let text = embedding_text("title", &long, "F=ma");
|
||||
assert!(text.len() <= MAX_INPUT_CHARS * 4);
|
||||
assert!(std::str::from_utf8(text.as_bytes()).is_ok());
|
||||
assert_eq!(embedding_content_digest("abc"), sha256_prefixed(b"abc"));
|
||||
}
|
||||
}
|
||||
+19
-8
@@ -138,6 +138,7 @@ pub fn build(
|
||||
sources: &HashMap<&str, &str>,
|
||||
assets: &[AssetFile],
|
||||
missing_paths: &std::collections::HashSet<String>,
|
||||
okf_mode: bool,
|
||||
) -> Graph {
|
||||
let mut diagnostics = DiagnosticSet::new();
|
||||
for document in &facts {
|
||||
@@ -188,6 +189,7 @@ pub fn build(
|
||||
metadata: serde_json::json!({
|
||||
"format": document.format.as_str(),
|
||||
"title": document.document_title,
|
||||
"okf": serde_json::to_value(&document.okf).unwrap_or(serde_json::Value::Null),
|
||||
"analysis": document.analysis.as_ref().map(|analysis| serde_json::json!({
|
||||
"module_id": analysis.module_id,
|
||||
"context_id": analysis.context_id,
|
||||
@@ -389,6 +391,15 @@ pub fn build(
|
||||
});
|
||||
}
|
||||
|
||||
// OKF concept identity maps to this document node; never a second node.
|
||||
if let Some(concept_id) = &document.okf.concept_id {
|
||||
aliases.push(AliasRecord {
|
||||
alias: concept_id.clone(),
|
||||
context: None,
|
||||
node: doc_key.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
// Aliases for upstream identities.
|
||||
if let Some(analysis) = &document.analysis {
|
||||
aliases.push(AliasRecord {
|
||||
@@ -446,7 +457,7 @@ pub fn build(
|
||||
}
|
||||
|
||||
// Reference, import and call edges.
|
||||
let resolver = resolve::Resolver::new(&facts, assets, missing_paths);
|
||||
let resolver = resolve::Resolver::new(&facts, assets, missing_paths, okf_mode);
|
||||
let (external_nodes, resolved_edges, resolution_diagnostics) = resolver.resolve_all();
|
||||
diagnostics.merge(resolution_diagnostics);
|
||||
for node in external_nodes {
|
||||
@@ -650,7 +661,7 @@ mod tests {
|
||||
let (text, facts) = plain_facts("# A\n\n## B\n\ntext\n");
|
||||
let mut sources: HashMap<&str, &str> = HashMap::new();
|
||||
sources.insert("doc.md", text.as_str());
|
||||
let graph = build(facts, &sources, &[], &Default::default());
|
||||
let graph = build(facts, &sources, &[], &Default::default(), false);
|
||||
assert_eq!(
|
||||
graph
|
||||
.nodes
|
||||
@@ -694,7 +705,7 @@ mod tests {
|
||||
size: 3,
|
||||
digest: Some("sha256:abc".into()),
|
||||
}];
|
||||
let graph = build(facts, &sources, &assets, &Default::default());
|
||||
let graph = build(facts, &sources, &assets, &Default::default(), false);
|
||||
assert!(!graph.diagnostics.has_errors());
|
||||
let states: Vec<EdgeState> = graph
|
||||
.edges
|
||||
@@ -721,7 +732,7 @@ mod tests {
|
||||
let (text, facts) = plain_facts("# t\n\n[a](#t) [a](#t)\n");
|
||||
let mut sources: HashMap<&str, &str> = HashMap::new();
|
||||
sources.insert("doc.md", text.as_str());
|
||||
let graph = build(facts, &sources, &[], &Default::default());
|
||||
let graph = build(facts, &sources, &[], &Default::default(), false);
|
||||
let references: Vec<_> = graph
|
||||
.edges
|
||||
.iter()
|
||||
@@ -736,7 +747,7 @@ mod tests {
|
||||
let (text, facts) = plain_facts("# t\n\n## dup\n\na\n\n## dup\n\nb\n\n[x](#dup-1)\n");
|
||||
let mut sources: HashMap<&str, &str> = HashMap::new();
|
||||
sources.insert("doc.md", text.as_str());
|
||||
let graph = build(facts, &sources, &[], &Default::default());
|
||||
let graph = build(facts, &sources, &[], &Default::default(), false);
|
||||
let edge = graph
|
||||
.edges
|
||||
.iter()
|
||||
@@ -761,7 +772,7 @@ mod tests {
|
||||
}
|
||||
let mut sources: HashMap<&str, &str> = HashMap::new();
|
||||
sources.insert("doc.md", text.as_str());
|
||||
let graph = build(facts, &sources, &[], &Default::default());
|
||||
let graph = build(facts, &sources, &[], &Default::default(), false);
|
||||
let state = graph
|
||||
.edges
|
||||
.iter()
|
||||
@@ -779,11 +790,11 @@ mod tests {
|
||||
let (text, facts) = plain_facts("# A\n\ntext\n");
|
||||
let mut sources: HashMap<&str, &str> = HashMap::new();
|
||||
sources.insert("doc.md", text.as_str());
|
||||
let first = build(facts, &sources, &[], &Default::default()).logical_digest();
|
||||
let first = build(facts, &sources, &[], &Default::default(), false).logical_digest();
|
||||
let (text, facts) = plain_facts("# A\n\ntext\n");
|
||||
let mut sources: HashMap<&str, &str> = HashMap::new();
|
||||
sources.insert("doc.md", text.as_str());
|
||||
let second = build(facts, &sources, &[], &Default::default()).logical_digest();
|
||||
let second = build(facts, &sources, &[], &Default::default(), false).logical_digest();
|
||||
assert_eq!(first, second);
|
||||
}
|
||||
}
|
||||
@@ -186,6 +186,7 @@ enum FragmentLookup {
|
||||
}
|
||||
|
||||
pub struct Resolver<'a> {
|
||||
okf_mode: bool,
|
||||
facts: &'a [DocumentFacts],
|
||||
docs: HashMap<&'a str, &'a DocumentFacts>,
|
||||
modules: HashMap<&'a str, &'a str>,
|
||||
@@ -208,6 +209,7 @@ impl<'a> Resolver<'a> {
|
||||
facts: &'a [DocumentFacts],
|
||||
assets: &'a [AssetFile],
|
||||
missing_paths: &'a HashSet<String>,
|
||||
okf_mode: bool,
|
||||
) -> Self {
|
||||
let mut docs = HashMap::new();
|
||||
let mut modules = HashMap::new();
|
||||
@@ -256,6 +258,7 @@ impl<'a> Resolver<'a> {
|
||||
.map(|asset| (asset.rel_path.as_str(), asset))
|
||||
.collect();
|
||||
Self {
|
||||
okf_mode,
|
||||
facts,
|
||||
docs,
|
||||
modules,
|
||||
@@ -294,6 +297,7 @@ impl<'a> Resolver<'a> {
|
||||
for call in &fact.calls {
|
||||
self.resolve_call(fact, call, context.as_deref());
|
||||
}
|
||||
self.resolve_okf_resource(fact, context.as_deref());
|
||||
}
|
||||
let mut diagnostics = std::mem::take(&mut self.diagnostics);
|
||||
diagnostics.sorted();
|
||||
@@ -554,6 +558,90 @@ impl<'a> Resolver<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// OKF bundle-root absolute link (`/path.md`): a logical path inside the
|
||||
/// explicitly requested bundle, never an OS absolute path.
|
||||
fn resolve_okf_root_relative(
|
||||
&mut self,
|
||||
fact: &DocumentFacts,
|
||||
url: &str,
|
||||
span: Span,
|
||||
) -> ResolvedTarget {
|
||||
let rest = url.trim_start_matches('/');
|
||||
let (raw_path, raw_fragment) = match rest.split_once('#') {
|
||||
Some((path, fragment)) => (path, Some(fragment)),
|
||||
None => (rest, None),
|
||||
};
|
||||
let decode = |value: &str| -> Option<String> {
|
||||
let bytes = crate::model::percent_decode(value.as_bytes())?;
|
||||
String::from_utf8(bytes).ok()
|
||||
};
|
||||
let Some(path) = decode(raw_path) else {
|
||||
return ResolvedTarget::unresolved(
|
||||
EdgeState::Invalid,
|
||||
Some(self.reference_diagnostic(
|
||||
code::REFERENCE_INVALID,
|
||||
"OKF bundle path is not valid percent encoding",
|
||||
&fact.rel_path,
|
||||
span,
|
||||
)),
|
||||
);
|
||||
};
|
||||
let fragment = match raw_fragment {
|
||||
Some(fragment) => match decode(fragment) {
|
||||
Some(fragment) => Some(fragment),
|
||||
None => {
|
||||
return ResolvedTarget::unresolved(
|
||||
EdgeState::Invalid,
|
||||
Some(self.reference_diagnostic(
|
||||
code::REFERENCE_INVALID,
|
||||
"OKF bundle fragment is not valid percent encoding",
|
||||
&fact.rel_path,
|
||||
span,
|
||||
)),
|
||||
);
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
if crate::document::discovery::validate_relative_path(&path).is_err() {
|
||||
return ResolvedTarget::unresolved(
|
||||
EdgeState::OutOfScope,
|
||||
Some(self.reference_diagnostic(
|
||||
code::REFERENCE_OUT_OF_SCOPE,
|
||||
"OKF bundle path is not a safe logical path inside the bundle",
|
||||
&fact.rel_path,
|
||||
span,
|
||||
)),
|
||||
);
|
||||
}
|
||||
if let Some(target) = self.docs.get(path.as_str()).copied() {
|
||||
return self.resolve_document_target(target, fragment.as_deref(), span, &fact.rel_path);
|
||||
}
|
||||
if let Some(asset) = self.assets.get(path.as_str()) {
|
||||
return ResolvedTarget::node(identity::asset_key(asset.rel_path.as_str()));
|
||||
}
|
||||
if self.missing_paths.contains(&path) {
|
||||
return ResolvedTarget::unresolved(
|
||||
EdgeState::Missing,
|
||||
Some(self.reference_diagnostic(
|
||||
code::REFERENCE_MISSING,
|
||||
format!("OKF bundle target `/{path}` does not exist"),
|
||||
&fact.rel_path,
|
||||
span,
|
||||
)),
|
||||
);
|
||||
}
|
||||
ResolvedTarget::unresolved(
|
||||
EdgeState::NotLoaded,
|
||||
Some(self.reference_diagnostic(
|
||||
code::REFERENCE_NOT_LOADED,
|
||||
format!("OKF bundle target `/{path}` is not included in the checked bundle"),
|
||||
&fact.rel_path,
|
||||
span,
|
||||
)),
|
||||
)
|
||||
}
|
||||
|
||||
fn resolve_not_loaded(
|
||||
&mut self,
|
||||
fact: &DocumentFacts,
|
||||
@@ -671,6 +759,9 @@ impl<'a> Resolver<'a> {
|
||||
) -> ResolvedTarget {
|
||||
let span = reference.span;
|
||||
let path = &fact.rel_path;
|
||||
if self.okf_mode && reference.url.starts_with('/') && !reference.url.starts_with("//") {
|
||||
return self.resolve_okf_root_relative(fact, &reference.url, span);
|
||||
}
|
||||
let link = match parse_link(&reference.url) {
|
||||
Ok(link) => link,
|
||||
Err(LinkError::OutsideScope) => {
|
||||
@@ -868,6 +959,128 @@ impl<'a> Resolver<'a> {
|
||||
PathResolution::Missing(rel)
|
||||
}
|
||||
|
||||
/// `resource` is the only OKF metadata field that is explicitly a path. It
|
||||
/// is treated as a reference occurrence, never as execution or import.
|
||||
fn resolve_okf_resource(&mut self, fact: &DocumentFacts, context: Option<&str>) {
|
||||
let Some(resource) = fact.okf.resource_is_relative_path() else {
|
||||
return;
|
||||
};
|
||||
let source = self.doc_nodes[fact.rel_path.as_str()].clone();
|
||||
let span = fact
|
||||
.front_matter
|
||||
.as_ref()
|
||||
.map(|front_matter| front_matter.span);
|
||||
let link = match parse_link(resource) {
|
||||
Ok(link) => link,
|
||||
Err(LinkError::OutsideScope) => {
|
||||
let diagnostic = self.reference_diagnostic(
|
||||
code::REFERENCE_OUT_OF_SCOPE,
|
||||
"OKF resource path escapes the bundle root and was not read",
|
||||
&fact.rel_path,
|
||||
span.unwrap_or(Span::new(0, 0)),
|
||||
);
|
||||
self.diagnostics.push(diagnostic);
|
||||
self.push_edge(
|
||||
source,
|
||||
None,
|
||||
EdgeKind::References,
|
||||
EdgeOrigin::Document,
|
||||
resource.to_string(),
|
||||
span,
|
||||
&fact.rel_path,
|
||||
EdgeState::OutOfScope,
|
||||
context,
|
||||
);
|
||||
return;
|
||||
}
|
||||
Err(LinkError::Invalid(message)) => {
|
||||
let diagnostic = self.reference_diagnostic(
|
||||
code::REFERENCE_INVALID,
|
||||
format!("OKF resource path is invalid: {message}"),
|
||||
&fact.rel_path,
|
||||
span.unwrap_or(Span::new(0, 0)),
|
||||
);
|
||||
self.diagnostics.push(diagnostic);
|
||||
self.push_edge(
|
||||
source,
|
||||
None,
|
||||
EdgeKind::References,
|
||||
EdgeOrigin::Document,
|
||||
resource.to_string(),
|
||||
span,
|
||||
&fact.rel_path,
|
||||
EdgeState::Invalid,
|
||||
context,
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let ParsedLink::Local { path, fragment } = link else {
|
||||
return;
|
||||
};
|
||||
if self.okf_mode && resource.starts_with('/') && !resource.starts_with("//") {
|
||||
let resolved =
|
||||
self.resolve_okf_root_relative(fact, resource, span.unwrap_or(Span::new(0, 0)));
|
||||
if let Some(diagnostic) = resolved.diagnostic.clone() {
|
||||
self.diagnostics.push(diagnostic);
|
||||
}
|
||||
self.push_edge(
|
||||
source,
|
||||
resolved.node,
|
||||
EdgeKind::References,
|
||||
EdgeOrigin::Document,
|
||||
resource.to_string(),
|
||||
span,
|
||||
&fact.rel_path,
|
||||
resolved.state,
|
||||
context,
|
||||
);
|
||||
return;
|
||||
}
|
||||
let resolution = self.resolve_path(&fact.rel_path, &path);
|
||||
let (target, state) = match resolution {
|
||||
PathResolution::SameDocument => (
|
||||
Some(self.doc_nodes[fact.rel_path.as_str()].clone()),
|
||||
EdgeState::Resolved,
|
||||
),
|
||||
PathResolution::Document(rel) => (
|
||||
Some(self.doc_nodes[rel.as_str()].clone()),
|
||||
EdgeState::Resolved,
|
||||
),
|
||||
PathResolution::Asset(rel) => (Some(identity::asset_key(&rel)), EdgeState::Resolved),
|
||||
PathResolution::NotLoaded => (None, EdgeState::NotLoaded),
|
||||
PathResolution::Missing(_) => (None, EdgeState::Missing),
|
||||
PathResolution::Outside => (None, EdgeState::OutOfScope),
|
||||
PathResolution::Invalid(_) => (None, EdgeState::Invalid),
|
||||
};
|
||||
let _ = fragment;
|
||||
if state != EdgeState::Resolved {
|
||||
let diagnostic_code = match state {
|
||||
EdgeState::Missing => code::REFERENCE_MISSING,
|
||||
EdgeState::NotLoaded => code::REFERENCE_NOT_LOADED,
|
||||
EdgeState::OutOfScope => code::REFERENCE_OUT_OF_SCOPE,
|
||||
_ => code::REFERENCE_INVALID,
|
||||
};
|
||||
self.diagnostics.push(self.reference_diagnostic(
|
||||
diagnostic_code,
|
||||
"OKF resource path could not be verified",
|
||||
&fact.rel_path,
|
||||
span.unwrap_or(Span::new(0, 0)),
|
||||
));
|
||||
}
|
||||
self.push_edge(
|
||||
source,
|
||||
target,
|
||||
EdgeKind::References,
|
||||
EdgeOrigin::Document,
|
||||
resource.to_string(),
|
||||
span,
|
||||
&fact.rel_path,
|
||||
state,
|
||||
context,
|
||||
);
|
||||
}
|
||||
|
||||
fn resolve_import(
|
||||
&mut self,
|
||||
fact: &DocumentFacts,
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod cli;
|
||||
pub mod compiler;
|
||||
pub mod diagnostic;
|
||||
pub mod document;
|
||||
pub mod embedding;
|
||||
pub mod error;
|
||||
pub mod graph;
|
||||
pub mod model;
|
||||
|
||||
+79
-2
@@ -34,6 +34,10 @@ pub fn run_query(args: &QueryArgs, _marqdo_bin: Option<&Path>) -> Result<Output,
|
||||
let snapshot = discovery::discover(&scope)?;
|
||||
let store = ReadStore::open(&scope.database_path())?;
|
||||
let meta = store.build_meta()?;
|
||||
// Reproduce the stored referenced-asset inputs so freshness compares the
|
||||
// same input set that the build recorded.
|
||||
let mut snapshot = snapshot;
|
||||
populate_assets(&scope, &mut snapshot, &store)?;
|
||||
let currentness = store.currentness(&snapshot)?;
|
||||
let mut diagnostics = DiagnosticSet::new();
|
||||
if !currentness.current {
|
||||
@@ -94,6 +98,22 @@ pub fn run_query(args: &QueryArgs, _marqdo_bin: Option<&Path>) -> Result<Output,
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn populate_assets(
|
||||
scope: &crate::document::Scope,
|
||||
snapshot: &mut crate::document::SourceSnapshot,
|
||||
store: &ReadStore,
|
||||
) -> Result<(), KnowledgeError> {
|
||||
let mut facts = HashMap::new();
|
||||
for document in store.documents()? {
|
||||
if let Some(cached) = store.load_facts(&document.path)? {
|
||||
facts.insert(document.path.clone(), cached.facts);
|
||||
}
|
||||
}
|
||||
let (assets, _missing) = crate::compiler::collect_assets(scope, snapshot, &facts)?;
|
||||
snapshot.assets = assets;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Query result before rendering.
|
||||
struct QueryResult {
|
||||
hits: Vec<Hit>,
|
||||
@@ -340,14 +360,71 @@ impl<'a> Engine<'a> {
|
||||
"database has no semantic index; compile with embedding options first",
|
||||
)
|
||||
})?;
|
||||
let stored_endpoint = embedding
|
||||
.get("endpoint")
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let stored_model = embedding
|
||||
.get("model")
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let stored_revision = embedding
|
||||
.get("revision")
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let dimension = embedding
|
||||
.get("dimension")
|
||||
.and_then(|value| value.as_u64())
|
||||
.unwrap_or(0) as usize;
|
||||
let model_digest = embedding
|
||||
.get("model_digest")
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let url = args.embedding.embedding_url.clone().ok_or_else(|| {
|
||||
KnowledgeError::environment(
|
||||
code::EMBEDDING_UNAVAILABLE,
|
||||
"semantic search requires explicit embedding options",
|
||||
)
|
||||
})?;
|
||||
let model = args.embedding.embedding_model.clone().unwrap_or_default();
|
||||
let revision = args
|
||||
.embedding
|
||||
.embedding_revision
|
||||
.clone()
|
||||
.unwrap_or_default();
|
||||
let config = crate::embedding::EmbeddingConfig::new(
|
||||
&url,
|
||||
&model,
|
||||
&revision,
|
||||
args.embedding.allow_remote_embedding,
|
||||
)?;
|
||||
let client = crate::embedding::EmbeddingClient::new(&config)?;
|
||||
if client.endpoint() != stored_endpoint
|
||||
|| model != stored_model
|
||||
|| revision != stored_revision
|
||||
{
|
||||
return Err(KnowledgeError::environment(
|
||||
code::EMBEDDING_CONFIG_MISMATCH,
|
||||
"query embedding configuration does not match the compiled semantic index",
|
||||
)
|
||||
.with_hint("recompile with the new configuration or pass the original options"));
|
||||
}
|
||||
let (vectors, returned_dimension) = client.embed(std::slice::from_ref(&args.query))?;
|
||||
if returned_dimension != dimension {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::EMBEDDING_CONFIG_MISMATCH,
|
||||
"query embedding dimension does not match the compiled index",
|
||||
));
|
||||
}
|
||||
channels.push(semantic::channel(
|
||||
self.store,
|
||||
&args.query,
|
||||
model_digest,
|
||||
&vectors[0],
|
||||
&model_digest,
|
||||
dimension,
|
||||
200,
|
||||
)?);
|
||||
}
|
||||
|
||||
+43
-11
@@ -15,19 +15,51 @@ use crate::storage::read::ReadStore;
|
||||
/// Maximum number of stored vectors scanned by the exact cosine scan.
|
||||
pub const MAX_VECTOR_SCAN: usize = 50_000;
|
||||
|
||||
/// Run the semantic channel. The caller must have checked that semantic
|
||||
/// configuration matches the build metadata first.
|
||||
/// Run the semantic channel against stored vectors with the query embedding.
|
||||
pub fn channel(
|
||||
_store: &ReadStore,
|
||||
_query: &str,
|
||||
_model_digest: &str,
|
||||
_limit: usize,
|
||||
store: &ReadStore,
|
||||
query_vector: &[f32],
|
||||
model_digest: &str,
|
||||
dimension: usize,
|
||||
limit: usize,
|
||||
) -> Result<ChannelResult, KnowledgeError> {
|
||||
Err(KnowledgeError::environment(
|
||||
crate::diagnostic::code::EMBEDDING_UNAVAILABLE,
|
||||
"semantic search is not available in this build",
|
||||
)
|
||||
.with_hint("run `marqdo knowledge compile` with embedding options and a compatible endpoint"))
|
||||
if query_vector.len() != dimension {
|
||||
return Err(KnowledgeError::environment(
|
||||
crate::diagnostic::code::EMBEDDING_CONFIG_MISMATCH,
|
||||
"query embedding dimension does not match the compiled index",
|
||||
));
|
||||
}
|
||||
let rows = store.embeddings(model_digest, MAX_VECTOR_SCAN)?;
|
||||
if rows.is_empty() {
|
||||
return Err(KnowledgeError::environment(
|
||||
crate::diagnostic::code::EMBEDDING_UNAVAILABLE,
|
||||
"the semantic index is empty; recompile with embedding options",
|
||||
));
|
||||
}
|
||||
let truncated = rows.len() >= MAX_VECTOR_SCAN;
|
||||
let mut best: std::collections::HashMap<i64, (f64, i64)> = std::collections::HashMap::new();
|
||||
for row in &rows {
|
||||
if row.vector.len() != dimension {
|
||||
return Err(KnowledgeError::environment(
|
||||
crate::diagnostic::code::EMBEDDING_CONFIG_MISMATCH,
|
||||
"stored vector dimension does not match the compiled index",
|
||||
));
|
||||
}
|
||||
let Some(score) = crate::embedding::cosine(query_vector, &row.vector) else {
|
||||
continue;
|
||||
};
|
||||
let entry = best.entry(row.node_id).or_insert((f64::MIN, row.unit_id));
|
||||
if score > entry.0 {
|
||||
*entry = (score, row.unit_id);
|
||||
}
|
||||
}
|
||||
let scored: Vec<(i64, Option<i64>, f64)> = best
|
||||
.into_iter()
|
||||
.map(|(node_id, (score, unit_id))| (node_id, Some(unit_id), score))
|
||||
.collect();
|
||||
let mut result = ranked_from_scores(scored, limit);
|
||||
result.truncated |= truncated;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Candidate ordering helper used by the vector scan.
|
||||
|
||||
+139
-44
@@ -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
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user