diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fe21e3d27..02c3fcd2b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,6 +72,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 create-then-lock ordering now creates before it can know the lock will be refused. Harmless — the next open sees `is_new` and initialises normally — but worth knowing if you inspect the filesystem after a failed open. +- **`Minigraf`'s, `WriteTransaction`'s, and `PreparedQuery`'s public methods now + return `Result` instead of `anyhow::Result`** (#277). + `MinigrafError` implements `std::error::Error` (so `?` still works against + `anyhow::Result`/`Box` callers) and adds `.category() -> ErrorCategory` + and `.code() -> &'static str` for structured error matching. This lands the + foundation for issue #277; every error currently surfaces as the generic + `INT-000` code until each error category's follow-up PR wires up its real + `docs/ERROR_REFERENCE.md` codes. + Every error's `Display`/`to_string()` output now also carries a `[CODE] ` + prefix (e.g. `[INT-000] unclassified internal error: ...`) that it did not + have before — a behavior change beyond the type signature. Anything that + string-matches error output is affected, including the interactive REPL's + printed error messages and all 7 language-binding repos (Python, Node, + WASM, Java, Android, Swift, C). ### Bug fixes diff --git a/docs/ERROR_REFERENCE.md b/docs/ERROR_REFERENCE.md index b6b47acaeb..e039d41e19 100644 --- a/docs/ERROR_REFERENCE.md +++ b/docs/ERROR_REFERENCE.md @@ -1,12 +1,15 @@ # Minigraf Error Reference This document covers every user-facing error produced by the core Minigraf Rust library. -Errors surface as `anyhow::Error` values returned from `db.execute()`, `db.prepare()`, +Errors surface as `MinigrafError` values returned from `db.execute()`, `db.prepare()`, and related API methods. -**Reference codes** (e.g. `PRS-001`) are documentation-only identifiers. They do not -appear in runtime output today — runtime codes are tracked in -[#277](https://github.com/project-minigraf/minigraf/issues/277). +**Reference codes** (e.g. `PRS-001`) appear in runtime error output as +`[CODE] message`, and programmatically via `MinigrafError::code()` / +`MinigrafError::category()`. As of the [#277](https://github.com/project-minigraf/minigraf/issues/277) +foundation PR, every runtime error carries a code — but until each +category's follow-up migration PR lands, most still surface generically as +`INT-000` rather than their documented code below. **Out of scope**: FFI/binding errors from `minigraf-python`, `minigraf-node`, and `minigraf-wasm` are handled in those repos. @@ -147,6 +150,7 @@ appear in runtime output today — runtime codes are tracked in | API-007 | Only query commands can be prepared (rule) | Database API | | API-008 | Function registry lock poisoned | Database API | | API-009 | WAL not initialized | Database API | +| INT-000 | Unclassified internal error | Internal | --- @@ -2155,6 +2159,30 @@ db.execute("(rule [(ancestor ?x ?y) [?x :parent ?y]])")?; --- +## INT — Internal Errors + +`INT-000` is the generic catch-all every runtime error falls back to until its +call site is migrated to a specific structured code — see +[#277](https://github.com/project-minigraf/minigraf/issues/277). Internal +errors are invariant violations that should not be reachable through normal +use of the public API. If you see one of these in practice, it likely +indicates a bug in Minigraf itself; please +[file an issue](https://github.com/project-minigraf/minigraf/issues). + +### INT-000 Unclassified internal error + +**Error text**: `unclassified internal error: {}` + +**Cause**: A `bail!`/`anyhow!` call site has not yet been migrated to a specific structured error code, or the error genuinely is an unreachable internal invariant violation. + +**Resolution**: +- Read the wrapped message text (the `{}` above) for the underlying cause. +- Match on message content rather than this code if you need long-term programmatic stability — `INT-000` is expected to cover fewer cases over time as call sites gain specific codes. + +**Scenario**: Any error not yet covered by a migrated `PRS-`/`STG-`/`WAL-`/`QRY-`/`API-` code. + +--- + ## Appendix: Internal Errors The following error strings indicate a bug in the Minigraf library itself, not a diff --git a/docs/superpowers/plans/2026-08-25-structured-error-codes-foundation.md b/docs/superpowers/plans/2026-08-25-structured-error-codes-foundation.md index 09a55565f7..02c314f61d 100644 --- a/docs/superpowers/plans/2026-08-25-structured-error-codes-foundation.md +++ b/docs/superpowers/plans/2026-08-25-structured-error-codes-foundation.md @@ -478,12 +478,20 @@ EOF - [ ] **Step 1: Export the new types from `lib.rs`** -In `src/lib.rs`, add `pub mod error;` next to the other `pub mod` declarations (near line 77's `pub mod db;`), and add to the `pub use` block (near line 91-92): +Task 1's implementer already added `pub(crate) mod error;` to `src/lib.rs` — necessary for `cargo test --lib error::` to compile/run at all in Task 1, since a source file isn't part of the crate tree until some reachable `mod` declares it; the original brief didn't anticipate this. Ruling recorded in the SDD ledger (Task 1 review). Do not insert a second `mod error;` line — that's a duplicate-declaration compile error. Instead, change the existing line's visibility: + +```rust +pub(crate) mod error; +``` + +to: ```rust pub mod error; ``` +And add to the `pub use` block (near line 91-92): + ```rust pub use error::{ErrorCategory, MinigrafError}; ``` @@ -1328,7 +1336,7 @@ Expected: no warnings. Fix anything flagged (likely candidates: an unused `Resul - [ ] **Step 3: Full test suite** Run: `cargo test` -Expected: PASS, same or greater test count than before this plan started (`cargo test 2>&1 | tail -5` — compare against the pre-change baseline of 1023 tests noted in `CLAUDE.md`; the 4 new tests in `error_codes_foundation_test.rs` plus 12 in `src/error.rs`'s own module bring the count up by 16). +Expected: PASS, same or greater test count than before this plan started (`cargo test 2>&1 | tail -5` — compare against the pre-change baseline of 1023 tests noted in `CLAUDE.md`; the 8 new tests in `error_codes_foundation_test.rs` plus 12 in `src/error.rs`'s own module bring the count up by 20). - [ ] **Step 4: WASM target build check (best-effort)** diff --git a/docs/superpowers/specs/2026-08-25-structured-error-codes-design.md b/docs/superpowers/specs/2026-08-25-structured-error-codes-design.md index c2af053871..80bbc18cf4 100644 --- a/docs/superpowers/specs/2026-08-25-structured-error-codes-design.md +++ b/docs/superpowers/specs/2026-08-25-structured-error-codes-design.md @@ -212,6 +212,36 @@ becomes the umbrella tracking issue and splits into: 2. **PRS sub-issue/PR** — migrate all parser call sites to `bail_coded!` with their real PRS-0xx codes; add regression tests asserting the specific code comes back from `db.execute()` for each. + + **Blocker discovered during the Foundation PR's final review, must be + resolved before this PR is planned in detail**: `src/query/datalog/ + parser.rs` is NOT `anyhow`-based — every parser function, including + `pub fn parse_datalog_command(input: &str) -> Result` (118 `Err(...)` returns across the file), returns + `Result<_, String>`. `bail_coded!`/`err_coded!` expand to + `Err(anyhow::Error::new(CodedError::new(...)))`, which is a type error + inside any `Result<_, String>`-returning function — they cannot be used + as a drop-in replacement in `parser.rs` as originally assumed ("a + drop-in replacement for existing `bail!(...)`/`anyhow!(...)` call + sites" in the Call-site macros section above holds for every other + module, but not this one). PRS is 79 of the 130 documented codes — + the largest category and the very next PR, so this must be decided + before that PR's plan is written, not discovered mid-implementation. + Compounding it: `Minigraf::execute`/`WriteTransaction::execute`/ + `Minigraf::prepare` in `src/db.rs` each call + `parse_datalog_command(input).map_err(|e| anyhow::anyhow!("{}", e))?` + — even if the parser produced a `CodedError` some other way, this + `map_err` stringifies it via `Display`, destroying the error chain at + exactly the boundary the code-detection in `MinigrafError::from` + depends on (the chain-walk would find nothing and silently fall back + to `INT-000`, defeating the whole PR). Two options to resolve before + PRS is planned: (a) change `parser.rs`'s error type to `anyhow::Error` + (or a new `CodedError`-carrying type) and drop the three stringifying + `map_err` calls in `db.rs`, or (b) add a parallel `String`-flavored + code-carrying mechanism for `parser.rs` specifically. (a) is simpler + and keeps one mechanism crate-wide; (b) avoids touching parser.rs's + error type but permanently duplicates the tagging machinery. No + decision made yet — flag for brainstorming when PRS is picked up. 3. **STG sub-issue/PR** — storage/file-format call sites, STG-0xx. 4. **WAL sub-issue/PR** — WAL call sites, WAL-0xx. 5. **QRY sub-issue/PR** — query executor call sites, QRY-0xx. diff --git a/src/db.rs b/src/db.rs index 1b5d4b40a4..ac1e86ab28 100644 --- a/src/db.rs +++ b/src/db.rs @@ -15,6 +15,7 @@ use crate::graph::types::{Fact, TxId, VALID_TIME_FOREVER}; /// in any practical context, avoiding the collision that `0` would have with the Unix /// epoch (1970-01-01T00:00:00Z), which is a legitimate `valid_from` value. pub(crate) const VALID_FROM_USE_TX_TIME: i64 = i64::MIN; +use crate::error::MinigrafError; use crate::graph::FactStorage; use crate::graph::types::Value; use crate::query::datalog::evaluator::DEFAULT_MAX_DERIVED_FACTS; @@ -218,7 +219,7 @@ impl OpenOptions { /// # Errors /// /// Returns an error if the in-memory storage backend fails to initialise. - pub fn open_memory(self) -> Result { + pub fn open_memory(self) -> Result { Minigraf::in_memory_with_options(self) } } @@ -238,7 +239,7 @@ impl OpenOptionsWithPath { /// /// Returns an error if the file cannot be opened, the header is corrupt, /// or WAL replay fails. - pub fn open(self) -> Result { + pub fn open(self) -> Result { Minigraf::open_with_options(self.path, self.opts) } } @@ -359,7 +360,7 @@ impl Minigraf { /// Returns an error if the file cannot be opened, the header is corrupt, /// or WAL replay fails. #[cfg(not(target_arch = "wasm32"))] - pub fn open(path: impl AsRef) -> Result { + pub fn open(path: impl AsRef) -> Result { Self::open_with_options(path, OpenOptions::default()) } @@ -370,7 +371,15 @@ impl Minigraf { /// Returns an error if the file cannot be opened, the header is corrupt, /// or WAL replay fails. #[cfg(not(target_arch = "wasm32"))] - pub fn open_with_options(path: impl AsRef, opts: OpenOptions) -> Result { + pub fn open_with_options( + path: impl AsRef, + opts: OpenOptions, + ) -> Result { + Self::open_with_options_inner(path, opts).map_err(MinigrafError::from) + } + + #[cfg(not(target_arch = "wasm32"))] + fn open_with_options_inner(path: impl AsRef, opts: OpenOptions) -> Result { let db_path = path.as_ref().to_path_buf(); // Open the main .graph file @@ -417,7 +426,7 @@ impl Minigraf { /// # Errors /// /// Returns an error if the in-memory storage backend fails to initialise. - pub fn in_memory() -> Result { + pub fn in_memory() -> Result { Self::in_memory_with_options(OpenOptions::default()) } @@ -429,7 +438,11 @@ impl Minigraf { /// # Errors /// /// Returns an error if the in-memory storage backend fails to initialise. - pub fn in_memory_with_options(opts: OpenOptions) -> Result { + pub fn in_memory_with_options(opts: OpenOptions) -> Result { + Self::in_memory_with_options_inner(opts).map_err(MinigrafError::from) + } + + fn in_memory_with_options_inner(opts: OpenOptions) -> Result { let backend = MemoryBackend::new(); let pfs = PersistentFactStorage::new(backend, memory_page_cache_capacity(&opts))?; let fact_storage = pfs.storage().clone(); @@ -512,7 +525,11 @@ impl Minigraf { /// - Parsing fails. /// - Execution fails. /// - WAL write fails (file-backed databases). - pub fn execute(&self, input: &str) -> Result { + pub fn execute(&self, input: &str) -> Result { + self.execute_inner(input).map_err(MinigrafError::from) + } + + fn execute_inner(&self, input: &str) -> Result { // Detect same-thread reentrant write (would deadlock on the Mutex). if is_write_tx_active() { bail!( @@ -623,7 +640,11 @@ impl Minigraf { /// # Errors /// /// Returns an error if a `WriteTransaction` is already active on **this thread**. - pub fn begin_write(&self) -> Result> { + pub fn begin_write(&self) -> Result, MinigrafError> { + self.begin_write_inner().map_err(MinigrafError::from) + } + + fn begin_write_inner(&self) -> Result> { if is_write_tx_active() { bail!( "a WriteTransaction is already in progress on this thread; use tx.execute() instead" @@ -654,7 +675,11 @@ impl Minigraf { /// # Errors /// /// Returns an error if the write lock is poisoned or the checkpoint I/O fails. - pub fn checkpoint(&self) -> Result<()> { + pub fn checkpoint(&self) -> Result<(), MinigrafError> { + self.checkpoint_inner().map_err(MinigrafError::from) + } + + fn checkpoint_inner(&self) -> Result<()> { let mut ctx = self.inner.write_lock.lock().map_err(|_| { anyhow::anyhow!("write lock is poisoned; database may be in an inconsistent state") })?; @@ -740,6 +765,13 @@ impl Minigraf { pub fn prepare( &self, query_str: &str, + ) -> Result { + self.prepare_inner(query_str).map_err(MinigrafError::from) + } + + fn prepare_inner( + &self, + query_str: &str, ) -> Result { use crate::query::datalog::prepared::prepare_query; @@ -898,6 +930,20 @@ impl Minigraf { init: impl Fn() -> Acc + Send + Sync + 'static, step: impl Fn(&mut Acc, &Value) + Send + Sync + 'static, finalise: impl Fn(&Acc, usize) -> Value + Send + Sync + 'static, + ) -> Result<(), MinigrafError> + where + Acc: Any + Send + 'static, + { + self.register_aggregate_inner(name, init, step, finalise) + .map_err(MinigrafError::from) + } + + fn register_aggregate_inner( + &self, + name: &str, + init: impl Fn() -> Acc + Send + Sync + 'static, + step: impl Fn(&mut Acc, &Value) + Send + Sync + 'static, + finalise: impl Fn(&Acc, usize) -> Value + Send + Sync + 'static, ) -> Result<()> where Acc: Any + Send + 'static, @@ -954,6 +1000,15 @@ impl Minigraf { &self, name: &str, f: impl Fn(&Value) -> bool + Send + Sync + 'static, + ) -> Result<(), MinigrafError> { + self.register_predicate_inner(name, f) + .map_err(MinigrafError::from) + } + + fn register_predicate_inner( + &self, + name: &str, + f: impl Fn(&Value) -> bool + Send + Sync + 'static, ) -> Result<()> { let desc = PredicateDesc { f: Arc::new(f), @@ -1008,7 +1063,11 @@ impl<'a> WriteTransaction<'a> { /// # Errors /// /// Returns an error if parsing or execution fails. - pub fn execute(&mut self, input: &str) -> Result { + pub fn execute(&mut self, input: &str) -> Result { + self.execute_inner(input).map_err(MinigrafError::from) + } + + fn execute_inner(&mut self, input: &str) -> Result { let cmd = parse_datalog_command(input).map_err(|e| anyhow::anyhow!("{}", e))?; match cmd { @@ -1094,7 +1153,11 @@ impl<'a> WriteTransaction<'a> { /// # Errors /// /// Returns an error if the WAL write or fact application fails. - pub fn commit(mut self) -> Result<()> { + pub fn commit(self) -> Result<(), MinigrafError> { + self.commit_inner().map_err(MinigrafError::from) + } + + fn commit_inner(mut self) -> Result<()> { let facts_to_commit = std::mem::take(&mut self.pending_facts); if !facts_to_commit.is_empty() { diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000000..eb60bb7772 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,457 @@ +//! Structured runtime error codes surfaced through `MinigrafError`. +//! +//! See `docs/superpowers/specs/2026-08-25-structured-error-codes-design.md` +//! and `docs/ERROR_REFERENCE.md` for the design and the full code registry. + +use std::fmt; + +/// Coarse-grained error category — the type library consumers match on. +/// +/// `#[non_exhaustive]`: a future category can be added without that being a +/// breaking change. Downstream `match` expressions must include a wildcard +/// `_` arm. Has no effect within this crate. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum ErrorCategory { + /// Datalog/EDN syntax errors (`PRS-` codes). + Parser, + /// Query planning/execution errors (`QRY-` codes). + Query, + /// On-disk storage/file-format errors (`STG-` codes). + Storage, + /// Write-ahead log errors (`WAL-` codes). + Wal, + /// Public `Minigraf` API misuse or internal sequencing errors (`API-` codes). + Api, + /// Unclassified internal invariant violations (`INT-` codes). + Internal, +} + +/// Crate-internal handle for one documented `docs/ERROR_REFERENCE.md` code. +/// +/// Never exposed to library consumers — only the `&'static str` code string +/// it resolves to via [`REGISTRY`] is public (through [`MinigrafError::code`]). +/// Kept internal so this enum is free to be reorganized without breaking any +/// downstream `match`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ErrorCode { + Int000, +} + +/// Single source of truth: (code, code string, message template, category). +/// +/// The message template is verified against `docs/ERROR_REFERENCE.md`'s +/// "Error text" lines by the sync test in this module (added once real +/// codes exist in a follow-up category PR — see the design spec). +pub(crate) const REGISTRY: &[(ErrorCode, &str, &str, ErrorCategory)] = &[( + ErrorCode::Int000, + "INT-000", + "unclassified internal error: {}", + ErrorCategory::Internal, +)]; + +pub(crate) fn registry_entry(code: ErrorCode) -> (&'static str, &'static str, ErrorCategory) { + let entry = REGISTRY.iter().find(|(c, ..)| *c == code); + // This is NOT exhaustively guaranteed: `registry_is_a_subset_of_error_reference_doc` + // iterates over `REGISTRY`, not over `ErrorCode` variants, so it cannot catch a new + // `ErrorCode` variant added without a matching `REGISTRY` row. The `debug_assert!` + // below catches that mistake in debug/test builds only — nothing catches it in a + // release build, where it silently falls back to the always-present INT-000 entry + // below instead of panicking, since `unwrap`/`expect`/`panic!` are denied crate-wide. + // `error::tests::every_error_code_variant_has_a_registry_entry` is the real + // exhaustiveness guarantee: its `match` over `ErrorCode` fails to compile if a new + // variant is added without also being handled there. + debug_assert!( + entry.is_some(), + "every ErrorCode variant must have a REGISTRY entry" + ); + match entry { + Some((_, code_str, template, category)) => (*code_str, *template, *category), + None => ( + "INT-000", + "unclassified internal error: {}", + ErrorCategory::Internal, + ), + } +} + +/// Fill a message template's positional `{}` placeholders from `args`, in order. +/// +/// Not `std::fmt`-based: the template is runtime data pulled from [`REGISTRY`], +/// and `format!` requires a compile-time string literal. +#[allow(dead_code)] // unused until the PRS category PR wires up real call sites +pub(crate) fn format_template(template: &str, args: &[&dyn fmt::Display]) -> String { + let placeholder_count = template.matches("{}").count(); + debug_assert_eq!( + placeholder_count, + args.len(), + "format_template: template has a different placeholder count than args supplied" + ); + let mut out = String::with_capacity(template.len()); + let mut args = args.iter(); + let mut rest = template; + while let Some(pos) = rest.find("{}") { + out.push_str(&rest[..pos]); + if let Some(arg) = args.next() { + out.push_str(&arg.to_string()); + } + rest = &rest[pos + 2..]; + } + out.push_str(rest); + out +} + +/// An `anyhow`-compatible error carrying a compile-time-checked [`ErrorCode`]. +/// +/// Built exclusively through [`bail_coded!`]/[`err_coded!`] and wrapped as an +/// `anyhow::Error`, so it rides through the crate's existing `anyhow::Result` +/// plumbing (`?`, `.context()`) unchanged. Recovered at the public API +/// boundary by [`MinigrafError::from`]`(anyhow::Error)` walking the error +/// chain for the first `CodedError` via `downcast_ref`. +#[derive(Debug)] +pub(crate) struct CodedError { + code: ErrorCode, + message: String, +} + +impl CodedError { + #[allow(dead_code)] // unused until the PRS category PR wires up real call sites + pub(crate) fn new(code: ErrorCode, args: &[&dyn fmt::Display]) -> Self { + let (_, template, _) = registry_entry(code); + CodedError { + code, + message: format_template(template, args), + } + } + + pub(crate) fn code(&self) -> ErrorCode { + self.code + } +} + +impl fmt::Display for CodedError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for CodedError {} + +/// Return early with a coded, `anyhow`-compatible error. +/// +/// `bail_coded!(ErrorCode::Prs001)` for a static message, or +/// `bail_coded!(ErrorCode::Prs002, ch)` to fill the template's `{}` +/// placeholders positionally. A drop-in replacement for `anyhow::bail!`. +#[allow(unused_macros)] // unused until the PRS category PR wires up real call sites +macro_rules! bail_coded { + ($code:expr $(,)?) => { + return Err(::anyhow::Error::new($crate::error::CodedError::new($code, &[]))) + }; + ($code:expr, $($arg:expr),+ $(,)?) => { + return Err(::anyhow::Error::new($crate::error::CodedError::new( + $code, + &[$(&$arg as &dyn ::std::fmt::Display),+], + ))) + }; +} + +/// Build (without returning) a coded, `anyhow`-compatible error. +/// +/// For use where an `anyhow::Error` value is needed directly, e.g. +/// `.ok_or_else(|| err_coded!(ErrorCode::Api009))`. +#[allow(unused_macros)] // unused until the PRS category PR wires up real call sites +macro_rules! err_coded { + ($code:expr $(,)?) => { + ::anyhow::Error::new($crate::error::CodedError::new($code, &[])) + }; + ($code:expr, $($arg:expr),+ $(,)?) => { + ::anyhow::Error::new($crate::error::CodedError::new( + $code, + &[$(&$arg as &dyn ::std::fmt::Display),+], + )) + }; +} + +#[allow(unused_imports)] // unused until the PRS category PR wires up real call sites +pub(crate) use bail_coded; +#[allow(unused_imports)] // unused until the PRS category PR wires up real call sites +pub(crate) use err_coded; + +/// The error type returned from Minigraf's public API. +/// +/// Carries a matchable [`category`](MinigrafError::category) and a stable +/// [`code`](MinigrafError::code) (e.g. `"PRS-001"`) documented in +/// `docs/ERROR_REFERENCE.md`. `Display` renders as `[CODE] message`. +#[derive(Debug)] +pub struct MinigrafError { + category: ErrorCategory, + code: &'static str, + message: String, + source: anyhow::Error, +} + +impl MinigrafError { + /// The coarse-grained category — the type to `match` on. + pub fn category(&self) -> ErrorCategory { + self.category + } + + /// The stable reference code, e.g. `"PRS-001"`. See `docs/ERROR_REFERENCE.md`. + pub fn code(&self) -> &'static str { + self.code + } +} + +impl fmt::Display for MinigrafError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "[{}] {}", self.code, self.message) + } +} + +impl std::error::Error for MinigrafError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&*self.source) + } +} + +impl From for MinigrafError { + fn from(err: anyhow::Error) -> Self { + for cause in err.chain() { + if let Some(coded) = cause.downcast_ref::() { + let (code_str, _, category) = registry_entry(coded.code()); + return MinigrafError { + category, + code: code_str, + message: coded.to_string(), + source: err, + }; + } + } + let message_text = err.to_string(); + let (code_str, template, category) = registry_entry(ErrorCode::Int000); + let message = format_template(template, &[&message_text as &dyn fmt::Display]); + MinigrafError { + category, + code: code_str, + message, + source: err, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn format_template_no_placeholders() { + assert_eq!( + format_template("no placeholders here", &[]), + "no placeholders here" + ); + } + + #[test] + fn format_template_one_placeholder() { + let arg = 42; + assert_eq!( + format_template("value: {}", &[&arg as &dyn std::fmt::Display]), + "value: 42" + ); + } + + #[test] + fn format_template_multiple_placeholders() { + let a = "x"; + let b = 7; + assert_eq!( + format_template( + "{} then {}", + &[&a as &dyn std::fmt::Display, &b as &dyn std::fmt::Display] + ), + "x then 7" + ); + } + + /// Exhaustively verifies every `ErrorCode` variant resolves to a real + /// `REGISTRY` entry, not `registry_entry`'s INT-000 fallback. The `match` + /// below must list every `ErrorCode` variant explicitly (no `_` arm) so + /// that adding a new variant without also handling it here is a compile + /// error — the real exhaustiveness guarantee `registry_entry`'s + /// `debug_assert!` cannot provide on its own (it's compiled out in + /// release builds, and `registry_is_a_subset_of_error_reference_doc` + /// only walks `REGISTRY`, not `ErrorCode`). Necessarily small today + /// since `ErrorCode` has just one variant, but the structure is what + /// matters for the PRS category PR that adds ~79 more. + #[test] + fn every_error_code_variant_has_a_registry_entry() { + fn assert_has_registry_entry(code: ErrorCode) { + let (code_str, _, _) = registry_entry(code); + assert_ne!( + code_str, "", + "ErrorCode variant resolved to an empty registry code" + ); + assert!( + REGISTRY.iter().any(|(c, ..)| *c == code), + "ErrorCode variant has no REGISTRY entry" + ); + } + + match ErrorCode::Int000 { + ErrorCode::Int000 => assert_has_registry_entry(ErrorCode::Int000), + } + } + + #[test] + fn registry_entry_resolves_int000() { + let (code_str, template, category) = registry_entry(ErrorCode::Int000); + assert_eq!(code_str, "INT-000"); + assert_eq!(template, "unclassified internal error: {}"); + assert_eq!(category, ErrorCategory::Internal); + } + + #[test] + fn coded_error_display_uses_template() { + let e = CodedError::new(ErrorCode::Int000, &[&"boom" as &dyn std::fmt::Display]); + assert_eq!(e.to_string(), "unclassified internal error: boom"); + } + + #[test] + fn bail_coded_returns_anyhow_error_wrapping_coded_error() { + fn inner() -> anyhow::Result<()> { + bail_coded!(ErrorCode::Int000, "boom"); + } + let err = inner().unwrap_err(); + let coded = err + .downcast_ref::() + .expect("expected a CodedError"); + assert_eq!(coded.code(), ErrorCode::Int000); + assert_eq!(coded.to_string(), "unclassified internal error: boom"); + } + + #[test] + fn err_coded_builds_anyhow_error_without_returning() { + let err = err_coded!(ErrorCode::Int000, "boom"); + let coded = err + .downcast_ref::() + .expect("expected a CodedError"); + assert_eq!(coded.code(), ErrorCode::Int000); + } + + #[test] + fn minigraf_error_display_format() { + let anyhow_err = err_coded!(ErrorCode::Int000, "boom"); + let e: MinigrafError = anyhow_err.into(); + assert_eq!(e.to_string(), "[INT-000] unclassified internal error: boom"); + assert_eq!(e.code(), "INT-000"); + assert_eq!(e.category(), ErrorCategory::Internal); + } + + #[test] + fn minigraf_error_finds_coded_error_through_context_chain() { + let anyhow_err = err_coded!(ErrorCode::Int000, "boom").context("extra context"); + let e: MinigrafError = anyhow_err.into(); + assert_eq!(e.code(), "INT-000"); + assert_eq!(e.to_string(), "[INT-000] unclassified internal error: boom"); + } + + #[test] + fn minigraf_error_finds_coded_error_through_two_context_hops() { + let anyhow_err = err_coded!(ErrorCode::Int000, "boom") + .context("first context") + .context("second context"); + let e: MinigrafError = anyhow_err.into(); + assert_eq!(e.code(), "INT-000"); + assert_eq!(e.to_string(), "[INT-000] unclassified internal error: boom"); + } + + // A genuine arg-count mismatch trips the `debug_assert_eq!` in + // `format_template` — active under `cargo test`'s debug build, which is + // what this test exercises. In a release build (`debug_assert!` compiled + // out) the same call does not panic: the loop below the assert simply + // drops the text of any `{}` placeholder with no matching arg. + #[test] + #[should_panic(expected = "different placeholder count")] + fn format_template_arg_count_mismatch_debug_asserts() { + format_template("value: {}", &[]); + } + + #[test] + fn minigraf_error_falls_back_to_int000_for_uncoded_anyhow_error() { + let anyhow_err = anyhow::anyhow!("plain uncoded error"); + let e: MinigrafError = anyhow_err.into(); + assert_eq!(e.code(), "INT-000"); + assert_eq!(e.category(), ErrorCategory::Internal); + assert_eq!( + e.to_string(), + "[INT-000] unclassified internal error: plain uncoded error" + ); + } + + #[test] + fn minigraf_error_implements_std_error_source() { + let anyhow_err = err_coded!(ErrorCode::Int000, "boom"); + let e: MinigrafError = anyhow_err.into(); + let err: &dyn std::error::Error = &e; + assert!(err.source().is_some()); + } + + /// `docs/ERROR_REFERENCE.md` already documents all 130 codes (from #192) + /// before #277 starts touching runtime codes — the doc isn't built up + /// incrementally alongside `REGISTRY`, it's already complete. So this + /// test can only check `REGISTRY` is a content-matched subset of the + /// doc (every registry entry's code+template appears in the doc + /// verbatim) — not that every documented code has a registry entry yet. + /// A documented code with no registry entry just means that call site + /// hasn't been migrated. The final category PR (once every remaining + /// call site is audited and coded) should upgrade this to a full + /// bidirectional equality check. + #[test] + fn registry_is_a_subset_of_error_reference_doc() { + let doc = include_str!("../docs/ERROR_REFERENCE.md"); + let mut doc_entries: std::collections::HashMap = Default::default(); + let mut lines = doc.lines().peekable(); + while let Some(line) = lines.next() { + let Some(rest) = line.strip_prefix("### ") else { + continue; + }; + let code = rest.split_whitespace().next().unwrap_or("").to_string(); + if !is_error_reference_code(&code) { + continue; + } + let mut error_text = None; + while let Some(&next_line) = lines.peek() { + if next_line.starts_with("### ") || next_line.starts_with("## ") { + break; + } + if let Some(text) = next_line.strip_prefix("**Error text**: `") { + error_text = text.strip_suffix('`').map(str::to_string); + lines.next(); + break; + } + lines.next(); + } + if let Some(text) = error_text { + doc_entries.insert(code, text); + } + } + + for (_, code_str, template, _) in REGISTRY { + match doc_entries.get(*code_str) { + Some(doc_text) => assert_eq!( + doc_text, template, + "REGISTRY template for a documented code doesn't match its ERROR_REFERENCE.md Error text" + ), + None => panic!("REGISTRY has a code with no ERROR_REFERENCE.md entry at all"), + } + } + } + + fn is_error_reference_code(s: &str) -> bool { + let bytes = s.as_bytes(); + bytes.len() == 7 + && bytes[..3].iter().all(u8::is_ascii_uppercase) + && bytes[3] == b'-' + && bytes[4..].iter().all(u8::is_ascii_digit) + } +} diff --git a/src/lib.rs b/src/lib.rs index 12c448d36d..80ce28b87d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -75,6 +75,7 @@ //! - **WASI / server-side** (`wasm32-wasip1`) — `cargo build --target wasm32-wasip1 --release --bin minigraf` pub mod db; +pub mod error; pub(crate) mod graph; pub(crate) mod query; /// Interactive REPL for exploring a [`Minigraf`] database from the command line. @@ -90,6 +91,7 @@ pub mod browser; #[cfg(not(target_arch = "wasm32"))] pub use db::OpenOptionsWithPath; pub use db::{Minigraf, OpenOptions, SyncMode, WriteTransaction}; +pub use error::{ErrorCategory, MinigrafError}; pub use repl::Repl; // EAV value types — users construct and match on these diff --git a/src/query/datalog/prepared.rs b/src/query/datalog/prepared.rs index 2d3d06b2d5..f401b38a4c 100644 --- a/src/query/datalog/prepared.rs +++ b/src/query/datalog/prepared.rs @@ -1,3 +1,4 @@ +use crate::error::MinigrafError; use crate::graph::FactStorage; use crate::graph::types::Value; use crate::query::datalog::executor::{DatalogExecutor, QueryResult}; @@ -98,7 +99,11 @@ impl PreparedQuery { /// # Errors /// - Missing bind value for a slot present in the query. /// - Type mismatch (e.g. `Val` supplied for an `:as-of` slot). - pub fn execute(&self, bindings: &[(&str, BindValue)]) -> Result { + pub fn execute(&self, bindings: &[(&str, BindValue)]) -> Result { + self.execute_inner(bindings).map_err(MinigrafError::from) + } + + fn execute_inner(&self, bindings: &[(&str, BindValue)]) -> Result { let binding_map: HashMap<&str, &BindValue> = bindings.iter().map(|(name, val)| (*name, val)).collect(); diff --git a/tests/error_codes_foundation_test.rs b/tests/error_codes_foundation_test.rs new file mode 100644 index 0000000000..3bf0cda027 --- /dev/null +++ b/tests/error_codes_foundation_test.rs @@ -0,0 +1,104 @@ +use minigraf::{ErrorCategory, Minigraf}; + +#[test] +fn in_memory_open_returns_ok() { + let db = Minigraf::in_memory(); + assert!(db.is_ok(), "in_memory() should succeed"); +} + +#[test] +fn open_nonexistent_directory_returns_coded_error() { + let bad_path = "/nonexistent-dir-for-minigraf-test-277/db.graph"; + let result = Minigraf::open(bad_path); + // `Result::expect_err`/`unwrap_err` require the `Ok` type (`Minigraf`) to + // implement `Debug`, which it deliberately does not (its fields include + // non-`Debug` function-pointer registries). Extract the error manually. + let err = match result { + Err(e) => e, + Ok(_) => panic!("opening a file in a nonexistent directory should fail"), + }; + assert_eq!(err.category(), ErrorCategory::Internal); + assert_eq!(err.code(), "INT-000"); +} + +#[test] +fn execute_parse_error_returns_coded_error() { + let db = Minigraf::in_memory().unwrap(); + let result = db.execute("(this is not valid datalog"); + let err = result.expect_err("malformed input should fail to parse"); + assert_eq!(err.category(), ErrorCategory::Internal); + assert_eq!(err.code(), "INT-000"); +} + +#[test] +fn execute_valid_transact_returns_ok() { + let db = Minigraf::in_memory().unwrap(); + let result = + db.execute(r#"(transact [[#uuid "550e8400-e29b-41d4-a716-446655440000" :name "alice"]])"#); + assert!(result.is_ok(), "valid transact should succeed"); +} + +#[test] +fn begin_write_then_checkpoint_returns_ok() { + let db = Minigraf::in_memory().unwrap(); + let tx = db.begin_write(); + assert!(tx.is_ok(), "begin_write on a fresh db should succeed"); + tx.unwrap().rollback(); + let checkpoint = db.checkpoint(); + assert!( + checkpoint.is_ok(), + "checkpoint on an in-memory db is a no-op success" + ); +} + +#[test] +fn prepare_and_register_predicate_return_ok() { + use minigraf::Value; + + let db = Minigraf::in_memory().unwrap(); + let prepared = db.prepare("(query [:find ?e :where [?e :name $name]])"); + assert!(prepared.is_ok(), "preparing a valid query should succeed"); + + let registered = db.register_predicate( + "even277?", + |v: &Value| matches!(v, Value::Integer(i) if i % 2 == 0), + ); + assert!( + registered.is_ok(), + "registering a new predicate name should succeed" + ); +} + +#[test] +fn write_transaction_execute_and_commit_return_ok() { + let db = Minigraf::in_memory().unwrap(); + let mut tx = db.begin_write().unwrap(); + let exec = + tx.execute(r#"(transact [[#uuid "550e8400-e29b-41d4-a716-446655440001" :name "bob"]])"#); + assert!( + exec.is_ok(), + "staging a valid transact in a tx should succeed" + ); + let commit = tx.commit(); + assert!( + commit.is_ok(), + "committing a valid transaction should succeed" + ); +} + +#[test] +fn prepared_query_execute_returns_ok() { + use minigraf::{BindValue, Value}; + + let db = Minigraf::in_memory().unwrap(); + db.execute(r#"(transact [[:carol :person/name "Carol"]])"#) + .unwrap(); + let prepared = db + .prepare("(query [:find ?e :where [?e :person/name $name]])") + .unwrap(); + let result = prepared.execute(&[("name", BindValue::Val(Value::String("Carol".to_string())))]); + assert!( + result.is_ok(), + "executing a prepared query with a valid binding should succeed" + ); +}