From 68cde9c5fd98327a5bd9a3b7e87ed7388a075240 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 11:23:12 +0530 Subject: [PATCH 01/25] docs: fix test count in foundation plan Task 11 (8 not 4 new integration tests) Preflight scan caught the discrepancy before dispatching implementers. Part of #277. --- .../plans/2026-08-25-structured-error-codes-foundation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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..d6dea10b76 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 @@ -1328,7 +1328,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)** From f176d074cbcbcf3e7d9974c4d66f845b4e4f243e Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 11:26:41 +0530 Subject: [PATCH 02/25] feat: add ErrorCategory/ErrorCode/REGISTRY/format_template for #277 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Foundation types for structured runtime error codes. No call sites wired up yet — this is pure scaffolding. Part of #277. --- src/error.rs | 113 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 2 files changed, 114 insertions(+) create mode 100644 src/error.rs diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000000..beb1a7d13b --- /dev/null +++ b/src/error.rs @@ -0,0 +1,113 @@ +//! 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. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ErrorCategory { + Parser, + Query, + Storage, + Wal, + Api, + 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) { + REGISTRY + .iter() + .find(|(c, ..)| *c == code) + .map(|(_, code_str, template, category)| (*code_str, *template, *category)) + .expect("every ErrorCode variant must have a REGISTRY entry") +} + +/// 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. +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 +} + +#[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" + ); + } + + #[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); + } +} diff --git a/src/lib.rs b/src/lib.rs index 12c448d36d..78c8124065 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(crate) mod error; pub(crate) mod graph; pub(crate) mod query; /// Interactive REPL for exploring a [`Minigraf`] database from the command line. From 311f4566894b5c4b2583d5ed5772b1f77672c370 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 11:31:19 +0530 Subject: [PATCH 03/25] docs: fix Task 4 plan text to upgrade Task 1's lib.rs mod declaration Task 1's implementer necessarily added `pub(crate) mod error;` to src/lib.rs -- cargo test --lib error:: cannot compile/run without the module being part of the crate tree, a gap the original brief didn't anticipate. Task 4 was written assuming no such line existed yet and would have inserted a duplicate `mod error;`, a compile error. Fixed Task 4's text to upgrade the existing line's visibility instead. Ruling from Task 1's task review. Part of #277. --- .../2026-08-25-structured-error-codes-foundation.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) 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 d6dea10b76..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}; ``` From 09cffe74ba6807430713ca5f943def2e0a9dddf5 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 11:32:48 +0530 Subject: [PATCH 04/25] feat: add CodedError and bail_coded!/err_coded! macros for #277 Call-site macros that tag an anyhow::Error with a compile-time-checked ErrorCode, formatted from the code's REGISTRY template. Not yet used by any real call site. Part of #277. --- src/error.rs | 95 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/src/error.rs b/src/error.rs index beb1a7d13b..b6817cc936 100644 --- a/src/error.rs +++ b/src/error.rs @@ -72,6 +72,77 @@ pub(crate) fn format_template(template: &str, args: &[&dyn fmt::Display]) -> Str 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 { + 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!`. +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))`. +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),+], + )) + }; +} + +pub(crate) use bail_coded; +pub(crate) use err_coded; + #[cfg(test)] mod tests { use super::*; @@ -110,4 +181,28 @@ mod tests { 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); + } } From c9d89a8e72898f872e57bdf46c37b85fd0a706a5 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 11:36:58 +0530 Subject: [PATCH 05/25] feat: add MinigrafError and anyhow::Error boundary conversion for #277 MinigrafError is the new public error type: category + stable code + Display as "[CODE] message" + std::error::Error. From walks the error chain for a CodedError, falling back to INT-000 for any error not yet migrated to a specific code. Part of #277. --- src/error.rs | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/src/error.rs b/src/error.rs index b6817cc936..f935b96835 100644 --- a/src/error.rs +++ b/src/error.rs @@ -143,6 +143,66 @@ macro_rules! err_coded { pub(crate) use bail_coded; 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 = err.to_string(); + MinigrafError { + category: ErrorCategory::Internal, + code: "INT-000", + message, + source: err, + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -205,4 +265,38 @@ mod tests { 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_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] 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()); + } } From f28000b03d9c76851c60610abc23de250628608b Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 13:31:33 +0530 Subject: [PATCH 06/25] feat: export MinigrafError/ErrorCategory; document INT-000; sync test Wires the new error module into the public API surface, documents the INT-000 catch-all code in ERROR_REFERENCE.md, and adds a test that fails if REGISTRY and the doc's code list/message templates ever diverge. Part of #277. --- docs/ERROR_REFERENCE.md | 33 +++++++++++++++++++-- src/error.rs | 65 +++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 3 +- 3 files changed, 97 insertions(+), 4 deletions(-) diff --git a/docs/ERROR_REFERENCE.md b/docs/ERROR_REFERENCE.md index b6b47acaeb..aabec911f5 100644 --- a/docs/ERROR_REFERENCE.md +++ b/docs/ERROR_REFERENCE.md @@ -4,9 +4,12 @@ This document covers every user-facing error produced by the core Minigraf Rust Errors surface as `anyhow::Error` 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,29 @@ db.execute("(rule [(ancestor ?x ?y) [?x :parent ?y]])")?; --- +## INT — Internal Errors + +Internal errors are invariant violations that should not be reachable through +normal use of the public API. `INT-000` is also 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). +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/src/error.rs b/src/error.rs index f935b96835..011b40d99e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -8,11 +8,17 @@ use std::fmt; /// Coarse-grained error category — the type library consumers match on. #[derive(Debug, Clone, Copy, PartialEq, Eq)] 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, } @@ -299,4 +305,63 @@ mod tests { 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 78c8124065..80ce28b87d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -75,7 +75,7 @@ //! - **WASI / server-side** (`wasm32-wasip1`) — `cargo build --target wasm32-wasip1 --release --bin minigraf` pub mod db; -pub(crate) mod error; +pub mod error; pub(crate) mod graph; pub(crate) mod query; /// Interactive REPL for exploring a [`Minigraf`] database from the command line. @@ -91,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 From f575a19418659896469905b0ecef22f203e746ef Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 13:38:36 +0530 Subject: [PATCH 07/25] fix: silence expected dead-code warnings on unused bail_coded!/err_coded! These have no production call sites until the first category PR (PRS) starts using them -- Task 11's clippy -D warnings gate needs this clean now rather than deferred. Also replaces registry_entry's expect() with a debug_assert! + defensive fallback, since clippy::expect_used is denied crate-wide and this was blocking `cargo clippy --all-features -- -D warnings` independently of the dead-code warnings. Part of #277. --- src/error.rs | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/src/error.rs b/src/error.rs index 011b40d99e..d97240723e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -46,17 +46,30 @@ pub(crate) const REGISTRY: &[(ErrorCode, &str, &str, ErrorCategory)] = &[( )]; pub(crate) fn registry_entry(code: ErrorCode) -> (&'static str, &'static str, ErrorCategory) { - REGISTRY - .iter() - .find(|(c, ..)| *c == code) - .map(|(_, code_str, template, category)| (*code_str, *template, *category)) - .expect("every ErrorCode variant must have a REGISTRY entry") + let entry = REGISTRY.iter().find(|(c, ..)| *c == code); + // Unreachable in practice: every `ErrorCode` variant is added together with its + // `REGISTRY` entry (and `registry_is_a_subset_of_error_reference_doc` exercises + // every variant). Falls back to the always-present INT-000 entry rather than + // panicking, since `unwrap`/`expect`/`panic!` are denied crate-wide. + 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!( @@ -92,6 +105,7 @@ pub(crate) struct CodedError { } 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 { @@ -118,6 +132,7 @@ impl std::error::Error for CodedError {} /// `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, &[]))) @@ -134,6 +149,7 @@ macro_rules! bail_coded { /// /// 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, &[])) @@ -146,7 +162,9 @@ macro_rules! err_coded { }; } +#[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. From 73ee5b443fcb17505211cfbcef08f2117e3fed14 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 13:45:30 +0530 Subject: [PATCH 08/25] feat: migrate Minigraf::open/in_memory family to MinigrafError open, open_with_options, in_memory, in_memory_with_options, and the OpenOptions/OpenOptionsWithPath builders now return Result. Bodies are unchanged (renamed to _inner twins); every error still surfaces as INT-000 until a later category PR wires up real codes. Part of #277. --- src/db.rs | 25 +++++++++++++++++++------ tests/error_codes_foundation_test.rs | 22 ++++++++++++++++++++++ 2 files changed, 41 insertions(+), 6 deletions(-) create mode 100644 tests/error_codes_foundation_test.rs diff --git a/src/db.rs b/src/db.rs index 1b5d4b40a4..c33cf28709 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(); diff --git a/tests/error_codes_foundation_test.rs b/tests/error_codes_foundation_test.rs new file mode 100644 index 0000000000..2202a035ed --- /dev/null +++ b/tests/error_codes_foundation_test.rs @@ -0,0 +1,22 @@ +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"); +} From 8085484bd37ed32bc4c82e7239df71945df40c7b Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 13:49:28 +0530 Subject: [PATCH 09/25] feat: migrate Minigraf::execute to MinigrafError Signature-only change; body renamed to execute_inner, unchanged. Part of #277. --- src/db.rs | 6 +++++- tests/error_codes_foundation_test.rs | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/db.rs b/src/db.rs index c33cf28709..13b29b904a 100644 --- a/src/db.rs +++ b/src/db.rs @@ -525,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!( diff --git a/tests/error_codes_foundation_test.rs b/tests/error_codes_foundation_test.rs index 2202a035ed..0e4556765c 100644 --- a/tests/error_codes_foundation_test.rs +++ b/tests/error_codes_foundation_test.rs @@ -20,3 +20,19 @@ fn open_nonexistent_directory_returns_coded_error() { 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"); +} From bac7f58f6a871434e4a657c941ec30156135914f Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 13:53:23 +0530 Subject: [PATCH 10/25] feat: migrate Minigraf::begin_write/checkpoint to MinigrafError Signature-only changes; bodies renamed to _inner twins, unchanged. Part of #277. --- src/db.rs | 12 ++++++++++-- tests/error_codes_foundation_test.rs | 10 ++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/db.rs b/src/db.rs index 13b29b904a..5c2e14761d 100644 --- a/src/db.rs +++ b/src/db.rs @@ -640,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" @@ -671,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") })?; diff --git a/tests/error_codes_foundation_test.rs b/tests/error_codes_foundation_test.rs index 0e4556765c..02dfdfe92b 100644 --- a/tests/error_codes_foundation_test.rs +++ b/tests/error_codes_foundation_test.rs @@ -36,3 +36,13 @@ fn execute_valid_transact_returns_ok() { 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"); +} From 395ef3f90d4cb654f958ca04dfc5c9284263f3d3 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 13:58:04 +0530 Subject: [PATCH 11/25] feat: migrate Minigraf::prepare/register_aggregate/register_predicate Signature-only changes; bodies renamed to _inner twins, unchanged. Part of #277. --- src/db.rs | 29 ++++++++++++++++++++++++++++ tests/error_codes_foundation_test.rs | 14 ++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/src/db.rs b/src/db.rs index 5c2e14761d..cfcd499146 100644 --- a/src/db.rs +++ b/src/db.rs @@ -765,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; @@ -923,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, @@ -979,6 +1000,14 @@ 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), diff --git a/tests/error_codes_foundation_test.rs b/tests/error_codes_foundation_test.rs index 02dfdfe92b..34de176da9 100644 --- a/tests/error_codes_foundation_test.rs +++ b/tests/error_codes_foundation_test.rs @@ -46,3 +46,17 @@ fn begin_write_then_checkpoint_returns_ok() { 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"); +} From 1dbfff16cf9d2101ecddcffaefcc63b53f9ecc38 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 14:01:38 +0530 Subject: [PATCH 12/25] feat: migrate WriteTransaction::execute/commit to MinigrafError Signature-only changes; bodies renamed to _inner twins, unchanged. Part of #277. --- src/db.rs | 12 ++++++++++-- tests/error_codes_foundation_test.rs | 10 ++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/db.rs b/src/db.rs index cfcd499146..881515c40d 100644 --- a/src/db.rs +++ b/src/db.rs @@ -1062,7 +1062,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 { @@ -1148,7 +1152,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(mut 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/tests/error_codes_foundation_test.rs b/tests/error_codes_foundation_test.rs index 34de176da9..32318c9f1f 100644 --- a/tests/error_codes_foundation_test.rs +++ b/tests/error_codes_foundation_test.rs @@ -60,3 +60,13 @@ fn prepare_and_register_predicate_return_ok() { }); 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"); +} From 5150eac283d7b954704ece331b681cece65dacc5 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 14:04:28 +0530 Subject: [PATCH 13/25] fix: remove unnecessary mut from WriteTransaction::commit wrapper The mutation happens inside commit_inner, which already declares its own mut self -- the outer wrapper never mutates self directly. Part of #277. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01P7e4uTBWtM8fMZiPZc4bCw --- src/db.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/db.rs b/src/db.rs index 881515c40d..1ae14b0f0e 100644 --- a/src/db.rs +++ b/src/db.rs @@ -1152,7 +1152,7 @@ impl<'a> WriteTransaction<'a> { /// # Errors /// /// Returns an error if the WAL write or fact application fails. - pub fn commit(mut self) -> Result<(), MinigrafError> { + pub fn commit(self) -> Result<(), MinigrafError> { self.commit_inner().map_err(MinigrafError::from) } From 3db6465658eef02457256163df844ddc074206f2 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 14:08:53 +0530 Subject: [PATCH 14/25] feat: migrate PreparedQuery::execute to MinigrafError Signature-only change; body renamed to execute_inner, unchanged. This completes the public API signature migration for #277's foundation PR. Part of #277. --- src/query/datalog/prepared.rs | 7 ++++++- tests/error_codes_foundation_test.rs | 13 +++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/query/datalog/prepared.rs b/src/query/datalog/prepared.rs index 2d3d06b2d5..9fdb52dae7 100644 --- a/src/query/datalog/prepared.rs +++ b/src/query/datalog/prepared.rs @@ -6,6 +6,7 @@ use crate::query::datalog::rules::RuleRegistry; use crate::query::datalog::types::{ AsOf, AttributeSpec, DatalogCommand, DatalogQuery, EdnValue, Expr, ValidAt, WhereClause, }; +use crate::error::MinigrafError; use anyhow::Result; use std::collections::{HashMap, HashSet}; use std::sync::{Arc, RwLock}; @@ -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 index 32318c9f1f..3cfe1128ef 100644 --- a/tests/error_codes_foundation_test.rs +++ b/tests/error_codes_foundation_test.rs @@ -70,3 +70,16 @@ fn write_transaction_execute_and_commit_return_ok() { 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"); +} From 3599eb5d43bd12df3dda80eebe1763da1858219a Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 14:15:02 +0530 Subject: [PATCH 15/25] fix: remove unused re-exports and apply formatting - Remove unused `pub use` re-exports of FaultConfig and FaultInjectingBackend (tests import directly from fault_inject module, not through the re-export) - Apply rustfmt formatting to match project style - Verify all clippy checks pass with -D warnings Part of #277. --- src/db.rs | 3 +- src/error.rs | 13 +++++++-- src/query/datalog/prepared.rs | 2 +- src/storage/backend/mod.rs | 2 -- tests/error_codes_foundation_test.rs | 41 ++++++++++++++++++++-------- 5 files changed, 43 insertions(+), 18 deletions(-) diff --git a/src/db.rs b/src/db.rs index 1ae14b0f0e..ac1e86ab28 100644 --- a/src/db.rs +++ b/src/db.rs @@ -1001,7 +1001,8 @@ impl Minigraf { name: &str, f: impl Fn(&Value) -> bool + Send + Sync + 'static, ) -> Result<(), MinigrafError> { - self.register_predicate_inner(name, f).map_err(MinigrafError::from) + self.register_predicate_inner(name, f) + .map_err(MinigrafError::from) } fn register_predicate_inner( diff --git a/src/error.rs b/src/error.rs index d97240723e..e8ec24f6ca 100644 --- a/src/error.rs +++ b/src/error.rs @@ -233,7 +233,10 @@ mod tests { #[test] fn format_template_no_placeholders() { - assert_eq!(format_template("no placeholders here", &[]), "no placeholders here"); + assert_eq!( + format_template("no placeholders here", &[]), + "no placeholders here" + ); } #[test] @@ -278,7 +281,9 @@ mod tests { bail_coded!(ErrorCode::Int000, "boom"); } let err = inner().unwrap_err(); - let coded = err.downcast_ref::().expect("expected a CodedError"); + let coded = err + .downcast_ref::() + .expect("expected a CodedError"); assert_eq!(coded.code(), ErrorCode::Int000); assert_eq!(coded.to_string(), "unclassified internal error: boom"); } @@ -286,7 +291,9 @@ mod tests { #[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"); + let coded = err + .downcast_ref::() + .expect("expected a CodedError"); assert_eq!(coded.code(), ErrorCode::Int000); } diff --git a/src/query/datalog/prepared.rs b/src/query/datalog/prepared.rs index 9fdb52dae7..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}; @@ -6,7 +7,6 @@ use crate::query::datalog::rules::RuleRegistry; use crate::query::datalog::types::{ AsOf, AttributeSpec, DatalogCommand, DatalogQuery, EdnValue, Expr, ValidAt, WhereClause, }; -use crate::error::MinigrafError; use anyhow::Result; use std::collections::{HashMap, HashSet}; use std::sync::{Arc, RwLock}; diff --git a/src/storage/backend/mod.rs b/src/storage/backend/mod.rs index f24e835c18..4fa0e292b2 100644 --- a/src/storage/backend/mod.rs +++ b/src/storage/backend/mod.rs @@ -6,8 +6,6 @@ pub mod file; #[cfg(test)] pub mod fault_inject; -#[cfg(test)] -pub use fault_inject::{FaultConfig, FaultInjectingBackend}; // Future: WASM backend // #[cfg(target_arch = "wasm32")] diff --git a/tests/error_codes_foundation_test.rs b/tests/error_codes_foundation_test.rs index 3cfe1128ef..3bf0cda027 100644 --- a/tests/error_codes_foundation_test.rs +++ b/tests/error_codes_foundation_test.rs @@ -33,7 +33,8 @@ fn execute_parse_error_returns_coded_error() { #[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"]])"#); + let result = + db.execute(r#"(transact [[#uuid "550e8400-e29b-41d4-a716-446655440000" :name "alice"]])"#); assert!(result.is_ok(), "valid transact should succeed"); } @@ -44,7 +45,10 @@ fn begin_write_then_checkpoint_returns_ok() { 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"); + assert!( + checkpoint.is_ok(), + "checkpoint on an in-memory db is a no-op success" + ); } #[test] @@ -55,20 +59,31 @@ fn prepare_and_register_predicate_return_ok() { 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"); + 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 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"); + assert!( + commit.is_ok(), + "committing a valid transaction should succeed" + ); } #[test] @@ -76,10 +91,14 @@ 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(); + 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"); + assert!( + result.is_ok(), + "executing a prepared query with a valid binding should succeed" + ); } From 48ba182012cb47ff3a7157cfaa1d42da461a86e9 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 14:23:32 +0530 Subject: [PATCH 16/25] revert: keep pre-existing storage/backend/mod.rs warning out of #277's scope The unused FaultConfig/FaultInjectingBackend re-export predates this branch (confirmed via git log against the merge-base with main) and is unrelated to structured error codes. Reported, not fixed, matching how Tasks 4/8/9 handled other pre-existing out-of-scope issues in this same plan. Part of #277. --- src/storage/backend/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/storage/backend/mod.rs b/src/storage/backend/mod.rs index 4fa0e292b2..f24e835c18 100644 --- a/src/storage/backend/mod.rs +++ b/src/storage/backend/mod.rs @@ -6,6 +6,8 @@ pub mod file; #[cfg(test)] pub mod fault_inject; +#[cfg(test)] +pub use fault_inject::{FaultConfig, FaultInjectingBackend}; // Future: WASM backend // #[cfg(target_arch = "wasm32")] From 3b6dacd229d53814d08a669eed4563155effb0ab Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 14:26:54 +0530 Subject: [PATCH 17/25] docs: add CHANGELOG entry for the MinigrafError breaking change Part of #277. --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fe21e3d27..aec1285e76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,6 +72,14 @@ 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() -> &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. ### Bug fixes From 4b6f944621217b6a19d9f4433bf24de4c04d67a3 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 14:40:20 +0530 Subject: [PATCH 18/25] docs: fix ERROR_REFERENCE.md self-contradiction on error surface type Line 4 said errors surface as anyhow::Error, but this PR (part of #277) made db.execute()/db.prepare()/etc. return MinigrafError, as the very next paragraph already documented. Align line 4 with reality. --- docs/ERROR_REFERENCE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ERROR_REFERENCE.md b/docs/ERROR_REFERENCE.md index aabec911f5..d814ad1a19 100644 --- a/docs/ERROR_REFERENCE.md +++ b/docs/ERROR_REFERENCE.md @@ -1,7 +1,7 @@ # 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`) appear in runtime error output as From ca78d16531d026c871fccc5da25a3b84ca086944 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 14:41:11 +0530 Subject: [PATCH 19/25] fix: route MinigrafError's anyhow fallback through the INT-000 registry entry From's fallback branch (no CodedError found in the chain) hardcoded code/category/message instead of calling registry_entry, so the emitted Display text never actually matched the documented 'unclassified internal error: {}' template in ERROR_REFERENCE.md. Route it through registry_entry(ErrorCode::Int000) + format_template instead, removing the third hardcoded duplicate of INT-000/Internal (REGISTRY and registry_entry's own fallback were the other two). Updates one existing test's expected Display text to the now-correct template-prefixed form; part of #277. --- src/error.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/error.rs b/src/error.rs index e8ec24f6ca..ee0fce301c 100644 --- a/src/error.rs +++ b/src/error.rs @@ -217,10 +217,12 @@ impl From for MinigrafError { }; } } - let message = err.to_string(); + 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: ErrorCategory::Internal, - code: "INT-000", + category, + code: code_str, message, source: err, } @@ -320,7 +322,10 @@ mod tests { 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] plain uncoded error"); + assert_eq!( + e.to_string(), + "[INT-000] unclassified internal error: plain uncoded error" + ); } #[test] From 98bbae7e4945a1123a760efc058bf51a9414e6f3 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 14:42:04 +0530 Subject: [PATCH 20/25] feat: mark ErrorCategory #[non_exhaustive] for future-proof matching ErrorCategory is a public enum designed for downstream consumers to match on, in a library targeting decades-long API stability per PHILOSOPHY.md. Marking it non_exhaustive now, before any release ships it, means a future 7th category (STG/WAL/QRY/API's categories already exist as variants; further growth is plausible) won't be a breaking change for consumers who already have to write a wildcard arm. No effect within this crate. Part of #277. --- src/error.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/error.rs b/src/error.rs index ee0fce301c..273fe6132d 100644 --- a/src/error.rs +++ b/src/error.rs @@ -6,7 +6,12 @@ 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, From e048f953428773f64220014346845b20bf39c9eb Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 14:42:16 +0530 Subject: [PATCH 21/25] docs: note Display format change and fix .code() signature typo in CHANGELOG MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The #277 foundation entry was missing that every error's Display/ to_string() now carries a [CODE] prefix it didn't have before — a behavior change beyond the Result type signature, affecting anything that string-matches error output (the REPL's printed errors, and all 7 language-binding repos per cascade-monitoring practice). Also fixes .code() -> &str to the actual signature, .code() -> &'static str. Part of #277. --- CHANGELOG.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aec1285e76..02c3fcd2b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,10 +76,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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() -> &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. + 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 From d669b32d15ff5018ec2bad561c760197446fbe4b Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 14:43:13 +0530 Subject: [PATCH 22/25] docs: surface the INT-000 transitional caveat before the file-an-issue advice During the multi-PR #277 migration window (this Foundation PR is 1 of 6; only INT-000 exists so far), ordinary user syntax mistakes surface as INT-000 too, same as genuine internal bugs, since nothing is migrated to specific codes yet. Reorder the INT section's opening sentences so a reader hits that transitional caveat before the 'likely indicates a bug ... please file an issue' advice, not after. Part of #277. --- docs/ERROR_REFERENCE.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/ERROR_REFERENCE.md b/docs/ERROR_REFERENCE.md index d814ad1a19..e039d41e19 100644 --- a/docs/ERROR_REFERENCE.md +++ b/docs/ERROR_REFERENCE.md @@ -2161,12 +2161,13 @@ db.execute("(rule [(ancestor ?x ?y) [?x :parent ?y]])")?; ## INT — Internal Errors -Internal errors are invariant violations that should not be reachable through -normal use of the public API. `INT-000` is also 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). -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` 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 From d3c14336f9eda6acd20a86ce329dbe4a15921bad Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 14:44:07 +0530 Subject: [PATCH 23/25] docs+test: correct registry_entry's safety comment; add exhaustive ErrorCode coverage test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit registry_entry's doc comment claimed the sync test (registry_is_a_subset_of_error_reference_doc) exercises every ErrorCode variant — false, it iterates REGISTRY, not ErrorCode, so a new ErrorCode variant added without a matching REGISTRY row is caught by nothing outside a debug_assert! that's compiled out in release builds. Correct the comment, and add error::tests::every_error_code_variant_has_a_registry_entry: an exhaustive match over ErrorCode with no wildcard arm, so the PRS category PR's ~79 new variants (and every one after) fail to compile here if a REGISTRY row is missing, rather than silently falling back to INT-000 at runtime. Part of #277. --- src/error.rs | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/src/error.rs b/src/error.rs index 273fe6132d..9d905c6e78 100644 --- a/src/error.rs +++ b/src/error.rs @@ -52,10 +52,15 @@ pub(crate) const REGISTRY: &[(ErrorCode, &str, &str, ErrorCategory)] = &[( pub(crate) fn registry_entry(code: ErrorCode) -> (&'static str, &'static str, ErrorCategory) { let entry = REGISTRY.iter().find(|(c, ..)| *c == code); - // Unreachable in practice: every `ErrorCode` variant is added together with its - // `REGISTRY` entry (and `registry_is_a_subset_of_error_reference_doc` exercises - // every variant). Falls back to the always-present INT-000 entry rather than - // panicking, since `unwrap`/`expect`/`panic!` are denied crate-wide. + // 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" @@ -268,6 +273,35 @@ mod tests { ); } + /// 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); From 314208c0eb951a5bcb0de9c9c2c265de293c9def Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 14:45:55 +0530 Subject: [PATCH 24/25] test: cover format_template's arg-count mismatch and a two-hop context chain Two small gaps flagged as risk for the next (PRS category) PR, which will be the first real caller of both bail_coded!/err_coded! (multi-hop .context() chains are routine there) and format_template with varying arg counts: - format_template_arg_count_mismatch_debug_asserts: a #[should_panic] test confirming the debug_assert_eq! fires under cargo test's debug build; in release (debug_assert compiled out) the same call does not panic and instead drops the unfilled placeholder's text, per the function's existing doc comment. - minigraf_error_finds_coded_error_through_two_context_hops: extends the existing single-hop context-chain test to two .context() calls, proving the chain-walk in MinigrafError::from finds a CodedError buried multiple hops deep, not just one. Part of #277. --- src/error.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/error.rs b/src/error.rs index 9d905c6e78..eb60bb7772 100644 --- a/src/error.rs +++ b/src/error.rs @@ -355,6 +355,27 @@ mod tests { 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"); From 4ee93051401e49b90433338809db4fb554c265c3 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 25 Aug 2026 14:47:25 +0530 Subject: [PATCH 25/25] docs: record parser.rs String-vs-anyhow blocker for the PRS follow-up PR Final whole-branch review of the Foundation PR found that src/query/datalog/parser.rs returns Result<_, String> everywhere, not anyhow::Result -- bail_coded!/err_coded! (which produce anyhow::Error) won't compile there as a drop-in replacement the way they do everywhere else in the crate. This doesn't require any code change in this PR, but must be decided before the PRS category PR (79 of 130 codes, the next PR in the #277 rollout) is planned. Part of #277. --- ...026-08-25-structured-error-codes-design.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) 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.