Skip to main content

core_api/
lib.rs

1pub mod algo;
2mod db;
3pub mod digest;
4mod exact_knn;
5pub mod explain_digest;
6pub mod history;
7mod ingest;
8pub mod mask;
9pub mod memory;
10pub mod memory_schema;
11pub mod reader;
12pub mod restore;
13pub mod roles;
14pub mod schema;
15mod shared;
16pub mod subscription;
17
18pub use algo::{
19    AlgoDir, Community, CommunityReport, DegreeConfig, DegreeReport, LouvainConfig, PageRankConfig,
20    PageRankReport, WccConfig, WccReport,
21};
22pub use core_query::{CmpOp, Dir, Filter, ResultSet};
23pub use core_rules::suggest::DEFAULT_SEED as SUGGEST_DEFAULT_SEED;
24pub use core_rules::{
25    default_max_edges, is_keymatch_rooted, AggFn, BuildProgress, Predicate, RuleDef,
26    RuleSuggestion, SuggestConfig, SuggestReport, ViewDef, ViewSource, ViewStore,
27    DEFAULT_KEYMATCH_TOP_K, DEFAULT_SCORED_TOP_K, HNSW_BUILD_BATCH, MAX_CHAIN_DEPTH,
28};
29pub use core_storage::fs::RealFs;
30pub use core_storage::{Direction, GraphError, Result, Value};
31pub use db::{
32    ambiguous_exactness_last_warning, ambiguous_exactness_warns, ambiguous_exactness_warns_reset,
33};
34pub use db::{query_sub_exec_count, reset_query_sub_exec_count};
35pub use db::{
36    snapshot_version_at, valid_namespace, write_snapshot_bak, AsOfScope, BackupReport,
37    BatchBuilder, BatchOp, BatchOutcome, DeleteReport, EdgeAt, EdgeInfo, Explanation, ExportEdge,
38    FsyncPolicy, GraphDb, MaskedEdge, MaskedNodeResult, MutationEvent, NamespaceStats, NodeInfo,
39    NodeRef, OnConflict, OpenOptions, Precondition, PredicateSummary, RuleStats, SlowQueryEntry,
40    SlowQuerySnapshot, SnapshotOptions, Stats, WhatIf, WriteAuthz,
41    MERGE_CREATE_NEEDS_ONE_NAMESPACE, NS_DEFAULT, NS_MAX_LEN, NS_PROP, WRITE_LOCK_WAIT,
42};
43pub use exact_knn::{with_pairwise_caps, PAIRWISE_GRAM_MAX, PAIRWISE_MAX_N};
44
45/// The similarity floor `find_similar` applies when the caller names none.
46///
47/// One value, read by every surface that has a default — the MCP tool, HTTP
48/// `POST /find_similar` and the Python binding. Through 0.6 each hard-coded
49/// its own literal, and they disagreed: MCP 0.8, the other two 0.0, so a call
50/// ported between them changed its results with nothing raised. The engine
51/// itself has no default: `GraphDb::find_similar_vector_filtered` takes `min`
52/// as an argument.
53///
54/// `pairwise_similar` is a different operation and defaults to 0.0 everywhere.
55pub const FIND_SIMILAR_DEFAULT_MIN: f64 = 0.8;
56
57/// The on-disk snapshot version a store that has opted in to nothing writes —
58/// the **floor**, not the whole answer.
59///
60/// Exposed so CLI and tooling can print `V<SNAPSHOT_VERSION>` without depending
61/// directly on `core-storage`.
62///
63/// Since v0.6.10 this build writes 9 **or** 10 depending on the store
64/// (`core_storage::snapshot::version_for`: a store that has called
65/// `GraphDb::enable_multiplicity` writes 10) and reads 5 through 10. Compare a
66/// store's stamp against this with `>=`, never `==` — see `cli::run_migrate`,
67/// which would otherwise report an opted-in store as `V10 -> V9`.
68pub const SNAPSHOT_VERSION: u16 = core_storage::snapshot::VERSION;
69pub use history::{EdgeEvent, EdgeHistoryEvent, HistoryChange, HistoryEntry, HistoryResult};
70pub use ingest::{
71    json_to_rows, json_to_value, AutoFk, FkSkip, IngestOptions, IngestReport, JsonRows,
72};
73pub use mask::{MaskMode, NodeMask, RoleMaskCache, Scope};
74pub use reader::{CommitDelta, FrozenOverlay, ReaderSnapshot, FOLD_EVERY_K};
75pub use roles::{PropPredicate, RoleDef, WriteScope};
76pub use schema::{Schema, SchemaDiff};
77pub use shared::{SharedDb, WriteGuard};
78pub use subscription::{DbEvent, Subscription, DEFAULT_SUB_CAPACITY};
79
80/// One verification entry per section: `(section_id, section_name, bytes_checked, result)`.
81///
82/// Returned by [`verify_snapshot`].
83pub type SectionVerifyResult = (u8, &'static str, usize, std::result::Result<(), String>);
84
85/// Validate the CRC32 integrity of every section in the V8 snapshot at `dir`.
86///
87/// Returns one entry per section directory entry (see [`SectionVerifyResult`]).
88///
89/// Large sections (TOPOLOGY, COLUMNS, EDGE_PROPS, HNSW, PROVENANCE, IVF_STATE)
90/// skip CRC on the normal hot query path; this function always checks them.
91/// Use it to implement `mushroomdb verify` without depending on `core-storage`
92/// directly.
93pub fn verify_snapshot(dir: &std::path::Path) -> crate::Result<Vec<SectionVerifyResult>> {
94    let snap_path = dir.join("snapshot.bin");
95    let mapped = core_storage::v8::MappedBase::map(&snap_path)?;
96    // Bounds first, then per-section CRC32, then a structural (rkyv bytecheck)
97    // pass over the sections the hot path reads unchecked. The structural pass
98    // rejects a maliciously crafted snapshot whose relative pointers would
99    // otherwise trigger UB on open — a threat CRC32 alone can't catch (an
100    // attacker can recompute the CRC). Fail loud on structural corruption.
101    mapped.validate_section_bounds()?;
102    let results = mapped.verify_integrity();
103    mapped.validate_hot_sections()?;
104    Ok(results)
105}
106
107/// Return `true` if `cypher` is a write statement (CREATE / MERGE / MATCH…SET /
108/// MATCH…DELETE).  Returns `Err` only when the string fails to lex.
109///
110/// Used by the HTTP server to dispatch to the write lock without a full parse.
111pub fn is_write_query(cypher: &str) -> std::result::Result<bool, String> {
112    let toks = core_query::cypher::lex(cypher).map_err(|e| format!("lex: {e}"))?;
113    Ok(core_query::cypher::is_write_tokens(&toks))
114}
115
116/// Return the number of valid WAL commits in the database at `dir`.
117///
118/// Useful for displaying "as-of commit N of M" in CLIs without opening the
119/// full database.  Returns 0 if the WAL file does not exist (e.g., after
120/// `snapshot()` which truncates it to empty).
121pub fn wal_commit_count_at(dir: &std::path::Path) -> crate::Result<u64> {
122    let wal_path = dir.join("wal.bin");
123    let bytes = match std::fs::read(&wal_path) {
124        Ok(b) => b,
125        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
126        Err(e) => return Err(core_storage::GraphError::Io(e)),
127    };
128    Ok(core_storage::wal::wal_commits(&bytes))
129}