feat(query): exact, lexical, fuzzy, graph and slice query surface

- exact channel resolves canonical ids, aliases and unique exact names only;
  multiple exact names are returned as candidates, never silently chosen
- lexical channel uses weighted FTS5 BM25 over CJK-bigram segmented fields and
  reports the matching field; fuzzy channel recalls via the gram index with
  bounded edit distance, CJK single-character and prefix fallbacks for typos
  whose bigrams do not overlap
- weighted RRF fuses per-node ranks (exact 1.5, lexical/fuzzy/semantic 1.0) and
  bounded graph expansion follows references both ways, contains children,
  calls/imports in their direction with --relation/--reverse, depth decay and
  explicit truncation; --kind filters after expansion
- document/execution/hybrid slices share one plan+materialise traversal, skip
  ancestor duplication, include module context for execution imports, report
  external/dynamic gaps, enforce the 32 KiB budget on UTF-8 boundaries and keep
  exact source text with path/span provenance
- stale databases are refused unless --snapshot is explicit; query never
  compiles implicitly and emits the single result envelope with honest
  channels/truncated/diagnostics
- add end-to-end query tests for CJK recall, typo recall, exact/ambiguous ids,
  kind filtering, graph neighbours, slices, staleness, missing database,
  no-result honesty and explicit semantic-config failure
This commit is contained in:
marqdo-knowledge committed 2026-11-26 01:46:17 +08:00
1 parent 66f3e168c4
commit 514d9fbd4c
10 files changed
+2414 -16

No files matched your search

+265
View File
@@ -0,0 +1,265 @@
//! End-to-end query tests over a compiled plain-Markdown project.
use marqdo_knowledge::cli::{
CheckArgs, CompileArgs, EmbeddingArgs, OutputFormat, QueryArgs, SliceKind,
};
use marqdo_knowledge::compiler;
use marqdo_knowledge::query;
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(),
};
compiler::compile(&args, None).unwrap();
}
fn query_args(root: &Path, query: &str) -> 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: false,
embedding: EmbeddingArgs::default(),
}
}
fn run(_root: &Path, args: QueryArgs) -> serde_json::Value {
let output = query::run_query(&args, None).unwrap();
assert_eq!(output.exit_code, 0, "{}", output.stderr);
serde_json::from_str(&output.stdout).expect("query envelope is valid JSON")
}
fn sample_project() -> PathBuf {
let root = project(&[
(
"physics/mechanics.md",
"# 经典力学\n\n## 牛顿第二定律\n\n合外力等于质量与加速度的乘积。\n\n计算入口:[计算力](../compute.md#计算力)。\n\n## 归一化动机\n\n消除向量模长影响,归一化是常见操作。\n\n相关计算:[计算力](../compute.md#计算力)。\n",
),
(
"compute.md",
"# 计算\n\n## 计算力\n\n依据[牛顿第二定律](physics/mechanics.md#牛顿第二定律)。\n\n`return m * a`\n\n| 符号 | 含义 |\n| --- | --- |\n| m | 质量 |\n",
),
]);
compile(&root);
root
}
#[test]
fn lexical_channel_finds_two_character_chinese() {
let root = sample_project();
let value = run(&root, query_args(&root, "牛顿"));
let hits = value["hits"].as_array().unwrap();
assert!(!hits.is_empty());
assert_eq!(hits[0]["title"], "牛顿第二定律");
assert_eq!(value["schema"], "marqdo.knowledge.result");
assert_eq!(value["command"], "query");
assert_eq!(value["current"], true);
assert!(value["channels"]
.as_array()
.unwrap()
.iter()
.any(|channel| channel == "lexical"));
// Snippets are exact source substrings.
let source = std::fs::read_to_string(root.join("physics/mechanics.md")).unwrap();
assert!(source.contains(hits[0]["snippet"].as_str().unwrap()));
}
#[test]
fn fuzzy_channel_recalls_a_typo_query() {
let root = sample_project();
let value = run(&root, query_args(&root, "归依化"));
let hits = value["hits"].as_array().unwrap();
assert!(!hits.is_empty());
let titles: Vec<&str> = hits
.iter()
.filter_map(|hit| hit["title"].as_str())
.collect();
assert!(titles.iter().any(|title| title.contains("归一化")));
assert!(value["channels"]
.as_array()
.unwrap()
.iter()
.any(|channel| channel == "fuzzy"));
}
#[test]
fn exact_mode_returns_address_or_ambiguous_candidates() {
let root = sample_project();
let mut args = query_args(&root, "牛顿第二定律");
args.exact = true;
let value = run(&root, args);
assert_eq!(value["hits"].as_array().unwrap().len(), 1);
assert_eq!(value["hits"][0]["matches"][0]["field"], "address");
let canonical = value["hits"][0]["id"].as_str().unwrap().to_string();
let mut args = query_args(&root, &canonical);
args.exact = true;
let value = run(&root, args);
assert_eq!(value["hits"][0]["id"], canonical);
// Two nodes share the display title "经典力学" (document + H1 unit).
let mut args = query_args(&root, "经典力学");
args.exact = true;
let value = run(&root, args);
assert_eq!(value["hits"].as_array().unwrap().len(), 2);
assert!(value["diagnostics"]
.as_array()
.unwrap()
.iter()
.any(|diagnostic| diagnostic["code"] == "knowledge.query_ambiguous"));
}
#[test]
fn kind_filter_applies_after_expansion() {
let root = sample_project();
let mut args = query_args(&root, "计算力");
args.kind = Some("function".to_string());
let value = run(&root, args);
// No function exists in a plain-Markdown project.
assert!(value["hits"].as_array().unwrap().is_empty());
assert!(value["diagnostics"]
.as_array()
.unwrap()
.iter()
.any(|diagnostic| diagnostic["code"] == "knowledge.query_no_results"));
}
#[test]
fn graph_expansion_finds_linked_neighbours() {
let root = sample_project();
let mut args = query_args(&root, "归一化动机");
args.depth = Some(1);
let value = run(&root, args);
let hits = value["hits"].as_array().unwrap();
assert!(
hits.iter().any(|hit| {
hit["title"] == "计算力"
&& hit["matches"]
.as_array()
.unwrap()
.iter()
.any(|reason| reason["channel"] == "graph")
}),
"graph expansion must reach the linked section: {hits:?}"
);
}
#[test]
fn slices_keep_exact_source_and_respect_the_budget() {
let root = sample_project();
let mut args = query_args(&root, "牛顿第二定律");
args.slice = Some(SliceKind::Document);
let value = run(&root, args);
let slice = &value["payload"]["slice"];
assert_eq!(slice["kind"], "document");
assert_eq!(slice["complete"], true);
let pieces = slice["pieces"].as_array().unwrap();
assert!(!pieces.is_empty());
let seed_text = pieces[0]["text"].as_str().unwrap();
let source = std::fs::read_to_string(root.join("physics/mechanics.md")).unwrap();
assert!(source.contains(seed_text));
assert!(slice["returned_bytes"].as_u64().unwrap() <= 32768);
let mut args = query_args(&root, "牛顿第二定律");
args.slice = Some(SliceKind::Execution);
let value = run(&root, args);
assert_eq!(value["payload"]["slice"]["kind"], "execution");
}
#[test]
fn stale_database_is_refused_unless_snapshot_is_explicit() {
let root = sample_project();
std::fs::write(root.join("compute.md"), "# 计算\n\n新的内容。\n").unwrap();
let error = query::run_query(&query_args(&root, "牛顿"), None).unwrap_err();
assert_eq!(error.code, "knowledge.database_stale");
assert_eq!(error.exit_code, 2);
let mut args = query_args(&root, "牛顿");
args.snapshot = true;
let value = run(&root, args);
assert_eq!(value["current"], false);
assert!(value["diagnostics"]
.as_array()
.unwrap()
.iter()
.any(|diagnostic| diagnostic["code"] == "knowledge.snapshot_stale"));
}
#[test]
fn missing_database_does_not_compile_implicitly() {
let root = project(&[("doc.md", "# t\n")]);
let error = query::run_query(&query_args(&root, "t"), None).unwrap_err();
assert_eq!(error.code, "knowledge.database_missing");
assert!(!root.join(".marqdo/knowledge.sqlite").exists());
}
#[test]
fn no_result_query_returns_no_fabricated_hits() {
let root = sample_project();
let value = run(&root, query_args(&root, "完全无关的查询词xyzzy"));
assert!(value["hits"].as_array().unwrap().is_empty());
assert!(value["diagnostics"]
.as_array()
.unwrap()
.iter()
.any(|diagnostic| diagnostic["code"] == "knowledge.query_no_results"));
}
#[test]
fn semantic_without_index_is_an_explicit_error() {
let root = sample_project();
let mut args = query_args(&root, "牛顿");
args.semantic = true;
args.embedding = EmbeddingArgs {
embedding_url: Some("http://127.0.0.1:1/v1".into()),
embedding_model: Some("test".into()),
embedding_revision: Some("r1".into()),
allow_remote_embedding: false,
};
let error = query::run_query(&args, None).unwrap_err();
assert!(matches!(
error.code,
"knowledge.embedding_config_mismatch" | "knowledge.embedding_unavailable"
));
}
#[test]
fn check_sees_the_database_as_current_after_compile() {
let root = sample_project();
let args = CheckArgs {
root: root.clone(),
okf: false,
json: true,
};
let output = compiler::check(&args, None).unwrap();
assert_eq!(output.exit_code, 0, "{}", output.stderr);
let value: serde_json::Value = serde_json::from_str(&output.stdout).unwrap();
assert_eq!(value["payload"]["database"], "current");
}