feat(embedding): explicit OpenAI-compatible semantic channel

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

No files matched your search

+334
View File
@@ -0,0 +1,334 @@
//! Semantic channel end-to-end tests against a local mock embeddings server.
//!
//! The mock proves protocol handling, validation, storage and fusion. It is not
//! a semantic-quality benchmark: no real-model claim is made here.
use marqdo_knowledge::cli::{CompileArgs, EmbeddingArgs, OutputFormat, QueryArgs};
use marqdo_knowledge::compiler;
use marqdo_knowledge::query;
use marqdo_knowledge::storage::read::ReadStore;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
struct MockServer {
port: u16,
requests: Arc<AtomicUsize>,
}
impl MockServer {
/// Deterministic fake embedding: "模长"/"归一" -> [0,1,0], "量子" -> [1,0,0],
/// otherwise [0,0,1]. This lets the test assert cross-vocabulary recall.
fn start() -> Self {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let requests = Arc::new(AtomicUsize::new(0));
let counter = requests.clone();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { break };
counter.fetch_add(1, Ordering::SeqCst);
let response = handle(&mut stream);
let _ = stream.write_all(response.as_bytes());
}
});
Self { port, requests }
}
fn embed_args(&self) -> EmbeddingArgs {
EmbeddingArgs {
embedding_url: Some(format!("http://127.0.0.1:{}/v1", self.port)),
embedding_model: Some("mock-embed".into()),
embedding_revision: Some("r1".into()),
allow_remote_embedding: false,
}
}
fn requests(&self) -> usize {
self.requests.load(Ordering::SeqCst)
}
}
fn handle(stream: &mut TcpStream) -> String {
let mut buffer = Vec::new();
let mut chunk = [0u8; 4096];
let header_end = loop {
let read = stream.read(&mut chunk).unwrap_or(0);
if read == 0 {
return error_response(400, "empty request");
}
buffer.extend_from_slice(&chunk[..read]);
if let Some(position) = find_subsequence(&buffer, b"\r\n\r\n") {
break position + 4;
}
};
let header = String::from_utf8_lossy(&buffer[..header_end]).to_string();
let content_length = header
.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
if name.eq_ignore_ascii_case("content-length") {
value.trim().parse::<usize>().ok()
} else {
None
}
})
.unwrap_or(0);
while buffer.len() < header_end + content_length {
let read = stream.read(&mut chunk).unwrap_or(0);
if read == 0 {
break;
}
buffer.extend_from_slice(&chunk[..read]);
}
let body = String::from_utf8_lossy(
&buffer[header_end..(header_end + content_length).min(buffer.len())],
);
let value: serde_json::Value = match serde_json::from_str(&body) {
Ok(value) => value,
Err(error) => return error_response(400, &format!("bad request JSON: {error}")),
};
let inputs = value["input"].as_array().cloned().unwrap_or_default();
let data: Vec<serde_json::Value> = inputs
.iter()
.enumerate()
.map(|(index, input)| {
let text = input.as_str().unwrap_or_default();
let vector = if text.contains("模长") || text.contains("归一") {
vec![0.0, 1.0, 0.0]
} else if text.contains("量子") {
vec![1.0, 0.0, 0.0]
} else {
vec![0.0, 0.0, 1.0]
};
serde_json::json!({"index": index, "embedding": vector})
})
.collect();
let response = serde_json::json!({"model": "mock-embed", "data": data});
let body = response.to_string();
format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
body.len(),
body
)
}
fn error_response(status: u16, message: &str) -> String {
let body = serde_json::json!({"error": message}).to_string();
format!(
"HTTP/1.1 {status} Error\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
body.len(),
body
)
}
fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack
.windows(needle.len())
.position(|window| window == needle)
}
fn project() -> PathBuf {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().to_path_buf();
std::fs::create_dir_all(root.join("physics")).unwrap();
std::fs::write(
root.join("physics/quantum.md"),
"# 量子态\n\n量子态是否合法取决于归一化。\n",
)
.unwrap();
std::fs::create_dir_all(root.join("math")).unwrap();
std::fs::write(
root.join("math/normalize.md"),
"# 归一化\n\n消除向量模长影响是归一化的常见写法。\n",
)
.unwrap();
std::mem::forget(temp);
root
}
fn compile_with(
root: &Path,
embedding: EmbeddingArgs,
) -> Result<(), marqdo_knowledge::error::KnowledgeError> {
let args = CompileArgs {
root: root.to_path_buf(),
exclude: Vec::new(),
rebuild: false,
json: true,
embedding,
};
compiler::compile(&args, None).map(|_| ())
}
fn query_args(root: &Path, query: &str, semantic: bool, embedding: EmbeddingArgs) -> QueryArgs {
QueryArgs {
query: query.to_string(),
root: root.to_path_buf(),
exact: false,
kind: None,
limit: None,
depth: None,
relation: Vec::new(),
reverse: false,
slice: None,
format: OutputFormat::Json,
snapshot: false,
semantic,
embedding,
}
}
#[test]
fn semantic_index_is_built_and_queried_with_explicit_opt_in() {
let server = MockServer::start();
let root = project();
compile_with(&root, server.embed_args()).unwrap();
let store = ReadStore::open(&root.join(".marqdo/knowledge.sqlite")).unwrap();
let (_, _, _) = store.counts().unwrap();
let search_units = store.search_unit_count().unwrap();
let stored_vectors = store
.embeddings(
store.build_meta().unwrap().embedding.unwrap()["model_digest"]
.as_str()
.unwrap(),
100,
)
.unwrap();
assert!(!stored_vectors.is_empty());
assert!(stored_vectors.len() as u64 <= search_units);
let before = server.requests();
// The query has no lexical overlap with the target ("消除模长影响" vs
// "归一化") but the mock maps both to the same vector.
let output = query::run_query(
&query_args(&root, "消除模长影响", true, server.embed_args()),
None,
)
.unwrap();
assert_eq!(output.exit_code, 0, "{}", output.stderr);
let value: serde_json::Value = serde_json::from_str(&output.stdout).unwrap();
assert!(value["channels"]
.as_array()
.unwrap()
.iter()
.any(|channel| channel == "semantic"));
let hits = value["hits"].as_array().unwrap();
assert!(
hits.iter().any(|hit| hit["title"] == "归一化"),
"semantic channel must recall the cross-vocabulary target: {hits:?}"
);
assert!(server.requests() > before);
// A normal query stays offline even though vectors exist.
let before = server.requests();
let output = query::run_query(
&query_args(&root, "量子态", false, EmbeddingArgs::default()),
None,
)
.unwrap();
assert_eq!(output.exit_code, 0);
assert_eq!(
server.requests(),
before,
"default query must not perform network I/O"
);
}
#[test]
fn remote_endpoint_requires_explicit_consent_and_tls() {
let config = EmbeddingArgs {
embedding_url: Some("https://example.com/v1".into()),
embedding_model: Some("m".into()),
embedding_revision: Some("r".into()),
allow_remote_embedding: false,
};
let error = marqdo_knowledge::embedding::EmbeddingConfig::new(
config.embedding_url.as_deref().unwrap(),
"m",
"r",
false,
)
.unwrap_err();
assert_eq!(
error.code,
marqdo_knowledge::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED
);
let error =
marqdo_knowledge::embedding::EmbeddingConfig::new("http://example.com/v1", "m", "r", true)
.unwrap_err();
assert_eq!(
error.code,
marqdo_knowledge::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED
);
// Plain http loopback is allowed without remote consent.
assert!(marqdo_knowledge::embedding::EmbeddingConfig::new(
"http://127.0.0.1:9/v1",
"m",
"r",
false
)
.is_ok());
}
#[test]
fn invalid_embedding_response_does_not_publish_a_mixed_index() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { break };
let mut buffer = Vec::new();
let mut chunk = [0u8; 4096];
loop {
let read = stream.read(&mut chunk).unwrap_or(0);
if read == 0 {
break;
}
buffer.extend_from_slice(&chunk[..read]);
if find_subsequence(&buffer, b"\r\n\r\n").is_some() {
break;
}
}
let body = serde_json::json!({"data": [
{"index": 0, "embedding": [1.0, 0.0]}
]});
let body = body.to_string();
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
body.len(),
body
);
let _ = stream.write_all(response.as_bytes());
}
});
let root = project();
let embedding = EmbeddingArgs {
embedding_url: Some(format!("http://127.0.0.1:{port}/v1")),
embedding_model: Some("m".into()),
embedding_revision: Some("r".into()),
allow_remote_embedding: false,
};
let error = compile_with(&root, embedding).unwrap_err();
assert!(
error.code == marqdo_knowledge::diagnostic::code::EMBEDDING_INVALID_RESPONSE
|| error.code == marqdo_knowledge::diagnostic::code::EMBEDDING_TRANSPORT,
"unexpected error: {error:?}"
);
assert!(!root.join(".marqdo/knowledge.sqlite").exists());
}
#[test]
fn semantic_query_without_a_compiled_index_is_an_error() {
let server = MockServer::start();
let root = project();
compile_with(&root, EmbeddingArgs::default()).unwrap();
let error =
query::run_query(&query_args(&root, "模长", true, server.embed_args()), None).unwrap_err();
assert_eq!(
error.code,
marqdo_knowledge::diagnostic::code::EMBEDDING_CONFIG_MISMATCH
);
}
+242
View File
@@ -0,0 +1,242 @@
//! OKF v0.3 recognition, metadata preservation and `check --okf` conformance.
use marqdo_knowledge::cli::{CheckArgs, CompileArgs, EmbeddingArgs, OutputFormat, QueryArgs};
use marqdo_knowledge::compiler;
use marqdo_knowledge::document::discovery::{discover, resolve_scope};
use marqdo_knowledge::document::markdown::parse_plain;
use marqdo_knowledge::graph;
use marqdo_knowledge::model::EdgeState;
use marqdo_knowledge::query;
use marqdo_knowledge::storage::read::ReadStore;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
fn project(files: &[(&str, &str)]) -> PathBuf {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().to_path_buf();
for (path, content) in files {
let absolute = root.join(path);
if let Some(parent) = absolute.parent() {
std::fs::create_dir_all(parent).unwrap();
}
std::fs::write(absolute, content).unwrap();
}
std::mem::forget(temp);
root
}
fn compile(root: &Path) {
let args = CompileArgs {
root: root.to_path_buf(),
exclude: Vec::new(),
rebuild: false,
json: true,
embedding: EmbeddingArgs::default(),
};
let output = compiler::compile(&args, None).unwrap();
assert_eq!(output.exit_code, 0, "{}", output.stderr);
}
fn check_okf(root: &Path) -> (i32, serde_json::Value) {
let args = CheckArgs {
root: root.to_path_buf(),
okf: true,
json: true,
};
let output = compiler::check(&args, None).unwrap();
(
output.exit_code,
serde_json::from_str(&output.stdout).unwrap(),
)
}
fn bundle() -> PathBuf {
project(&[
("index.md", "# Knowledge\n\n- [经典力学](physics/mechanics.md)\n"),
("log.md", "# Change log\n\n## 2026-11-25\n\n- initial concept\n"),
(
"physics/mechanics.md",
"---\ntype: Theory\ntitle: 经典力学\ntags: [physics, mechanics]\ndescription: 力学总览\ncustom_key: preserved\n---\n\n# 经典力学\n\n## 牛顿第二定律\n\n合外力等于质量与加速度的乘积。\n",
),
(
"datasets/table.md",
"---\ntype: Dataset\ntitle: 数据表\nresource: ../data/values.csv\n---\n\n# 数据表\n\n数据说明。\n",
),
("data/values.csv", "a,b\n1,2\n"),
])
}
#[test]
fn concept_metadata_and_roles_are_recognised() {
let root = bundle();
compile(&root);
let store = ReadStore::open(&root.join(".marqdo/knowledge.sqlite")).unwrap();
let mut roles: Vec<(String, String)> = store
.documents()
.unwrap()
.into_iter()
.map(|document| (document.path, document.role))
.collect();
roles.sort();
assert_eq!(
roles,
vec![
("datasets/table.md".to_string(), "concept".to_string()),
("index.md".to_string(), "index".to_string()),
("log.md".to_string(), "log".to_string()),
("physics/mechanics.md".to_string(), "concept".to_string()),
]
);
// Concept identity maps to the document node through an exact alias.
let aliases = store.aliases_for("physics/mechanics").unwrap();
assert_eq!(aliases.len(), 1);
let node = &aliases[0].1;
assert_eq!(node.kind, marqdo_knowledge::model::NodeKind::Document);
assert_eq!(node.metadata["okf"]["concept_type"], "Theory");
assert_eq!(node.metadata["okf"]["tags"][0], "physics");
assert_eq!(node.metadata["okf"]["metadata"]["custom_key"], "preserved");
// Reserved files never get concept ids.
assert!(store.aliases_for("index").unwrap().is_empty());
assert!(store.aliases_for("log").unwrap().is_empty());
}
#[test]
fn exact_query_resolves_a_concept_id() {
let root = bundle();
compile(&root);
let args = QueryArgs {
query: "physics/mechanics".into(),
root: root.clone(),
exact: true,
kind: None,
limit: None,
depth: None,
relation: Vec::new(),
reverse: false,
slice: None,
format: OutputFormat::Json,
snapshot: false,
semantic: false,
embedding: EmbeddingArgs::default(),
};
let output = query::run_query(&args, None).unwrap();
assert_eq!(output.exit_code, 0);
let value: serde_json::Value = serde_json::from_str(&output.stdout).unwrap();
assert_eq!(value["hits"][0]["title"], "经典力学");
assert_eq!(value["hits"][0]["kind"], "document");
}
#[test]
fn okf_resource_is_a_reference_edge_to_the_asset() {
let root = bundle();
compile(&root);
let store = ReadStore::open(&root.join(".marqdo/knowledge.sqlite")).unwrap();
let document = store
.node_by_key(graph::identity::document_key("datasets/table.md").as_str())
.unwrap()
.unwrap();
let edges = store
.edges_from(
&[document.id],
&[marqdo_knowledge::model::EdgeKind::References],
)
.unwrap();
let resource_edge = edges
.iter()
.find(|edge| edge.raw_target == "../data/values.csv")
.expect("resource reference edge");
assert_eq!(resource_edge.state, EdgeState::Resolved);
let target = store
.node_by_id(resource_edge.target_id.unwrap())
.unwrap()
.unwrap();
assert_eq!(target.kind, marqdo_knowledge::model::NodeKind::Resource);
assert_eq!(target.metadata["path"], "data/values.csv");
}
#[test]
fn valid_bundle_passes_okf_check() {
let root = bundle();
let (exit, value) = check_okf(&root);
assert_eq!(exit, 0, "{value:?}");
assert_eq!(value["payload"]["errors"], 0);
}
#[test]
fn non_reserved_file_without_type_fails_okf_check_only() {
let root = project(&[
("index.md", "# Knowledge\n"),
("concept.md", "---\ntype: Note\ntitle: ok\n---\n\n# ok\n"),
("loose.md", "# no front matter\n"),
]);
// Native compile still works: ordinary documents remain knowledge.
compile(&root);
let (exit, value) = check_okf(&root);
assert_eq!(exit, 1);
assert!(value["diagnostics"]
.as_array()
.unwrap()
.iter()
.any(|diagnostic| diagnostic["code"] == "knowledge.okf_invalid"));
}
#[test]
fn broken_links_are_tolerated_in_okf_mode_but_not_in_plain_check() {
let root = project(&[
("index.md", "# Knowledge\n"),
(
"concept.md",
"---\ntype: Note\n---\n\n# note\n\n[missing](missing-target.md)\n",
),
]);
let (exit, _) = check_okf(&root);
assert_eq!(exit, 0, "OKF conformance tolerates broken links");
let plain = compiler::check(
&CheckArgs {
root: root.clone(),
okf: false,
json: true,
},
None,
)
.unwrap();
assert_eq!(
plain.exit_code, 1,
"plain check fails on a definite broken link"
);
}
#[test]
fn root_absolute_okf_links_resolve_inside_the_bundle() {
let root = project(&[
("index.md", "# Knowledge\n"),
("a.md", "---\ntype: Note\n---\n\n# a\n\n[b](/b.md#b)\n"),
("b.md", "---\ntype: Note\n---\n\n# b\n\ncontent\n"),
]);
let scope = resolve_scope(&root, &[]).unwrap();
let snapshot = discover(&scope).unwrap();
let facts: Vec<_> = snapshot.files.iter().map(parse_plain).collect();
let mut sources: HashMap<&str, &str> = HashMap::new();
for file in &snapshot.files {
sources.insert(file.rel_path.as_str(), file.text.as_str());
}
let missing: HashSet<String> = HashSet::new();
let native = graph::build(facts.clone(), &sources, &snapshot.assets, &missing, false);
let native_edge = native
.edges
.iter()
.find(|edge| edge.raw_target == "/b.md#b")
.unwrap();
assert_eq!(native_edge.state, EdgeState::OutOfScope);
let okf = graph::build(facts, &sources, &snapshot.assets, &missing, true);
let okf_edge = okf
.edges
.iter()
.find(|edge| edge.raw_target == "/b.md#b")
.unwrap();
assert_eq!(okf_edge.state, EdgeState::Resolved);
assert!(okf_edge.target.is_some());
assert!(okf.diagnostics.iter().all(|diagnostic| !diagnostic
.message
.contains("escapes the allowed knowledge root")));
}
+3 -1
View File
@@ -44,7 +44,7 @@ fn build_graph(snapshot: &SourceSnapshot) -> marqdo_knowledge::graph::Graph {
sources.insert(file.rel_path.as_str(), file.text.as_str());
}
let missing: HashSet<String> = HashSet::new();
graph::build(facts, &sources, &snapshot.assets, &missing)
graph::build(facts, &sources, &snapshot.assets, &missing, false)
}
fn meta(
@@ -81,6 +81,7 @@ fn publish(
graph,
snapshot,
contexts: &[],
embeddings: None,
};
storage::publish(request).unwrap();
}
@@ -197,6 +198,7 @@ fn foreign_database_is_never_overwritten() {
graph: &graph,
snapshot: &snapshot,
contexts: &[],
embeddings: None,
};
let error = storage::publish(request).unwrap_err();
assert_eq!(error.code, "knowledge.database_not_ours");