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
);
}