Files
marqdo-knowledge/tests/storage.rs
T
marqdo-knowledge cca8fbdab1 feat(storage): one rebuildable SQLite projection with derived indexes
- add schema revision 1 with application id, singleton build row, documents,
  nodes, aliases, edges, contexts, inputs, diagnostics, search_units,
  FTS5 search_fts, grams and embeddings tables; spans and resolved-target
  invariants are enforced by CHECK constraints and foreign_keys=ON
- full rebuild stages a private database in the target directory and renames
  it atomically after source recheck and quick_check; a foreign or symlinked
  database is refused, never overwritten
- incremental publish replaces the projection inside one transaction, so
  readers see the old or the new complete snapshot and failures roll back to
  the last successful artifact
- store exact UTF-8 source bytes and digest-guarded normalised facts for the
  incremental re-analysis cache; inputs are content digests, never mtimes
- build one search unit per structural node/chunk with CJK bigram FTS
  segmentation, weighted FTS fields and bounded 2/3-gram fuzzy rows
- add read-only store API (nodes, aliases, edges, units, FTS/gram candidates,
  exact-name lookup, embeddings, diagnostics, integrity, currentness) and
  integration tests for publish/read/search/incremental/foreign-db safety
2026-11-26 01:10:39 +08:00

228 lines
8.3 KiB
Rust

//! Storage integration tests: publish, read, search indexes, freshness,
//! rebuild and incremental semantics.
use marqdo_knowledge::document::discovery::{discover, resolve_scope};
use marqdo_knowledge::document::markdown::parse_plain;
use marqdo_knowledge::document::SourceSnapshot;
use marqdo_knowledge::graph;
use marqdo_knowledge::storage::{self, read::ReadStore, BuildMeta, PublishRequest};
use std::collections::{HashMap, HashSet};
use std::path::Path;
fn project(files: &[(&str, &str)]) -> std::path::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 snap(root: &Path) -> SourceSnapshot {
let scope = resolve_scope(root, &[]).unwrap();
discover(&scope).unwrap()
}
fn facts_for(snapshot: &SourceSnapshot) -> Vec<marqdo_knowledge::document::DocumentFacts> {
snapshot
.files
.iter()
.filter(|file| file.format == marqdo_knowledge::document::DocumentFormat::PlainMarkdown)
.map(parse_plain)
.collect()
}
fn build_graph(snapshot: &SourceSnapshot) -> marqdo_knowledge::graph::Graph {
let facts = facts_for(snapshot);
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();
graph::build(facts, &sources, &snapshot.assets, &missing)
}
fn meta(
root: &Path,
snapshot: &SourceSnapshot,
graph: &marqdo_knowledge::graph::Graph,
generation: u64,
) -> BuildMeta {
let mut meta = BuildMeta::new(
env!("CARGO_PKG_VERSION"),
snapshot.snapshot_digest(),
graph.logical_digest(),
);
meta.scope = snapshot.scope.describe();
meta.producer_version = "3.0.0-rc.4".into();
meta.core_identity = "marqdo@3.0.0-rc.4/sha256:test".into();
meta.rebuild_generation = generation;
meta.facts_cache_version = 1;
let _ = root;
meta
}
fn publish(
root: &Path,
snapshot: &SourceSnapshot,
graph: &marqdo_knowledge::graph::Graph,
rebuild: bool,
generation: u64,
) {
let request = PublishRequest {
database_path: root.join(".marqdo/knowledge.sqlite"),
rebuild,
meta: meta(root, snapshot, graph, generation),
graph,
snapshot,
contexts: &[],
};
storage::publish(request).unwrap();
}
#[test]
fn publish_and_read_back_graph_and_indexes() {
let root = project(&[
(
"physics/mechanics.md",
"# 经典力学\n\n## 牛顿第二定律\n\n合外力等于质量与加速度的乘积。\n\n$$F=ma$$\n\n计算入口见[计算力](../compute.md#计算力)。\n",
),
("compute.md", "# 计算\n\n## 计算力\n\n`return m * a`\n"),
]);
let snapshot = snap(&root);
let graph = build_graph(&snapshot);
assert!(!graph.diagnostics.has_errors());
publish(&root, &snapshot, &graph, true, 1);
let database = root.join(".marqdo/knowledge.sqlite");
assert!(database.is_file());
let store = ReadStore::open(&database).unwrap();
let (documents, nodes, edges) = store.counts().unwrap();
assert_eq!(documents, 2);
assert!(nodes > 0 && edges > 0);
assert_eq!(
store.build_meta().unwrap().snapshot_digest,
snapshot.snapshot_digest()
);
assert_eq!(store.inputs().unwrap().len(), snapshot.inputs().len());
store.integrity_check(true).unwrap();
// Two-character CJK query works through the bigram FTS segmentation.
let query = marqdo_knowledge::text::fts_query("牛顿").unwrap();
let hits = store.fts_search(&query, 10).unwrap();
assert!(!hits.is_empty(), "CJK bigram query must hit");
let node = store.node_by_id(hits[0].node_id).unwrap().unwrap();
assert_eq!(node.title, "牛顿第二定律");
// Fuzzy grams can recall the same title by a typo.
let grams = marqdo_knowledge::text::grams("牛顿第二定绿");
let candidates = store.gram_candidates(&grams, 20).unwrap();
assert!(!candidates.is_empty());
// Links are stored as reference edges with real spans.
// Reference source is the innermost unit, not the document; query the
// target through the graph API.
let target = store
.nodes_by_exact_name(&marqdo_knowledge::text::normalize("计算力"))
.unwrap()
.into_iter()
.find(|node| node.kind == marqdo_knowledge::model::NodeKind::Section)
.unwrap();
let incoming = store
.edges_to(
&[target.id],
&[marqdo_knowledge::model::EdgeKind::References],
)
.unwrap();
assert!(!incoming.is_empty());
assert!(incoming
.iter()
.all(|edge| edge.state == marqdo_knowledge::model::EdgeState::Resolved));
}
#[test]
fn currentness_detects_changes_and_incremental_update_replaces_projection() {
let root = project(&[("doc.md", "# 标题\n\n第一版本内容。\n")]);
let snapshot = snap(&root);
let graph = build_graph(&snapshot);
publish(&root, &snapshot, &graph, true, 1);
let database = root.join(".marqdo/knowledge.sqlite");
let store = ReadStore::open(&database).unwrap();
let stored = store.build_meta().unwrap();
assert_eq!(stored.rebuild_generation, 1);
drop(store);
// Unchanged sources are current.
let store = ReadStore::open(&database).unwrap();
let mut current_snapshot = snap(&root);
current_snapshot.assets = snapshot.assets.clone();
let currentness = store.currentness(&current_snapshot).unwrap();
assert!(currentness.current, "{:?}", currentness.changed_inputs);
drop(store);
std::thread::sleep(std::time::Duration::from_millis(10));
std::fs::write(root.join("doc.md"), "# 标题\n\n第二版本内容。\n").unwrap();
let snapshot = snap(&root);
assert_ne!(stored.snapshot_digest, snapshot.snapshot_digest());
let graph = build_graph(&snapshot);
publish(&root, &snapshot, &graph, false, 2);
let store = ReadStore::open(&database).unwrap();
let stored = store.build_meta().unwrap();
assert_eq!(stored.rebuild_generation, 2);
assert_eq!(stored.snapshot_digest, snapshot.snapshot_digest());
let old_query = marqdo_knowledge::text::fts_query("一版").unwrap();
assert!(store.fts_search(&old_query, 10).unwrap().is_empty());
let new_query = marqdo_knowledge::text::fts_query("二版").unwrap();
assert!(!store.fts_search(&new_query, 10).unwrap().is_empty());
store.integrity_check(true).unwrap();
}
#[test]
fn foreign_database_is_never_overwritten() {
let root = project(&[("doc.md", "# t\n")]);
std::fs::create_dir_all(root.join(".marqdo")).unwrap();
std::fs::write(root.join(".marqdo/knowledge.sqlite"), b"not a database").unwrap();
let snapshot = snap(&root);
let graph = build_graph(&snapshot);
let request = PublishRequest {
database_path: root.join(".marqdo/knowledge.sqlite"),
rebuild: true,
meta: meta(&root, &snapshot, &graph, 1),
graph: &graph,
snapshot: &snapshot,
contexts: &[],
};
let error = storage::publish(request).unwrap_err();
assert_eq!(error.code, "knowledge.database_not_ours");
assert_eq!(
std::fs::read(root.join(".marqdo/knowledge.sqlite")).unwrap(),
b"not a database"
);
}
#[test]
fn switching_to_rebuild_semantics_keeps_one_artifact() {
let root = project(&[("a.md", "# A\n\ntext\n")]);
let snapshot = snap(&root);
let graph = build_graph(&snapshot);
publish(&root, &snapshot, &graph, true, 1);
let entries: Vec<_> = std::fs::read_dir(root.join(".marqdo"))
.unwrap()
.map(|entry| entry.unwrap().file_name().to_string_lossy().to_string())
.collect();
// Only the published database (and possibly SQLite journaling files) is
// persistent; no staging database is left behind.
assert!(entries.iter().any(|name| name == "knowledge.sqlite"));
assert!(!entries
.iter()
.any(|name| name.starts_with(".knowledge.sqlite.tmp.")));
let store = ReadStore::open(&root.join(".marqdo/knowledge.sqlite")).unwrap();
assert!(store.build_meta().unwrap().rebuild_generation != 0);
}