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
This commit is contained in:
1 parent
1871ded5ed
commit
cca8fbdab1
7 files changed
+2990
No files matched your search
@@ -13,6 +13,8 @@ pub mod error;
|
||||
pub mod graph;
|
||||
pub mod model;
|
||||
pub mod query;
|
||||
pub mod storage;
|
||||
pub mod text;
|
||||
|
||||
/// Run the command line. Returns the process exit code (0/1/2).
|
||||
pub fn run() -> i32 {
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
//! Derived search-index construction.
|
||||
//!
|
||||
//! Search units are generated only from source structure: heading scopes,
|
||||
//! extracted blocks, function interface metadata and front-matter metadata.
|
||||
//! Texts are segmented with [`crate::text`] before entering FTS5 so two-character
|
||||
//! Chinese queries do not depend on a trigram tokenizer. Gram rows support the
|
||||
//! bounded fuzzy channel. Nothing here generates facts or rewrites source.
|
||||
|
||||
use crate::document::{BlockFact, DocumentFacts, UnitKind};
|
||||
use crate::graph::identity;
|
||||
use crate::graph::{Graph, Node};
|
||||
use crate::model::Span;
|
||||
use crate::text;
|
||||
use rusqlite::Transaction;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Maximum source bytes in one search unit chunk.
|
||||
const MAX_CHUNK_BYTES: usize = 4096;
|
||||
/// Per-field gram caps keep the fuzzy index bounded for large documents.
|
||||
const MAX_GRAMS_PER_FIELD: usize = 2048;
|
||||
const MAX_BODY_GRAMS: usize = 2048;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct IndexStats {
|
||||
pub search_units: u64,
|
||||
pub grams: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct UnitSpec {
|
||||
node_key: String,
|
||||
span: Span,
|
||||
fields: SearchFields,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct SearchFields {
|
||||
title: String,
|
||||
body: String,
|
||||
symbols: String,
|
||||
metadata: String,
|
||||
formula: String,
|
||||
tabular: String,
|
||||
links: String,
|
||||
}
|
||||
|
||||
impl SearchFields {
|
||||
fn append_block(&mut self, block: &BlockFact) {
|
||||
push_field(&mut self.body, &block.text);
|
||||
push_field(&mut self.formula, &block.formula);
|
||||
push_field(&mut self.tabular, &block.table);
|
||||
push_field(&mut self.links, &block.links);
|
||||
}
|
||||
|
||||
fn byte_len(&self) -> usize {
|
||||
self.body.len() + self.formula.len() + self.tabular.len() + self.links.len()
|
||||
}
|
||||
}
|
||||
|
||||
fn push_field(field: &mut String, value: &str) {
|
||||
if value.is_empty() {
|
||||
return;
|
||||
}
|
||||
if !field.is_empty() {
|
||||
field.push('\n');
|
||||
}
|
||||
field.push_str(value);
|
||||
}
|
||||
|
||||
/// Build search units and gram rows for the whole graph inside the publish
|
||||
/// transaction.
|
||||
pub fn build_index(
|
||||
tx: &Transaction<'_>,
|
||||
graph: &Graph,
|
||||
doc_ids: &HashMap<&str, i64>,
|
||||
node_ids: &HashMap<&str, i64>,
|
||||
) -> Result<IndexStats, rusqlite::Error> {
|
||||
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 {
|
||||
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;
|
||||
};
|
||||
// One search unit per (node, span chunk): never duplicate text.
|
||||
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),
|
||||
],
|
||||
)?;
|
||||
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),
|
||||
],
|
||||
)?;
|
||||
stats.search_units += 1;
|
||||
stats.grams += insert_grams(tx, unit_id, &spec.fields)?;
|
||||
}
|
||||
}
|
||||
Ok(stats)
|
||||
}
|
||||
|
||||
fn insert_grams(
|
||||
tx: &Transaction<'_>,
|
||||
unit_id: i64,
|
||||
fields: &SearchFields,
|
||||
) -> Result<u64, rusqlite::Error> {
|
||||
let mut count = 0u64;
|
||||
let mut seen: HashSet<(String, &'static str)> = HashSet::new();
|
||||
for (field_name, text_value) in [
|
||||
("title", fields.title.as_str()),
|
||||
("symbols", fields.symbols.as_str()),
|
||||
("metadata", fields.metadata.as_str()),
|
||||
] {
|
||||
let mut grams = text::grams(text_value);
|
||||
grams.truncate(MAX_GRAMS_PER_FIELD);
|
||||
for gram in grams {
|
||||
if !seen.insert((gram.clone(), field_name)) {
|
||||
continue;
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT OR IGNORE INTO grams (norm_gram, search_unit_id, field) VALUES (?1, ?2, ?3)",
|
||||
rusqlite::params![gram, unit_id, field_name],
|
||||
)?;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
let mut body_grams: Vec<String> = text::grams(&fields.body)
|
||||
.into_iter()
|
||||
.filter(|gram| {
|
||||
let chars: Vec<char> = gram.chars().collect();
|
||||
chars.len() == 2 && chars.iter().all(|ch| text::is_cjk(*ch))
|
||||
})
|
||||
.collect();
|
||||
body_grams.truncate(MAX_BODY_GRAMS);
|
||||
for gram in body_grams {
|
||||
if !seen.insert((gram.clone(), "body")) {
|
||||
continue;
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT OR IGNORE INTO grams (norm_gram, search_unit_id, field) VALUES (?1, ?2, ?3)",
|
||||
rusqlite::params![gram, unit_id, "body"],
|
||||
)?;
|
||||
count += 1;
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let mut specs = Vec::new();
|
||||
let node_by_key: HashMap<&str, &Node> = graph
|
||||
.nodes
|
||||
.iter()
|
||||
.map(|node| (node.key.as_str(), node))
|
||||
.collect();
|
||||
let mut blocks_by_unit: HashMap<usize, Vec<&BlockFact>> = HashMap::new();
|
||||
for block in &facts.blocks {
|
||||
blocks_by_unit.entry(block.unit).or_default().push(block);
|
||||
}
|
||||
for (unit_index, unit) in facts.units.iter().enumerate() {
|
||||
let node_key = if unit_index == 0 {
|
||||
identity::document_key(&facts.rel_path)
|
||||
} else {
|
||||
identity::unit_key(&facts.rel_path, unit.occurrence, &unit.path)
|
||||
};
|
||||
let node_key = node_key.as_str().to_string();
|
||||
let Some(node) = node_by_key.get(node_key.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
if !node.is_searchable() {
|
||||
continue;
|
||||
}
|
||||
let base = SearchFields {
|
||||
title: node.title.clone(),
|
||||
symbols: symbols_for(facts, unit_index),
|
||||
metadata: metadata_for(facts, unit_index, node),
|
||||
..SearchFields::default()
|
||||
};
|
||||
let blocks = blocks_by_unit.get(&unit_index).cloned().unwrap_or_default();
|
||||
if blocks.is_empty() {
|
||||
let span = if unit_index == 0 {
|
||||
Span::new(0, source_len(facts))
|
||||
} else {
|
||||
unit.span
|
||||
};
|
||||
specs.push(UnitSpec {
|
||||
node_key,
|
||||
span,
|
||||
fields: base,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
// Chunk on block boundaries. Title/symbols/metadata are emitted only in
|
||||
// the first chunk so a long document cannot multiply title matches.
|
||||
let mut current_fields = SearchFields::default();
|
||||
let mut chunk_start = blocks[0].span.start;
|
||||
let mut chunk_end = blocks[0].span.end;
|
||||
let mut first = true;
|
||||
let flush = |fields: SearchFields,
|
||||
start: u64,
|
||||
end: u64,
|
||||
first: bool,
|
||||
specs: &mut Vec<UnitSpec>,
|
||||
base: &SearchFields,
|
||||
node_key: &str| {
|
||||
if fields.byte_len() == 0 && !first {
|
||||
return;
|
||||
}
|
||||
let mut merged = fields;
|
||||
if first {
|
||||
merged.title = base.title.clone();
|
||||
merged.symbols = base.symbols.clone();
|
||||
merged.metadata = base.metadata.clone();
|
||||
}
|
||||
specs.push(UnitSpec {
|
||||
node_key: node_key.to_string(),
|
||||
span: Span::new(start, end),
|
||||
fields: merged,
|
||||
});
|
||||
};
|
||||
for block in blocks {
|
||||
let block_len =
|
||||
block.text.len() + block.formula.len() + block.table.len() + block.links.len();
|
||||
if !first && current_fields.byte_len() + block_len > MAX_CHUNK_BYTES {
|
||||
flush(
|
||||
std::mem::take(&mut current_fields),
|
||||
chunk_start,
|
||||
chunk_end,
|
||||
first,
|
||||
&mut specs,
|
||||
&base,
|
||||
&node_key,
|
||||
);
|
||||
first = false;
|
||||
chunk_start = block.span.start;
|
||||
}
|
||||
current_fields.append_block(block);
|
||||
chunk_end = block.span.end;
|
||||
}
|
||||
flush(
|
||||
current_fields,
|
||||
chunk_start,
|
||||
chunk_end,
|
||||
first,
|
||||
&mut specs,
|
||||
&base,
|
||||
&node_key,
|
||||
);
|
||||
}
|
||||
let _ = node_by_key;
|
||||
specs
|
||||
}
|
||||
|
||||
fn source_len(facts: &DocumentFacts) -> u64 {
|
||||
facts
|
||||
.units
|
||||
.first()
|
||||
.map(|unit| unit.span.end)
|
||||
.unwrap_or_else(|| facts.ast.span.end)
|
||||
}
|
||||
|
||||
fn symbols_for(facts: &DocumentFacts, unit_index: usize) -> String {
|
||||
let mut symbols = String::new();
|
||||
if facts.units[unit_index].kind == UnitKind::Function {
|
||||
if let Some(function) = facts
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.unit == unit_index)
|
||||
{
|
||||
push_field(&mut symbols, &function.local_name);
|
||||
push_field(&mut symbols, &function.function_id);
|
||||
if let Some(namespace) = &function.namespace {
|
||||
push_field(&mut symbols, namespace);
|
||||
}
|
||||
if let Some(params) = function
|
||||
.signature
|
||||
.get("params")
|
||||
.and_then(|params| params.as_array())
|
||||
{
|
||||
for param in params {
|
||||
if let Some(name) = param.get("name").and_then(|name| name.as_str()) {
|
||||
push_field(&mut symbols, name);
|
||||
}
|
||||
if let Some(type_name) =
|
||||
param.get("type").and_then(|type_name| type_name.as_str())
|
||||
{
|
||||
push_field(&mut symbols, type_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
push_field(&mut symbols, &facts.units[unit_index].path.join(" "));
|
||||
if let Some(unit_id) = &facts.units[unit_index].unit_id {
|
||||
push_field(&mut symbols, unit_id);
|
||||
}
|
||||
symbols
|
||||
}
|
||||
|
||||
fn metadata_for(facts: &DocumentFacts, unit_index: usize, node: &Node) -> String {
|
||||
let mut metadata = String::new();
|
||||
if unit_index == 0 {
|
||||
if let Some(front_matter) = &facts.front_matter {
|
||||
if let Some(value) = &front_matter.value {
|
||||
let mut flat = String::new();
|
||||
flatten_json(value, &mut flat, 0);
|
||||
push_field(&mut metadata, &flat);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(analysis) = &facts.analysis {
|
||||
push_field(&mut metadata, &analysis.module_id);
|
||||
push_field(&mut metadata, &analysis.entry_module_id);
|
||||
push_field(&mut metadata, &analysis.root_id);
|
||||
}
|
||||
if let Some(signature) = node.metadata.get("signature") {
|
||||
if let Ok(serialized) = serde_json::to_string(signature) {
|
||||
push_field(&mut metadata, &serialized);
|
||||
}
|
||||
}
|
||||
metadata
|
||||
}
|
||||
|
||||
fn flatten_json(value: &serde_json::Value, out: &mut String, depth: usize) {
|
||||
if depth > 8 {
|
||||
return;
|
||||
}
|
||||
match value {
|
||||
serde_json::Value::Object(object) => {
|
||||
for (key, value) in object {
|
||||
push_field(out, key);
|
||||
flatten_json(value, out, depth + 1);
|
||||
}
|
||||
}
|
||||
serde_json::Value::Array(items) => {
|
||||
for item in items {
|
||||
flatten_json(item, out, depth + 1);
|
||||
}
|
||||
}
|
||||
serde_json::Value::String(text) => push_field(out, text),
|
||||
serde_json::Value::Number(number) => push_field(out, &number.to_string()),
|
||||
serde_json::Value::Bool(boolean) => {
|
||||
push_field(out, if *boolean { "true" } else { "false" })
|
||||
}
|
||||
serde_json::Value::Null => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn field_append_keeps_lines_separate() {
|
||||
let mut fields = SearchFields::default();
|
||||
fields.append_block(&BlockFact {
|
||||
kind: crate::document::BlockKind::Paragraph,
|
||||
span: Span::new(0, 1),
|
||||
unit: 0,
|
||||
text: "a".into(),
|
||||
formula: "f".into(),
|
||||
table: "t".into(),
|
||||
links: "l".into(),
|
||||
code: String::new(),
|
||||
});
|
||||
fields.append_block(&BlockFact {
|
||||
kind: crate::document::BlockKind::Paragraph,
|
||||
span: Span::new(1, 2),
|
||||
unit: 0,
|
||||
text: "b".into(),
|
||||
formula: String::new(),
|
||||
table: String::new(),
|
||||
links: String::new(),
|
||||
code: String::new(),
|
||||
});
|
||||
assert_eq!(fields.body, "a\nb");
|
||||
assert_eq!(fields.formula, "f");
|
||||
assert_eq!(fields.byte_len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flatten_json_preserves_keys_and_scalars() {
|
||||
let value = serde_json::json!({"type": "Theory", "tags": ["physics"], "n": 3});
|
||||
let mut out = String::new();
|
||||
flatten_json(&value, &mut out, 0);
|
||||
assert!(out.contains("type"));
|
||||
assert!(out.contains("Theory"));
|
||||
assert!(out.contains("physics"));
|
||||
assert!(out.contains('3'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,872 @@
|
||||
//! SQLite storage: one derived artifact, one schema revision, one writer.
|
||||
//!
|
||||
//! `publish` is the only write path. A full rebuild stages a private database
|
||||
//! in the target directory and renames it into place; an incremental update
|
||||
//! rewrites the projection inside one transaction on the existing file. Both
|
||||
//! share the same writer and only become visible when complete. A failure
|
||||
//! leaves the previous successful artifact untouched.
|
||||
|
||||
pub mod index;
|
||||
pub mod read;
|
||||
|
||||
use crate::diagnostic::{code, Diagnostic};
|
||||
use crate::document::analysis::ProjectContext;
|
||||
use crate::document::SourceSnapshot;
|
||||
use crate::error::KnowledgeError;
|
||||
use crate::graph::Graph;
|
||||
use crate::model::{sha256_prefixed, Span};
|
||||
use rusqlite::{Connection, OpenFlags, Transaction};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// On-disk schema revision. Incompatible databases are rejected and require an
|
||||
/// explicit rebuild; there is no migration.
|
||||
pub const SCHEMA_REVISION: u32 = 1;
|
||||
/// SQLite `application_id` marker (ASCII "MKN1").
|
||||
pub const APPLICATION_ID: i64 = 0x4D4B_4E31;
|
||||
/// Busy timeout for concurrent writer attempts.
|
||||
pub const BUSY_TIMEOUT_MS: u32 = 5_000;
|
||||
/// Maximum database size accepted or produced.
|
||||
pub const MAX_DATABASE_BYTES: u64 = 4 * 1024 * 1024 * 1024;
|
||||
const SCHEMA_SQL: &str = include_str!("schema.sql");
|
||||
|
||||
/// Build metadata persisted in the singleton row.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct BuildMeta {
|
||||
pub tool_version: String,
|
||||
pub schema_revision: u32,
|
||||
pub producer_version: String,
|
||||
pub core_identity: String,
|
||||
pub snapshot_digest: String,
|
||||
pub logical_digest: String,
|
||||
pub scope: serde_json::Value,
|
||||
pub options: serde_json::Value,
|
||||
pub index_config: serde_json::Value,
|
||||
pub embedding: Option<serde_json::Value>,
|
||||
pub facts_cache_version: u32,
|
||||
pub rebuild_generation: u64,
|
||||
pub complete: bool,
|
||||
}
|
||||
|
||||
impl BuildMeta {
|
||||
pub fn new(tool_version: &str, snapshot_digest: String, logical_digest: String) -> Self {
|
||||
Self {
|
||||
tool_version: tool_version.to_string(),
|
||||
schema_revision: SCHEMA_REVISION,
|
||||
producer_version: String::new(),
|
||||
core_identity: String::new(),
|
||||
snapshot_digest,
|
||||
logical_digest,
|
||||
scope: serde_json::Value::Null,
|
||||
options: serde_json::Value::Null,
|
||||
index_config: serde_json::json!({"fts": "unicode61", "grams": [2, 3], "chunk_bytes": 4096}),
|
||||
embedding: None,
|
||||
facts_cache_version: 1,
|
||||
rebuild_generation: 1,
|
||||
complete: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct PublishStats {
|
||||
pub mode: String,
|
||||
pub documents: u64,
|
||||
pub nodes: u64,
|
||||
pub edges: u64,
|
||||
pub search_units: u64,
|
||||
pub grams: u64,
|
||||
pub rebuild_generation: u64,
|
||||
}
|
||||
|
||||
pub struct PublishRequest<'a> {
|
||||
pub database_path: PathBuf,
|
||||
pub rebuild: bool,
|
||||
pub meta: BuildMeta,
|
||||
pub graph: &'a Graph,
|
||||
pub snapshot: &'a SourceSnapshot,
|
||||
pub contexts: &'a [ProjectContext],
|
||||
}
|
||||
|
||||
/// Open a connection with the mandatory safety pragmas.
|
||||
fn configure(conn: &Connection) -> Result<(), KnowledgeError> {
|
||||
conn.execute_batch(&format!(
|
||||
"PRAGMA foreign_keys = ON;\nPRAGMA busy_timeout = {BUSY_TIMEOUT_MS};"
|
||||
))
|
||||
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))
|
||||
}
|
||||
|
||||
/// Open the current database read-only and verify it is ours and current.
|
||||
pub fn open_read_only(path: &Path) -> Result<Connection, KnowledgeError> {
|
||||
if !path.is_file() {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::DATABASE_MISSING,
|
||||
"knowledge database does not exist",
|
||||
)
|
||||
.with_hint("run `marqdo knowledge compile` for this root"));
|
||||
}
|
||||
let metadata = std::fs::metadata(path).map_err(|error| {
|
||||
KnowledgeError::environment(
|
||||
code::DATABASE_MISSING,
|
||||
format!("database cannot be read: {error}"),
|
||||
)
|
||||
})?;
|
||||
if metadata.len() > MAX_DATABASE_BYTES {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::BUDGET_EXCEEDED,
|
||||
"knowledge database exceeds the size budget",
|
||||
));
|
||||
}
|
||||
let conn = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)
|
||||
.map_err(|error| database_error(path, error))?;
|
||||
configure(&conn)?;
|
||||
verify_schema(&conn, path)?;
|
||||
Ok(conn)
|
||||
}
|
||||
|
||||
/// Verify application id, schema revision, required tables and quick integrity.
|
||||
pub fn verify_schema(conn: &Connection, path: &Path) -> Result<(), KnowledgeError> {
|
||||
let application_id: i64 = conn
|
||||
.query_row("PRAGMA application_id", [], |row| row.get(0))
|
||||
.map_err(|error| database_error(path, error))?;
|
||||
if application_id != APPLICATION_ID {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::DATABASE_NOT_OURS,
|
||||
"file is not a marqdo-knowledge database",
|
||||
)
|
||||
.with_hint("move the foreign file away; this tool never overwrites unknown databases"));
|
||||
}
|
||||
let user_version: i64 = conn
|
||||
.query_row("PRAGMA user_version", [], |row| row.get(0))
|
||||
.map_err(|error| database_error(path, error))?;
|
||||
if user_version != i64::from(SCHEMA_REVISION) {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::DATABASE_OLD_SCHEMA,
|
||||
format!(
|
||||
"database schema revision {user_version} is not the current revision {SCHEMA_REVISION}"
|
||||
),
|
||||
)
|
||||
.with_hint("run `marqdo knowledge compile --rebuild` to rebuild the derived database"));
|
||||
}
|
||||
for table in [
|
||||
"build",
|
||||
"documents",
|
||||
"nodes",
|
||||
"aliases",
|
||||
"edges",
|
||||
"contexts",
|
||||
"inputs",
|
||||
"diagnostics",
|
||||
"search_units",
|
||||
"search_fts",
|
||||
"grams",
|
||||
"embeddings",
|
||||
] {
|
||||
let count: i64 = conn
|
||||
.query_row(
|
||||
"SELECT count(*) FROM sqlite_master WHERE (name = ?1 AND type IN ('table','view'))",
|
||||
[table],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(|error| database_error(path, error))?;
|
||||
if count != 1 {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::DATABASE_CORRUPT,
|
||||
format!("knowledge database is missing table `{table}`"),
|
||||
)
|
||||
.with_hint("run `marqdo knowledge compile --rebuild`"));
|
||||
}
|
||||
}
|
||||
let revision: i64 = conn
|
||||
.query_row(
|
||||
"SELECT schema_revision FROM build WHERE id = 1",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(|error| database_error(path, error))?;
|
||||
if revision != i64::from(SCHEMA_REVISION) {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::DATABASE_OLD_SCHEMA,
|
||||
"knowledge build metadata uses an incompatible schema revision",
|
||||
)
|
||||
.with_hint("run `marqdo knowledge compile --rebuild`"));
|
||||
}
|
||||
let check: String = conn
|
||||
.query_row("PRAGMA quick_check", [], |row| row.get(0))
|
||||
.map_err(|error| database_error(path, error))?;
|
||||
if check != "ok" {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::DATABASE_CORRUPT,
|
||||
"knowledge database failed its integrity check",
|
||||
)
|
||||
.with_hint("run `marqdo knowledge compile --rebuild`"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn database_error(path: &Path, error: rusqlite::Error) -> KnowledgeError {
|
||||
let message = error.to_string();
|
||||
if message.contains("not a database") || message.contains("file is encrypted") {
|
||||
return KnowledgeError::environment(
|
||||
code::DATABASE_NOT_OURS,
|
||||
"file is not a SQLite database this tool created",
|
||||
)
|
||||
.with_hint("move the foreign file away; this tool never overwrites unknown databases");
|
||||
}
|
||||
let _ = path;
|
||||
KnowledgeError::environment(code::DATABASE_CORRUPT, format!("database error: {message}"))
|
||||
}
|
||||
|
||||
/// Publish a complete projection. Chooses an atomic rebuild or a transactional
|
||||
/// incremental rewrite automatically.
|
||||
pub fn publish(request: PublishRequest<'_>) -> Result<PublishStats, KnowledgeError> {
|
||||
if request.graph.diagnostics.has_errors() {
|
||||
return Err(KnowledgeError::input(
|
||||
code::INTERNAL,
|
||||
"refusing to publish a graph that contains blocking diagnostics",
|
||||
));
|
||||
}
|
||||
let database_path = request.database_path.clone();
|
||||
let parent = database_path
|
||||
.parent()
|
||||
.ok_or_else(|| KnowledgeError::internal("database path has no parent directory"))?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
set_owner_only_directory(parent);
|
||||
|
||||
let exists = database_path.exists();
|
||||
let rebuild = request.rebuild || !exists;
|
||||
if rebuild {
|
||||
ensure_replaceable(&database_path)?;
|
||||
} else {
|
||||
// Validate before rewriting.
|
||||
let conn = open_read_only(&database_path)?;
|
||||
drop(conn);
|
||||
}
|
||||
|
||||
let mut stats = if rebuild {
|
||||
publish_rebuild(&request)?
|
||||
} else {
|
||||
publish_incremental(&request)?
|
||||
};
|
||||
stats.mode = if rebuild {
|
||||
"rebuild".into()
|
||||
} else {
|
||||
"incremental".into()
|
||||
};
|
||||
stats.rebuild_generation = request.meta.rebuild_generation;
|
||||
Ok(stats)
|
||||
}
|
||||
|
||||
fn publish_rebuild(request: &PublishRequest<'_>) -> Result<PublishStats, KnowledgeError> {
|
||||
let database_path = &request.database_path;
|
||||
let parent = database_path
|
||||
.parent()
|
||||
.ok_or_else(|| KnowledgeError::internal("database path has no parent directory"))?;
|
||||
let temp_path = temp_database_path(parent);
|
||||
let _cleanup = TempFileGuard {
|
||||
path: temp_path.clone(),
|
||||
};
|
||||
let mut conn = Connection::open(&temp_path).map_err(|error| {
|
||||
KnowledgeError::environment(code::IO, format!("cannot create staging database: {error}"))
|
||||
})?;
|
||||
configure(&conn)?;
|
||||
conn.execute_batch(SCHEMA_SQL)
|
||||
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
|
||||
conn.execute_batch(&format!(
|
||||
"PRAGMA application_id = {APPLICATION_ID};\nPRAGMA user_version = {SCHEMA_REVISION};"
|
||||
))
|
||||
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
|
||||
let mut meta = request.meta.clone();
|
||||
meta.rebuild_generation = if request.meta.rebuild_generation == 0 {
|
||||
1
|
||||
} else {
|
||||
request.meta.rebuild_generation
|
||||
};
|
||||
meta.complete = true;
|
||||
let stats = write_projection(&mut conn, request, &meta)?;
|
||||
// Verify before publishing.
|
||||
let check: String = conn
|
||||
.query_row("PRAGMA quick_check", [], |row| row.get(0))
|
||||
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
|
||||
if check != "ok" {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::DATABASE_CORRUPT,
|
||||
"staged database failed its integrity check; nothing was published",
|
||||
));
|
||||
}
|
||||
drop(conn);
|
||||
set_owner_only_file(&temp_path);
|
||||
// Re-check the target is still safe, then replace atomically.
|
||||
ensure_replaceable(database_path)?;
|
||||
std::fs::rename(&temp_path, database_path).map_err(|error| {
|
||||
KnowledgeError::environment(code::IO, format!("cannot publish database: {error}"))
|
||||
})?;
|
||||
set_owner_only_file(database_path);
|
||||
Ok(stats)
|
||||
}
|
||||
|
||||
fn publish_incremental(request: &PublishRequest<'_>) -> Result<PublishStats, KnowledgeError> {
|
||||
let database_path = &request.database_path;
|
||||
let mut conn = Connection::open(database_path).map_err(|error| {
|
||||
KnowledgeError::environment(
|
||||
code::IO,
|
||||
format!("cannot open database for update: {error}"),
|
||||
)
|
||||
})?;
|
||||
configure(&conn)?;
|
||||
verify_schema(&conn, database_path)?;
|
||||
// Rollback journal keeps the single persistent artifact self-contained.
|
||||
conn.execute_batch("PRAGMA journal_mode = DELETE;")
|
||||
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
|
||||
let transaction = conn.transaction().map_err(|error| {
|
||||
KnowledgeError::environment(
|
||||
code::DATABASE_CORRUPT,
|
||||
format!("cannot start transaction: {error}"),
|
||||
)
|
||||
})?;
|
||||
// Derived content is replaced atomically. Re-analysis is avoided by the
|
||||
// compiler's digest-guarded facts cache; the write set is the full
|
||||
// projection, which keeps incremental semantics equal to a full build.
|
||||
transaction
|
||||
.execute_batch(
|
||||
"INSERT INTO search_fts(search_fts) VALUES('delete-all');
|
||||
DELETE FROM embeddings;
|
||||
DELETE FROM grams;
|
||||
DELETE FROM search_units;
|
||||
DELETE FROM edges;
|
||||
DELETE FROM aliases;
|
||||
DELETE FROM nodes;
|
||||
DELETE FROM documents;
|
||||
DELETE FROM contexts;
|
||||
DELETE FROM inputs;
|
||||
DELETE FROM diagnostics;
|
||||
DELETE FROM build;",
|
||||
)
|
||||
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
|
||||
let mut meta = request.meta.clone();
|
||||
meta.rebuild_generation = request.meta.rebuild_generation;
|
||||
meta.complete = false;
|
||||
insert_build(&transaction, &meta)?;
|
||||
let stats = write_rows(&transaction, request, &meta)?;
|
||||
transaction
|
||||
.execute("UPDATE build SET complete = 1 WHERE id = 1", [])
|
||||
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
|
||||
transaction.commit().map_err(|error| {
|
||||
KnowledgeError::environment(code::DATABASE_CORRUPT, format!("commit failed: {error}"))
|
||||
})?;
|
||||
let check: String = conn
|
||||
.query_row("PRAGMA quick_check", [], |row| row.get(0))
|
||||
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
|
||||
if check != "ok" {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::DATABASE_CORRUPT,
|
||||
"updated database failed its integrity check",
|
||||
));
|
||||
}
|
||||
Ok(stats)
|
||||
}
|
||||
|
||||
fn write_projection(
|
||||
conn: &mut Connection,
|
||||
request: &PublishRequest<'_>,
|
||||
meta: &BuildMeta,
|
||||
) -> Result<PublishStats, KnowledgeError> {
|
||||
let transaction = conn.transaction().map_err(|error| {
|
||||
KnowledgeError::environment(
|
||||
code::DATABASE_CORRUPT,
|
||||
format!("cannot start transaction: {error}"),
|
||||
)
|
||||
})?;
|
||||
insert_build(&transaction, meta)?;
|
||||
let stats = write_rows(&transaction, request, meta)?;
|
||||
transaction.commit().map_err(|error| {
|
||||
KnowledgeError::environment(code::DATABASE_CORRUPT, format!("commit failed: {error}"))
|
||||
})?;
|
||||
Ok(stats)
|
||||
}
|
||||
|
||||
fn insert_build(transaction: &Transaction<'_>, meta: &BuildMeta) -> Result<(), KnowledgeError> {
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO build
|
||||
(id, schema_revision, application_id, tool_version, producer_version,
|
||||
core_identity, snapshot_digest, logical_digest, scope_json, options_json,
|
||||
index_config_json, embedding_json, facts_cache_version,
|
||||
rebuild_generation, complete)
|
||||
VALUES (1, ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
|
||||
rusqlite::params![
|
||||
i64::from(meta.schema_revision),
|
||||
APPLICATION_ID,
|
||||
meta.tool_version,
|
||||
meta.producer_version,
|
||||
meta.core_identity,
|
||||
meta.snapshot_digest,
|
||||
meta.logical_digest,
|
||||
serde_json::to_string(&meta.scope).unwrap_or_else(|_| "null".into()),
|
||||
serde_json::to_string(&meta.options).unwrap_or_else(|_| "null".into()),
|
||||
serde_json::to_string(&meta.index_config).unwrap_or_else(|_| "null".into()),
|
||||
meta.embedding
|
||||
.as_ref()
|
||||
.map(|embedding| serde_json::to_string(embedding)
|
||||
.unwrap_or_else(|_| "null".into())),
|
||||
i64::from(meta.facts_cache_version),
|
||||
meta.rebuild_generation as i64,
|
||||
i64::from(meta.complete),
|
||||
],
|
||||
)
|
||||
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_rows(
|
||||
transaction: &Transaction<'_>,
|
||||
request: &PublishRequest<'_>,
|
||||
meta: &BuildMeta,
|
||||
) -> Result<PublishStats, KnowledgeError> {
|
||||
let mut stats = PublishStats::default();
|
||||
// Documents.
|
||||
let mut doc_ids: HashMap<&str, i64> = HashMap::new();
|
||||
for facts in &request.graph.facts {
|
||||
let Some(file) = request
|
||||
.snapshot
|
||||
.files
|
||||
.iter()
|
||||
.find(|file| file.rel_path == facts.rel_path)
|
||||
else {
|
||||
return Err(KnowledgeError::input(
|
||||
code::INTERNAL,
|
||||
format!("document `{}` has no source snapshot entry", facts.rel_path),
|
||||
));
|
||||
};
|
||||
let facts_json = serde_json::to_string(facts).map_err(|error| {
|
||||
KnowledgeError::internal(format!("cannot serialise document facts: {error}"))
|
||||
})?;
|
||||
let facts_digest = sha256_prefixed(facts_json.as_bytes());
|
||||
let front_matter = facts
|
||||
.front_matter
|
||||
.as_ref()
|
||||
.and_then(|front_matter| front_matter.value.as_ref())
|
||||
.map(|value| serde_json::to_string(value).unwrap_or_else(|_| "null".into()));
|
||||
let status = if facts.diagnostics.has_errors() {
|
||||
"warnings"
|
||||
} else if facts.diagnostics.is_empty() {
|
||||
"ok"
|
||||
} else {
|
||||
"warnings"
|
||||
};
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO documents
|
||||
(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)",
|
||||
rusqlite::params![
|
||||
facts.rel_path,
|
||||
facts.format.as_str(),
|
||||
facts.source_digest,
|
||||
file.text.as_bytes(),
|
||||
facts.document_title,
|
||||
front_matter,
|
||||
facts
|
||||
.analysis
|
||||
.as_ref()
|
||||
.map(|analysis| analysis.context_id.clone()),
|
||||
facts
|
||||
.analysis
|
||||
.as_ref()
|
||||
.map(|analysis| analysis.module_id.clone()),
|
||||
facts_json,
|
||||
facts_digest,
|
||||
i64::from(meta.facts_cache_version),
|
||||
status,
|
||||
],
|
||||
)
|
||||
.map_err(|error| {
|
||||
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
|
||||
})?;
|
||||
doc_ids.insert(facts.rel_path.as_str(), transaction.last_insert_rowid());
|
||||
stats.documents += 1;
|
||||
}
|
||||
|
||||
// Nodes (parents updated in a second pass so insertion order is irrelevant).
|
||||
let mut node_ids: HashMap<&str, i64> = HashMap::new();
|
||||
for node in &request.graph.nodes {
|
||||
let doc_id = if node.doc_path.is_empty() {
|
||||
None
|
||||
} else {
|
||||
doc_ids.get(node.doc_path.as_str()).copied()
|
||||
};
|
||||
let title_norm = crate::text::normalize(&node.title);
|
||||
let symbol_norm = node
|
||||
.metadata
|
||||
.get("local_name")
|
||||
.and_then(|value| value.as_str())
|
||||
.map(crate::text::normalize);
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO nodes
|
||||
(canonical_key, kind, doc_id, parent_id, span_start, span_end,
|
||||
title, title_norm, symbol_norm, content_digest, semantic_digest,
|
||||
searchable, metadata_json)
|
||||
VALUES (?1, ?2, ?3, NULL, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
|
||||
rusqlite::params![
|
||||
node.key.as_str(),
|
||||
node.kind.as_str(),
|
||||
doc_id,
|
||||
node.span.map(|span| span.start as i64),
|
||||
node.span.map(|span| span.end as i64),
|
||||
node.title,
|
||||
title_norm,
|
||||
symbol_norm,
|
||||
node.content_digest,
|
||||
node.semantic_digest,
|
||||
i64::from(node.is_searchable()),
|
||||
serde_json::to_string(&node.metadata).unwrap_or_else(|_| "null".into()),
|
||||
],
|
||||
)
|
||||
.map_err(|error| {
|
||||
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
|
||||
})?;
|
||||
node_ids.insert(node.key.as_str(), transaction.last_insert_rowid());
|
||||
stats.nodes += 1;
|
||||
}
|
||||
for node in &request.graph.nodes {
|
||||
let Some(parent) = &node.parent else {
|
||||
continue;
|
||||
};
|
||||
let (Some(node_id), Some(parent_id)) = (
|
||||
node_ids.get(node.key.as_str()),
|
||||
node_ids.get(parent.as_str()),
|
||||
) else {
|
||||
return Err(KnowledgeError::internal(
|
||||
"node parent is missing during publication",
|
||||
));
|
||||
};
|
||||
transaction
|
||||
.execute(
|
||||
"UPDATE nodes SET parent_id = ?1 WHERE id = ?2",
|
||||
rusqlite::params![parent_id, node_id],
|
||||
)
|
||||
.map_err(|error| {
|
||||
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
|
||||
})?;
|
||||
}
|
||||
|
||||
// Aliases.
|
||||
for alias in &request.graph.aliases {
|
||||
let Some(node_id) = node_ids.get(alias.node.as_str()) else {
|
||||
return Err(KnowledgeError::internal(
|
||||
"alias node is missing during publication",
|
||||
));
|
||||
};
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO aliases (alias, context_id, node_id) VALUES (?1, ?2, ?3)",
|
||||
rusqlite::params![
|
||||
alias.alias,
|
||||
alias.context.clone().unwrap_or_default(),
|
||||
node_id
|
||||
],
|
||||
)
|
||||
.map_err(|error| {
|
||||
KnowledgeError::environment(
|
||||
code::INTERFACE_CONFLICT,
|
||||
format!("alias cannot be stored unambiguously: {error}"),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
|
||||
// Edges.
|
||||
for edge in &request.graph.edges {
|
||||
let Some(source_id) = node_ids.get(edge.source.as_str()).copied() else {
|
||||
return Err(KnowledgeError::internal(
|
||||
"edge source is missing during publication",
|
||||
));
|
||||
};
|
||||
let target_id = match &edge.target {
|
||||
Some(target) => Some(*node_ids.get(target.as_str()).ok_or_else(|| {
|
||||
KnowledgeError::internal("edge target is missing during publication")
|
||||
})?),
|
||||
None => None,
|
||||
};
|
||||
let doc_id = doc_ids.get(edge.doc_path.as_str()).copied();
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO edges
|
||||
(source_id, target_id, kind, origin, raw_target, span_start, span_end,
|
||||
doc_id, state, context_id)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
rusqlite::params![
|
||||
source_id,
|
||||
target_id,
|
||||
edge.kind.as_str(),
|
||||
edge.origin.as_str(),
|
||||
edge.raw_target,
|
||||
edge.span.map(|span| span.start as i64),
|
||||
edge.span.map(|span| span.end as i64),
|
||||
doc_id,
|
||||
edge.state.as_str(),
|
||||
edge.context,
|
||||
],
|
||||
)
|
||||
.map_err(|error| {
|
||||
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
|
||||
})?;
|
||||
stats.edges += 1;
|
||||
}
|
||||
|
||||
// Analysis contexts.
|
||||
for context in request.contexts {
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT OR IGNORE INTO contexts
|
||||
(context_id, entry_module_id, root_id, identity_kind, manifest_digest,
|
||||
lock_digest, stdlib_digest, producer_version, analysis_digest, extensions_json)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
rusqlite::params![
|
||||
context.context_id,
|
||||
context.entry_module_id,
|
||||
context.root_id,
|
||||
context.identity_kind,
|
||||
context.manifest_digest,
|
||||
context.lock_digest,
|
||||
context.stdlib_digest,
|
||||
context.producer_version,
|
||||
context.analysis_digest,
|
||||
serde_json::to_string(&context.extensions).unwrap_or_else(|_| "null".into()),
|
||||
],
|
||||
)
|
||||
.map_err(|error| {
|
||||
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
|
||||
})?;
|
||||
}
|
||||
|
||||
// Input snapshot.
|
||||
for input in request.snapshot.inputs() {
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT OR REPLACE INTO inputs (path, kind, digest, size) VALUES (?1, ?2, ?3, ?4)",
|
||||
rusqlite::params![
|
||||
input.path,
|
||||
input.kind.as_str(),
|
||||
input.digest,
|
||||
input.size as i64
|
||||
],
|
||||
)
|
||||
.map_err(|error| {
|
||||
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
|
||||
})?;
|
||||
}
|
||||
|
||||
// Diagnostics (also those discovered by the graph layer).
|
||||
for diagnostic in request.graph.diagnostics.iter() {
|
||||
insert_diagnostic(transaction, diagnostic)?;
|
||||
}
|
||||
for diagnostic in request.snapshot.diagnostics.iter() {
|
||||
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()))?;
|
||||
stats.search_units = index_stats.search_units;
|
||||
stats.grams = index_stats.grams;
|
||||
Ok(stats)
|
||||
}
|
||||
|
||||
fn insert_diagnostic(
|
||||
transaction: &Transaction<'_>,
|
||||
diagnostic: &Diagnostic,
|
||||
) -> Result<(), KnowledgeError> {
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO diagnostics
|
||||
(code, severity, path, span_start, span_end, message, hints_json)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
|
||||
rusqlite::params![
|
||||
diagnostic.code,
|
||||
diagnostic.severity.as_str(),
|
||||
diagnostic.path,
|
||||
diagnostic.span.map(|span| span.start as i64),
|
||||
diagnostic.span.map(|span| span.end as i64),
|
||||
diagnostic.message,
|
||||
serde_json::to_string(&diagnostic.hints).unwrap_or_else(|_| "[]".into()),
|
||||
],
|
||||
)
|
||||
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_replaceable(database_path: &Path) -> Result<(), KnowledgeError> {
|
||||
match std::fs::symlink_metadata(database_path) {
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(error) => Err(KnowledgeError::environment(
|
||||
code::IO,
|
||||
format!("database path cannot be inspected: {error}"),
|
||||
)),
|
||||
Ok(metadata) if metadata.file_type().is_symlink() => Err(KnowledgeError::environment(
|
||||
code::DATABASE_NOT_OURS,
|
||||
"database path is a symbolic link; refusing to replace it",
|
||||
)),
|
||||
Ok(metadata) if !metadata.is_file() => Err(KnowledgeError::environment(
|
||||
code::DATABASE_NOT_OURS,
|
||||
"database path is not a regular file; refusing to replace it",
|
||||
)),
|
||||
Ok(_) => {
|
||||
// Only replace a database this tool created.
|
||||
let conn = Connection::open_with_flags(database_path, OpenFlags::SQLITE_OPEN_READ_ONLY)
|
||||
.map_err(|error| database_error(database_path, error))?;
|
||||
let application_id: i64 = conn
|
||||
.query_row("PRAGMA application_id", [], |row| row.get(0))
|
||||
.map_err(|error| database_error(database_path, error))?;
|
||||
if application_id != APPLICATION_ID {
|
||||
return Err(KnowledgeError::environment(
|
||||
code::DATABASE_NOT_OURS,
|
||||
"existing database was not created by this tool; refusing to overwrite it",
|
||||
)
|
||||
.with_hint("move the foreign file away manually"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn temp_database_path(parent: &Path) -> PathBuf {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
parent.join(format!(
|
||||
".knowledge.sqlite.tmp.{}.{}",
|
||||
std::process::id(),
|
||||
counter
|
||||
))
|
||||
}
|
||||
|
||||
struct TempFileGuard {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Drop for TempFileGuard {
|
||||
fn drop(&mut self) {
|
||||
if self.path.exists() {
|
||||
let _ = std::fs::remove_file(&self.path);
|
||||
let _ = std::fs::remove_file(self.path.with_extension("sqlite-journal"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn set_owner_only_directory(path: &Path) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700));
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn set_owner_only_directory(_path: &Path) {}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn set_owner_only_file(path: &Path) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn set_owner_only_file(_path: &Path) {}
|
||||
|
||||
/// Currentness of the stored snapshot relative to the current source inputs.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Currentness {
|
||||
pub current: bool,
|
||||
pub snapshot_digest: String,
|
||||
pub stored_snapshot_digest: String,
|
||||
pub changed_inputs: Vec<String>,
|
||||
}
|
||||
|
||||
/// Compare the stored input manifest with the current source snapshot.
|
||||
pub fn check_current(
|
||||
conn: &Connection,
|
||||
snapshot: &SourceSnapshot,
|
||||
) -> Result<Currentness, KnowledgeError> {
|
||||
let stored_snapshot_digest: String = conn
|
||||
.query_row(
|
||||
"SELECT snapshot_digest FROM build WHERE id = 1",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
|
||||
let mut stored_inputs: HashMap<String, String> = HashMap::new();
|
||||
{
|
||||
let mut statement = conn
|
||||
.prepare("SELECT path, digest FROM inputs")
|
||||
.map_err(|error| {
|
||||
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
|
||||
})?;
|
||||
let rows = statement
|
||||
.query_map([], |row| {
|
||||
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
|
||||
})
|
||||
.map_err(|error| {
|
||||
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
|
||||
})?;
|
||||
for row in rows {
|
||||
let (path, digest) = row.map_err(|error| {
|
||||
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
|
||||
})?;
|
||||
stored_inputs.insert(path, digest);
|
||||
}
|
||||
}
|
||||
let current_inputs = snapshot.inputs();
|
||||
let current_digest = snapshot.snapshot_digest();
|
||||
let mut changed = Vec::new();
|
||||
for input in ¤t_inputs {
|
||||
match stored_inputs.get(&input.path) {
|
||||
Some(digest) if digest == &input.digest => {}
|
||||
_ => changed.push(input.path.clone()),
|
||||
}
|
||||
}
|
||||
for path in stored_inputs.keys() {
|
||||
if !current_inputs.iter().any(|input| &input.path == path) {
|
||||
changed.push(path.clone());
|
||||
}
|
||||
}
|
||||
changed.sort();
|
||||
changed.dedup();
|
||||
Ok(Currentness {
|
||||
current: changed.is_empty() && current_digest == stored_snapshot_digest,
|
||||
snapshot_digest: current_digest,
|
||||
stored_snapshot_digest,
|
||||
changed_inputs: changed,
|
||||
})
|
||||
}
|
||||
|
||||
/// Read one stored span as an exact source slice (used for snippets and
|
||||
/// slices). Returns `None` for invalid ranges.
|
||||
pub fn source_slice(source: &[u8], span: Span) -> Option<&str> {
|
||||
span.slice(source)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn application_id_marker_is_stable() {
|
||||
assert_eq!(APPLICATION_ID, 0x4D4B_4E31);
|
||||
assert_eq!(SCHEMA_REVISION, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temp_database_paths_are_unique_and_sibling() {
|
||||
let parent = Path::new("/tmp/example");
|
||||
let first = temp_database_path(parent);
|
||||
let second = temp_database_path(parent);
|
||||
assert_ne!(first, second);
|
||||
assert_eq!(first.parent(), Some(parent));
|
||||
assert!(first
|
||||
.file_name()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.starts_with(".knowledge.sqlite.tmp."));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,924 @@
|
||||
//! Read-only storage API. Query and check code use only this module; they never
|
||||
//! write graph facts.
|
||||
|
||||
use super::{open_read_only, BuildMeta, Currentness};
|
||||
use crate::document::analysis::ProjectContext;
|
||||
use crate::document::{DocumentFacts, DocumentFormat, InputKind, InputRecord};
|
||||
use crate::error::KnowledgeError;
|
||||
use crate::model::{EdgeKind, EdgeOrigin, EdgeState, NodeKind, Span};
|
||||
use rusqlite::Connection;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StoredDocumentMeta {
|
||||
pub id: i64,
|
||||
pub path: String,
|
||||
pub format: DocumentFormat,
|
||||
pub source_digest: String,
|
||||
pub title: String,
|
||||
pub role: String,
|
||||
pub analysis_context_id: Option<String>,
|
||||
pub module_id: Option<String>,
|
||||
pub facts_cache_version: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CachedFacts {
|
||||
pub facts_cache_version: u32,
|
||||
pub facts_digest: String,
|
||||
pub facts: DocumentFacts,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StoredNode {
|
||||
pub id: i64,
|
||||
pub key: String,
|
||||
pub kind: NodeKind,
|
||||
pub doc_id: Option<i64>,
|
||||
pub parent_id: Option<i64>,
|
||||
pub span: Option<Span>,
|
||||
pub title: String,
|
||||
pub title_norm: String,
|
||||
pub symbol_norm: Option<String>,
|
||||
pub content_digest: String,
|
||||
pub semantic_digest: Option<String>,
|
||||
pub searchable: bool,
|
||||
pub metadata: serde_json::Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StoredEdge {
|
||||
pub id: i64,
|
||||
pub source_id: i64,
|
||||
pub target_id: Option<i64>,
|
||||
pub kind: EdgeKind,
|
||||
pub origin: EdgeOrigin,
|
||||
pub raw_target: String,
|
||||
pub span: Option<Span>,
|
||||
pub doc_id: Option<i64>,
|
||||
pub state: EdgeState,
|
||||
pub context_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SearchUnitRow {
|
||||
pub id: i64,
|
||||
pub node_id: i64,
|
||||
pub doc_id: i64,
|
||||
pub span: Span,
|
||||
pub title: String,
|
||||
pub body: String,
|
||||
pub symbols: String,
|
||||
pub metadata: String,
|
||||
pub formula: String,
|
||||
pub tabular: String,
|
||||
pub links: String,
|
||||
}
|
||||
|
||||
impl SearchUnitRow {
|
||||
/// Field text used for snippets is never taken from generated strings; the
|
||||
/// caller slices the stored exact source with `span`.
|
||||
pub fn fields_for_matching(&self) -> [(&'static str, &str); 7] {
|
||||
[
|
||||
("title", &self.title),
|
||||
("body", &self.body),
|
||||
("symbols", &self.symbols),
|
||||
("metadata", &self.metadata),
|
||||
("formula", &self.formula),
|
||||
("table", &self.tabular),
|
||||
("links", &self.links),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FtsHit {
|
||||
pub unit_id: i64,
|
||||
pub node_id: i64,
|
||||
pub rank: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct GramHit {
|
||||
pub unit_id: i64,
|
||||
pub node_id: i64,
|
||||
pub overlap: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NodeIdHit {
|
||||
pub node_id: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EmbeddingRow {
|
||||
pub unit_id: i64,
|
||||
pub node_id: i64,
|
||||
pub vector: Vec<f32>,
|
||||
}
|
||||
|
||||
pub struct ReadStore {
|
||||
conn: Connection,
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
impl ReadStore {
|
||||
pub fn open(path: &Path) -> Result<Self, KnowledgeError> {
|
||||
let conn = open_read_only(path)?;
|
||||
Ok(Self {
|
||||
conn,
|
||||
path: path.to_path_buf(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_meta(&self) -> Result<BuildMeta, KnowledgeError> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT schema_revision, tool_version, producer_version, core_identity,
|
||||
snapshot_digest, logical_digest, scope_json, options_json,
|
||||
index_config_json, embedding_json, facts_cache_version,
|
||||
rebuild_generation, complete
|
||||
FROM build WHERE id = 1",
|
||||
[],
|
||||
|row| {
|
||||
let embedding_json: Option<String> = row.get(9)?;
|
||||
Ok(BuildMeta {
|
||||
schema_revision: row.get::<_, i64>(0)? as u32,
|
||||
tool_version: row.get(1)?,
|
||||
producer_version: row.get(2)?,
|
||||
core_identity: row.get(3)?,
|
||||
snapshot_digest: row.get(4)?,
|
||||
logical_digest: row.get(5)?,
|
||||
scope: serde_json::from_str(&row.get::<_, String>(6)?)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
options: serde_json::from_str(&row.get::<_, String>(7)?)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
index_config: serde_json::from_str(&row.get::<_, String>(8)?)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
embedding: embedding_json.and_then(|json| serde_json::from_str(&json).ok()),
|
||||
facts_cache_version: row.get::<_, i64>(10)? as u32,
|
||||
rebuild_generation: row.get::<_, i64>(11)? as u64,
|
||||
complete: row.get::<_, i64>(12)? != 0,
|
||||
})
|
||||
},
|
||||
)
|
||||
.map_err(|error| {
|
||||
KnowledgeError::environment(
|
||||
crate::diagnostic::code::DATABASE_CORRUPT,
|
||||
error.to_string(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn inputs(&self) -> Result<Vec<InputRecord>, KnowledgeError> {
|
||||
let mut statement = self
|
||||
.conn
|
||||
.prepare("SELECT path, kind, digest, size FROM inputs ORDER BY path, kind")
|
||||
.map_err(db)?;
|
||||
let rows = statement
|
||||
.query_map([], |row| {
|
||||
Ok(InputRecord {
|
||||
path: row.get(0)?,
|
||||
kind: match row.get::<_, String>(1)?.as_str() {
|
||||
"document" => InputKind::Document,
|
||||
"manifest" => InputKind::Manifest,
|
||||
"lock" => InputKind::Lock,
|
||||
_ => InputKind::Asset,
|
||||
},
|
||||
digest: row.get(2)?,
|
||||
size: row.get::<_, i64>(3)? as u64,
|
||||
})
|
||||
})
|
||||
.map_err(db)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
out.push(row.map_err(db)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn contexts(&self) -> Result<Vec<ProjectContext>, KnowledgeError> {
|
||||
let mut statement = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT context_id, entry_module_id, root_id, identity_kind, manifest_digest,
|
||||
lock_digest, stdlib_digest, producer_version, analysis_digest, extensions_json
|
||||
FROM contexts ORDER BY context_id",
|
||||
)
|
||||
.map_err(db)?;
|
||||
let rows = statement
|
||||
.query_map([], |row| {
|
||||
Ok(ProjectContext {
|
||||
context_id: row.get(0)?,
|
||||
entry_module_id: row.get(1)?,
|
||||
root_id: row.get(2)?,
|
||||
identity_kind: row.get(3)?,
|
||||
manifest_digest: row.get(4)?,
|
||||
lock_digest: row.get(5)?,
|
||||
stdlib_digest: row.get(6)?,
|
||||
producer_version: row.get(7)?,
|
||||
analysis_digest: row.get(8)?,
|
||||
extensions: serde_json::from_str(&row.get::<_, String>(9)?)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
})
|
||||
})
|
||||
.map_err(db)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
out.push(row.map_err(db)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn documents(&self) -> Result<Vec<StoredDocumentMeta>, KnowledgeError> {
|
||||
let mut statement = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT id, path, format, source_digest, title, document_role,
|
||||
analysis_context_id, module_id, facts_cache_version
|
||||
FROM documents ORDER BY path",
|
||||
)
|
||||
.map_err(db)?;
|
||||
let rows = statement
|
||||
.query_map([], |row| {
|
||||
let format: String = row.get(2)?;
|
||||
Ok(StoredDocumentMeta {
|
||||
id: row.get(0)?,
|
||||
path: row.get(1)?,
|
||||
format: if format == "marqdo" {
|
||||
DocumentFormat::Marqdo
|
||||
} else {
|
||||
DocumentFormat::PlainMarkdown
|
||||
},
|
||||
source_digest: row.get(3)?,
|
||||
title: row.get(4)?,
|
||||
role: row.get(5)?,
|
||||
analysis_context_id: row.get(6)?,
|
||||
module_id: row.get(7)?,
|
||||
facts_cache_version: row.get::<_, Option<i64>>(8)?.map(|value| value as u32),
|
||||
})
|
||||
})
|
||||
.map_err(db)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
out.push(row.map_err(db)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn document_meta(&self, path: &str) -> Result<Option<StoredDocumentMeta>, KnowledgeError> {
|
||||
Ok(self
|
||||
.documents()?
|
||||
.into_iter()
|
||||
.find(|document| document.path == path))
|
||||
}
|
||||
|
||||
pub fn load_facts(&self, path: &str) -> Result<Option<CachedFacts>, KnowledgeError> {
|
||||
let row: Option<(Option<String>, Option<i64>, Option<String>)> = self
|
||||
.conn
|
||||
.query_row(
|
||||
"SELECT facts_json, facts_cache_version, facts_digest FROM documents WHERE path = ?1",
|
||||
[path],
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
|
||||
)
|
||||
.optional()
|
||||
.map_err(db)?;
|
||||
let Some((facts_json, version, digest)) = row else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (Some(facts_json), Some(version), Some(digest)) = (facts_json, version, digest) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let facts: DocumentFacts = serde_json::from_str(&facts_json).map_err(|error| {
|
||||
KnowledgeError::environment(
|
||||
crate::diagnostic::code::DATABASE_CORRUPT,
|
||||
format!("cached document facts are invalid: {error}"),
|
||||
)
|
||||
})?;
|
||||
Ok(Some(CachedFacts {
|
||||
facts_cache_version: version as u32,
|
||||
facts_digest: digest,
|
||||
facts,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn document_source(&self, doc_id: i64) -> Result<Vec<u8>, KnowledgeError> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT source FROM documents WHERE id = ?1",
|
||||
[doc_id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(db)
|
||||
}
|
||||
|
||||
pub fn node_by_key(&self, key: &str) -> Result<Option<StoredNode>, KnowledgeError> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT id, canonical_key, kind, doc_id, parent_id, span_start, span_end,
|
||||
title, title_norm, symbol_norm, content_digest, semantic_digest,
|
||||
searchable, metadata_json
|
||||
FROM nodes WHERE canonical_key = ?1",
|
||||
[key],
|
||||
map_node,
|
||||
)
|
||||
.optional()
|
||||
.map_err(db)
|
||||
}
|
||||
|
||||
pub fn node_by_id(&self, id: i64) -> Result<Option<StoredNode>, KnowledgeError> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT id, canonical_key, kind, doc_id, parent_id, span_start, span_end,
|
||||
title, title_norm, symbol_norm, content_digest, semantic_digest,
|
||||
searchable, metadata_json
|
||||
FROM nodes WHERE id = ?1",
|
||||
[id],
|
||||
map_node,
|
||||
)
|
||||
.optional()
|
||||
.map_err(db)
|
||||
}
|
||||
|
||||
pub fn nodes_by_ids(&self, ids: &[i64]) -> Result<Vec<StoredNode>, KnowledgeError> {
|
||||
let mut out = Vec::with_capacity(ids.len());
|
||||
for id in ids {
|
||||
if let Some(node) = self.node_by_id(*id)? {
|
||||
out.push(node);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn aliases_for(&self, alias: &str) -> Result<Vec<(String, StoredNode)>, KnowledgeError> {
|
||||
let mut statement = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT a.context_id, n.id, n.canonical_key, n.kind, n.doc_id, n.parent_id,
|
||||
n.span_start, n.span_end, n.title, n.title_norm, n.symbol_norm,
|
||||
n.content_digest, n.semantic_digest, n.searchable, n.metadata_json
|
||||
FROM aliases a JOIN nodes n ON n.id = a.node_id
|
||||
WHERE a.alias = ?1 ORDER BY a.context_id",
|
||||
)
|
||||
.map_err(db)?;
|
||||
let rows = statement
|
||||
.query_map([alias], |row| {
|
||||
Ok((row.get::<_, String>(0)?, map_node(row)?))
|
||||
})
|
||||
.map_err(db)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
out.push(row.map_err(db)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Exact normalised title or function-name matches. Used by the exact
|
||||
/// channel; ambiguity is returned as multiple rows and never resolved by
|
||||
/// the storage layer.
|
||||
pub fn nodes_by_exact_name(&self, normalized: &str) -> Result<Vec<StoredNode>, KnowledgeError> {
|
||||
let mut statement = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT id, canonical_key, kind, doc_id, parent_id, span_start, span_end,
|
||||
title, title_norm, symbol_norm, content_digest, semantic_digest,
|
||||
searchable, metadata_json
|
||||
FROM nodes
|
||||
WHERE (title_norm = ?1 OR symbol_norm = ?1) AND searchable = 1
|
||||
ORDER BY canonical_key LIMIT 64",
|
||||
)
|
||||
.map_err(db)?;
|
||||
let rows = statement.query_map([normalized], map_node).map_err(db)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
out.push(row.map_err(db)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn edges_from(
|
||||
&self,
|
||||
source_ids: &[i64],
|
||||
kinds: &[EdgeKind],
|
||||
) -> Result<Vec<StoredEdge>, KnowledgeError> {
|
||||
self.edges_for(source_ids, kinds, false)
|
||||
}
|
||||
|
||||
pub fn edges_to(
|
||||
&self,
|
||||
target_ids: &[i64],
|
||||
kinds: &[EdgeKind],
|
||||
) -> Result<Vec<StoredEdge>, KnowledgeError> {
|
||||
self.edges_for(target_ids, kinds, true)
|
||||
}
|
||||
|
||||
fn edges_for(
|
||||
&self,
|
||||
ids: &[i64],
|
||||
kinds: &[EdgeKind],
|
||||
reverse: bool,
|
||||
) -> Result<Vec<StoredEdge>, KnowledgeError> {
|
||||
if ids.is_empty() || kinds.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let column = if reverse { "target_id" } else { "source_id" };
|
||||
let select = "SELECT id, source_id, target_id, kind, origin, raw_target,
|
||||
span_start, span_end, doc_id, state, context_id FROM edges";
|
||||
let mut out = Vec::new();
|
||||
for kind in kinds {
|
||||
let mut statement = self
|
||||
.conn
|
||||
.prepare(&format!(
|
||||
"{select} WHERE {column} = ?1 AND kind = ?2 ORDER BY id LIMIT 2000"
|
||||
))
|
||||
.map_err(db)?;
|
||||
for id in ids {
|
||||
let rows = statement
|
||||
.query_map(rusqlite::params![id, kind.as_str()], map_edge)
|
||||
.map_err(db)?;
|
||||
for row in rows {
|
||||
out.push(row.map_err(db)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| {
|
||||
a.source_id
|
||||
.cmp(&b.source_id)
|
||||
.then(a.target_id.cmp(&b.target_id))
|
||||
.then(a.kind.as_str().cmp(b.kind.as_str()))
|
||||
.then(a.id.cmp(&b.id))
|
||||
});
|
||||
out.dedup_by(|a, b| a.id == b.id);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn adjacent_node_ids(
|
||||
&self,
|
||||
node_ids: &[i64],
|
||||
kinds: &[EdgeKind],
|
||||
reverse: bool,
|
||||
) -> Result<Vec<i64>, KnowledgeError> {
|
||||
let edges = self.edges_for(node_ids, kinds, reverse)?;
|
||||
let mut out: Vec<i64> = edges
|
||||
.iter()
|
||||
.filter(|edge| edge.state.is_bound())
|
||||
.filter_map(|edge| {
|
||||
if reverse {
|
||||
Some(edge.source_id)
|
||||
} else {
|
||||
edge.target_id
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out.dedup();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn search_unit(&self, unit_id: i64) -> Result<Option<SearchUnitRow>, KnowledgeError> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT id, node_id, doc_id, span_start, span_end, title, body, symbols,
|
||||
metadata, formula, tabular, links
|
||||
FROM search_units WHERE id = ?1",
|
||||
[unit_id],
|
||||
map_search_unit,
|
||||
)
|
||||
.optional()
|
||||
.map_err(db)
|
||||
}
|
||||
|
||||
pub fn search_units_for_nodes(
|
||||
&self,
|
||||
node_ids: &[i64],
|
||||
) -> Result<Vec<SearchUnitRow>, KnowledgeError> {
|
||||
let mut out = Vec::new();
|
||||
for node_id in node_ids {
|
||||
let mut statement = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT id, node_id, doc_id, span_start, span_end, title, body, symbols,
|
||||
metadata, formula, tabular, links
|
||||
FROM search_units WHERE node_id = ?1 ORDER BY span_start, span_end",
|
||||
)
|
||||
.map_err(db)?;
|
||||
let rows = statement
|
||||
.query_map([node_id], map_search_unit)
|
||||
.map_err(db)?;
|
||||
for row in rows {
|
||||
out.push(row.map_err(db)?);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Lexical channel: FTS5 BM25 with field weights. The caller supplies a safe
|
||||
/// quoted OR query built by `crate::text::fts_query`.
|
||||
pub fn fts_search(&self, query: &str, limit: usize) -> Result<Vec<FtsHit>, KnowledgeError> {
|
||||
let mut statement = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT su.id, su.node_id,
|
||||
bm25(search_fts, 5.0, 1.0, 4.0, 3.0, 1.0, 1.0, 1.0) AS rank
|
||||
FROM search_fts JOIN search_units su ON su.id = search_fts.rowid
|
||||
WHERE search_fts MATCH ?1
|
||||
ORDER BY rank, su.id LIMIT ?2",
|
||||
)
|
||||
.map_err(db)?;
|
||||
let rows = statement
|
||||
.query_map(rusqlite::params![query, limit as i64], |row| {
|
||||
Ok(FtsHit {
|
||||
unit_id: row.get(0)?,
|
||||
node_id: row.get(1)?,
|
||||
rank: row.get(2)?,
|
||||
})
|
||||
})
|
||||
.map_err(db)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
out.push(row.map_err(db)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Fuzzy channel: gram overlap candidates, bounded.
|
||||
pub fn gram_candidates(
|
||||
&self,
|
||||
grams: &[String],
|
||||
limit: usize,
|
||||
) -> Result<Vec<GramHit>, KnowledgeError> {
|
||||
if grams.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let placeholders = vec!["?"; grams.len()].join(",");
|
||||
let sql = format!(
|
||||
"SELECT g.search_unit_id, su.node_id, COUNT(*) AS overlap
|
||||
FROM grams g JOIN search_units su ON su.id = g.search_unit_id
|
||||
WHERE g.norm_gram IN ({placeholders})
|
||||
GROUP BY g.search_unit_id
|
||||
ORDER BY overlap DESC, g.search_unit_id
|
||||
LIMIT {limit}"
|
||||
);
|
||||
let mut statement = self.conn.prepare(&sql).map_err(db)?;
|
||||
let params: Vec<&dyn rusqlite::ToSql> = grams
|
||||
.iter()
|
||||
.map(|gram| gram as &dyn rusqlite::ToSql)
|
||||
.collect();
|
||||
let rows = statement
|
||||
.query_map(params.as_slice(), |row| {
|
||||
Ok(GramHit {
|
||||
unit_id: row.get(0)?,
|
||||
node_id: row.get(1)?,
|
||||
overlap: row.get(2)?,
|
||||
})
|
||||
})
|
||||
.map_err(db)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
out.push(row.map_err(db)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Bounded single-character fallback: exact character search over titles,
|
||||
/// symbols and a limited body scan. This is intentionally not exhaustive.
|
||||
pub fn single_char_candidates(
|
||||
&self,
|
||||
chars: &[char],
|
||||
limit: usize,
|
||||
) -> Result<Vec<NodeIdHit>, KnowledgeError> {
|
||||
let Some(first) = chars.first() else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let like = format!("%{}%", escape_like(&first.to_string()));
|
||||
let mut out = Vec::new();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
{
|
||||
let mut statement = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT id FROM nodes
|
||||
WHERE searchable = 1 AND (title LIKE ?1 ESCAPE '\\' OR symbol_norm LIKE ?1 ESCAPE '\\')
|
||||
ORDER BY id LIMIT ?2",
|
||||
)
|
||||
.map_err(db)?;
|
||||
let rows = statement
|
||||
.query_map(rusqlite::params![like, limit as i64], |row| {
|
||||
row.get::<_, i64>(0)
|
||||
})
|
||||
.map_err(db)?;
|
||||
for row in rows {
|
||||
let id = row.map_err(db)?;
|
||||
if seen.insert(id) {
|
||||
out.push(NodeIdHit { node_id: id });
|
||||
}
|
||||
}
|
||||
}
|
||||
if out.len() < limit {
|
||||
let remaining = (limit - out.len()) as i64;
|
||||
let mut statement = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT DISTINCT node_id FROM search_units
|
||||
WHERE body LIKE ?1 ESCAPE '\\' LIMIT ?2",
|
||||
)
|
||||
.map_err(db)?;
|
||||
let rows = statement
|
||||
.query_map(rusqlite::params![like, remaining], |row| {
|
||||
row.get::<_, i64>(0)
|
||||
})
|
||||
.map_err(db)?;
|
||||
for row in rows {
|
||||
let id = row.map_err(db)?;
|
||||
if seen.insert(id) {
|
||||
out.push(NodeIdHit { node_id: id });
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn embeddings(
|
||||
&self,
|
||||
model_digest: &str,
|
||||
limit: usize,
|
||||
) -> Result<Vec<EmbeddingRow>, KnowledgeError> {
|
||||
let mut statement = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT e.search_unit_id, su.node_id, e.vector
|
||||
FROM embeddings e JOIN search_units su ON su.id = e.search_unit_id
|
||||
WHERE e.model_digest = ?1
|
||||
ORDER BY e.search_unit_id LIMIT ?2",
|
||||
)
|
||||
.map_err(db)?;
|
||||
let rows = statement
|
||||
.query_map(rusqlite::params![model_digest, limit as i64], |row| {
|
||||
let blob: Vec<u8> = row.get(2)?;
|
||||
let mut vector = Vec::with_capacity(blob.len() / 4);
|
||||
for chunk in blob.as_chunks::<4>().0 {
|
||||
vector.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
|
||||
}
|
||||
Ok(EmbeddingRow {
|
||||
unit_id: row.get(0)?,
|
||||
node_id: row.get(1)?,
|
||||
vector,
|
||||
})
|
||||
})
|
||||
.map_err(db)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
out.push(row.map_err(db)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn diagnostics(&self) -> Result<Vec<crate::diagnostic::Diagnostic>, KnowledgeError> {
|
||||
let mut statement = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT code, severity, path, span_start, span_end, message, hints_json
|
||||
FROM diagnostics ORDER BY path, span_start, code, message",
|
||||
)
|
||||
.map_err(db)?;
|
||||
let rows = statement
|
||||
.query_map([], |row| {
|
||||
let severity: String = row.get(1)?;
|
||||
let hints_json: String = row.get(6)?;
|
||||
Ok(crate::diagnostic::Diagnostic {
|
||||
code: row.get(0)?,
|
||||
severity: if severity == "error" {
|
||||
crate::diagnostic::Severity::Error
|
||||
} else {
|
||||
crate::diagnostic::Severity::Warning
|
||||
},
|
||||
path: row.get(2)?,
|
||||
span: map_span(row, 3, 4)?,
|
||||
message: row.get(5)?,
|
||||
hints: serde_json::from_str(&hints_json).unwrap_or_default(),
|
||||
})
|
||||
})
|
||||
.map_err(db)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
out.push(row.map_err(db)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn currentness(
|
||||
&self,
|
||||
snapshot: &crate::document::SourceSnapshot,
|
||||
) -> Result<Currentness, KnowledgeError> {
|
||||
super::check_current(&self.conn, snapshot)
|
||||
}
|
||||
|
||||
pub fn integrity_check(&self, full: bool) -> Result<(), KnowledgeError> {
|
||||
let pragma = if full {
|
||||
"PRAGMA integrity_check"
|
||||
} else {
|
||||
"PRAGMA quick_check"
|
||||
};
|
||||
let result: String = self
|
||||
.conn
|
||||
.query_row(pragma, [], |row| row.get(0))
|
||||
.map_err(db)?;
|
||||
if result == "ok" {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(KnowledgeError::environment(
|
||||
crate::diagnostic::code::DATABASE_CORRUPT,
|
||||
"knowledge database failed its integrity check",
|
||||
)
|
||||
.with_hint("run `marqdo knowledge compile --rebuild`"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn counts(&self) -> Result<(u64, u64, u64), KnowledgeError> {
|
||||
let documents: i64 = self
|
||||
.conn
|
||||
.query_row("SELECT count(*) FROM documents", [], |row| row.get(0))
|
||||
.map_err(db)?;
|
||||
let nodes: i64 = self
|
||||
.conn
|
||||
.query_row("SELECT count(*) FROM nodes", [], |row| row.get(0))
|
||||
.map_err(db)?;
|
||||
let edges: i64 = self
|
||||
.conn
|
||||
.query_row("SELECT count(*) FROM edges", [], |row| row.get(0))
|
||||
.map_err(db)?;
|
||||
Ok((documents as u64, nodes as u64, edges as u64))
|
||||
}
|
||||
|
||||
/// Known document paths for a set of node ids (query result assembly).
|
||||
pub fn doc_paths(&self, doc_ids: &[i64]) -> Result<HashMap<i64, String>, KnowledgeError> {
|
||||
let mut out = HashMap::new();
|
||||
for doc_id in doc_ids {
|
||||
let path: Option<String> = self
|
||||
.conn
|
||||
.query_row(
|
||||
"SELECT path FROM documents WHERE id = ?1",
|
||||
[doc_id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()
|
||||
.map_err(db)?;
|
||||
if let Some(path) = path {
|
||||
out.insert(*doc_id, path);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn document_source_by_path(&self, path: &str) -> Result<Option<Vec<u8>>, KnowledgeError> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT source FROM documents WHERE path = ?1",
|
||||
[path],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()
|
||||
.map_err(db)
|
||||
}
|
||||
}
|
||||
|
||||
fn db(error: rusqlite::Error) -> KnowledgeError {
|
||||
KnowledgeError::environment(
|
||||
crate::diagnostic::code::DATABASE_CORRUPT,
|
||||
format!("database read failed: {error}"),
|
||||
)
|
||||
}
|
||||
|
||||
fn escape_like(value: &str) -> String {
|
||||
value
|
||||
.replace('\\', "\\\\")
|
||||
.replace('%', "\\%")
|
||||
.replace('_', "\\_")
|
||||
}
|
||||
|
||||
fn map_span(row: &rusqlite::Row<'_>, start: usize, end: usize) -> rusqlite::Result<Option<Span>> {
|
||||
let start: Option<i64> = row.get(start)?;
|
||||
let end: Option<i64> = row.get(end)?;
|
||||
Ok(match (start, end) {
|
||||
(Some(start), Some(end)) if start >= 0 && end >= start => {
|
||||
Some(Span::new(start as u64, end as u64))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn map_node(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoredNode> {
|
||||
let kind: String = row.get(2)?;
|
||||
Ok(StoredNode {
|
||||
id: row.get(0)?,
|
||||
key: row.get(1)?,
|
||||
kind: kind.parse::<NodeKind>().unwrap_or(NodeKind::External),
|
||||
doc_id: row.get(3)?,
|
||||
parent_id: row.get(4)?,
|
||||
span: map_span(row, 5, 6)?,
|
||||
title: row.get(7)?,
|
||||
title_norm: row.get(8)?,
|
||||
symbol_norm: row.get(9)?,
|
||||
content_digest: row.get(10)?,
|
||||
semantic_digest: row.get(11)?,
|
||||
searchable: row.get::<_, i64>(12)? != 0,
|
||||
metadata: serde_json::from_str(&row.get::<_, String>(13)?)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
})
|
||||
}
|
||||
|
||||
fn map_edge(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoredEdge> {
|
||||
let kind: String = row.get(3)?;
|
||||
let origin: String = row.get(4)?;
|
||||
let state: String = row.get(9)?;
|
||||
Ok(StoredEdge {
|
||||
id: row.get(0)?,
|
||||
source_id: row.get(1)?,
|
||||
target_id: row.get(2)?,
|
||||
kind: kind.parse::<EdgeKind>().unwrap_or(EdgeKind::References),
|
||||
origin: if origin == "analysis" {
|
||||
EdgeOrigin::Analysis
|
||||
} else {
|
||||
EdgeOrigin::Document
|
||||
},
|
||||
raw_target: row.get(5)?,
|
||||
span: map_span(row, 6, 7)?,
|
||||
doc_id: row.get(8)?,
|
||||
state: parse_state(&state),
|
||||
context_id: row.get(10)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_state(value: &str) -> EdgeState {
|
||||
match value {
|
||||
"resolved" => EdgeState::Resolved,
|
||||
"not_loaded" => EdgeState::NotLoaded,
|
||||
"missing" => EdgeState::Missing,
|
||||
"ambiguous" => EdgeState::Ambiguous,
|
||||
"external" => EdgeState::External,
|
||||
"out_of_scope" => EdgeState::OutOfScope,
|
||||
"invalid" => EdgeState::Invalid,
|
||||
"dynamic" => EdgeState::Dynamic,
|
||||
_ => EdgeState::Unresolved,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_search_unit(row: &rusqlite::Row<'_>) -> rusqlite::Result<SearchUnitRow> {
|
||||
let start: i64 = row.get(3)?;
|
||||
let end: i64 = row.get(4)?;
|
||||
Ok(SearchUnitRow {
|
||||
id: row.get(0)?,
|
||||
node_id: row.get(1)?,
|
||||
doc_id: row.get(2)?,
|
||||
span: Span::new(start as u64, end as u64),
|
||||
title: row.get(5)?,
|
||||
body: row.get(6)?,
|
||||
symbols: row.get(7)?,
|
||||
metadata: row.get(8)?,
|
||||
formula: row.get(9)?,
|
||||
tabular: row.get(10)?,
|
||||
links: row.get(11)?,
|
||||
})
|
||||
}
|
||||
|
||||
use rusqlite::OptionalExtension;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn like_escaping_is_safe() {
|
||||
assert_eq!(escape_like("a%b_c\\d"), "a\\%b\\_c\\\\d");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn states_round_trip_from_strings() {
|
||||
for state in [
|
||||
EdgeState::Resolved,
|
||||
EdgeState::NotLoaded,
|
||||
EdgeState::Missing,
|
||||
EdgeState::Ambiguous,
|
||||
EdgeState::External,
|
||||
EdgeState::OutOfScope,
|
||||
EdgeState::Invalid,
|
||||
EdgeState::Dynamic,
|
||||
EdgeState::Unresolved,
|
||||
] {
|
||||
assert_eq!(parse_state(state.as_str()), state);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_format_parsing_uses_path_suffix() {
|
||||
assert_eq!(
|
||||
DocumentFormat::from_path("a/b.mq.md"),
|
||||
Some(DocumentFormat::Marqdo)
|
||||
);
|
||||
assert_eq!(
|
||||
DocumentFormat::from_path("a/b.md"),
|
||||
Some(DocumentFormat::PlainMarkdown)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
-- marqdo-knowledge derived database schema (revision 1).
|
||||
--
|
||||
-- This file is private to the tool. It is not a public API and it is not a
|
||||
-- knowledge format: delete the database and rebuild at any time.
|
||||
--
|
||||
-- Invariants enforced here:
|
||||
-- * one build row (singleton) with schema revision and logical snapshot digest;
|
||||
-- * one document row per root-relative path, exact UTF-8 source bytes;
|
||||
-- * one node row per canonical key; spans are NULL together and ordered;
|
||||
-- * one alias row per (alias, context); only unambiguous bindings;
|
||||
-- * edges keep unresolved targets NULL and a non-NULL target only for
|
||||
-- 'resolved' state; every occurrence has its own row and source span;
|
||||
-- * search index rows are derived from source structure only;
|
||||
-- * every foreign key is enforced by the connection (PRAGMA foreign_keys=ON).
|
||||
|
||||
CREATE TABLE build (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
schema_revision INTEGER NOT NULL,
|
||||
application_id INTEGER NOT NULL,
|
||||
tool_version TEXT NOT NULL,
|
||||
producer_version TEXT NOT NULL,
|
||||
core_identity TEXT NOT NULL,
|
||||
snapshot_digest TEXT NOT NULL,
|
||||
logical_digest TEXT NOT NULL,
|
||||
scope_json TEXT NOT NULL,
|
||||
options_json TEXT NOT NULL,
|
||||
index_config_json TEXT NOT NULL,
|
||||
embedding_json TEXT,
|
||||
facts_cache_version INTEGER NOT NULL,
|
||||
rebuild_generation INTEGER NOT NULL,
|
||||
complete INTEGER NOT NULL CHECK (complete IN (0, 1))
|
||||
);
|
||||
|
||||
CREATE TABLE documents (
|
||||
id INTEGER PRIMARY KEY,
|
||||
path TEXT NOT NULL UNIQUE,
|
||||
format TEXT NOT NULL CHECK (format IN ('plain_markdown', 'marqdo')),
|
||||
source_digest TEXT NOT NULL,
|
||||
source BLOB NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
front_matter_json TEXT,
|
||||
document_role TEXT NOT NULL CHECK (document_role IN ('native', 'concept', 'index', 'log')),
|
||||
okf_json TEXT,
|
||||
analysis_context_id TEXT,
|
||||
module_id TEXT,
|
||||
facts_json TEXT,
|
||||
facts_digest TEXT,
|
||||
facts_cache_version INTEGER,
|
||||
diagnostic_status TEXT NOT NULL CHECK (diagnostic_status IN ('ok', 'warnings')),
|
||||
CHECK ((analysis_context_id IS NULL) = (module_id IS NULL)),
|
||||
CHECK ((facts_json IS NULL) = (facts_digest IS NULL))
|
||||
);
|
||||
|
||||
CREATE TABLE nodes (
|
||||
id INTEGER PRIMARY KEY,
|
||||
canonical_key TEXT NOT NULL UNIQUE,
|
||||
kind TEXT NOT NULL CHECK (kind IN (
|
||||
'document', 'namespace', 'section', 'function',
|
||||
'statement', 'resource', 'external')),
|
||||
doc_id INTEGER REFERENCES documents(id) ON DELETE CASCADE,
|
||||
parent_id INTEGER REFERENCES nodes(id) ON DELETE CASCADE,
|
||||
span_start INTEGER,
|
||||
span_end INTEGER,
|
||||
title TEXT NOT NULL,
|
||||
title_norm TEXT NOT NULL,
|
||||
symbol_norm TEXT,
|
||||
content_digest TEXT NOT NULL,
|
||||
semantic_digest TEXT,
|
||||
searchable INTEGER NOT NULL DEFAULT 1 CHECK (searchable IN (0, 1)),
|
||||
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)
|
||||
);
|
||||
|
||||
CREATE INDEX nodes_doc ON nodes(doc_id);
|
||||
CREATE INDEX nodes_parent ON nodes(parent_id);
|
||||
CREATE INDEX nodes_kind ON nodes(kind);
|
||||
CREATE INDEX nodes_title_norm ON nodes(title_norm);
|
||||
CREATE INDEX nodes_symbol_norm ON nodes(symbol_norm);
|
||||
|
||||
CREATE TABLE aliases (
|
||||
id INTEGER PRIMARY KEY,
|
||||
alias TEXT NOT NULL,
|
||||
context_id TEXT NOT NULL DEFAULT '',
|
||||
node_id INTEGER NOT NULL REFERENCES nodes(id) ON DELETE CASCADE,
|
||||
UNIQUE (alias, context_id)
|
||||
);
|
||||
|
||||
CREATE INDEX aliases_node ON aliases(node_id);
|
||||
|
||||
CREATE TABLE edges (
|
||||
id INTEGER PRIMARY KEY,
|
||||
source_id INTEGER NOT NULL REFERENCES nodes(id) ON DELETE CASCADE,
|
||||
target_id INTEGER REFERENCES nodes(id) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL CHECK (kind IN ('contains', 'references', 'imports', 'calls')),
|
||||
origin TEXT NOT NULL CHECK (origin IN ('document', 'analysis')),
|
||||
raw_target TEXT NOT NULL,
|
||||
span_start INTEGER,
|
||||
span_end INTEGER,
|
||||
doc_id INTEGER REFERENCES documents(id) ON DELETE CASCADE,
|
||||
state TEXT NOT NULL CHECK (state IN (
|
||||
'resolved', 'not_loaded', 'missing', 'ambiguous',
|
||||
'external', 'out_of_scope', 'invalid', 'dynamic',
|
||||
'unresolved')),
|
||||
context_id TEXT,
|
||||
CHECK ((span_start IS NULL) = (span_end IS NULL)),
|
||||
CHECK (span_start IS NULL OR (span_start >= 0 AND span_end >= span_start)),
|
||||
CHECK ((target_id IS NOT NULL) = (state = 'resolved'))
|
||||
);
|
||||
|
||||
CREATE INDEX edges_source ON edges(source_id, kind);
|
||||
CREATE INDEX edges_target ON edges(target_id, kind);
|
||||
CREATE INDEX edges_doc ON edges(doc_id);
|
||||
CREATE INDEX edges_kind ON edges(kind);
|
||||
|
||||
CREATE TABLE contexts (
|
||||
id INTEGER PRIMARY KEY,
|
||||
context_id TEXT NOT NULL UNIQUE,
|
||||
entry_module_id TEXT NOT NULL,
|
||||
root_id TEXT NOT NULL,
|
||||
identity_kind TEXT NOT NULL,
|
||||
manifest_digest TEXT NOT NULL,
|
||||
lock_digest TEXT NOT NULL,
|
||||
stdlib_digest TEXT,
|
||||
producer_version TEXT NOT NULL,
|
||||
analysis_digest TEXT NOT NULL,
|
||||
extensions_json TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE inputs (
|
||||
path TEXT NOT NULL,
|
||||
kind TEXT NOT NULL CHECK (kind IN ('document', 'manifest', 'lock', 'asset')),
|
||||
digest TEXT NOT NULL,
|
||||
size INTEGER NOT NULL CHECK (size >= 0),
|
||||
UNIQUE (path, kind)
|
||||
);
|
||||
|
||||
CREATE TABLE diagnostics (
|
||||
id INTEGER PRIMARY KEY,
|
||||
code TEXT NOT NULL,
|
||||
severity TEXT NOT NULL CHECK (severity IN ('error', 'warning')),
|
||||
path TEXT,
|
||||
span_start INTEGER,
|
||||
span_end INTEGER,
|
||||
message TEXT NOT NULL,
|
||||
hints_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))
|
||||
);
|
||||
|
||||
CREATE TABLE search_units (
|
||||
id INTEGER PRIMARY KEY,
|
||||
node_id INTEGER NOT NULL REFERENCES nodes(id) ON DELETE CASCADE,
|
||||
doc_id INTEGER NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
|
||||
span_start INTEGER NOT NULL,
|
||||
span_end INTEGER NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
symbols TEXT NOT NULL,
|
||||
metadata TEXT NOT NULL,
|
||||
formula TEXT NOT NULL,
|
||||
tabular TEXT NOT NULL,
|
||||
links TEXT NOT NULL,
|
||||
CHECK (span_end >= span_start)
|
||||
);
|
||||
|
||||
CREATE INDEX search_units_node ON search_units(node_id);
|
||||
CREATE INDEX search_units_doc ON search_units(doc_id);
|
||||
|
||||
CREATE VIRTUAL TABLE search_fts USING fts5(
|
||||
title,
|
||||
body,
|
||||
symbols,
|
||||
metadata,
|
||||
formula,
|
||||
tabular,
|
||||
links,
|
||||
content = 'search_units',
|
||||
content_rowid = 'id',
|
||||
tokenize = 'unicode61 remove_diacritics 2'
|
||||
);
|
||||
|
||||
CREATE TABLE grams (
|
||||
norm_gram TEXT NOT NULL,
|
||||
search_unit_id INTEGER NOT NULL REFERENCES search_units(id) ON DELETE CASCADE,
|
||||
field TEXT NOT NULL CHECK (field IN ('title', 'symbols', 'metadata', 'body')),
|
||||
UNIQUE (norm_gram, search_unit_id, field)
|
||||
);
|
||||
|
||||
CREATE INDEX grams_lookup ON grams(norm_gram);
|
||||
|
||||
CREATE TABLE embeddings (
|
||||
search_unit_id INTEGER PRIMARY KEY REFERENCES search_units(id) ON DELETE CASCADE,
|
||||
content_digest TEXT NOT NULL,
|
||||
model_digest TEXT NOT NULL,
|
||||
dimension INTEGER NOT NULL CHECK (dimension > 0),
|
||||
vector BLOB NOT NULL
|
||||
);
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
//! Deterministic search normalisation and tokenisation.
|
||||
//!
|
||||
//! Used by the write path to build the FTS/gram indexes and by the read path to
|
||||
//! segment queries. Normalisation is for indexing and queries only: original
|
||||
//! text, canonical ids and program symbols keep their exact case and Unicode
|
||||
//! form.
|
||||
//!
|
||||
//! * NFKC + lowercase + whitespace collapse for search text;
|
||||
//! * ASCII identifiers are split on camelCase/snake_case/kebab-case boundaries;
|
||||
//! * CJK runs are represented by character bigrams (and trigrams for grams) so
|
||||
//! two-character Chinese queries do not depend on a trigram tokenizer;
|
||||
//! * single-character CJK queries are handled by a bounded exact-character
|
||||
//! fallback in the query layer, not by unbounded scan;
|
||||
//! * quotes/brackets/operators are never passed through as FTS syntax.
|
||||
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
|
||||
/// A CJK/kana/hangul character, treated as one search unit.
|
||||
pub fn is_cjk(ch: char) -> bool {
|
||||
matches!(ch,
|
||||
'\u{3040}'..='\u{30FF}' // kana
|
||||
| '\u{3400}'..='\u{4DBF}' // CJK extension A
|
||||
| '\u{4E00}'..='\u{9FFF}' // CJK unified
|
||||
| '\u{F900}'..='\u{FAFF}' // compatibility ideographs
|
||||
| '\u{AC00}'..='\u{D7AF}' // hangul syllables
|
||||
| '\u{20000}'..='\u{2FA1F}' // CJK extensions B-F
|
||||
)
|
||||
}
|
||||
|
||||
/// Search normalisation: NFKC, Unicode lowercase, control characters removed,
|
||||
/// whitespace runs collapsed to one space and trimmed.
|
||||
pub fn normalize(text: &str) -> String {
|
||||
let normalized: String = text.nfkc().flat_map(char::to_lowercase).collect();
|
||||
let mut out = String::with_capacity(normalized.len());
|
||||
let mut pending_space = false;
|
||||
for ch in normalized.chars() {
|
||||
if ch.is_control() {
|
||||
continue;
|
||||
}
|
||||
if ch.is_whitespace() {
|
||||
pending_space = !out.is_empty();
|
||||
continue;
|
||||
}
|
||||
if pending_space {
|
||||
out.push(' ');
|
||||
pending_space = false;
|
||||
}
|
||||
out.push(ch);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// NFKC without lowercasing or whitespace collapsing, used before identifier
|
||||
/// splitting so camelCase boundaries survive.
|
||||
fn nfkc_only(text: &str) -> String {
|
||||
text.nfkc().filter(|ch| !ch.is_control()).collect()
|
||||
}
|
||||
|
||||
/// Split one ASCII identifier run into searchable parts. Both the whole word
|
||||
/// and the parts are returned, in a stable order.
|
||||
fn identifier_parts(word: &str) -> Vec<String> {
|
||||
let mut parts = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut previous: Option<char> = None;
|
||||
for ch in word.chars() {
|
||||
let boundary = match previous {
|
||||
Some(previous) => {
|
||||
(previous.is_ascii_lowercase() || previous.is_ascii_digit())
|
||||
&& ch.is_ascii_uppercase()
|
||||
|| !ch.is_ascii_alphanumeric()
|
||||
}
|
||||
None => !ch.is_ascii_alphanumeric(),
|
||||
};
|
||||
if boundary && !current.is_empty() {
|
||||
parts.push(std::mem::take(&mut current));
|
||||
}
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
current.push(ch.to_ascii_lowercase());
|
||||
}
|
||||
previous = Some(ch);
|
||||
}
|
||||
if !current.is_empty() {
|
||||
parts.push(current);
|
||||
}
|
||||
if parts.len() > 1 {
|
||||
let whole = parts.concat();
|
||||
if !parts.iter().any(|part| part == &whole) {
|
||||
parts.insert(0, whole);
|
||||
}
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
/// Tokenise text for the FTS index and for queries.
|
||||
pub fn tokens(text: &str) -> Vec<String> {
|
||||
let normalized = nfkc_only(text);
|
||||
let mut out = Vec::new();
|
||||
let mut ascii = String::new();
|
||||
let mut cjk_run: Vec<char> = Vec::new();
|
||||
let flush_ascii = |ascii: &mut String, out: &mut Vec<String>| {
|
||||
if !ascii.is_empty() {
|
||||
out.extend(identifier_parts(ascii));
|
||||
ascii.clear();
|
||||
}
|
||||
};
|
||||
let flush_cjk = |run: &mut Vec<char>, out: &mut Vec<String>| {
|
||||
if run.is_empty() {
|
||||
return;
|
||||
}
|
||||
if run.len() == 1 {
|
||||
out.push(run[0].to_string());
|
||||
} else {
|
||||
for window in run.windows(2) {
|
||||
out.push(window.iter().collect());
|
||||
}
|
||||
}
|
||||
run.clear();
|
||||
};
|
||||
for ch in normalized.chars() {
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
flush_cjk(&mut cjk_run, &mut out);
|
||||
ascii.push(ch);
|
||||
} else if is_cjk(ch) {
|
||||
flush_ascii(&mut ascii, &mut out);
|
||||
cjk_run.push(ch);
|
||||
} else {
|
||||
flush_ascii(&mut ascii, &mut out);
|
||||
flush_cjk(&mut cjk_run, &mut out);
|
||||
}
|
||||
}
|
||||
flush_ascii(&mut ascii, &mut out);
|
||||
flush_cjk(&mut cjk_run, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Join tokens into the space-separated text stored in the FTS content columns.
|
||||
pub fn segment(text: &str) -> String {
|
||||
tokens(text).join(" ")
|
||||
}
|
||||
|
||||
/// Fuzzy gram candidates: 2/3-gram CJK windows and ASCII identifier parts.
|
||||
pub fn grams(text: &str) -> Vec<String> {
|
||||
let normalized = nfkc_only(text);
|
||||
let mut out = Vec::new();
|
||||
let mut ascii = String::new();
|
||||
let mut cjk_run: Vec<char> = Vec::new();
|
||||
let flush_ascii = |ascii: &mut String, out: &mut Vec<String>| {
|
||||
if ascii.is_empty() {
|
||||
return;
|
||||
}
|
||||
for part in identifier_parts(ascii) {
|
||||
if part.chars().count() >= 2 {
|
||||
out.push(part);
|
||||
}
|
||||
}
|
||||
ascii.clear();
|
||||
};
|
||||
let flush_cjk = |run: &mut Vec<char>, out: &mut Vec<String>| {
|
||||
for width in [2usize, 3usize] {
|
||||
if run.len() >= width {
|
||||
for window in run.windows(width) {
|
||||
out.push(window.iter().collect());
|
||||
}
|
||||
}
|
||||
}
|
||||
run.clear();
|
||||
};
|
||||
for ch in normalized.chars() {
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
flush_cjk(&mut cjk_run, &mut out);
|
||||
ascii.push(ch);
|
||||
} else if is_cjk(ch) {
|
||||
flush_ascii(&mut ascii, &mut out);
|
||||
cjk_run.push(ch);
|
||||
} else {
|
||||
flush_ascii(&mut ascii, &mut out);
|
||||
flush_cjk(&mut cjk_run, &mut out);
|
||||
}
|
||||
}
|
||||
flush_ascii(&mut ascii, &mut out);
|
||||
flush_cjk(&mut cjk_run, &mut out);
|
||||
out.sort();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// Bounded Damerau-Levenshtein distance (adjacent transposition) with an early
|
||||
/// exit when the distance is already above `limit`. Never panics.
|
||||
pub fn edit_distance_at_most(left: &str, right: &str, limit: usize) -> Option<usize> {
|
||||
let a: Vec<char> = left.chars().collect();
|
||||
let b: Vec<char> = right.chars().collect();
|
||||
if a.len().abs_diff(b.len()) > limit {
|
||||
return None;
|
||||
}
|
||||
if a == b {
|
||||
return Some(0);
|
||||
}
|
||||
let mut previous_previous: Vec<usize> = Vec::new();
|
||||
let mut previous: Vec<usize> = (0..=b.len()).collect();
|
||||
for (i, a_char) in a.iter().enumerate() {
|
||||
let mut current = vec![i + 1; b.len() + 1];
|
||||
let mut row_min = i + 1;
|
||||
for (j, b_char) in b.iter().enumerate() {
|
||||
let cost = usize::from(a_char != b_char);
|
||||
let mut value = (previous[j + 1] + 1)
|
||||
.min(current[j] + 1)
|
||||
.min(previous[j] + cost);
|
||||
if i > 0 && j > 0 && a_char == &b[j - 1] && a[i - 1] == *b_char {
|
||||
value = value.min(previous_previous[j - 1] + 1);
|
||||
}
|
||||
current[j + 1] = value;
|
||||
row_min = row_min.min(value);
|
||||
}
|
||||
if row_min > limit {
|
||||
return None;
|
||||
}
|
||||
previous_previous = std::mem::replace(&mut previous, current);
|
||||
}
|
||||
let distance = previous[b.len()];
|
||||
(distance <= limit).then_some(distance)
|
||||
}
|
||||
|
||||
/// Similarity in `0.0..=1.0` between a query and one candidate token/title.
|
||||
pub fn similarity(left: &str, right: &str) -> f64 {
|
||||
let left = normalize(left);
|
||||
let right = normalize(right);
|
||||
if left.is_empty() || right.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let max_len = left.chars().count().max(right.chars().count());
|
||||
let limit = max_len.min(8);
|
||||
match edit_distance_at_most(&left, &right, limit) {
|
||||
Some(distance) => 1.0 - distance as f64 / max_len as f64,
|
||||
None => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape one token for an FTS5 query: the token is emitted as a quoted string
|
||||
/// literal, so no FTS operator can be injected. Empty tokens are dropped.
|
||||
pub fn fts_quote(token: &str) -> Option<String> {
|
||||
let cleaned = token.replace('"', "");
|
||||
if cleaned.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(format!("\"{cleaned}\""))
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a safe OR query from user text. Returns `None` when no token remains.
|
||||
pub fn fts_query(text: &str) -> Option<String> {
|
||||
let quoted: Vec<String> = tokens(text)
|
||||
.iter()
|
||||
.filter_map(|token| fts_quote(token))
|
||||
.collect();
|
||||
if quoted.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(quoted.join(" OR "))
|
||||
}
|
||||
}
|
||||
|
||||
/// Single CJK character fallback candidates (bounded by the caller).
|
||||
pub fn single_char_terms(text: &str) -> Vec<char> {
|
||||
normalize(text)
|
||||
.chars()
|
||||
.filter(|ch| is_cjk(*ch))
|
||||
.take(8)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn normalization_is_search_only() {
|
||||
assert_eq!(normalize(" Hello WORLD "), "hello world");
|
||||
assert_eq!(normalize("ABC123"), "abc123");
|
||||
assert_eq!(normalize("e\u{0301}"), "\u{00e9}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identifiers_split_on_case_and_separators() {
|
||||
let parts = tokens("normalizeVectorMagnitude");
|
||||
assert!(parts.contains(&"normalize".to_string()));
|
||||
assert!(parts.contains(&"vector".to_string()));
|
||||
assert!(parts.contains(&"magnitude".to_string()));
|
||||
assert!(parts.contains(&"normalizevectormagnitude".to_string()));
|
||||
let parts = tokens("snake_case-kebab");
|
||||
assert!(parts.contains(&"snake".to_string()));
|
||||
assert!(parts.contains(&"case".to_string()));
|
||||
assert!(parts.contains(&"kebab".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cjk_two_character_queries_use_bigrams() {
|
||||
assert_eq!(tokens("量子"), vec!["量子"]);
|
||||
assert_eq!(tokens("量子力学"), vec!["量子", "子力", "力学"]);
|
||||
assert_eq!(tokens("力"), vec!["力"]);
|
||||
let segmented = segment("概率归一化");
|
||||
assert!(segmented.split_whitespace().any(|token| token == "概率"));
|
||||
assert!(segmented.split_whitespace().any(|token| token == "归一"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grams_include_bigrams_and_trigrams() {
|
||||
let cjk_grams = grams("量子力学");
|
||||
assert!(cjk_grams.contains(&"量子".to_string()));
|
||||
assert!(cjk_grams.contains(&"量子力".to_string()));
|
||||
assert!(cjk_grams.contains(&"力学".to_string()));
|
||||
let ascii_grams = grams("normalizeVector");
|
||||
assert!(ascii_grams.contains(&"normalize".to_string()));
|
||||
assert!(ascii_grams.contains(&"vector".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fts_queries_cannot_inject_operators() {
|
||||
let query = fts_query("\"quoted\" AND (paren) *").unwrap();
|
||||
assert!(!query.contains("AND"));
|
||||
assert!(!query.contains("("));
|
||||
assert!(!query.contains("*"));
|
||||
assert!(query.contains("\"quoted\""));
|
||||
assert!(fts_query(" ").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_distance_is_bounded_and_counts_transpositions() {
|
||||
assert_eq!(edit_distance_at_most("kitten", "sitting", 3), Some(3));
|
||||
assert_eq!(edit_distance_at_most("量子", "量子", 1), Some(0));
|
||||
assert_eq!(edit_distance_at_most("归一化", "归一话", 1), Some(1));
|
||||
assert_eq!(edit_distance_at_most("abc", "xyz", 1), None);
|
||||
assert_eq!(edit_distance_at_most("ab", "ba", 1), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn similarity_is_bounded() {
|
||||
assert!(similarity("归一化", "归一化") == 1.0);
|
||||
let score = similarity("归一话", "归一化检查");
|
||||
assert!((0.0..=1.0).contains(&score));
|
||||
assert_eq!(similarity("", "x"), 0.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
//! 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(¤t_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);
|
||||
}
|
||||
Reference in new issue
Block a user