From 35e2aa693b976e9b99b4f7aead6a6db7bf88d99d Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Wed, 26 Aug 2026 08:49:38 +0530 Subject: [PATCH 1/3] =?UTF-8?q?feat:=20migrate=20db.rs=20to=20API-0xx=20an?= =?UTF-8?q?d=20audit=20remaining=20call=20sites=20to=20INT-0xx=20=E2=80=94?= =?UTF-8?q?=20#277=20(6/6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Final sub-PR of the #277 structured error codes umbrella issue. Part 1: migrates src/db.rs's remaining API-layer bail!/anyhow! call sites to their documented API-0xx codes (API-001 write lock poisoned, API-002 unexpected command variant, API-003/004 attribute-keyword/pseudo-attribute at the materialize_transaction/materialize_retraction layer, API-005/006/007 db.prepare() rejecting transact/retract/rule, API-008 function registry lock poisoned, API-009 WAL not initialized), with regression tests asserting the exact code for every reachable one (including two new lock-poisoning tests using catch_unwind to genuinely poison write_lock/ functions rather than just inspecting the code path). Part 2: audits every remaining uncoded bail!/anyhow! call site crate-wide (~250 sites across 18 files) and assigns each a new INT-0xx code (INT-001 through INT-055) with a docs/ERROR_REFERENCE.md entry, using parameterised shared codes for mechanically-repeated call sites (e.g. INT-011 for all ten "unexpected end of " parser messages, INT-050 for all thirteen lock-poisoned sites across four files, INT-048/INT-049 as broad storage overflow/invariant buckets) rather than one code per line — mirroring the QRY-005/STG-016/WAL-006 pattern already established for wrapping an arbitrary underlying cause. Two regression tests that had locked in INT-000 for the recursion-limit and aggregate-type-mismatch families (out of scope for the QRY PR) were updated to their new INT-020/ INT-041 codes. Upgrades the REGISTRY<->ERROR_REFERENCE.md sync test from subset-checking to full bidirectional equality (registry_matches_error_reference_doc_bidirectionally), now that every documented code has a real call site behind it. Final tally: 186 total ErrorCode variants (122 pre-existing + 9 new API-0xx + 55 new INT-0xx). Release binary: 1068 KiB, well under the 1200 KiB budget. Closes #362 Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01P7e4uTBWtM8fMZiPZc4bCw --- CHANGELOG.md | 75 +++ docs/ERROR_REFERENCE.md | 772 ++++++++++++++++++++++++++-- src/browser/buffer.rs | 9 +- src/db.rs | 270 +++++++--- src/error.rs | 629 +++++++++++++++++++++- src/graph/storage.rs | 22 +- src/query/datalog/evaluator.rs | 120 +++-- src/query/datalog/executor.rs | 63 +-- src/query/datalog/functions.rs | 31 +- src/query/datalog/parser.rs | 274 ++++++---- src/query/datalog/prepared.rs | 55 +- src/query/datalog/rules.rs | 8 +- src/query/datalog/stratification.rs | 7 +- src/storage/backend/file.rs | 47 +- src/storage/backend/memory.rs | 13 +- src/storage/btree.rs | 210 +++++--- src/storage/btree_v6.rs | 241 ++++++--- src/storage/cache.rs | 7 +- src/storage/mod.rs | 36 +- src/storage/packed_pages.rs | 124 +++-- src/storage/persistent_facts.rs | 18 +- src/temporal.rs | 36 +- tests/error_codes_qry_test.rs | 32 +- 23 files changed, 2426 insertions(+), 673 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5eeaf97abe..11bb7075aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -185,6 +185,81 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 pre-#277 baseline, which no further micro-optimization of already-maxed settings can absorb. ~1.2MB keeps meaningful headroom above that projection without abandoning the philosophy's small-binary principle. +- **Every remaining `bail!`/`anyhow!` call site in the crate now carries a + structured code — nothing falls through to `INT-000` by default anymore** + (#362, #277 step 6/6, the final sub-PR of the umbrella issue). Two parts: + + **Part 1 — `src/db.rs`'s API-layer call sites now carry their real + `API-0xx` codes**: `API-001` write lock poisoned (`execute`/`begin_write`/ + `checkpoint`), `API-002` unexpected command variant in the write path + (structurally unreachable — kept for defensive completeness, no test + possible), `API-003`/`API-004` attribute-must-be-keyword / + cannot-transact-a-pseudo-attribute at the `materialize_transaction`/ + `materialize_retraction` layer (mirroring `QRY-002`/`QRY-003`), `API-005`/ + `API-006`/`API-007` `db.prepare()` rejecting `transact`/`retract`/`rule`, + `API-008` function registry lock poisoned (`register_aggregate`/ + `register_predicate`), `API-009` WAL not initialized (also structurally + unreachable — `wal_write_stamped_batch` always populates `wal` two lines + above the `ok_or_else`). Regression tests assert the exact code for every + reachable one, including two new lock-poisoning tests that deliberately + panic while holding `write_lock`/`functions` (via `catch_unwind`) to + exercise `API-001`/`API-008` for real rather than by inspection. + `db.rs`'s own "invalid entity"/"invalid value" checks in + `materialize_transaction`/`materialize_retraction` have no `API-0xx` + counterpart in `docs/ERROR_REFERENCE.md` (only `QRY-001`/`QRY-004` do, and + those cover a different, unreachable-from-`db.rs` call path — see the QRY + entry above) and a `WriteTransaction`-already-active reentrancy check has + no documented code at all, so all three became new `INT-0xx` codes + (`INT-001`, `INT-002`, `INT-003`) — part of the audit below. + + **Part 2 — every other uncoded `bail!`/`anyhow!` site crate-wide + (~250 of them, across 18 files: `temporal.rs`, `parser.rs`'s long-tail + internal-error/syntax branches the PRS migration left uncoded, + `evaluator.rs`, `executor.rs`'s remaining sites, `prepared.rs`, + `functions.rs`, `rules.rs`, `stratification.rs`, `graph/storage.rs`, + `storage/mod.rs`, `storage/persistent_facts.rs`, `storage/packed_pages.rs`, + `storage/btree.rs`, `storage/btree_v6.rs`, + `storage/backend/{file,memory}.rs`, `storage/cache.rs`, + `browser/buffer.rs`) — assigned one of 52 new `INT-0xx` codes** + (`INT-004`–`INT-055`; `docs/ERROR_REFERENCE.md`'s old "Appendix: Internal + Errors" bullet list is gone, replaced by `INT-006`'s formal entry, which + covers the same 8 "internal parser error: expected X token" strings via a + `{}` placeholder). Mechanically-repeated call sites share one + parameterised code rather than getting one each — mirroring the pattern + `QRY-005`/`STG-016`/`WAL-006` already established for "wrap an arbitrary + underlying cause" and "one poisoned-lock code per resource": e.g. `INT-011` + covers all ten "unexpected end of ``" parser messages, `INT-018` + covers all four "variable not bound by any outer/earlier clause" messages, + `INT-050` covers all thirteen lock-poisoned sites across four files + (`{}` names the specific lock), and `INT-048`/`INT-049` are broad + "storage: arithmetic overflow"/"storage: internal invariant violation" + buckets covering dozens of B+tree/packed-page bounds-check and + overflow-guard sites that were never meaningfully distinct from one + another. A handful of genuinely user-reachable conditions that + the original five category PRs simply never got to — the recursion/ + derived-facts/result-limit family in `evaluator.rs` (`INT-020`) and the + runtime aggregate type-mismatch family in `functions.rs` (`INT-041`– + `INT-044`) among them — are `INT-0xx` rather than `QRY-0xx` purely because + this PR's scope is "assign every remaining site an `INT` code," not + "reopen the closed PRS/QRY/STG/WAL category PRs to extend their code + ranges"; two existing regression tests in `tests/error_codes_qry_test.rs` + that had locked in `INT-000` for exactly these two families before this PR + (`recursive_rule_derived_facts_limit_returns_int000`, + `aggregate_type_mismatch_returns_int000`) were updated in place to assert + their new codes instead, and two similarly-named unit tests in + `src/query/datalog/evaluator.rs` were fixed the same way. +- **The `REGISTRY`↔`docs/ERROR_REFERENCE.md` sync test is now a full + bidirectional equality check** (#362, #277 step 6/6), replacing the + subset-only check the foundation PR (#357) introduced. Renamed + `registry_is_a_subset_of_error_reference_doc` → + `registry_matches_error_reference_doc_bidirectionally`: it now also + asserts every documented `### CODE` section with an "Error text" line has + a matching `REGISTRY` row, not just the reverse. This is only safe now + that Part 2 above means no documented code can be missing a registry + entry because its call site hasn't been migrated yet — the last such gap + is closed. The final tally: 122 pre-#362 `ErrorCode` variants (`PRS`×79, + `QRY`×9, `STG`×27, `WAL`×6, `INT-000`×1) plus 9 new `API-0xx` and 55 new + `INT-0xx` (`INT-001`–`INT-055`) = 186 total. ### Bug fixes diff --git a/docs/ERROR_REFERENCE.md b/docs/ERROR_REFERENCE.md index 8251872237..b170028ecd 100644 --- a/docs/ERROR_REFERENCE.md +++ b/docs/ERROR_REFERENCE.md @@ -6,10 +6,11 @@ and related API methods. **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. +`MinigrafError::category()`. As of [#277](https://github.com/project-minigraf/minigraf/issues/277), +every `bail!`/`anyhow!` call site in the crate has been migrated to a specific +structured code — `INT-000` is now reserved for the rare case of a raw, +non-`anyhow` error (e.g. an `io::Error`) reaching the public API boundary +with no `CodedError` anywhere in its chain. **Out of scope**: FFI/binding errors from `minigraf-python`, `minigraf-node`, and `minigraf-wasm` are handled in those repos. @@ -151,6 +152,61 @@ category's follow-up migration PR lands, most still surface generically as | API-008 | Function registry lock poisoned | Database API | | API-009 | WAL not initialized | Database API | | INT-000 | Unclassified internal error | Internal | +| INT-001 | WriteTransaction already in progress on this thread | Internal | +| INT-002 | Invalid entity (API layer) | Internal | +| INT-003 | Invalid value (API layer) | Internal | +| INT-004 | Invalid timestamp | Internal | +| INT-005 | Millisecond value outside supported datetime range | Internal | +| INT-006 | Internal parser error: expected token | Internal | +| INT-007 | Float literal out of range | Internal | +| INT-008 | Integer literal out of range | Internal | +| INT-009 | Symbol exceeds maximum length | Internal | +| INT-010 | Exceeded maximum recursion depth | Internal | +| INT-011 | Unexpected end of clause | Internal | +| INT-012 | Duplicate query option | Internal | +| INT-013 | Query option requires a value | Internal | +| INT-014 | Query option must be >= 1 | Internal | +| INT-015 | Query option must be a positive integer | Internal | +| INT-016 | (or)/(or-join) nested inside (not)/(not-join) | Internal | +| INT-017 | Pseudo-attribute not valid in this position | Internal | +| INT-018 | Variable not bound by any outer/earlier clause | Internal | +| INT-019 | Datalog parser internal error | Internal | +| INT-020 | Evaluator iteration/result limit exceeded | Internal | +| INT-021 | Evaluator: unsupported where-clause in evaluate_rule | Internal | +| INT-022 | Datalog evaluator internal error | Internal | +| INT-023 | Packed page: fact exceeds slot capacity | Internal | +| INT-024 | Packed page: malformed page data | Internal | +| INT-025 | Unsubstituted :valid-at bind slot reached executor | Internal | +| INT-026 | Temporal pseudo-attributes require :any-valid-time | Internal | +| INT-027 | Query has no :where clause, rules, or aggregates | Internal | +| INT-028 | Rule invocation argument count mismatch | Internal | +| INT-029 | Unknown aggregate function | Internal | +| INT-030 | Unknown window function | Internal | +| INT-031 | or-join variable not bound in incoming scope | Internal | +| INT-032 | Query executor internal error | Internal | +| INT-033 | Missing bind value for slot | Internal | +| INT-034 | Bind slot not permitted in attribute position | Internal | +| INT-035 | Bind slot type mismatch | Internal | +| INT-036 | Header too short: need N..M bytes | Internal | +| INT-037 | Header slice not the exact expected byte length | Internal | +| INT-038 | Header too short for a specific field | Internal | +| INT-039 | Invalid magic number | Internal | +| INT-040 | Function/predicate name already registered | Internal | +| INT-041 | sum: unsupported value type | Internal | +| INT-042 | min/max: no non-null values in group | Internal | +| INT-043 | Cannot compare values of different types | Internal | +| INT-044 | Aggregate: unsupported value type | Internal | +| INT-045 | Pending fact index out of bounds | Internal | +| INT-046 | Missing CommittedFactReader for a committed FactRef | Internal | +| INT-047 | into_backend: backend Arc has multiple owners | Internal | +| INT-048 | Storage: arithmetic overflow | Internal | +| INT-049 | Storage: internal invariant violation | Internal | +| INT-050 | Internal lock poisoned | Internal | +| INT-051 | Invalid page size | Internal | +| INT-052 | Page not found | Internal | +| INT-053 | Header checksum mismatch: possible file corruption | Internal | +| INT-054 | Unstratifiable negative recursion cycle | Internal | +| INT-055 | Rule predicate disappeared during rollback | Internal | --- @@ -2161,40 +2217,696 @@ 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). +Internal errors are invariant violations or edge cases that are not expected +to occur through normal use of the public API, or (for a handful of codes +inherited from before every call site was audited — see +[#277](https://github.com/project-minigraf/minigraf/issues/277)) genuine +user-reachable mistakes that were never given a category-specific `PRS-`/ +`QRY-`/`API-` code of their own. If you see one of these in practice and +cannot explain it from your own input, it likely indicates a bug in +Minigraf itself; please +[file an issue](https://github.com/project-minigraf/minigraf/issues) with +the full error message and the input that triggered it. + +Many `INT-` codes below are intentionally shared by several call sites in +the same subsystem (mirroring how, e.g., `QRY-005`/`QRY-006` already wrap +an arbitrary underlying failure) — the `{}` placeholder in the "Error text" +carries the specific underlying detail. This keeps the registry a +manageable size while still giving every call site a real, matchable code +instead of falling through to the generic `INT-000` fallback. ### 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. +**Cause**: A raw, non-`anyhow` error (e.g. `io::Error`, a panic caught at a +FFI boundary) reached the public API boundary with no `CodedError` anywhere +in its `anyhow::Error` chain. As of [#277](https://github.com/project-minigraf/minigraf/issues/277) +every `bail!`/`anyhow!` call site in the crate has been migrated to a +specific code, so this should now be rare. **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. +- If you see this in practice, please file an issue — it likely means a new + call site was added without going through `bail_coded!`/`err_coded!`. -**Scenario**: Any error not yet covered by a migrated `PRS-`/`STG-`/`WAL-`/`QRY-`/`API-` code. +**Scenario**: An I/O error from the underlying filesystem propagates through +`?` without ever being wrapped in a `CodedError`. ---- +### INT-001 WriteTransaction already in progress on this thread + +**Error text**: `a WriteTransaction is already in progress on this thread; use tx.execute() instead` + +**Cause**: `Minigraf::execute()` or `Minigraf::begin_write()` was called on +the same thread that already holds an active `WriteTransaction`. Acquiring +the write lock again on that thread would deadlock, so this is detected and +rejected instead. + +**Resolution**: +- Use the existing `WriteTransaction`'s `tx.execute()` for further writes + instead of calling `db.execute()` again on the same thread. + +**Scenario**: Code inside a `WriteTransaction` write closure calls +`db.execute("(transact ...)")` on the outer `db` handle instead of +`tx.execute(...)`. + +### INT-002 Invalid entity (API layer) + +**Error text**: `invalid entity: {}` + +**Cause**: `Minigraf::materialize_transaction`/`materialize_retraction` +(the API-layer write path used by `db.execute()` and `WriteTransaction`) +could not resolve an entity ID in a fact. This mirrors `QRY-001` but fires +at the API layer's own materialization step, which runs before the WAL +write for correct WAL-first ordering. + +**Resolution**: +- Ensure entity IDs are UUIDs (`#uuid "..."` tagged literals) or values + resolvable to a UUID. + +### INT-003 Invalid value (API layer) + +**Error text**: `invalid value: {}` + +**Cause**: `Minigraf::materialize_transaction`/`materialize_retraction` +found a fact value of a type Minigraf cannot store. This mirrors `QRY-004` +but fires at the API layer's own materialization step. + +**Resolution**: +- Use only supported value types: string, integer, float, boolean, UUID + ref, or keyword. + +### INT-004 Invalid timestamp + +**Error text**: `invalid timestamp: {}` + +**Cause**: `parse_timestamp` (used for `:as-of`, `:valid-at`, `:valid-from`, +and `:valid-to` date strings) rejected the input — either a timezone offset +was present (only UTC `Z` timestamps are supported, to avoid chrono's local +timezone handling, GHSA-wcg3-cvx6-7396), or the string did not parse as an +RFC 3339 datetime or `YYYY-MM-DD` date. + +**Resolution**: +- Use a UTC timestamp like `"2024-01-15T10:00:00Z"` or a bare date like + `"2024-01-15"`. Do not include a timezone offset such as `+05:30`. + +### INT-005 Millisecond value outside supported datetime range + +**Error text**: `millisecond value {} is outside the supported datetime range` + +**Cause**: `millis_to_timestamp_string` was given a millisecond value +outside the range chrono can represent as a UTC datetime. `i64::MAX` +(`VALID_TIME_FOREVER`) must never be passed to this function directly — +callers should check for the sentinel before formatting. + +**Resolution**: +- Check for `VALID_TIME_FOREVER` before formatting a `valid_to` value. + +### INT-006 Internal parser error: expected token + +**Error text**: `internal parser error: expected {} token` + +**Cause**: The Datalog/EDN parser's second pass expected a specific +lexer-token kind (keyword, symbol, string, integer, float, boolean, tagged +literal, or bind slot) at a position the first pass had already validated +would hold that kind. This indicates the parser's two passes have gone out +of sync — a bug in Minigraf, not a user mistake. + +**Resolution**: +- File a bug report with the exact input string that triggered this error. + +### INT-007 Float literal out of range + +**Error text**: `Float literal out of range: {}` + +**Cause**: A numeric literal in the input parsed as a float token but +overflowed Rust's `f64` range during conversion. + +**Resolution**: +- Use a value within `f64`'s representable range. + +### INT-008 Integer literal out of range + +**Error text**: `Integer literal out of range: {}` + +**Cause**: A numeric literal in the input parsed as an integer token but +overflowed Rust's `i64` range during conversion. + +**Resolution**: +- Use a value within `i64`'s representable range (roughly ±9.2×10¹⁸). + +### INT-009 Symbol exceeds maximum length + +**Error text**: `Symbol exceeds maximum length of {} bytes` + +**Cause**: A Datalog symbol (variable name, predicate name, etc.) exceeded +the parser's maximum symbol length. + +**Resolution**: +- Shorten the symbol name. + +### INT-010 Exceeded maximum recursion depth + +**Error text**: `Exceeded maximum recursion depth of {}` + +**Cause**: The input's nested list/vector structure exceeded the parser's +maximum recursion depth — a guard against stack overflow on deeply nested +or adversarial input. + +**Resolution**: +- Flatten the query structure; deeply nested `(and ...)`/`(or ...)` forms + are rarely necessary. + +### INT-011 Unexpected end of clause + +**Error text**: `unexpected end of {}` + +**Cause**: The parser reached the end of the input while still expecting +more elements inside a clause (e.g. `:over`, a query vector, an expression +clause, `not`/`not-join`/`or`/`or-join`, a rule invocation, or `and`). The +`{}` names which clause was left incomplete. + +**Resolution**: +- Check the input for a missing closing `]`/`)` or a truncated clause. + +### INT-012 Duplicate query option + +**Error text**: `duplicate {}` + +**Cause**: A query specified the same top-level option (`:max-derived-facts` +or `:max-results`) more than once. + +**Resolution**: +- Specify each query option at most once. + +### INT-013 Query option requires a value + +**Error text**: `{} requires a value` + +**Cause**: A query option keyword (`:max-derived-facts` or `:max-results`) +was present with no following value. + +**Resolution**: +- Supply a positive integer value after the option keyword. + +### INT-014 Query option must be >= 1 + +**Error text**: `{} must be >= 1` + +**Cause**: `:max-derived-facts` or `:max-results` was given a value less +than 1. + +**Resolution**: +- Use a value of 1 or greater. + +### INT-015 Query option must be a positive integer + +**Error text**: `{} must be a positive integer` + +**Cause**: `:max-derived-facts` or `:max-results` was given a non-integer +value. + +**Resolution**: +- Supply a positive integer literal. + +### INT-016 (or)/(or-join) nested inside (not)/(not-join) + +**Error text**: `(or)/(or-join) cannot appear inside (not)/(not-join)` + +**Cause**: A `(not ...)` or `(not-join ...)` clause's body contained a +nested `(or ...)`/`(or-join ...)`, which is not supported. + +**Resolution**: +- Restructure the query to avoid nesting `or`/`or-join` inside negation. + +### INT-017 Pseudo-attribute not valid in this position + +**Error text**: `pseudo-attribute {} is not valid in {} position` + +**Cause**: A pseudo-attribute (e.g. `:db/valid-from`) was used in the +entity or value position of a pattern, where only real attributes and +plain values are permitted. + +**Resolution**: +- Use pseudo-attributes only in the attribute position of a pattern. + +### INT-018 Variable not bound by any outer/earlier clause + +**Error text**: `{} {} in {} is not bound by any {} clause` + +**Cause**: A variable referenced inside `(not ...)`, `(not-join ...)`, an +expression clause, or `(or-join ...)` was never bound by an outer or +earlier clause in the query. + +**Resolution**: +- Ensure every variable used inside negation, expressions, or `or-join` + also appears in a preceding pattern that binds it. + +### INT-019 Datalog parser internal error + +**Error text**: `datalog parser: {}` + +**Cause**: A shared catch-all for the parser's remaining long-tail syntax +and structural errors (malformed `:with`/`:find` clauses, malformed +fact/rule/pattern vectors, invalid regex literals in `matches?`, and +similar). The `{}` carries the specific underlying message. + +**Resolution**: +- Read the wrapped message text for the specific syntax problem and correct + the input accordingly. + +### INT-020 Evaluator iteration/result limit exceeded + +**Error text**: `evaluator: iteration or result limit exceeded: {}` + +**Cause**: The recursive rule evaluator (semi-naive evaluation) exceeded its +maximum iteration count, maximum derived facts per iteration, or maximum +query result count — guards against infinite recursion/cycles or +runaway-generating rules. + +**Resolution**: +- Check the rule for an unintended cycle (e.g. `(ancestor ?x ?y) [?x + :parent ?y]` combined with a cyclic `:parent` graph). Raise the relevant + limit via query options if the workload is legitimately large. + +### INT-021 Evaluator: unsupported where-clause in evaluate_rule + +**Error text**: `evaluator: unsupported where-clause in evaluate_rule: {}` + +**Cause**: A rule body contained a `not`, `not-join`, `or`, or `or-join` +clause, but was evaluated through the non-stratified `RecursiveEvaluator` +instead of `StratifiedEvaluator`, which is required for rules with +negation/disjunction. This indicates an internal dispatch bug — the +executor should route negation-containing rules to the stratified +evaluator. + +**Resolution**: +- File a bug report with the rule definition that triggered this error. + +### INT-022 Datalog evaluator internal error + +**Error text**: `datalog evaluator: {}` + +**Cause**: A shared catch-all for the recursive rule evaluator's remaining +internal invariant checks around rule invocation/head parsing (e.g. a rule +invocation or head with an unexpected shape, an unbound variable in a rule +head, or a window-function row-index bound check). These conditions should +already be rejected by the parser and are not expected to reach the +evaluator through normal use. + +**Resolution**: +- File a bug report with the rule/query that triggered this error. + +### INT-023 Packed page: fact exceeds slot capacity + +**Error text**: `packed page: fact record exceeds slot capacity: {}` + +**Cause**: A fact's postcard-encoded size exceeds the maximum a packed fact +page slot can hold. + +**Resolution**: +- Store large payloads externally and reference them with a `Value::String` + URL/path or `Value::Ref` entity ID, the same guidance as `WAL-003`. + +### INT-024 Packed page: malformed page data + +**Error text**: `packed page: malformed page data: {}` + +**Cause**: A shared catch-all for packed-fact-page invariant violations — +a page shorter than expected, a directory entry or record slice out of +bounds, or an offset/length computation that would overflow. These +indicate on-disk corruption or a bug in the packed-page encoder, not a +user mistake. + +**Resolution**: +- If this occurs on a database file that was not modified outside + Minigraf, please file a bug report with the file (or a minimal + reproduction) attached. + +### INT-025 Unsubstituted :valid-at bind slot reached executor + +**Error text**: `internal: unsubstituted :valid-at bind slot reached the executor` + +**Cause**: A prepared query's `:valid-at` clause still contained an +unresolved `$slot` bind placeholder when it reached the query executor. +`PreparedQuery::execute` is expected to substitute all bind slots before +handing the query to the executor. + +**Resolution**: +- File a bug report — this indicates a gap in `PreparedQuery`'s bind-slot + substitution. + +### INT-026 Temporal pseudo-attributes require :any-valid-time + +**Error text**: `temporal pseudo-attributes :db/valid-from, :db/valid-to, :db/tx-count, and :db/tx-id require :any-valid-time; add :any-valid-time to your query` + +**Cause**: A query referenced a temporal pseudo-attribute (`:db/valid-from`, +`:db/valid-to`, `:db/tx-count`, `:db/tx-id`) without also specifying +`:valid-at :any-valid-time`. These pseudo-attributes expose per-fact +temporal metadata that only makes sense when the query is not filtering to +a single point in valid time. + +**Resolution**: +- Add `:valid-at :any-valid-time` to the query. + +### INT-027 Query has no :where clause, rules, or aggregates + +**Error text**: `query has no :where clause, rules, or aggregates — nothing binds the variables. Add a :where clause (e.g., [:find ?e ?a ?v :where [?e ?a ?v]]) or use an aggregate.` + +**Cause**: A `(query ...)` command's `:find` variables have nothing to +bind them — no `:where` clause, no rule invocation, and no aggregate. + +**Resolution**: +- Add a `:where` clause that binds every variable in `:find`. + +### INT-028 Rule invocation argument count mismatch -## Appendix: Internal Errors - -The following error strings indicate a bug in the Minigraf library itself, not a -user mistake. If you encounter one, please -[open a GitHub issue](https://github.com/project-minigraf/minigraf/issues/new) -with the full error message and the input that triggered it. - -- `internal parser error: expected keyword token` -- `internal parser error: expected symbol token` -- `internal parser error: expected string token` -- `internal parser error: expected integer token` -- `internal parser error: expected float token` -- `internal parser error: expected boolean token` -- `internal parser error: expected tagged literal token` -- `internal parser error: expected bind slot token` +**Error text**: `Rule invocation '{}' must have 1 or 2 arguments, got {}` + +**Cause**: A rule was invoked with an argument count other than 1 (entity +only) or 2 (entity and value). Minigraf's rule invocations only support +these two arities. + +**Resolution**: +- Invoke the rule with 1 or 2 arguments, matching its definition. + +### INT-029 Unknown aggregate function + +**Error text**: `unknown aggregate function: '{}'` + +**Cause**: A `:find` or `:with` clause referenced an aggregate function +name that is neither a built-in (`count`, `sum`, `avg`, `min`, `max`, etc.) +nor a user-defined function registered via `db.register_aggregate()`. + +**Resolution**: +- Check the function name for typos, or register it first with + `db.register_aggregate()`. + +### INT-030 Unknown window function + +**Error text**: `unknown window function '{}' — register it with register_aggregate() before querying` + +**Cause**: An `:over` (window) clause referenced a function name that is +not a recognized window-compatible built-in and has not been registered. + +**Resolution**: +- Register the function with `db.register_aggregate()` before using it in + an `:over` clause. + +### INT-031 or-join variable not bound in incoming scope + +**Error text**: `or-join variable {} is not bound in the incoming scope` + +**Cause**: An `(or-join [vars] ...)` clause's declared join variable was +not actually bound in the scope the `or-join` was evaluated in. + +**Resolution**: +- Ensure every variable listed in `or-join`'s join-vars vector is bound by + a clause preceding it in the query. + +### INT-032 Query executor internal error + +**Error text**: `query executor: {}` + +**Cause**: A shared catch-all for a handful of query executor invariant +checks that are not expected to be user-reachable (an empty rule head +reaching execution, a rule head not starting with a predicate symbol, or a +window function's row-number position overflowing). + +**Resolution**: +- File a bug report with the query that triggered this error. + +### INT-033 Missing bind value for slot + +**Error text**: `missing bind value for slot '${}'` + +**Cause**: `PreparedQuery::execute()` was called without supplying a bind +value for every `$slot` the prepared query declared. + +**Resolution**: +- Supply a `BindValue` for every named slot before calling `execute()`. + +### INT-034 Bind slot not permitted in attribute position + +**Error text**: `bind slot '${}' is not permitted in attribute position; the query optimizer selects an index based on the attribute at prepare time and cannot handle a parameterised attribute` + +**Cause**: A `$slot` bind placeholder appeared in the attribute position of +a pattern in a prepared query. The query optimizer picks an index (EAVT, +AEVT, AVET, VAET) based on the attribute at `prepare()` time, which is not +possible if the attribute itself is a runtime-bound parameter. + +**Resolution**: +- Use a literal attribute keyword in patterns; reserve bind slots for the + entity or value position. + +### INT-035 Bind slot type mismatch + +**Error text**: `slot '${}' in {} position requires {}, got {}` + +**Cause**: A bind value supplied to `PreparedQuery::execute()` was of the +wrong `BindValue` variant for the position its slot appears in (entity +position requires `Entity`, value/expression position requires `Val`, +`:as-of` position requires `TxCount` or `Timestamp`, `:valid-at` position +requires `Timestamp` or `AnyValidTime`). + +**Resolution**: +- Supply a `BindValue` of the variant the slot's position requires. + +### INT-036 Header too short: need N..M bytes + +**Error text**: `header too short: need {}..{}, got {} bytes` + +**Cause**: A file-header field read (a 4-byte or 8-byte fixed-width field) +extended past the end of the available header bytes. + +**Resolution**: +- The file is likely truncated or corrupted. Restore from a backup. + +### INT-037 Header slice not the exact expected byte length + +**Error text**: `header: slice at {} not exactly {} bytes` + +**Cause**: An internal invariant check found a header field slice that was +not exactly the expected width (4 or 8 bytes) after a bounds check that +should have guaranteed it. Indicates a bug in the header-parsing slicing +logic. + +**Resolution**: +- File a bug report with the file header bytes attached. + +### INT-038 Header too short for a specific field + +**Error text**: `header too short for {}` + +**Cause**: The v7 header parser ran out of bytes while reading a specific +field (the magic bytes, `fact_page_format`, or one of the reserved padding +bytes). + +**Resolution**: +- The file is likely truncated or corrupted. Restore from a backup. + +### INT-039 Invalid magic number + +**Error text**: `Invalid magic number` + +**Cause**: A legacy-format header parsing path found a magic number that +does not match `"MGRF"`. This mirrors `STG-002` but fires on a different +internal parsing path. + +**Resolution**: +- The file is not a Minigraf `.graph` file, or is corrupted. + +### INT-040 Function/predicate name already registered + +**Error text**: `{} '{}' is already registered` + +**Cause**: `db.register_aggregate()` or `db.register_predicate()` was +called with a name that is already registered — either a built-in or a +previously registered user-defined function. + +**Resolution**: +- Choose a unique name, or only register the function once. + +### INT-041 sum: unsupported value type + +**Error text**: `sum: expected Integer, Float, or Null, got {}` + +**Cause**: The built-in `sum` aggregate encountered a value in its input +group that is not an `Integer`, `Float`, or `Null`. + +**Resolution**: +- Ensure the attribute being summed only ever holds numeric or null + values. + +### INT-042 min/max: no non-null values in group + +**Error text**: `min/max: no non-null values in group` + +**Cause**: The built-in `min`/`max` aggregate was applied to a group whose +values were all `Null`, leaving nothing to compare. + +**Resolution**: +- Filter out rows with a null value before aggregating, or handle the + all-null-group case in your query. + +### INT-043 Cannot compare values of different types + +**Error text**: `{}: cannot compare {} and {} values` + +**Cause**: An aggregate that orders values (`min`, `max`) encountered two +values of different, non-comparable `Value` types within the same group. + +**Resolution**: +- Ensure the attribute being aggregated holds a consistent value type + across all matching facts. + +### INT-044 Aggregate: unsupported value type + +**Error text**: `{}: expected Integer, Float, String, or Null, got {}` + +**Cause**: An aggregate that requires an orderable scalar type (e.g. `min`, +`max`) encountered a value type it does not support (such as a `Boolean` +or `Ref`). + +**Resolution**: +- Ensure the aggregated attribute only holds Integer, Float, String, or + Null values. + +### INT-045 Pending fact index out of bounds + +**Error text**: `pending fact index {} out of bounds` + +**Cause**: A `FactRef` pointed at a pending (not-yet-committed) fact slot +index that no longer exists in the pending fact buffer. + +**Resolution**: +- File a bug report — this indicates a lifecycle bug between fact + materialization and lookup. + +### INT-046 Missing CommittedFactReader for a committed FactRef + +**Error text**: `no CommittedFactReader but got committed FactRef (page_id={})` + +**Cause**: A `FactRef` pointing at a committed (on-disk) fact was resolved +without a `CommittedFactReader` configured to read it. + +**Resolution**: +- File a bug report — this indicates the storage backend was constructed + without the reader it needs for the facts it is indexing. + +### INT-047 into_backend: backend Arc has multiple owners + +**Error text**: `into_backend: backend Arc has multiple owners` + +**Cause**: `PersistentFactStorage::into_backend()` requires exclusive +ownership of its internal `Arc>` to unwrap it, but another +clone of the `Arc` was still alive when it was called. + +**Resolution**: +- Ensure no other handle (e.g. a second `Minigraf` clone) is holding a + reference to the same backend when converting it back into a raw + backend. + +### INT-048 Storage: arithmetic overflow + +**Error text**: `storage: arithmetic overflow: {}` + +**Cause**: A shared catch-all for arithmetic-overflow guards throughout the +storage layer (B+tree page/entry-length computations, page-count/page-id +arithmetic, packed-page offset arithmetic) — a checked or `saturating_*` +computation would have overflowed its target integer width. Only reachable +on databases far larger than any realistic deployment. + +**Resolution**: +- File a bug report if this occurs on a database of reasonable size — it + likely indicates a corrupt page count or index in the file header. + +### INT-049 Storage: internal invariant violation + +**Error text**: `storage: internal invariant violation: {}` + +**Cause**: A shared catch-all for storage-layer invariant violations — +malformed or corrupted B+tree/packed-fact page bytes, an out-of-bounds +page/entry index, an unexpected page type where a specific type was +required, or an "impossible" empty internal structure (e.g. `BUG: +cur_first_key empty when writing leaf page`). These indicate either +on-disk corruption or a bug in Minigraf's B+tree/page-encoding logic. + +**Resolution**: +- If this occurs on a database file that was not modified outside + Minigraf, please file a bug report with the file (or a minimal + reproduction) attached. + +### INT-050 Internal lock poisoned + +**Error text**: `{} lock poisoned` + +**Cause**: One of Minigraf's internal `Mutex`/`RwLock` guards (the shared +fact-storage data lock, the page cache lock, the in-memory backend's page +table lock, or the on-disk `MutexStorageBackend`'s lock) was poisoned by a +previous operation panicking while holding it. + +**Resolution**: +- Restart the process. If panics recur, investigate the root cause before + retrying — a poisoned lock is permanent for the life of the process. + +### INT-051 Invalid page size + +**Error text**: `Invalid page size: {} bytes (expected {})` + +**Cause**: A page passed to a storage backend's `write_page` was not +exactly `PAGE_SIZE` (4096) bytes. + +**Resolution**: +- This is an internal contract violation between the storage layer and its + backend, not a user mistake. File a bug report. + +### INT-052 Page not found + +**Error text**: `Page {} not found` + +**Cause**: A storage backend was asked to read a page ID that does not +exist in its page table (in-memory or browser IndexedDB-backed backends). + +**Resolution**: +- File a bug report — this indicates a page was referenced (e.g. by a + B+tree pointer) without having first been written. + +### INT-053 Header checksum mismatch: possible file corruption + +**Error text**: `Header checksum mismatch: possible file corruption. Database may be damaged.` + +**Cause**: The v7 file header's stored checksum does not match a freshly +computed checksum of the header bytes — the header was modified outside +Minigraf, corrupted by a partial write, or damaged by the underlying +storage medium. + +**Resolution**: +- Restore the database file from a backup. If the file was open at the + time of a crash, check for a `.wal` sidecar next to it — replaying it on + the last-known-good copy may recover recent writes. + +### INT-054 Unstratifiable negative recursion cycle + +**Error text**: `unstratifiable: predicate '{}' is involved in a negative cycle through '{}'` + +**Cause**: A set of rules contains a predicate that depends negatively +(through `not`/`not-join`) on itself, directly or transitively — this has +no well-defined semantics under stratified negation and cannot be +evaluated. + +**Resolution**: +- Restructure the rules so that no predicate's definition negatively + depends on itself, even indirectly through other rules. + +### INT-055 Rule predicate disappeared during rollback + +**Error text**: `rule predicate '{}' disappeared during rollback` + +**Cause**: `WriteTransaction::rollback()` (or an implicit rollback on +drop) attempted to remove a rule that had been staged for registration in +this transaction, but the rule registry no longer contained it. + +**Resolution**: +- File a bug report — this indicates a lifecycle bug in + `WriteTransaction`'s rule-staging/rollback logic. diff --git a/src/browser/buffer.rs b/src/browser/buffer.rs index ad24edcd19..d170390a2c 100644 --- a/src/browser/buffer.rs +++ b/src/browser/buffer.rs @@ -1,3 +1,4 @@ +use crate::error::{ErrorCode, bail_coded, err_coded}; use crate::storage::{PAGE_SIZE, StorageBackend}; use anyhow::Result; use std::collections::{HashMap, HashSet}; @@ -65,11 +66,7 @@ impl BrowserBufferBackend { impl StorageBackend for BrowserBufferBackend { fn write_page(&mut self, page_id: u64, data: &[u8]) -> Result<()> { if data.len() != PAGE_SIZE { - anyhow::bail!( - "Invalid page size: {} bytes (expected {})", - data.len(), - PAGE_SIZE - ); + bail_coded!(ErrorCode::Int051, data.len(), PAGE_SIZE); } self.pages.insert(page_id, data.to_vec()); self.dirty.insert(page_id); @@ -80,7 +77,7 @@ impl StorageBackend for BrowserBufferBackend { self.pages .get(&page_id) .cloned() - .ok_or_else(|| anyhow::anyhow!("Page {} not found", page_id)) + .ok_or_else(|| err_coded!(ErrorCode::Int052, page_id)) } fn sync(&mut self) -> Result<()> { diff --git a/src/db.rs b/src/db.rs index ba8301f5d5..6a874fc3f8 100644 --- a/src/db.rs +++ b/src/db.rs @@ -15,7 +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::error::{ErrorCode, MinigrafError, bail_coded, err_coded}; use crate::graph::FactStorage; use crate::graph::types::Value; use crate::query::datalog::evaluator::DEFAULT_MAX_DERIVED_FACTS; @@ -34,7 +34,7 @@ use crate::storage::backend::file::FileBackend; use crate::storage::persistent_facts::PersistentFactStorage; #[cfg(not(target_arch = "wasm32"))] use crate::wal::WalWriter; -use anyhow::{Result, bail}; +use anyhow::Result; use std::any::Any; #[cfg(not(target_arch = "wasm32"))] use std::path::{Path, PathBuf}; @@ -532,9 +532,7 @@ impl Minigraf { fn execute_inner(&self, input: &str) -> Result { // Detect same-thread reentrant write (would deadlock on the Mutex). if is_write_tx_active() { - bail!( - "a WriteTransaction is already in progress on this thread; use tx.execute() instead" - ); + bail_coded!(ErrorCode::Int001); } let cmd = parse_datalog_command(input)?; @@ -547,9 +545,11 @@ impl Minigraf { ); if is_write { - let mut ctx = self.inner.write_lock.lock().map_err(|_| { - anyhow::anyhow!("write lock is poisoned; database may be in an inconsistent state") - })?; + let mut ctx = self + .inner + .write_lock + .lock() + .map_err(|_| err_coded!(ErrorCode::Api001))?; // Handle write commands with correct WAL-first ordering for Transact/Retract: // 1. Materialize facts (no storage mutation yet) @@ -570,7 +570,7 @@ impl Minigraf { ); return executor.execute(cmd); } - _ => return Err(anyhow::anyhow!("unexpected command variant in write path")), + _ => return Err(err_coded!(ErrorCode::Api002)), }; let tx_count = self.inner.fact_storage.allocate_tx_count(); @@ -646,13 +646,13 @@ impl Minigraf { 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" - ); + bail_coded!(ErrorCode::Int001); } - let guard = self.inner.write_lock.lock().map_err(|_| { - anyhow::anyhow!("write lock is poisoned; database may be in an inconsistent state") - })?; + let guard = self + .inner + .write_lock + .lock() + .map_err(|_| err_coded!(ErrorCode::Api001))?; // Set flag only after successfully acquiring the lock set_write_tx_active(true); Ok(WriteTransaction { @@ -680,9 +680,11 @@ impl Minigraf { } 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") - })?; + let mut ctx = self + .inner + .write_lock + .lock() + .map_err(|_| err_coded!(ErrorCode::Api001))?; Self::do_checkpoint(&self.inner.fact_storage, &mut ctx) } @@ -780,13 +782,13 @@ impl Minigraf { let query = match cmd { DatalogCommand::Query(q) => q, DatalogCommand::Transact(_) => { - anyhow::bail!("only (query ...) commands can be prepared; got transact") + bail_coded!(ErrorCode::Api005); } DatalogCommand::Retract(_) => { - anyhow::bail!("only (query ...) commands can be prepared; got retract") + bail_coded!(ErrorCode::Api006); } DatalogCommand::Rule(_) => { - anyhow::bail!("only (query ...) commands can be prepared; got rule") + bail_coded!(ErrorCode::Api007); } }; @@ -842,17 +844,17 @@ impl Minigraf { let mut facts = Vec::new(); for pattern in &tx.facts { - let entity = edn_to_entity_id(&pattern.entity) - .map_err(|e| anyhow::anyhow!("invalid entity: {}", e))?; + let entity = + edn_to_entity_id(&pattern.entity).map_err(|e| err_coded!(ErrorCode::Int002, e))?; let attr = match &pattern.attribute { AttributeSpec::Real(EdnValue::Keyword(k)) => k.clone(), - AttributeSpec::Real(_) => anyhow::bail!("attribute must be a keyword"), - AttributeSpec::Pseudo(_) => anyhow::bail!("cannot transact a pseudo-attribute"), + AttributeSpec::Real(_) => bail_coded!(ErrorCode::Api003), + AttributeSpec::Pseudo(_) => bail_coded!(ErrorCode::Api004), }; - let value = edn_to_value(&pattern.value) - .map_err(|e| anyhow::anyhow!("invalid value: {}", e))?; + let value = + edn_to_value(&pattern.value).map_err(|e| err_coded!(ErrorCode::Int003, e))?; let valid_from = pattern .valid_from @@ -879,17 +881,17 @@ impl Minigraf { let mut facts = Vec::new(); for pattern in &tx.facts { - let entity = edn_to_entity_id(&pattern.entity) - .map_err(|e| anyhow::anyhow!("invalid entity: {}", e))?; + let entity = + edn_to_entity_id(&pattern.entity).map_err(|e| err_coded!(ErrorCode::Int002, e))?; let attr = match &pattern.attribute { AttributeSpec::Real(EdnValue::Keyword(k)) => k.clone(), - AttributeSpec::Real(_) => anyhow::bail!("attribute must be a keyword"), - AttributeSpec::Pseudo(_) => anyhow::bail!("cannot transact a pseudo-attribute"), + AttributeSpec::Real(_) => bail_coded!(ErrorCode::Api003), + AttributeSpec::Pseudo(_) => bail_coded!(ErrorCode::Api004), }; - let value = edn_to_value(&pattern.value) - .map_err(|e| anyhow::anyhow!("invalid value: {}", e))?; + let value = + edn_to_value(&pattern.value).map_err(|e| err_coded!(ErrorCode::Int003, e))?; let mut f = Fact::retract(entity, attr, value, 0); f.tx_count = 0; @@ -973,7 +975,7 @@ impl Minigraf { self.inner .functions .write() - .map_err(|e| anyhow::anyhow!("function registry lock poisoned: {}", e))? + .map_err(|_| err_coded!(ErrorCode::Api008))? .register_aggregate_desc(name.to_string(), desc) } @@ -1017,7 +1019,7 @@ impl Minigraf { self.inner .functions .write() - .map_err(|e| anyhow::anyhow!("function registry lock poisoned: {}", e))? + .map_err(|_| err_coded!(ErrorCode::Api008))? .register_predicate_desc(name.to_string(), desc) } } @@ -1236,9 +1238,7 @@ impl<'a> WriteTransaction<'a> { *wal = Some(WalWriter::open_or_create(&wal_path, opts.synchronous)?); } - let wal_writer = wal - .as_mut() - .ok_or_else(|| anyhow::anyhow!("WAL not initialized"))?; + let wal_writer = wal.as_mut().ok_or_else(|| err_coded!(ErrorCode::Api009))?; wal_writer.append_entry(tx_count, facts)?; pfs.mark_dirty(); *wal_entry_count = wal_entry_count.saturating_add(1); @@ -1605,12 +1605,98 @@ mod tests { .execute(r#"(transact [[:bob :person/name "Bob"]])"#) .unwrap_err(); - assert!( - err.to_string() - .contains("WriteTransaction is already in progress"), - "expected reentrant-write error, got: {}", - err - ); + assert_eq!(err.code(), "INT-001"); + } + + #[test] + fn test_same_thread_reentrant_begin_write_returns_error() { + let db = Minigraf::in_memory().unwrap(); + + let _tx = db.begin_write().unwrap(); + + // While _tx is active, begin_write() on the same thread should fail fast + // (INT-001, same code as the execute()-path reentrancy check above). + let Err(err) = db.begin_write() else { + panic!("expected begin_write() to fail"); + }; + + assert_eq!(err.code(), "INT-001"); + } + + // ── API-001: write lock poisoned ─────────────────────────────────────────── + + #[test] + fn test_write_lock_poisoned_returns_api001() { + let db = Minigraf::in_memory().unwrap(); + + // Poison the write-lock mutex by panicking while holding it. + let poison_db = db.clone(); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let _guard = poison_db.inner.write_lock.lock().unwrap(); + panic!("intentionally poisoning the write lock for a test"); + })); + + let err = db + .execute(r#"(transact [[:bob :person/name "Bob"]])"#) + .unwrap_err(); + assert_eq!(err.code(), "API-001"); + + let Err(err) = db.begin_write() else { + panic!("expected begin_write() to fail"); + }; + assert_eq!(err.code(), "API-001"); + + let err = db.checkpoint().unwrap_err(); + assert_eq!(err.code(), "API-001"); + } + + // ── API-005/006/007: only query commands can be prepared ────────────────── + + #[test] + fn test_prepare_transact_returns_api005() { + let db = Minigraf::in_memory().unwrap(); + let err = db + .prepare(r#"(transact [[:bob :person/name "Bob"]])"#) + .unwrap_err(); + assert_eq!(err.code(), "API-005"); + } + + #[test] + fn test_prepare_retract_returns_api006() { + let db = Minigraf::in_memory().unwrap(); + let err = db + .prepare(r#"(retract [[:bob :person/name "Bob"]])"#) + .unwrap_err(); + assert_eq!(err.code(), "API-006"); + } + + #[test] + fn test_prepare_rule_returns_api007() { + let db = Minigraf::in_memory().unwrap(); + let err = db + .prepare("(rule [(ancestor ?x ?y) [?x :parent ?y]])") + .unwrap_err(); + assert_eq!(err.code(), "API-007"); + } + + // ── API-008: function registry lock poisoned ─────────────────────────────── + + #[test] + fn test_function_registry_lock_poisoned_returns_api008() { + use crate::graph::types::Value; + + let db = Minigraf::in_memory().unwrap(); + + let poison_db = db.clone(); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let _guard = poison_db.inner.functions.write().unwrap(); + panic!("intentionally poisoning the function registry lock for a test"); + })); + + let err = db + .register_predicate("always_true", |_: &Value| true) + .unwrap_err(); + assert_eq!(err.code(), "API-008"); } // ── thread-local flag cleared after commit ──────────────────────────────── @@ -1931,10 +2017,8 @@ mod tests { valid_to: None, }; let r = Minigraf::materialize_transaction(&tx); - assert!( - r.is_err(), - "materialize_transaction with non-keyword Real attr must fail" - ); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "API-003"); } #[test] @@ -1952,10 +2036,8 @@ mod tests { valid_to: None, }; let r = Minigraf::materialize_retraction(&tx); - assert!( - r.is_err(), - "materialize_retraction with non-keyword Real attr must fail" - ); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "API-003"); } #[test] @@ -1973,10 +2055,8 @@ mod tests { valid_to: None, }; let r = Minigraf::materialize_transaction(&tx); - assert!( - r.is_err(), - "materialize_transaction with pseudo-attr must fail" - ); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "API-004"); } #[test] @@ -1994,10 +2074,80 @@ mod tests { valid_to: None, }; let r = Minigraf::materialize_retraction(&tx); - assert!( - r.is_err(), - "materialize_retraction with pseudo-attr must fail" - ); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "API-004"); + } + + #[test] + fn test_materialize_transaction_invalid_entity_returns_int002() { + use crate::query::datalog::types::EdnValue; + use crate::query::datalog::types::{Pattern, Transaction}; + let tx = Transaction { + facts: vec![Pattern::new( + EdnValue::Boolean(true), // not resolvable to an entity id + EdnValue::Keyword(":person/name".to_string()), + EdnValue::String("Alice".to_string()), + )], + valid_from: None, + valid_to: None, + }; + let r = Minigraf::materialize_transaction(&tx); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "INT-002"); + } + + #[test] + fn test_materialize_retraction_invalid_entity_returns_int002() { + use crate::query::datalog::types::EdnValue; + use crate::query::datalog::types::{Pattern, Transaction}; + let tx = Transaction { + facts: vec![Pattern::new( + EdnValue::Boolean(true), + EdnValue::Keyword(":person/name".to_string()), + EdnValue::String("Alice".to_string()), + )], + valid_from: None, + valid_to: None, + }; + let r = Minigraf::materialize_retraction(&tx); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "INT-002"); + } + + #[test] + fn test_materialize_transaction_invalid_value_returns_int003() { + use crate::query::datalog::types::EdnValue; + use crate::query::datalog::types::{Pattern, Transaction}; + let tx = Transaction { + facts: vec![Pattern::new( + EdnValue::Keyword(":alice".to_string()), + EdnValue::Keyword(":person/tags".to_string()), + EdnValue::Vector(vec![]), // not a storable Value + )], + valid_from: None, + valid_to: None, + }; + let r = Minigraf::materialize_transaction(&tx); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "INT-003"); + } + + #[test] + fn test_materialize_retraction_invalid_value_returns_int003() { + use crate::query::datalog::types::EdnValue; + use crate::query::datalog::types::{Pattern, Transaction}; + let tx = Transaction { + facts: vec![Pattern::new( + EdnValue::Keyword(":alice".to_string()), + EdnValue::Keyword(":person/tags".to_string()), + EdnValue::Vector(vec![]), + )], + valid_from: None, + valid_to: None, + }; + let r = Minigraf::materialize_retraction(&tx); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "INT-003"); } // ── begin_write flag not leaked on lock failure ──────────────────────────────── diff --git a/src/error.rs b/src/error.rs index 125abc5245..6c781ace89 100644 --- a/src/error.rs +++ b/src/error.rs @@ -35,12 +35,15 @@ pub enum ErrorCategory { /// downstream `match`. /// /// Deliberately does NOT derive `Debug`: this enum's variant count tracks -/// every documented error code (130 once all six #277 category PRs land), -/// and a derived `Debug` impl generates a per-variant string-literal match -/// arm that's pure binary-size cost with no runtime use anywhere in this -/// crate (nothing formats an `ErrorCode` with `{:?}` — [`CodedError`]'s own +/// every documented error code (186, as of #277's final API+INT category PR +/// — 130 originally documented `PRS`/`QRY`/`STG`/`WAL`/`API` codes plus 55 +/// `INT-0xx` codes assigned to the crate's remaining previously-uncoded +/// call sites, plus the original `INT-000` catch-all), and a derived +/// `Debug` impl generates a per-variant string-literal match arm that's +/// pure binary-size cost with no runtime use anywhere in this crate +/// (nothing formats an `ErrorCode` with `{:?}` — [`CodedError`]'s own /// hand-written `Debug` below only needs the already-formatted `message` -/// and the code string, not this enum). Keeps the project's <1MB binary +/// and the code string, not this enum). Keeps the project's binary /// size goal (see PHILOSOPHY.md) affordable as the registry grows. #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) enum ErrorCode { @@ -166,6 +169,70 @@ pub(crate) enum ErrorCode { Wal004, Wal005, Wal006, + Api001, + Api002, + Api003, + Api004, + Api005, + Api006, + Api007, + Api008, + Api009, + Int001, + Int002, + Int003, + Int004, + Int005, + Int006, + Int007, + Int008, + Int009, + Int010, + Int011, + Int012, + Int013, + Int014, + Int015, + Int016, + Int017, + Int018, + Int019, + Int020, + Int021, + Int022, + Int023, + Int024, + Int025, + Int026, + Int027, + Int028, + Int029, + Int030, + Int031, + Int032, + Int033, + Int034, + Int035, + Int036, + Int037, + Int038, + Int039, + Int040, + Int041, + Int042, + Int043, + Int044, + Int045, + Int046, + Int047, + Int048, + Int049, + Int050, + Int051, + Int052, + Int053, + Int054, + Int055, } /// Single source of truth: (code, code string, message template, category). @@ -905,6 +972,390 @@ pub(crate) const REGISTRY: &[(ErrorCode, &str, &str, ErrorCategory)] = &[ "failed to delete WAL file {}: {}", ErrorCategory::Wal, ), + ( + ErrorCode::Api001, + "API-001", + "write lock is poisoned; database may be in an inconsistent state", + ErrorCategory::Api, + ), + ( + ErrorCode::Api002, + "API-002", + "unexpected command variant in write path", + ErrorCategory::Api, + ), + ( + ErrorCode::Api003, + "API-003", + "attribute must be a keyword", + ErrorCategory::Api, + ), + ( + ErrorCode::Api004, + "API-004", + "cannot transact a pseudo-attribute", + ErrorCategory::Api, + ), + ( + ErrorCode::Api005, + "API-005", + "only (query ...) commands can be prepared; got transact", + ErrorCategory::Api, + ), + ( + ErrorCode::Api006, + "API-006", + "only (query ...) commands can be prepared; got retract", + ErrorCategory::Api, + ), + ( + ErrorCode::Api007, + "API-007", + "only (query ...) commands can be prepared; got rule", + ErrorCategory::Api, + ), + ( + ErrorCode::Api008, + "API-008", + "function registry lock poisoned: PoisonError { .. }", + ErrorCategory::Api, + ), + ( + ErrorCode::Api009, + "API-009", + "WAL not initialized", + ErrorCategory::Api, + ), + ( + ErrorCode::Int001, + "INT-001", + "a WriteTransaction is already in progress on this thread; use tx.execute() instead", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int002, + "INT-002", + "invalid entity: {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int003, + "INT-003", + "invalid value: {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int004, + "INT-004", + "invalid timestamp: {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int005, + "INT-005", + "millisecond value {} is outside the supported datetime range", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int006, + "INT-006", + "internal parser error: expected {} token", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int007, + "INT-007", + "Float literal out of range: {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int008, + "INT-008", + "Integer literal out of range: {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int009, + "INT-009", + "Symbol exceeds maximum length of {} bytes", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int010, + "INT-010", + "Exceeded maximum recursion depth of {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int011, + "INT-011", + "unexpected end of {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int012, + "INT-012", + "duplicate {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int013, + "INT-013", + "{} requires a value", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int014, + "INT-014", + "{} must be >= 1", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int015, + "INT-015", + "{} must be a positive integer", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int016, + "INT-016", + "(or)/(or-join) cannot appear inside (not)/(not-join)", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int017, + "INT-017", + "pseudo-attribute {} is not valid in {} position", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int018, + "INT-018", + "{} {} in {} is not bound by any {} clause", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int019, + "INT-019", + "datalog parser: {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int020, + "INT-020", + "evaluator: iteration or result limit exceeded: {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int021, + "INT-021", + "evaluator: unsupported where-clause in evaluate_rule: {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int022, + "INT-022", + "datalog evaluator: {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int023, + "INT-023", + "packed page: fact record exceeds slot capacity: {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int024, + "INT-024", + "packed page: malformed page data: {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int025, + "INT-025", + "internal: unsubstituted :valid-at bind slot reached the executor", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int026, + "INT-026", + "temporal pseudo-attributes :db/valid-from, :db/valid-to, :db/tx-count, and :db/tx-id require :any-valid-time; add :any-valid-time to your query", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int027, + "INT-027", + "query has no :where clause, rules, or aggregates — nothing binds the variables. Add a :where clause (e.g., [:find ?e ?a ?v :where [?e ?a ?v]]) or use an aggregate.", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int028, + "INT-028", + "Rule invocation '{}' must have 1 or 2 arguments, got {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int029, + "INT-029", + "unknown aggregate function: '{}'", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int030, + "INT-030", + "unknown window function '{}' — register it with register_aggregate() before querying", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int031, + "INT-031", + "or-join variable {} is not bound in the incoming scope", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int032, + "INT-032", + "query executor: {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int033, + "INT-033", + "missing bind value for slot '${}'", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int034, + "INT-034", + "bind slot '${}' is not permitted in attribute position; the query optimizer selects an index based on the attribute at prepare time and cannot handle a parameterised attribute", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int035, + "INT-035", + "slot '${}' in {} position requires {}, got {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int036, + "INT-036", + "header too short: need {}..{}, got {} bytes", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int037, + "INT-037", + "header: slice at {} not exactly {} bytes", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int038, + "INT-038", + "header too short for {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int039, + "INT-039", + "Invalid magic number", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int040, + "INT-040", + "{} '{}' is already registered", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int041, + "INT-041", + "sum: expected Integer, Float, or Null, got {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int042, + "INT-042", + "min/max: no non-null values in group", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int043, + "INT-043", + "{}: cannot compare {} and {} values", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int044, + "INT-044", + "{}: expected Integer, Float, String, or Null, got {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int045, + "INT-045", + "pending fact index {} out of bounds", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int046, + "INT-046", + "no CommittedFactReader but got committed FactRef (page_id={})", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int047, + "INT-047", + "into_backend: backend Arc has multiple owners", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int048, + "INT-048", + "storage: arithmetic overflow: {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int049, + "INT-049", + "storage: internal invariant violation: {}", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int050, + "INT-050", + "{} lock poisoned", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int051, + "INT-051", + "Invalid page size: {} bytes (expected {})", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int052, + "INT-052", + "Page {} not found", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int053, + "INT-053", + "Header checksum mismatch: possible file corruption. Database may be damaged.", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int054, + "INT-054", + "unstratifiable: predicate '{}' is involved in a negative cycle through '{}'", + ErrorCategory::Internal, + ), + ( + ErrorCode::Int055, + "INT-055", + "rule predicate '{}' disappeared during rollback", + ErrorCategory::Internal, + ), ]; pub(crate) fn registry_entry(code: ErrorCode) -> (&'static str, &'static str, ErrorCategory) { @@ -971,9 +1422,9 @@ pub(crate) struct CodedError { impl CodedError { /// `#[cold]`/`#[inline(never)]`: `bail_coded!`/`err_coded!` expand to a - /// call to this at every one of the (currently ~50, eventually ~250+ - /// once all six #277 category PRs land) error call sites across the - /// crate. Error construction is by definition the cold path, so forcing + /// call to this at every one of the (roughly 300, now that #277's six + /// category PRs have all landed) error call sites across the crate. + /// Error construction is by definition the cold path, so forcing /// it out of line keeps the lookup + `format_template` call from being /// duplicated inline at each one — pure binary-size cost for a path /// that, unlike the argument-array construction immediately at the call @@ -1298,7 +1749,71 @@ mod tests { | ErrorCode::Wal003 | ErrorCode::Wal004 | ErrorCode::Wal005 - | ErrorCode::Wal006 => assert_has_registry_entry(code), + | ErrorCode::Wal006 + | ErrorCode::Api001 + | ErrorCode::Api002 + | ErrorCode::Api003 + | ErrorCode::Api004 + | ErrorCode::Api005 + | ErrorCode::Api006 + | ErrorCode::Api007 + | ErrorCode::Api008 + | ErrorCode::Api009 + | ErrorCode::Int001 + | ErrorCode::Int002 + | ErrorCode::Int003 + | ErrorCode::Int004 + | ErrorCode::Int005 + | ErrorCode::Int006 + | ErrorCode::Int007 + | ErrorCode::Int008 + | ErrorCode::Int009 + | ErrorCode::Int010 + | ErrorCode::Int011 + | ErrorCode::Int012 + | ErrorCode::Int013 + | ErrorCode::Int014 + | ErrorCode::Int015 + | ErrorCode::Int016 + | ErrorCode::Int017 + | ErrorCode::Int018 + | ErrorCode::Int019 + | ErrorCode::Int020 + | ErrorCode::Int021 + | ErrorCode::Int022 + | ErrorCode::Int023 + | ErrorCode::Int024 + | ErrorCode::Int025 + | ErrorCode::Int026 + | ErrorCode::Int027 + | ErrorCode::Int028 + | ErrorCode::Int029 + | ErrorCode::Int030 + | ErrorCode::Int031 + | ErrorCode::Int032 + | ErrorCode::Int033 + | ErrorCode::Int034 + | ErrorCode::Int035 + | ErrorCode::Int036 + | ErrorCode::Int037 + | ErrorCode::Int038 + | ErrorCode::Int039 + | ErrorCode::Int040 + | ErrorCode::Int041 + | ErrorCode::Int042 + | ErrorCode::Int043 + | ErrorCode::Int044 + | ErrorCode::Int045 + | ErrorCode::Int046 + | ErrorCode::Int047 + | ErrorCode::Int048 + | ErrorCode::Int049 + | ErrorCode::Int050 + | ErrorCode::Int051 + | ErrorCode::Int052 + | ErrorCode::Int053 + | ErrorCode::Int054 + | ErrorCode::Int055 => assert_has_registry_entry(code), } } @@ -1425,6 +1940,70 @@ mod tests { ErrorCode::Wal004, ErrorCode::Wal005, ErrorCode::Wal006, + ErrorCode::Api001, + ErrorCode::Api002, + ErrorCode::Api003, + ErrorCode::Api004, + ErrorCode::Api005, + ErrorCode::Api006, + ErrorCode::Api007, + ErrorCode::Api008, + ErrorCode::Api009, + ErrorCode::Int001, + ErrorCode::Int002, + ErrorCode::Int003, + ErrorCode::Int004, + ErrorCode::Int005, + ErrorCode::Int006, + ErrorCode::Int007, + ErrorCode::Int008, + ErrorCode::Int009, + ErrorCode::Int010, + ErrorCode::Int011, + ErrorCode::Int012, + ErrorCode::Int013, + ErrorCode::Int014, + ErrorCode::Int015, + ErrorCode::Int016, + ErrorCode::Int017, + ErrorCode::Int018, + ErrorCode::Int019, + ErrorCode::Int020, + ErrorCode::Int021, + ErrorCode::Int022, + ErrorCode::Int023, + ErrorCode::Int024, + ErrorCode::Int025, + ErrorCode::Int026, + ErrorCode::Int027, + ErrorCode::Int028, + ErrorCode::Int029, + ErrorCode::Int030, + ErrorCode::Int031, + ErrorCode::Int032, + ErrorCode::Int033, + ErrorCode::Int034, + ErrorCode::Int035, + ErrorCode::Int036, + ErrorCode::Int037, + ErrorCode::Int038, + ErrorCode::Int039, + ErrorCode::Int040, + ErrorCode::Int041, + ErrorCode::Int042, + ErrorCode::Int043, + ErrorCode::Int044, + ErrorCode::Int045, + ErrorCode::Int046, + ErrorCode::Int047, + ErrorCode::Int048, + ErrorCode::Int049, + ErrorCode::Int050, + ErrorCode::Int051, + ErrorCode::Int052, + ErrorCode::Int053, + ErrorCode::Int054, + ErrorCode::Int055, ] { exhaustive(code); } @@ -1530,18 +2109,17 @@ mod tests { 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. + /// `docs/ERROR_REFERENCE.md` and `REGISTRY` must now be in full + /// bidirectional agreement: every `REGISTRY` entry's code+template + /// appears in the doc verbatim, AND every documented `### CODE` section + /// with an "Error text" line has a matching `REGISTRY` entry. This is + /// only safe now that #277's final category PR (API+INT) has audited + /// and coded every remaining `bail!`/`anyhow!` call site crate-wide — + /// before that, a documented code with no registry entry just meant + /// that call site hadn't been migrated yet (see the design spec's + /// "Directionality note"). #[test] - fn registry_is_a_subset_of_error_reference_doc() { + fn registry_matches_error_reference_doc_bidirectionally() { let doc = include_str!("../docs/ERROR_REFERENCE.md"); let mut doc_entries: std::collections::HashMap = Default::default(); let mut lines = doc.lines().peekable(); @@ -1570,6 +2148,7 @@ mod tests { } } + // Direction 1: every REGISTRY entry's code+template appears in the doc verbatim. for (_, code_str, template, _) in REGISTRY { match doc_entries.get(*code_str) { Some(doc_text) => assert_eq!( @@ -1579,6 +2158,16 @@ mod tests { None => panic!("REGISTRY has a code with no ERROR_REFERENCE.md entry at all"), } } + + // Direction 2: every documented code has a REGISTRY row. + let registry_codes: std::collections::HashSet<&str> = + REGISTRY.iter().map(|(_, code_str, ..)| *code_str).collect(); + for doc_code in doc_entries.keys() { + assert!( + registry_codes.contains(doc_code.as_str()), + "ERROR_REFERENCE.md documents a code with no REGISTRY entry" + ); + } } fn is_error_reference_code(s: &str) -> bool { diff --git a/src/graph/storage.rs b/src/graph/storage.rs index af16e91d1a..74c9405d78 100644 --- a/src/graph/storage.rs +++ b/src/graph/storage.rs @@ -1,3 +1,4 @@ +use crate::error::{ErrorCode, bail_coded, err_coded}; use crate::graph::types::{ Attribute, EntityId, Fact, TransactOptions, TxId, VALID_TIME_FOREVER, Value, tx_id_now, }; @@ -154,7 +155,7 @@ impl FactStorage { let mut d = self .data .write() - .map_err(|_| anyhow::anyhow!("data lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Int050, "data"))?; for (slot, fact) in (u16::try_from(d.facts.len()).unwrap_or(u16::MAX)..).zip(facts.iter()) { d.pending_keys.insert(pending_key(fact)); d.pending_indexes.insert( @@ -213,7 +214,7 @@ impl FactStorage { let mut d = self .data .write() - .map_err(|_| anyhow::anyhow!("data lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Int050, "data"))?; for (slot, fact) in (u16::try_from(d.facts.len()).unwrap_or(u16::MAX)..).zip(facts.iter()) { d.pending_keys.insert(pending_key(fact)); d.pending_indexes.insert( @@ -262,7 +263,7 @@ impl FactStorage { let mut d = self .data .write() - .map_err(|_| anyhow::anyhow!("data lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Int050, "data"))?; for (slot, fact) in (u16::try_from(d.facts.len()).unwrap_or(u16::MAX)..).zip(retractions.iter()) { @@ -292,7 +293,7 @@ impl FactStorage { let mut d = self .data .write() - .map_err(|_| anyhow::anyhow!("data lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Int050, "data"))?; // O(1) duplicate check via the pending_keys HashSet. // Previously this was an O(n) linear scan over d.facts, causing O(n²) @@ -322,7 +323,7 @@ impl FactStorage { let d = self .data .read() - .map_err(|_| anyhow::anyhow!("data lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Int050, "data"))?; let max = d.facts.iter().map(|f| f.tx_count).max().unwrap_or(0); self.tx_counter.store(max, Ordering::SeqCst); Ok(()) @@ -354,7 +355,7 @@ impl FactStorage { let d = self .data .read() - .map_err(|_| anyhow::anyhow!("data lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Int050, "data"))?; let mut all = Vec::new(); // Committed facts first (on disk, via CommittedFactReader) if let Some(loader) = &d.committed { @@ -388,7 +389,7 @@ impl FactStorage { let mut d = self .data .write() - .map_err(|_| anyhow::anyhow!("data lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Int050, "data"))?; d.facts.clear(); d.pending_keys.clear(); d.pending_indexes = Indexes::new(); @@ -587,14 +588,11 @@ fn resolve_fact_ref(d: &FactData, fr: FactRef) -> Result { d.facts .get(fr.slot_index as usize) .cloned() - .ok_or_else(|| anyhow::anyhow!("pending fact index {} out of bounds", fr.slot_index)) + .ok_or_else(|| err_coded!(ErrorCode::Int045, fr.slot_index)) } else { match &d.committed { Some(loader) => loader.resolve(fr), - None => anyhow::bail!( - "no CommittedFactReader but got committed FactRef (page_id={})", - fr.page_id - ), + None => bail_coded!(ErrorCode::Int046, fr.page_id), } } } diff --git a/src/query/datalog/evaluator.rs b/src/query/datalog/evaluator.rs index 8e42a96ee0..7e58d225cf 100644 --- a/src/query/datalog/evaluator.rs +++ b/src/query/datalog/evaluator.rs @@ -31,7 +31,7 @@ use crate::error::{ErrorCode, err_coded}; use crate::graph::FactStorage; use crate::graph::types::{Fact, Value}; use crate::storage::index::encode_value; -use anyhow::{Result, anyhow}; +use anyhow::Result; use std::collections::BTreeSet; use std::collections::HashSet; use std::sync::{Arc, RwLock}; @@ -141,9 +141,12 @@ impl RecursiveEvaluator { iteration += 1; if iteration > self.max_iterations { - return Err(anyhow!( - "Max iterations ({}) exceeded. Possible infinite recursion or cycle in rules.", - self.max_iterations + return Err(err_coded!( + ErrorCode::Int020, + format!( + "Max iterations ({}) exceeded. Possible infinite recursion or cycle in rules.", + self.max_iterations + ) )); } @@ -152,9 +155,12 @@ impl RecursiveEvaluator { // Check per-iteration fact limit if new_facts.len() > self.max_derived_facts { - return Err(anyhow!( - "Max derived facts per iteration ({}) exceeded. Rule may be generating too many facts.", - self.max_derived_facts + return Err(err_coded!( + ErrorCode::Int020, + format!( + "Max derived facts per iteration ({}) exceeded. Rule may be generating too many facts.", + self.max_derived_facts + ) )); } @@ -166,9 +172,9 @@ impl RecursiveEvaluator { if !seen_facts.contains(&key) { // Check total result limit if seen_facts.len() >= self.max_results { - return Err(anyhow!( - "Max query results ({}) exceeded.", - self.max_results + return Err(err_coded!( + ErrorCode::Int020, + format!("Max query results ({}) exceeded.", self.max_results) )); } seen_facts.insert(key); @@ -249,13 +255,15 @@ impl RecursiveEvaluator { } WhereClause::Not(_) => { // Not clauses are handled by StratifiedEvaluator, not here. - return Err(anyhow!( + return Err(err_coded!( + ErrorCode::Int021, "WhereClause::Not in evaluate_rule: use StratifiedEvaluator for rules with negation" )); } WhereClause::NotJoin { .. } => { // NotJoin clauses are handled by StratifiedEvaluator, not here. - return Err(anyhow!( + return Err(err_coded!( + ErrorCode::Int021, "WhereClause::NotJoin in evaluate_rule: use StratifiedEvaluator for rules with negation" )); } @@ -264,7 +272,8 @@ impl RecursiveEvaluator { } WhereClause::Or(_) | WhereClause::OrJoin { .. } => { // Or/OrJoin rules are routed to the mixed_rules path by StratifiedEvaluator before reaching here. - return Err(anyhow!( + return Err(err_coded!( + ErrorCode::Int021, "WhereClause::Or/OrJoin in evaluate_rule: not yet implemented" )); } @@ -304,17 +313,24 @@ impl RecursiveEvaluator { /// Example: (blocked ?x) -> [?x :blocked ?_rule_value] fn rule_invocation_to_pattern(&self, list: &[EdnValue]) -> Result { if list.is_empty() { - return Err(anyhow!("Rule invocation cannot be empty")); + return Err(err_coded!( + ErrorCode::Int022, + "Rule invocation cannot be empty" + )); } let predicate = match list.first() { Some(EdnValue::Symbol(s)) => s.clone(), Some(_) => { - return Err(anyhow!( + return Err(err_coded!( + ErrorCode::Int022, "Rule invocation must start with predicate name (symbol)" )); } None => { - return Err(anyhow!("Rule invocation cannot be empty")); + return Err(err_coded!( + ErrorCode::Int022, + "Rule invocation cannot be empty" + )); } }; let args: Vec = list.get(1..).unwrap_or_default().to_vec(); @@ -329,7 +345,8 @@ impl RecursiveEvaluator { /// Result: Fact(alice_uuid, ":reachable", Ref(bob_uuid)) fn instantiate_head(&self, head: &[EdnValue], binding: &Bindings) -> Result { if head.len() < 2 { - return Err(anyhow!( + return Err(err_coded!( + ErrorCode::Int022, "Rule head must have at least 2 elements: (predicate ?arg1)" )); } @@ -337,24 +354,31 @@ impl RecursiveEvaluator { // head[0] is predicate name let predicate = match head.first() { Some(EdnValue::Symbol(s)) => s.clone(), - _ => return Err(anyhow!("Rule head must start with predicate name (symbol)")), + _ => { + return Err(err_coded!( + ErrorCode::Int022, + "Rule head must start with predicate name (symbol)" + )); + } }; // head[1] is entity (usually a variable) let head_1 = head .get(1) - .ok_or_else(|| anyhow!("Rule head missing entity argument"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int022, "Rule head missing entity argument"))?; let entity_edn = self.substitute_variable(head_1, binding)?; let entity = edn_to_entity_id(&entity_edn) - .map_err(|e| anyhow!("Failed to convert entity: {}", e))?; + .map_err(|e| err_coded!(ErrorCode::Int022, format!("Failed to convert entity: {e}")))?; let value = if head.len() >= 3 { // 2-arg head: (reachable ?from ?to) — value is head[2] let head_2 = head .get(2) - .ok_or_else(|| anyhow!("Rule head missing value argument"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int022, "Rule head missing value argument"))?; let value_edn = self.substitute_variable(head_2, binding)?; - edn_to_value(&value_edn).map_err(|e| anyhow!("Failed to convert value: {}", e))? + edn_to_value(&value_edn).map_err(|e| { + err_coded!(ErrorCode::Int022, format!("Failed to convert value: {e}")) + })? } else { // 1-arg head: (blocked ?x) — store a Boolean(true) sentinel crate::graph::types::Value::Boolean(true) @@ -377,7 +401,10 @@ impl RecursiveEvaluator { // Convert Value back to EdnValue for entity/value conversion Ok(value_to_edn(value)) } else { - Err(anyhow!("Unbound variable in rule head: {}", s)) + Err(err_coded!( + ErrorCode::Int022, + format!("Unbound variable in rule head: {s}") + )) } } _ => Ok(edn.clone()), // Not a variable, use as-is @@ -438,7 +465,9 @@ pub(crate) fn rule_invocation_to_pattern(predicate: &str, args: &[EdnValue]) -> match args.len() { 1 => { // Safety: length checked above - let arg0 = args.first().ok_or_else(|| anyhow!("missing arg 0"))?; + let arg0 = args + .first() + .ok_or_else(|| err_coded!(ErrorCode::Int022, "missing arg 0"))?; Ok(Pattern::new( arg0.clone(), EdnValue::Keyword(format!(":{}", predicate)), @@ -446,19 +475,19 @@ pub(crate) fn rule_invocation_to_pattern(predicate: &str, args: &[EdnValue]) -> )) } 2 => { - let arg0 = args.first().ok_or_else(|| anyhow!("missing arg 0"))?; - let arg1 = args.get(1).ok_or_else(|| anyhow!("missing arg 1"))?; + let arg0 = args + .first() + .ok_or_else(|| err_coded!(ErrorCode::Int022, "missing arg 0"))?; + let arg1 = args + .get(1) + .ok_or_else(|| err_coded!(ErrorCode::Int022, "missing arg 1"))?; Ok(Pattern::new( arg0.clone(), EdnValue::Keyword(format!(":{}", predicate)), arg1.clone(), )) } - n => Err(anyhow!( - "Rule invocation '{}' must have 1 or 2 arguments, got {}", - predicate, - n - )), + n => Err(err_coded!(ErrorCode::Int028, predicate, n)), } } @@ -623,7 +652,7 @@ impl StratifiedEvaluator { while i < all_preds.len() { let pred = all_preds .get(i) - .ok_or_else(|| anyhow!("index out of bounds"))? + .ok_or_else(|| err_coded!(ErrorCode::Int022, "index out of bounds"))? .clone(); for rule in registry.get_rules(&pred) { for clause in &rule.body { @@ -1102,29 +1131,16 @@ mod tests { ); let result = evaluator.evaluate_recursive_rules(&["reachable".to_string()]); let code = expect_err_code(result); - // No QRY-0xx code is documented in ERROR_REFERENCE.md for the - // recursion/depth-limit family ("Max iterations exceeded", "Max - // derived facts exceeded", "Max query results exceeded") — the 9 - // documented QRY codes cover transact/retract validation, unknown - // predicates, and function/rule registry lock poisoning only. This - // is a live, public-API-reachable error path (a query over a - // non-terminating recursive rule with a low `max_derived_facts`/ - // `max_results`, or — as constructed directly here — a pathological - // `max_iterations`), currently falling through to the generic - // INT-000 catch-all by design (see src/error.rs's `MinigrafError::from` - // fallback). Locking in today's code here so this is a deliberate, - // documented gap rather than a silent one; assigning it a real code - // is candidate follow-up work for the API+INT category PR (#277 - // step 6), which audits every leftover uncoded call site crate-wide. - assert_eq!(code, "INT-000"); + // #277 step 6 (API+INT category PR) assigned this recursion/depth-limit + // family ("Max iterations exceeded", "Max derived facts exceeded", "Max + // query results exceeded") a shared INT-020 code — see ERROR_REFERENCE.md. + assert_eq!(code, "INT-020"); } #[test] - fn test_max_derived_facts_exceeded_returns_int000() { + fn test_max_derived_facts_exceeded_returns_int020() { // Same rationale as test_max_iterations_exceeded_returns_error above: - // "Max derived facts per iteration exceeded" has no documented QRY - // code, so it currently — and, for this PR, deliberately — surfaces - // as INT-000. + // "Max derived facts per iteration exceeded" shares INT-020. let storage = create_test_storage(); let rules = Arc::new(RwLock::new(RuleRegistry::new())); register_test_rule(&rules, r#"(rule [(reachable ?x ?y) [?x :connected ?y]])"#); @@ -1139,7 +1155,7 @@ mod tests { RecursiveEvaluator::new(storage, rules, functions, 1000, 0, DEFAULT_MAX_RESULTS); let result = evaluator.evaluate_recursive_rules(&["reachable".to_string()]); let code = expect_err_code(result); - assert_eq!(code, "INT-000"); + assert_eq!(code, "INT-020"); } #[test] diff --git a/src/query/datalog/executor.rs b/src/query/datalog/executor.rs index 7b4d6e7539..dfaa16aacc 100644 --- a/src/query/datalog/executor.rs +++ b/src/query/datalog/executor.rs @@ -10,7 +10,7 @@ use super::types::{ use crate::error::{ErrorCode, bail_coded, err_coded}; use crate::graph::FactStorage; use crate::graph::types::{Fact, TransactOptions, TxId, Value, tx_id_now}; -use anyhow::{Result, anyhow}; +use anyhow::Result; use std::collections::HashMap; use std::sync::{Arc, RwLock}; @@ -355,9 +355,7 @@ impl DatalogExecutor { .collect(), Some(ValidAt::AnyValidTime) => asserted, Some(ValidAt::Slot(_)) => { - return Err(anyhow!( - "internal: unsubstituted :valid-at bind slot reached the executor" - )); + return Err(err_coded!(ErrorCode::Int025)); } None => asserted .into_iter() @@ -464,10 +462,7 @@ impl DatalogExecutor { // Warn about queries with no binding mechanism if !query.has_binding_mechanism() { - return Err(anyhow!( - "query has no :where clause, rules, or aggregates — nothing binds the variables. \ - Add a :where clause (e.g., [:find ?e ?a ?v :where [?e ?a ?v]]) or use an aggregate." - )); + return Err(err_coded!(ErrorCode::Int027)); } // Compute query-level valid_at value for :db/valid-at pseudo-attribute binding. @@ -476,9 +471,7 @@ impl DatalogExecutor { Some(ValidAt::Timestamp(t)) => Value::Integer(*t), Some(ValidAt::AnyValidTime) => Value::Null, Some(ValidAt::Slot(_)) => { - return Err(anyhow!( - "internal: unsubstituted :valid-at bind slot reached the executor" - )); + return Err(err_coded!(ErrorCode::Int025)); } None => Value::Integer(now), }; @@ -487,10 +480,7 @@ impl DatalogExecutor { if query_uses_per_fact_pseudo_attr(&query) && !matches!(query.valid_at, Some(ValidAt::AnyValidTime)) { - return Err(anyhow!( - "temporal pseudo-attributes :db/valid-from, :db/valid-to, :db/tx-count, and \ - :db/tx-id require :any-valid-time; add :any-valid-time to your query" - )); + return Err(err_coded!(ErrorCode::Int026)); } // Apply temporal filters before pattern matching @@ -658,9 +648,7 @@ impl DatalogExecutor { Some(ValidAt::Timestamp(t)) => Value::Integer(*t), Some(ValidAt::AnyValidTime) => Value::Null, Some(ValidAt::Slot(_)) => { - return Err(anyhow!( - "internal: unsubstituted :valid-at bind slot reached the executor" - )); + return Err(err_coded!(ErrorCode::Int025)); } None => Value::Integer(now), }; @@ -669,10 +657,7 @@ impl DatalogExecutor { if query_uses_per_fact_pseudo_attr(&query) && !matches!(query.valid_at, Some(ValidAt::AnyValidTime)) { - return Err(anyhow!( - "temporal pseudo-attributes :db/valid-from, :db/valid-to, :db/tx-count, and \ - :db/tx-id require :any-valid-time; add :any-valid-time to your query" - )); + return Err(err_coded!(ErrorCode::Int026)); } // Apply temporal filters before evaluating recursive rules @@ -784,11 +769,7 @@ impl DatalogExecutor { Pattern::new(entity, EdnValue::Keyword(format!(":{}", predicate)), value) } n => { - return Err(anyhow!( - "Rule invocation '{}' must have 1 or 2 arguments, got {}", - predicate, - n - )); + return Err(err_coded!(ErrorCode::Int028, predicate, n)); } }; plan_clauses.push(WhereClause::Pattern(pattern)); @@ -918,14 +899,15 @@ impl DatalogExecutor { /// Extract the predicate name from a rule head fn extract_predicate(&self, rule: &Rule) -> Result { if rule.head.is_empty() { - return Err(anyhow!("Rule head cannot be empty")); + return Err(err_coded!(ErrorCode::Int032, "Rule head cannot be empty")); } // Safety: is_empty() check above guarantees index 0 exists. #[allow(clippy::indexing_slicing)] match &rule.head[0] { EdnValue::Symbol(s) => Ok(s.clone()), - _ => Err(anyhow!( + _ => Err(err_coded!( + ErrorCode::Int032, "Rule head must start with a symbol (predicate name)" )), } @@ -1505,7 +1487,7 @@ fn compute_aggregation( apply_builtin_aggregate(func, &non_null) } } - None => Err(anyhow::anyhow!("unknown aggregate function: '{}'", func)), + None => Err(err_coded!(ErrorCode::Int029, func)), }; match agg_val { Ok(v) => { @@ -1590,9 +1572,9 @@ fn apply_window_functions( WindowFunc::RowNumber => { let mut values = Vec::with_capacity(keyed.len()); for pos in 1..=keyed.len() { - values.push(Value::Integer( - i64::try_from(pos).map_err(|_| anyhow!("row number overflow"))?, - )); + values.push(Value::Integer(i64::try_from(pos).map_err(|_| { + err_coded!(ErrorCode::Int032, "row number overflow") + })?)); } values } @@ -1616,12 +1598,9 @@ fn apply_window_functions( // Accumulator-based: built-ins (sum, count, min, max, avg) and UDF aggregates. // UDF aggregates (WindowFunc::Udf) also route here via registry lookup. let func_name = ws.func_name(); - let desc = registry.get(&func_name).ok_or_else(|| { - anyhow::anyhow!( - "unknown window function '{}' — register it with register_aggregate() before querying", - func_name - ) - })?; + let desc = registry + .get(&func_name) + .ok_or_else(|| err_coded!(ErrorCode::Int030, func_name.clone()))?; let mut values = Vec::with_capacity(keyed.len()); // Safety: row_idx values come from enumerate() over bindings, so indices are valid. @@ -1727,9 +1706,7 @@ pub(crate) fn evaluate_branch( Some(ValidAt::Timestamp(t)) => Value::Integer(*t), Some(ValidAt::AnyValidTime) => Value::Null, Some(ValidAt::Slot(_)) => { - return Err(anyhow!( - "internal: unsubstituted :valid-at bind slot reached the executor" - )); + return Err(err_coded!(ErrorCode::Int025)); } None => Value::Integer(tx_id_now().cast_signed()), }; @@ -2076,7 +2053,7 @@ pub(crate) fn apply_or_clauses( // if a join_var is missing from outer_keys (hash-join key would be partial). for jv in join_vars.iter() { if !outer_keys.contains(jv.as_str()) { - anyhow::bail!("or-join variable {} is not bound in the incoming scope", jv); + bail_coded!(ErrorCode::Int031, jv); } } diff --git a/src/query/datalog/functions.rs b/src/query/datalog/functions.rs index 3b5ea54f7f..7f98c69838 100644 --- a/src/query/datalog/functions.rs +++ b/src/query/datalog/functions.rs @@ -1,3 +1,4 @@ +use crate::error::{ErrorCode, bail_coded, err_coded}; use crate::graph::types::Value; use std::any::Any; use std::collections::HashMap; @@ -322,7 +323,7 @@ impl FunctionRegistry { desc: AggregateDesc, ) -> anyhow::Result<()> { if self.aggregates.contains_key(&name) { - anyhow::bail!("aggregate function '{}' is already registered", name); + bail_coded!(ErrorCode::Int040, "aggregate function", name); } self.aggregates.insert(name, desc); Ok(()) @@ -335,7 +336,7 @@ impl FunctionRegistry { desc: PredicateDesc, ) -> anyhow::Result<()> { if self.predicates.contains_key(&name) { - anyhow::bail!("predicate '{}' is already registered", name); + bail_coded!(ErrorCode::Int040, "predicate", name); } self.predicates.insert(name, desc); Ok(()) @@ -428,10 +429,7 @@ pub fn apply_builtin_aggregate(name: &str, values: &[&Value]) -> anyhow::Result< Value::Float(f) => sum += f, Value::Integer(i) => sum += *i as f64, other => { - return Err(anyhow::anyhow!( - "sum: expected Integer, Float, or Null, got {}", - value_type_name(other) - )); + return Err(err_coded!(ErrorCode::Int041, value_type_name(other))); } } } @@ -442,10 +440,7 @@ pub fn apply_builtin_aggregate(name: &str, values: &[&Value]) -> anyhow::Result< match v { Value::Integer(i) => sum = sum.saturating_add(*i), other => { - return Err(anyhow::anyhow!( - "sum: expected Integer, Float, or Null, got {}", - value_type_name(other) - )); + return Err(err_coded!(ErrorCode::Int041, value_type_name(other))); } } } @@ -455,16 +450,16 @@ pub fn apply_builtin_aggregate(name: &str, values: &[&Value]) -> anyhow::Result< "min" | "max" => { if values.is_empty() { - return Err(anyhow::anyhow!("min/max: no non-null values in group")); + return Err(err_coded!(ErrorCode::Int042)); } let first = values .first() .copied() - .ok_or_else(|| anyhow::anyhow!("min/max: no non-null values in group"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int042))?; for v in values.get(1..).unwrap_or(&[]) { if std::mem::discriminant(*v) != std::mem::discriminant(first) { - return Err(anyhow::anyhow!( - "{}: cannot compare {} and {} values", + return Err(err_coded!( + ErrorCode::Int043, name, value_type_name(first), value_type_name(v) @@ -479,11 +474,7 @@ pub fn apply_builtin_aggregate(name: &str, values: &[&Value]) -> anyhow::Result< } (Value::String(a), Value::String(b)) => a.cmp(b), (_, other) => { - return Err(anyhow::anyhow!( - "{}: expected Integer, Float, String, or Null, got {}", - name, - value_type_name(other) - )); + return Err(err_coded!(ErrorCode::Int044, name, value_type_name(other))); } }; let replace = if name == "min" { @@ -522,7 +513,7 @@ pub fn apply_builtin_aggregate(name: &str, values: &[&Value]) -> anyhow::Result< } } - other => Err(anyhow::anyhow!("unknown aggregate function: '{}'", other)), + other => Err(err_coded!(ErrorCode::Int029, other)), } } diff --git a/src/query/datalog/parser.rs b/src/query/datalog/parser.rs index 1a8dbad916..645896653d 100644 --- a/src/query/datalog/parser.rs +++ b/src/query/datalog/parser.rs @@ -2,7 +2,7 @@ use super::types::*; use crate::error::{ErrorCode, bail_coded, err_coded}; use crate::graph::types::Value; use crate::temporal::parse_timestamp; -use anyhow::{Result, bail}; +use anyhow::Result; use uuid::Uuid; const MAX_STRING_LENGTH: usize = 1024 * 1024; // 1MB @@ -145,14 +145,14 @@ fn tokenize(input: &str) -> Result> { let mut num_str = String::from("-"); let (is_float, num) = parse_number(&mut chars, &mut num_str)?; if is_float { - let f: f64 = num.parse().map_err(|_| { - anyhow::anyhow!("Float literal out of range: {}", num) - })?; + let f: f64 = num + .parse() + .map_err(|_| err_coded!(ErrorCode::Int007, num.clone()))?; tokens.push(Token::Float(f)); } else { - let i: i64 = num.parse().map_err(|_| { - anyhow::anyhow!("Integer literal out of range: {}", num) - })?; + let i: i64 = num + .parse() + .map_err(|_| err_coded!(ErrorCode::Int008, num.clone()))?; tokens.push(Token::Integer(i)); } } else { @@ -174,12 +174,12 @@ fn tokenize(input: &str) -> Result> { if is_float { let f: f64 = num .parse() - .map_err(|_| anyhow::anyhow!("Float literal out of range: {}", num))?; + .map_err(|_| err_coded!(ErrorCode::Int007, num.clone()))?; tokens.push(Token::Float(f)); } else { let i: i64 = num .parse() - .map_err(|_| anyhow::anyhow!("Integer literal out of range: {}", num))?; + .map_err(|_| err_coded!(ErrorCode::Int008, num.clone()))?; tokens.push(Token::Integer(i)); } } @@ -189,10 +189,7 @@ fn tokenize(input: &str) -> Result> { while let Some(&ch) = chars.peek() { if ch.is_alphanumeric() || ch == '?' || ch == '_' || ch == '-' || ch == '/' { if symbol.len() >= MAX_SYMBOL_LENGTH { - bail!( - "Symbol exceeds maximum length of {} bytes", - MAX_SYMBOL_LENGTH - ); + bail_coded!(ErrorCode::Int009, MAX_SYMBOL_LENGTH); } symbol.push(ch); chars.next(); @@ -254,7 +251,10 @@ fn tokenize(input: &str) -> Result> { } } if name.is_empty() { - bail!("Bind slot '$' must be followed by an identifier (e.g. $entity)"); + bail_coded!( + ErrorCode::Int019, + "Bind slot '$' must be followed by an identifier (e.g. $entity)" + ); } tokens.push(Token::BindSlot(name)); } @@ -294,10 +294,7 @@ fn parse_symbol(chars: &mut std::iter::Peekable, first: char) - while let Some(&ch) = chars.peek() { if ch.is_alphanumeric() || ch == '?' || ch == '_' || ch == '-' || ch == '/' { if symbol.len() >= MAX_SYMBOL_LENGTH { - bail!( - "Symbol exceeds maximum length of {} bytes", - MAX_SYMBOL_LENGTH - ); + bail_coded!(ErrorCode::Int009, MAX_SYMBOL_LENGTH); } symbol.push(ch); chars.next(); @@ -355,10 +352,7 @@ impl Parser { self.depth += 1; if self.depth > MAX_RECURSION_DEPTH { self.depth -= 1; - bail!( - "Exceeded maximum recursion depth of {}", - MAX_RECURSION_DEPTH - ); + bail_coded!(ErrorCode::Int010, MAX_RECURSION_DEPTH); } let result = self.parse_value_inner(); self.depth -= 1; @@ -375,42 +369,42 @@ impl Parser { Ok(EdnValue::Keyword(k)) } else { // peek confirmed Keyword variant; advance should match - bail!("internal parser error: expected keyword token"); + bail_coded!(ErrorCode::Int006, "keyword"); } } Some(Token::Symbol(_)) => { if let Some(Token::Symbol(s)) = self.advance() { Ok(EdnValue::Symbol(s)) } else { - bail!("internal parser error: expected symbol token"); + bail_coded!(ErrorCode::Int006, "symbol"); } } Some(Token::String(_)) => { if let Some(Token::String(s)) = self.advance() { Ok(EdnValue::String(s)) } else { - bail!("internal parser error: expected string token"); + bail_coded!(ErrorCode::Int006, "string"); } } Some(Token::Integer(_)) => { if let Some(Token::Integer(i)) = self.advance() { Ok(EdnValue::Integer(i)) } else { - bail!("internal parser error: expected integer token"); + bail_coded!(ErrorCode::Int006, "integer"); } } Some(Token::Float(_)) => { if let Some(Token::Float(f)) = self.advance() { Ok(EdnValue::Float(f)) } else { - bail!("internal parser error: expected float token"); + bail_coded!(ErrorCode::Int006, "float"); } } Some(Token::Boolean(_)) => { if let Some(Token::Boolean(b)) = self.advance() { Ok(EdnValue::Boolean(b)) } else { - bail!("internal parser error: expected boolean token"); + bail_coded!(ErrorCode::Int006, "boolean"); } } Some(Token::TaggedLiteral(_)) => { @@ -429,7 +423,7 @@ impl Parser { bail_coded!(ErrorCode::Prs073, tag); } } else { - bail!("internal parser error: expected tagged literal token"); + bail_coded!(ErrorCode::Int006, "tagged literal"); } } Some(Token::Nil) => { @@ -440,7 +434,7 @@ impl Parser { if let Some(Token::BindSlot(name)) = self.advance() { Ok(EdnValue::BindSlot(name)) } else { - bail!("internal parser error: expected bind slot token"); + bail_coded!(ErrorCode::Int006, "bind slot"); } } Some(token) => { @@ -646,7 +640,7 @@ fn parse_window_expr(elems: &[EdnValue]) -> Result { while j < over_list.len() { let item = over_list .get(j) - .ok_or_else(|| anyhow::anyhow!("unexpected end of :over clause"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int011, ":over clause"))?; match item { EdnValue::Keyword(k) => match k.as_str() { ":partition-by" => { @@ -685,8 +679,12 @@ fn parse_window_expr(elems: &[EdnValue]) -> Result { j += 1; } - let order_by = - order_by.ok_or_else(|| anyhow::anyhow!("':order-by' is required in the ':over' clause"))?; + let order_by = order_by.ok_or_else(|| { + err_coded!( + ErrorCode::Int019, + "':order-by' is required in the ':over' clause" + ) + })?; Ok(FindSpec::Window(WindowSpec { func, @@ -711,7 +709,7 @@ fn parse_query(elements: &[EdnValue]) -> Result { #[allow(clippy::indexing_slicing)] let query_vector = elements[0] .as_vector() - .ok_or_else(|| anyhow::anyhow!("Query argument must be a vector"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int019, "Query argument must be a vector"))?; let mut find_specs: Vec = Vec::new(); let mut with_vars: Vec = Vec::new(); @@ -726,7 +724,7 @@ fn parse_query(elements: &[EdnValue]) -> Result { while i < query_vector.len() { let current_item = query_vector .get(i) - .ok_or_else(|| anyhow::anyhow!("unexpected end of query vector"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int011, "query vector"))?; if let Some(keyword) = current_item.as_keyword() { match keyword { ":as-of" => { @@ -738,7 +736,7 @@ fn parse_query(elements: &[EdnValue]) -> Result { let as_of = match as_of_val { EdnValue::Integer(n) if *n >= 0 => { let val = u64::try_from(*n).map_err(|_| { - anyhow::anyhow!(":as-of counter must be non-negative") + err_coded!(ErrorCode::Int019, ":as-of counter must be non-negative") })?; AsOf::Counter(val) } @@ -789,12 +787,12 @@ fn parse_query(elements: &[EdnValue]) -> Result { } ":max-derived-facts" => { if query_max_derived_facts.is_some() { - bail!("duplicate :max-derived-facts"); + bail_coded!(ErrorCode::Int012, ":max-derived-facts"); } i += 1; let val = query_vector .get(i) - .ok_or_else(|| anyhow::anyhow!(":max-derived-facts requires a value"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int013, ":max-derived-facts"))?; match val { EdnValue::Integer(n) if *n >= 1 => { #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)] @@ -803,10 +801,10 @@ fn parse_query(elements: &[EdnValue]) -> Result { } } EdnValue::Integer(_) => { - bail!(":max-derived-facts must be >= 1"); + bail_coded!(ErrorCode::Int014, ":max-derived-facts"); } _other => { - bail!(":max-derived-facts must be a positive integer"); + bail_coded!(ErrorCode::Int015, ":max-derived-facts"); } } i += 1; @@ -814,12 +812,12 @@ fn parse_query(elements: &[EdnValue]) -> Result { } ":max-results" => { if query_max_results.is_some() { - bail!("duplicate :max-results"); + bail_coded!(ErrorCode::Int012, ":max-results"); } i += 1; let val = query_vector .get(i) - .ok_or_else(|| anyhow::anyhow!(":max-results requires a value"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int013, ":max-results"))?; match val { EdnValue::Integer(n) if *n >= 1 => { #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)] @@ -828,10 +826,10 @@ fn parse_query(elements: &[EdnValue]) -> Result { } } EdnValue::Integer(_) => { - bail!(":max-results must be >= 1"); + bail_coded!(ErrorCode::Int014, ":max-results"); } _other => { - bail!(":max-results must be a positive integer"); + bail_coded!(ErrorCode::Int015, ":max-results"); } } i += 1; @@ -842,7 +840,7 @@ fn parse_query(elements: &[EdnValue]) -> Result { i += 1; while i < query_vector.len() { let with_item = query_vector.get(i).ok_or_else(|| { - anyhow::anyhow!("unexpected end of query vector in :with") + err_coded!(ErrorCode::Int011, "query vector in :with") })?; match with_item { EdnValue::Symbol(s) if s.starts_with('?') => { @@ -851,7 +849,10 @@ fn parse_query(elements: &[EdnValue]) -> Result { } EdnValue::Keyword(_) => break, other => { - bail!("':with' clause accepts only variables, got {:?}", other); + bail_coded!( + ErrorCode::Int019, + format!("':with' clause accepts only variables, got {other:?}") + ); } } } @@ -874,9 +875,11 @@ fn parse_query(elements: &[EdnValue]) -> Result { find_specs.push(parse_aggregate(elems)?); } other => { - bail!( - "Expected variable or aggregate expression in :find clause, got {:?}", - other + bail_coded!( + ErrorCode::Int019, + format!( + "Expected variable or aggregate expression in :find clause, got {other:?}" + ) ); } }, @@ -961,7 +964,10 @@ fn parse_transact(elements: &[EdnValue]) -> Result { // Check if the first element is a map (transaction-level options) let (tx_valid_from, tx_valid_to, facts_element, consumed) = if first_element.is_map() { let map = first_element.as_map().ok_or_else(|| { - anyhow::anyhow!("internal error: is_map() true but as_map() returned None") + err_coded!( + ErrorCode::Int019, + "internal error: is_map() true but as_map() returned None" + ) })?; let (from, to) = parse_valid_time_map(map)?; let facts_elem = elements @@ -1063,9 +1069,11 @@ fn parse_valid_time_map(pairs: &[(EdnValue, EdnValue)]) -> Result<(Option, valid_to = Some(parse_timestamp(s)?); } _ => { - bail!( - "Unknown key in valid-time map: {:?}; expected :valid-from or :valid-to", - key + bail_coded!( + ErrorCode::Int019, + format!( + "Unknown key in valid-time map: {key:?}; expected :valid-from or :valid-to" + ) ); } } @@ -1094,7 +1102,7 @@ fn parse_retract(elements: &[EdnValue]) -> Result { for fact in facts_vector { let fact_vec = fact .as_vector() - .ok_or_else(|| anyhow::anyhow!("Each fact must be a vector [e a v]"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int019, "Each fact must be a vector [e a v]"))?; patterns.push(Pattern::from_edn(fact_vec).map_err(anyhow::Error::msg)?); } @@ -1174,7 +1182,10 @@ fn parse_expr(list: &[EdnValue]) -> Result { match &rhs { Expr::Lit(Value::String(pattern)) => { let compiled = regex_lite::Regex::new(pattern).map_err(|e| { - anyhow::anyhow!("invalid regex pattern {:?}: {}", pattern, e) + err_coded!( + ErrorCode::Int019, + format!("invalid regex pattern {pattern:?}: {e}") + ) })?; let rhs_lit = Expr::Lit(Value::String(pattern.clone())); return Ok(Expr::BinOp( @@ -1237,12 +1248,18 @@ fn parse_expr(list: &[EdnValue]) -> Result { /// /// Called from `:where` dispatch when `vec[0]` is an `EdnValue::List`. fn parse_expr_clause(vec: &[EdnValue]) -> Result { - let first = vec - .first() - .ok_or_else(|| anyhow::anyhow!("parse_expr_clause called with empty vector"))?; + let first = vec.first().ok_or_else(|| { + err_coded!( + ErrorCode::Int019, + "parse_expr_clause called with empty vector" + ) + })?; let inner_list = match first { EdnValue::List(l) => l.as_slice(), - _ => bail!("parse_expr_clause called with non-list element 0"), + _ => bail_coded!( + ErrorCode::Int019, + "parse_expr_clause called with non-list element 0" + ), }; let expr = parse_expr(inner_list)?; let binding = match vec.len() { @@ -1250,7 +1267,7 @@ fn parse_expr_clause(vec: &[EdnValue]) -> Result { 2 => { let second = vec .get(1) - .ok_or_else(|| anyhow::anyhow!("unexpected end of expression clause"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int011, "expression clause"))?; match second { EdnValue::Symbol(s) if s.starts_with('?') => Some(s.clone()), other => { @@ -1286,7 +1303,7 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result Result Result { if !allow_not { - bail!("(not-join ...) cannot appear inside another (not ...) or (not-join ...)"); + bail_coded!( + ErrorCode::Int019, + "(not-join ...) cannot appear inside another (not ...) or (not-join ...)" + ); } // Syntax: (not-join [?v1 ?v2 ...] clause1 clause2 ...) if list.len() < 3 { @@ -1325,23 +1345,26 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result v, _ => { - bail!("(not-join) first argument must be a vector of join variables"); + bail_coded!( + ErrorCode::Int019, + "(not-join) first argument must be a vector of join variables" + ); } }; let join_vars: Vec = join_var_vec .iter() .map(|v| match v { EdnValue::Symbol(s) if s.starts_with('?') => Ok(s.clone()), - _ => Err(anyhow::anyhow!( - "(not-join) join variables must be logic variables, got {:?}", - v + _ => Err(err_coded!( + ErrorCode::Int019, + format!("(not-join) join variables must be logic variables, got {v:?}") )), }) .collect::>()?; let mut inner = Vec::new(); let rest = list .get(2..) - .ok_or_else(|| anyhow::anyhow!("unexpected end of not-join clause"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int011, "not-join clause"))?; for item in rest { if let Some(vec) = item.as_vector() { if matches!(vec.first(), Some(EdnValue::List(_))) { @@ -1355,15 +1378,17 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result Result> = Vec::new(); let rest = list .get(1..) - .ok_or_else(|| anyhow::anyhow!("unexpected end of or clause"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int011, "or clause"))?; for item in rest { let branch = parse_or_branch(item)?; branches.push(branch); @@ -1409,7 +1434,7 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result> = Vec::new(); let rest = list .get(2..) - .ok_or_else(|| anyhow::anyhow!("unexpected end of or-join clause"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int011, "or-join clause"))?; for item in rest { let branch = parse_or_branch(item)?; branches.push(branch); @@ -1422,16 +1447,16 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result { let args = list .get(1..) - .ok_or_else(|| anyhow::anyhow!("unexpected end of rule invocation"))? + .ok_or_else(|| err_coded!(ErrorCode::Int011, "rule invocation"))? .to_vec(); Ok(WhereClause::RuleInvocation { predicate: predicate.clone(), args, }) } - _ => bail!( - "Rule invocation must start with predicate name (symbol), got {:?}", - head + _ => bail_coded!( + ErrorCode::Int019, + format!("Rule invocation must start with predicate name (symbol), got {head:?}") ), } } @@ -1443,9 +1468,12 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result Result { if vec.len() != 3 { - bail!( - "Pattern must have exactly 3 elements (E A V), got {}", - vec.len() + bail_coded!( + ErrorCode::Int019, + format!( + "Pattern must have exactly 3 elements (E A V), got {}", + vec.len() + ) ); } @@ -1455,7 +1483,7 @@ fn parse_query_pattern(vec: &[EdnValue]) -> Result { if let EdnValue::Keyword(k) = &vec[0] && PseudoAttr::from_keyword(k).is_some() { - bail!("pseudo-attribute {} is not valid in entity position", k); + bail_coded!(ErrorCode::Int017, k, "entity"); } // Reject :db/* in value position @@ -1463,7 +1491,7 @@ fn parse_query_pattern(vec: &[EdnValue]) -> Result { if let EdnValue::Keyword(k) = &vec[2] && PseudoAttr::from_keyword(k).is_some() { - bail!("pseudo-attribute {} is not valid in value position", k); + bail_coded!(ErrorCode::Int017, k, "value"); } // Detect pseudo-attribute in attribute position @@ -1494,7 +1522,7 @@ fn parse_or_branch(item: &EdnValue) -> Result> { let mut clauses = Vec::new(); let rest = inner .get(1..) - .ok_or_else(|| anyhow::anyhow!("unexpected end of and clause"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int011, "and clause"))?; for clause_item in rest { clauses.push(parse_or_branch_item(clause_item)?); } @@ -1521,7 +1549,10 @@ fn parse_or_branch_item(item: &EdnValue) -> Result { // allow_not=true: or branches can contain not/not-join/or/or-join parse_list_as_where_clause(inner_list, true) } - _ => bail!("expected clause inside or branch, got {:?}", item), + _ => bail_coded!( + ErrorCode::Int019, + format!("expected clause inside or branch, got {item:?}") + ), } } @@ -1615,10 +1646,7 @@ fn check_not_safety( if let WhereClause::Not(_) = clause { for var in vars_in_not(clause) { if !outer_bound.contains(&var) { - bail!( - "variable {} in (not ...) is not bound by any outer clause", - var - ); + bail_coded!(ErrorCode::Int018, "variable", var, "(not ...)", "outer"); } } } @@ -1637,9 +1665,12 @@ fn check_not_join_safety( if let WhereClause::NotJoin { join_vars, .. } = clause { for var in join_vars { if !var.starts_with("?_") && !outer_bound.contains(var) { - bail!( - "join variable {} in (not-join ...) is not bound by any outer clause", - var + bail_coded!( + ErrorCode::Int018, + "join variable", + var, + "(not-join ...)", + "outer" ); } } @@ -1680,9 +1711,12 @@ fn check_expr_safety_with_bound( WhereClause::Expr { expr, binding } => { for var in expr_vars(expr) { if !bound.contains(&var) { - bail!( - "variable {} in expression clause is not bound by any earlier clause", - var + bail_coded!( + ErrorCode::Int018, + "variable", + var, + "expression clause", + "earlier" ); } } @@ -1730,9 +1764,12 @@ fn check_expr_safety_with_bound( } => { for var in join_vars { if !var.starts_with("?_") && !bound.contains(var) { - bail!( - "join variable {} in (or-join ...) is not bound by any earlier clause", - var + bail_coded!( + ErrorCode::Int018, + "join variable", + var, + "(or-join ...)", + "earlier" ); } } @@ -1757,7 +1794,7 @@ fn parse_rule(elements: &[EdnValue]) -> Result { // elements[0] = Vector with head (list) + body (patterns/rule calls) if elements.is_empty() { - bail!("Rule must have a body"); + bail_coded!(ErrorCode::Int019, "Rule must have a body"); } if elements.len() > 1 { @@ -1769,21 +1806,24 @@ fn parse_rule(elements: &[EdnValue]) -> Result { #[allow(clippy::indexing_slicing)] let body_vec = elements[0] .as_vector() - .ok_or_else(|| anyhow::anyhow!("Rule body must be a vector"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int019, "Rule body must be a vector"))?; if body_vec.is_empty() { - bail!("Rule body cannot be empty"); + bail_coded!(ErrorCode::Int019, "Rule body cannot be empty"); } // First element is the head (must be a list) // SAFETY: is_empty() check above guarantees index 0 exists #[allow(clippy::indexing_slicing)] - let head_list = body_vec[0] - .as_list() - .ok_or_else(|| anyhow::anyhow!("Rule head must be a list: (predicate ?args)"))?; + let head_list = body_vec[0].as_list().ok_or_else(|| { + err_coded!( + ErrorCode::Int019, + "Rule head must be a list: (predicate ?args)" + ) + })?; if head_list.is_empty() { - bail!("Rule head cannot be empty"); + bail_coded!(ErrorCode::Int019, "Rule head cannot be empty"); } // Verify head starts with a symbol (predicate name) @@ -1791,7 +1831,10 @@ fn parse_rule(elements: &[EdnValue]) -> Result { #[allow(clippy::indexing_slicing)] match &head_list[0] { EdnValue::Symbol(_) => {} - _ => bail!("Rule head must start with a symbol (predicate name)"), + _ => bail_coded!( + ErrorCode::Int019, + "Rule head must start with a symbol (predicate name)" + ), } // Rest of body_vec are patterns, rule invocations, or (not ...) clauses @@ -1812,15 +1855,20 @@ fn parse_rule(elements: &[EdnValue]) -> Result { let clause = parse_list_as_where_clause(list, true)?; body_clauses.push(clause); } else { - bail!( - "Rule body clause must be a vector (pattern) or list (rule invocation / not), got {:?}", - item + bail_coded!( + ErrorCode::Int019, + format!( + "Rule body clause must be a vector (pattern) or list (rule invocation / not), got {item:?}" + ) ); } } if body_clauses.is_empty() { - bail!("Rule must have at least one pattern or rule invocation in body"); + bail_coded!( + ErrorCode::Int019, + "Rule must have at least one pattern or rule invocation in body" + ); } // Safety check: variables in (not ...) must be bound by the rule head or outer body clauses diff --git a/src/query/datalog/prepared.rs b/src/query/datalog/prepared.rs index f401b38a4c..f59395e395 100644 --- a/src/query/datalog/prepared.rs +++ b/src/query/datalog/prepared.rs @@ -1,4 +1,4 @@ -use crate::error::MinigrafError; +use crate::error::{ErrorCode, MinigrafError, bail_coded}; use crate::graph::FactStorage; use crate::graph::types::Value; use crate::query::datalog::executor::{DatalogExecutor, QueryResult}; @@ -109,7 +109,7 @@ impl PreparedQuery { for name in &self.slot_names { if !binding_map.contains_key(name.as_str()) { - anyhow::bail!("missing bind value for slot '${}'", name); + bail_coded!(ErrorCode::Int033, name); } } @@ -154,11 +154,7 @@ fn validate_clauses_no_attr_slots(clauses: &[WhereClause]) -> Result<()> { match clause { WhereClause::Pattern(p) => { if let AttributeSpec::Real(EdnValue::BindSlot(name)) = &p.attribute { - anyhow::bail!( - "bind slot '${name}' is not permitted in attribute position; \ - the query optimizer selects an index based on the attribute at \ - prepare time and cannot handle a parameterised attribute" - ); + bail_coded!(ErrorCode::Int034, name); } } WhereClause::Not(inner) => validate_clauses_no_attr_slots(inner)?, @@ -355,33 +351,42 @@ fn substitute_edn_value(val: &mut EdnValue, bindings: &HashMap<&str, &BindValue> fn resolve_entity_slot(name: &str, bindings: &HashMap<&str, &BindValue>) -> Result { match bindings.get(name) { Some(BindValue::Entity(u)) => Ok(EdnValue::Uuid(*u)), - Some(other) => anyhow::bail!( - "slot '${name}' in entity position requires Entity, got {}", + Some(other) => bail_coded!( + ErrorCode::Int035, + name, + "entity", + "Entity", bind_value_type_name(other) ), - None => anyhow::bail!("missing bind value for slot '${name}'"), + None => bail_coded!(ErrorCode::Int033, name), } } fn resolve_value_slot(name: &str, bindings: &HashMap<&str, &BindValue>) -> Result { match bindings.get(name) { Some(BindValue::Val(v)) => Ok(value_to_edn(v)), - Some(other) => anyhow::bail!( - "slot '${name}' in value position requires Val, got {}", + Some(other) => bail_coded!( + ErrorCode::Int035, + name, + "value", + "Val", bind_value_type_name(other) ), - None => anyhow::bail!("missing bind value for slot '${name}'"), + None => bail_coded!(ErrorCode::Int033, name), } } fn resolve_val_slot(name: &str, bindings: &HashMap<&str, &BindValue>) -> Result { match bindings.get(name) { Some(BindValue::Val(v)) => Ok(v.clone()), - Some(other) => anyhow::bail!( - "slot '${name}' in expression position requires Val, got {}", + Some(other) => bail_coded!( + ErrorCode::Int035, + name, + "expression", + "Val", bind_value_type_name(other) ), - None => anyhow::bail!("missing bind value for slot '${name}'"), + None => bail_coded!(ErrorCode::Int033, name), } } @@ -389,11 +394,14 @@ fn resolve_as_of_slot(name: &str, bindings: &HashMap<&str, &BindValue>) -> Resul match bindings.get(name) { Some(BindValue::TxCount(n)) => Ok(AsOf::Counter(*n)), Some(BindValue::Timestamp(t)) => Ok(AsOf::Timestamp(*t)), - Some(other) => anyhow::bail!( - "slot '${name}' in :as-of position requires TxCount or Timestamp, got {}", + Some(other) => bail_coded!( + ErrorCode::Int035, + name, + ":as-of", + "TxCount or Timestamp", bind_value_type_name(other) ), - None => anyhow::bail!("missing bind value for slot '${name}'"), + None => bail_coded!(ErrorCode::Int033, name), } } @@ -401,11 +409,14 @@ fn resolve_valid_at_slot(name: &str, bindings: &HashMap<&str, &BindValue>) -> Re match bindings.get(name) { Some(BindValue::Timestamp(t)) => Ok(ValidAt::Timestamp(*t)), Some(BindValue::AnyValidTime) => Ok(ValidAt::AnyValidTime), - Some(other) => anyhow::bail!( - "slot '${name}' in :valid-at position requires Timestamp or AnyValidTime, got {}", + Some(other) => bail_coded!( + ErrorCode::Int035, + name, + ":valid-at", + "Timestamp or AnyValidTime", bind_value_type_name(other) ), - None => anyhow::bail!("missing bind value for slot '${name}'"), + None => bail_coded!(ErrorCode::Int033, name), } } diff --git a/src/query/datalog/rules.rs b/src/query/datalog/rules.rs index bc4f326f58..96de9c15c7 100644 --- a/src/query/datalog/rules.rs +++ b/src/query/datalog/rules.rs @@ -2,6 +2,7 @@ /// /// Rules are indexed by their predicate name (head). Multiple rules can share /// the same predicate (for defining base cases and recursive cases separately). +use crate::error::{ErrorCode, err_coded}; use crate::query::datalog::stratification::DependencyGraph; use crate::query::datalog::types::Rule; use anyhow::Result; @@ -65,9 +66,10 @@ impl RuleRegistry { let graph = DependencyGraph::from_rules(self); if let Err(e) = graph.stratify() { // Roll back: remove the rule we just added - let rules = self.rules.get_mut(&predicate).ok_or_else(|| { - anyhow::anyhow!("rule predicate '{}' disappeared during rollback", predicate) - })?; + let rules = self + .rules + .get_mut(&predicate) + .ok_or_else(|| err_coded!(ErrorCode::Int055, predicate.clone()))?; rules.pop(); if rules.is_empty() { self.rules.remove(&predicate); diff --git a/src/query/datalog/stratification.rs b/src/query/datalog/stratification.rs index 246a1966c4..b7f4076952 100644 --- a/src/query/datalog/stratification.rs +++ b/src/query/datalog/stratification.rs @@ -1,3 +1,4 @@ +use crate::error::{ErrorCode, err_coded}; use anyhow::Result; use std::collections::HashMap; @@ -94,11 +95,7 @@ impl DependencyGraph { } // Cycle detection: stratum >= n means unstratifiable if *strata.get(head).unwrap_or(&0) >= n { - return Err(anyhow::anyhow!( - "unstratifiable: predicate '{}' is involved in a negative cycle through '{}'", - head, - dep - )); + return Err(err_coded!(ErrorCode::Int054, head.clone(), dep.clone())); } } } diff --git a/src/storage/backend/file.rs b/src/storage/backend/file.rs index 7ce64df37e..9db2a66199 100644 --- a/src/storage/backend/file.rs +++ b/src/storage/backend/file.rs @@ -1,5 +1,5 @@ /// File-based storage backend for native platforms. -use crate::error::{ErrorCode, bail_coded}; +use crate::error::{ErrorCode, bail_coded, err_coded}; use crate::storage::{FileHeader, PAGE_SIZE, StorageBackend}; use anyhow::Result; use std::fs::{File, OpenOptions}; @@ -321,7 +321,7 @@ impl FileBackend { let mut page = vec![0u8; PAGE_SIZE]; let hlen = header_bytes.len(); page.get_mut(..hlen) - .ok_or_else(|| anyhow::anyhow!("header bytes exceed page size"))? + .ok_or_else(|| err_coded!(ErrorCode::Int049, "header bytes exceed page size"))? .copy_from_slice(&header_bytes); file.write_all(&page)?; @@ -340,16 +340,15 @@ impl FileBackend { impl StorageBackend for FileBackend { fn write_page(&mut self, page_id: u64, data: &[u8]) -> Result<()> { if data.len() != PAGE_SIZE { - anyhow::bail!( - "Invalid page size: {} bytes (expected {})", - data.len(), - PAGE_SIZE - ); + bail_coded!(ErrorCode::Int051, data.len(), PAGE_SIZE); } - let offset = page_id - .checked_mul(PAGE_SIZE as u64) - .ok_or_else(|| anyhow::anyhow!("page offset overflow for page_id {}", page_id))?; + let offset = page_id.checked_mul(PAGE_SIZE as u64).ok_or_else(|| { + err_coded!( + ErrorCode::Int048, + format!("page offset overflow for page_id {page_id}") + ) + })?; self.file.seek(SeekFrom::Start(offset))?; self.file.write_all(data)?; @@ -369,9 +368,12 @@ impl StorageBackend for FileBackend { // every time, so the on-disk header is self-consistent at // every single-page write, not just at the deliberate commits // in `PersistentFactStorage::save`. - self.header.page_count = page_id - .checked_add(1) - .ok_or_else(|| anyhow::anyhow!("page_count overflow for page_id {}", page_id))?; + self.header.page_count = page_id.checked_add(1).ok_or_else(|| { + err_coded!( + ErrorCode::Int048, + format!("page_count overflow for page_id {page_id}") + ) + })?; self.header.header_checksum = crate::storage::persistent_facts::compute_header_checksum(&self.header); Self::write_header(&mut self.file, &self.header)?; @@ -382,16 +384,21 @@ impl StorageBackend for FileBackend { fn read_page(&self, page_id: u64) -> Result> { if page_id >= self.header.page_count { - anyhow::bail!( - "Page {} out of bounds (total pages: {})", - page_id, - self.header.page_count + bail_coded!( + ErrorCode::Int049, + format!( + "Page {page_id} out of bounds (total pages: {})", + self.header.page_count + ) ); } - let offset = page_id - .checked_mul(PAGE_SIZE as u64) - .ok_or_else(|| anyhow::anyhow!("page offset overflow for page_id {}", page_id))?; + let offset = page_id.checked_mul(PAGE_SIZE as u64).ok_or_else(|| { + err_coded!( + ErrorCode::Int048, + format!("page offset overflow for page_id {page_id}") + ) + })?; let mut file = &self.file; file.seek(SeekFrom::Start(offset))?; diff --git a/src/storage/backend/memory.rs b/src/storage/backend/memory.rs index 422a0173a5..e1bf399824 100644 --- a/src/storage/backend/memory.rs +++ b/src/storage/backend/memory.rs @@ -1,4 +1,5 @@ /// In-memory storage backend for testing and embedded use. +use crate::error::{ErrorCode, bail_coded, err_coded}; use crate::storage::{PAGE_SIZE, StorageBackend}; use anyhow::Result; use std::collections::HashMap; @@ -40,17 +41,13 @@ impl Default for MemoryBackend { impl StorageBackend for MemoryBackend { fn write_page(&mut self, page_id: u64, data: &[u8]) -> Result<()> { if data.len() != PAGE_SIZE { - anyhow::bail!( - "Invalid page size: {} bytes (expected {})", - data.len(), - PAGE_SIZE - ); + bail_coded!(ErrorCode::Int051, data.len(), PAGE_SIZE); } let mut pages = self .pages .write() - .map_err(|_| anyhow::anyhow!("pages lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Int050, "pages"))?; pages.insert(page_id, data.to_vec()); Ok(()) } @@ -59,11 +56,11 @@ impl StorageBackend for MemoryBackend { let pages = self .pages .read() - .map_err(|_| anyhow::anyhow!("pages lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Int050, "pages"))?; pages .get(&page_id) .cloned() - .ok_or_else(|| anyhow::anyhow!("Page {} not found", page_id)) + .ok_or_else(|| err_coded!(ErrorCode::Int052, page_id)) } fn sync(&mut self) -> Result<()> { diff --git a/src/storage/btree.rs b/src/storage/btree.rs index e98615cfff..857eb9007c 100644 --- a/src/storage/btree.rs +++ b/src/storage/btree.rs @@ -33,7 +33,7 @@ //! //! Phase 6.1 uses these only for save/load. In-memory BTreeMaps handle queries. -use crate::error::{ErrorCode, bail_coded}; +use crate::error::{ErrorCode, bail_coded, err_coded}; use anyhow::Result; use std::collections::BTreeMap; @@ -62,15 +62,22 @@ const DATA_BYTES_PER_PAGE: usize = PAGE_SIZE - PAGE_HEADER_SIZE; fn write_blob(blob: &[u8], backend: &mut dyn StorageBackend, start_page_id: u64) -> Result { if blob.len() > u32::MAX as usize { - anyhow::bail!( - "index blob too large to serialize: {} bytes (max {})", - blob.len(), - u32::MAX + bail_coded!( + ErrorCode::Int048, + format!( + "index blob too large to serialize: {} bytes (max {})", + blob.len(), + u32::MAX + ) ); } // Safe: guarded by the > u32::MAX check above. - let total_len = u32::try_from(blob.len()) - .map_err(|_| anyhow::anyhow!("blob.len() overflows u32 (len={})", blob.len()))?; + let total_len = u32::try_from(blob.len()).map_err(|_| { + err_coded!( + ErrorCode::Int048, + format!("blob.len() overflows u32 (len={})", blob.len()) + ) + })?; let num_pages = if blob.is_empty() { 1usize // always write at least one page } else { @@ -78,88 +85,152 @@ fn write_blob(blob: &[u8], backend: &mut dyn StorageBackend, start_page_id: u64) }; for i in 0..num_pages { - let offset = i - .checked_mul(DATA_BYTES_PER_PAGE) - .ok_or_else(|| anyhow::anyhow!("btree write_blob: page offset overflow at i={i}"))?; + let offset = i.checked_mul(DATA_BYTES_PER_PAGE).ok_or_else(|| { + err_coded!( + ErrorCode::Int048, + format!("btree write_blob: page offset overflow at i={i}") + ) + })?; let chunk = if offset < blob.len() { - let end = blob.len().min( - offset - .checked_add(DATA_BYTES_PER_PAGE) - .ok_or_else(|| anyhow::anyhow!("btree write_blob: end offset overflow"))?, - ); + let end = blob + .len() + .min(offset.checked_add(DATA_BYTES_PER_PAGE).ok_or_else(|| { + err_coded!( + ErrorCode::Int048, + format!("btree write_blob: end offset overflow") + ) + })?); blob.get(offset..end).ok_or_else(|| { - anyhow::anyhow!("btree write_blob: slice {offset}..{end} out of bounds") + err_coded!( + ErrorCode::Int049, + format!("btree write_blob: slice {offset}..{end} out of bounds") + ) })? } else { &[] }; - let chunk_len = u32::try_from(chunk.len()) - .map_err(|_| anyhow::anyhow!("chunk.len() overflows u32 (len={})", chunk.len()))?; + let chunk_len = u32::try_from(chunk.len()).map_err(|_| { + err_coded!( + ErrorCode::Int048, + format!("chunk.len() overflows u32 (len={})", chunk.len()) + ) + })?; // num_pages >= 1 is guaranteed: write_blob always writes at least one page. let is_last: u8 = if i == num_pages - 1 { 0x01 } else { 0x00 }; let mut page = vec![0u8; PAGE_SIZE]; - *page - .get_mut(0) - .ok_or_else(|| anyhow::anyhow!("btree: page index 0 out of bounds"))? = PAGE_TYPE_INDEX; + *page.get_mut(0).ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("btree: page index 0 out of bounds") + ) + })? = PAGE_TYPE_INDEX; page.get_mut(1..5) - .ok_or_else(|| anyhow::anyhow!("btree: page slice 1..5 out of bounds"))? + .ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("btree: page slice 1..5 out of bounds") + ) + })? .copy_from_slice(&total_len.to_le_bytes()); page.get_mut(5..9) - .ok_or_else(|| anyhow::anyhow!("btree: page slice 5..9 out of bounds"))? + .ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("btree: page slice 5..9 out of bounds") + ) + })? .copy_from_slice(&chunk_len.to_le_bytes()); - *page - .get_mut(9) - .ok_or_else(|| anyhow::anyhow!("btree: page index 9 out of bounds"))? = is_last; + *page.get_mut(9).ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("btree: page index 9 out of bounds") + ) + })? = is_last; if !chunk.is_empty() { - let end = PAGE_HEADER_SIZE - .checked_add(chunk.len()) - .ok_or_else(|| anyhow::anyhow!("btree write_blob: data end overflow"))?; + let end = PAGE_HEADER_SIZE.checked_add(chunk.len()).ok_or_else(|| { + err_coded!( + ErrorCode::Int048, + format!("btree write_blob: data end overflow") + ) + })?; page.get_mut(PAGE_HEADER_SIZE..end) .ok_or_else(|| { - anyhow::anyhow!("btree: page slice {PAGE_HEADER_SIZE}..{end} out of bounds") + err_coded!( + ErrorCode::Int049, + format!("btree: page slice {PAGE_HEADER_SIZE}..{end} out of bounds") + ) })? .copy_from_slice(chunk); } - let page_offset = u64::try_from(i) - .map_err(|_| anyhow::anyhow!("btree write_blob: page index {i} overflows u64"))?; + let page_offset = u64::try_from(i).map_err(|_| { + err_coded!( + ErrorCode::Int048, + format!("btree write_blob: page index {i} overflows u64") + ) + })?; backend.write_page( - start_page_id - .checked_add(page_offset) - .ok_or_else(|| anyhow::anyhow!("btree write_blob: page_id overflow"))?, + start_page_id.checked_add(page_offset).ok_or_else(|| { + err_coded!( + ErrorCode::Int048, + format!("btree write_blob: page_id overflow") + ) + })?, &page, )?; } // Return the page ID immediately after the last page written. - let num_pages_u64 = u64::try_from(num_pages) - .map_err(|_| anyhow::anyhow!("btree write_blob: num_pages {num_pages} overflows u64"))?; - start_page_id - .checked_add(num_pages_u64) - .ok_or_else(|| anyhow::anyhow!("btree write_blob: final page_id overflow")) + let num_pages_u64 = u64::try_from(num_pages).map_err(|_| { + err_coded!( + ErrorCode::Int048, + format!("btree write_blob: num_pages {num_pages} overflows u64") + ) + })?; + start_page_id.checked_add(num_pages_u64).ok_or_else(|| { + err_coded!( + ErrorCode::Int048, + format!("btree write_blob: final page_id overflow") + ) + }) } fn read_blob(backend: &dyn StorageBackend, start_page_id: u64) -> Result> { // Read the first page to get total_len. let first_page = backend.read_page(start_page_id)?; - let first_byte = *first_page - .first() - .ok_or_else(|| anyhow::anyhow!("btree read_blob: first_page index 0 out of bounds"))?; + let first_byte = *first_page.first().ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("btree read_blob: first_page index 0 out of bounds") + ) + })?; if first_byte != PAGE_TYPE_INDEX { - anyhow::bail!( - "Expected index page type 0x{:02x}, got 0x{:02x}", - PAGE_TYPE_INDEX, - first_byte + bail_coded!( + ErrorCode::Int049, + format!( + "Expected index page type 0x{:02x}, got 0x{:02x}", + PAGE_TYPE_INDEX, first_byte + ) ); } let total_len = u32::from_le_bytes( first_page .get(1..5) - .ok_or_else(|| anyhow::anyhow!("btree read_blob: first_page slice 1..5 out of bounds"))? + .ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("btree read_blob: first_page slice 1..5 out of bounds") + ) + })? .try_into() - .map_err(|_| anyhow::anyhow!("btree read_blob: slice 1..5 not exactly 4 bytes"))?, + .map_err(|_| { + err_coded!( + ErrorCode::Int049, + format!("btree read_blob: slice 1..5 not exactly 4 bytes") + ) + })?, ) as usize; let mut blob = Vec::with_capacity(total_len); @@ -167,7 +238,10 @@ fn read_blob(backend: &dyn StorageBackend, start_page_id: u64) -> Result loop { let page = backend.read_page(page_id)?; let page_byte = *page.first().ok_or_else(|| { - anyhow::anyhow!("btree read_blob: page index 0 out of bounds (page {page_id})") + err_coded!( + ErrorCode::Int049, + format!("btree read_blob: page index 0 out of bounds (page {page_id})") + ) })?; if page_byte != PAGE_TYPE_INDEX { bail_coded!(ErrorCode::Stg012, page_id); @@ -175,24 +249,37 @@ fn read_blob(backend: &dyn StorageBackend, start_page_id: u64) -> Result let chunk_len = u32::from_le_bytes( page.get(5..9) .ok_or_else(|| { - anyhow::anyhow!( - "btree read_blob: page slice 5..9 out of bounds (page {page_id})" + err_coded!( + ErrorCode::Int049, + format!("btree read_blob: page slice 5..9 out of bounds (page {page_id})") ) })? .try_into() - .map_err(|_| anyhow::anyhow!("btree read_blob: slice 5..9 not exactly 4 bytes"))?, + .map_err(|_| { + err_coded!( + ErrorCode::Int049, + format!("btree read_blob: slice 5..9 not exactly 4 bytes") + ) + })?, ) as usize; let is_last = *page.get(9).ok_or_else(|| { - anyhow::anyhow!("btree read_blob: page index 9 out of bounds (page {page_id})") + err_coded!( + ErrorCode::Int049, + format!("btree read_blob: page index 9 out of bounds (page {page_id})") + ) })? == 0x01; if chunk_len > 0 { let end = PAGE_HEADER_SIZE.checked_add(chunk_len).ok_or_else(|| { - anyhow::anyhow!("btree read_blob: data end overflow (chunk_len={chunk_len})") + err_coded!( + ErrorCode::Int048, + format!("btree read_blob: data end overflow (chunk_len={chunk_len})") + ) })?; blob.extend_from_slice(page.get(PAGE_HEADER_SIZE..end).ok_or_else(|| { - anyhow::anyhow!( - "btree read_blob: page slice {PAGE_HEADER_SIZE}..{end} out of bounds" + err_coded!( + ErrorCode::Int049, + format!("btree read_blob: page slice {PAGE_HEADER_SIZE}..{end} out of bounds") ) })?); } @@ -200,9 +287,12 @@ fn read_blob(backend: &dyn StorageBackend, start_page_id: u64) -> Result if is_last { break; } - page_id = page_id - .checked_add(1) - .ok_or_else(|| anyhow::anyhow!("btree read_blob: page_id overflow"))?; + page_id = page_id.checked_add(1).ok_or_else(|| { + err_coded!( + ErrorCode::Int048, + format!("btree read_blob: page_id overflow") + ) + })?; } Ok(blob) diff --git a/src/storage/btree_v6.rs b/src/storage/btree_v6.rs index 6fc7eaf648..acada6e0e1 100644 --- a/src/storage/btree_v6.rs +++ b/src/storage/btree_v6.rs @@ -4,11 +4,11 @@ //! `build_btree` does a bulk-build (write-all-leaves, then internal levels //! bottom-up). Range scans traverse the tree through the cache. -use crate::error::{ErrorCode, bail_coded}; +use crate::error::{ErrorCode, bail_coded, err_coded}; use crate::storage::cache::PageCache; use crate::storage::index::FactRef; use crate::storage::{PAGE_SIZE, StorageBackend}; -use anyhow::{Result, anyhow}; +use anyhow::Result; use serde::{Deserialize, Serialize}; use std::sync::Arc; use std::sync::Mutex; @@ -35,26 +35,28 @@ const PAGE_FILL_BYTES: usize = PAGE_SIZE * 3 / 4; /// Read a u16 from 2 bytes at the given offset, returning an error if out of bounds. fn read_u16_at(page: &[u8], offset: usize) -> Result { - let bytes = page - .get(offset..offset.saturating_add(2)) - .ok_or_else(|| anyhow!("out of bounds: read_u16 at {offset} (len {})", page.len()))?; - Ok(u16::from_le_bytes( - bytes - .try_into() - .map_err(|_| anyhow!("slice at {offset} not 2 bytes"))?, - )) + let bytes = page.get(offset..offset.saturating_add(2)).ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("out of bounds: read_u16 at {offset} (len {})", page.len()) + ) + })?; + Ok(u16::from_le_bytes(bytes.try_into().map_err(|_| { + err_coded!(ErrorCode::Int049, format!("slice at {offset} not 2 bytes")) + })?)) } /// Read a u64 from 8 bytes at the given offset, returning an error if out of bounds. fn read_u64_at(page: &[u8], offset: usize) -> Result { - let bytes = page - .get(offset..offset.saturating_add(8)) - .ok_or_else(|| anyhow!("out of bounds: read_u64 at {offset} (len {})", page.len()))?; - Ok(u64::from_le_bytes( - bytes - .try_into() - .map_err(|_| anyhow!("slice at {offset} not 8 bytes"))?, - )) + let bytes = page.get(offset..offset.saturating_add(8)).ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("out of bounds: read_u64 at {offset} (len {})", page.len()) + ) + })?; + Ok(u64::from_le_bytes(bytes.try_into().map_err(|_| { + err_coded!(ErrorCode::Int049, format!("slice at {offset} not 8 bytes")) + })?)) } // ─── Low-level page writers ─────────────────────────────────────────────────── @@ -71,8 +73,12 @@ fn write_leaf_page( entries: &[Vec], next_leaf: u64, ) -> Result<()> { - let entry_count = - u16::try_from(entries.len()).map_err(|_| anyhow!("too many entries: {}", entries.len()))?; + let entry_count = u16::try_from(entries.len()).map_err(|_| { + err_coded!( + ErrorCode::Int049, + format!("too many entries: {}", entries.len()) + ) + })?; let mut page = vec![0u8; PAGE_SIZE]; // Fixed header @@ -87,10 +93,18 @@ fn write_leaf_page( write_pos -= entry.len(); page[write_pos..write_pos + entry.len()].copy_from_slice(entry); let slot_off = LEAF_HEADER_SIZE + i * SLOT_SIZE; - let write_pos_u16 = - u16::try_from(write_pos).map_err(|_| anyhow!("write_pos {write_pos} exceeds u16"))?; - let entry_len_u16 = u16::try_from(entry.len()) - .map_err(|_| anyhow!("entry len {} exceeds u16", entry.len()))?; + let write_pos_u16 = u16::try_from(write_pos).map_err(|_| { + err_coded!( + ErrorCode::Int048, + format!("write_pos {write_pos} exceeds u16") + ) + })?; + let entry_len_u16 = u16::try_from(entry.len()).map_err(|_| { + err_coded!( + ErrorCode::Int048, + format!("entry len {} exceeds u16", entry.len()) + ) + })?; page[slot_off..slot_off + 2].copy_from_slice(&write_pos_u16.to_le_bytes()); page[slot_off + 2..slot_off + 4].copy_from_slice(&entry_len_u16.to_le_bytes()); } @@ -119,11 +133,15 @@ fn write_internal_page( if child_ids.is_empty() { bail_coded!(ErrorCode::Stg011); } - let key_count = u16::try_from(sep_bytes.len()) - .map_err(|_| anyhow!("too many sep keys: {}", sep_bytes.len()))?; + let key_count = u16::try_from(sep_bytes.len()).map_err(|_| { + err_coded!( + ErrorCode::Int049, + format!("too many sep keys: {}", sep_bytes.len()) + ) + })?; let rightmost_child = *child_ids .last() - .ok_or_else(|| anyhow!("child_ids is empty"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int049, format!("child_ids is empty")))?; let mut page = vec![0u8; PAGE_SIZE]; @@ -149,10 +167,18 @@ fn write_internal_page( write_pos -= sep.len(); page[write_pos..write_pos + sep.len()].copy_from_slice(sep); let slot_off = slot_dir_start + i * SLOT_SIZE; - let write_pos_u16 = - u16::try_from(write_pos).map_err(|_| anyhow!("write_pos {write_pos} exceeds u16"))?; - let sep_len_u16 = - u16::try_from(sep.len()).map_err(|_| anyhow!("sep len {} exceeds u16", sep.len()))?; + let write_pos_u16 = u16::try_from(write_pos).map_err(|_| { + err_coded!( + ErrorCode::Int048, + format!("write_pos {write_pos} exceeds u16") + ) + })?; + let sep_len_u16 = u16::try_from(sep.len()).map_err(|_| { + err_coded!( + ErrorCode::Int048, + format!("sep len {} exceeds u16", sep.len()) + ) + })?; page[slot_off..slot_off + 2].copy_from_slice(&write_pos_u16.to_le_bytes()); page[slot_off + 2..slot_off + 4].copy_from_slice(&sep_len_u16.to_le_bytes()); } @@ -217,7 +243,10 @@ pub fn build_btree( if projected > PAGE_FILL_BYTES && !cur_entries.is_empty() { write_leaf_page(backend, cache, next_page, &cur_entries, 0)?; let first_key = cur_first_key.take().ok_or_else(|| { - anyhow::anyhow!("BUG: cur_first_key empty when writing leaf page") + err_coded!( + ErrorCode::Int049, + format!("BUG: cur_first_key empty when writing leaf page") + ) })?; leaf_infos.push((next_page, first_key)); next_page += 1; @@ -242,7 +271,10 @@ pub fn build_btree( if !cur_entries.is_empty() { write_leaf_page(backend, cache, next_page, &cur_entries, 0)?; let first_key = cur_first_key.take().ok_or_else(|| { - anyhow::anyhow!("BUG: cur_first_key empty when flushing last leaf page") + err_coded!( + ErrorCode::Int049, + format!("BUG: cur_first_key empty when flushing last leaf page") + ) })?; leaf_infos.push((next_page, first_key)); next_page += 1; @@ -252,17 +284,27 @@ pub fn build_btree( for i in 0..leaf_infos.len() - 1 { let (pid, _) = leaf_infos .get(i) - .ok_or_else(|| anyhow!("leaf_infos[{i}] out of bounds"))? + .ok_or_else(|| err_coded!(ErrorCode::Int049, format!("leaf_infos[{i}] out of bounds")))? .clone(); let (next_lid, _) = leaf_infos .get(i + 1) - .ok_or_else(|| anyhow!("leaf_infos[{}] out of bounds", i + 1))? + .ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("leaf_infos[{}] out of bounds", i + 1) + ) + })? .clone(); let cached = cache.get_or_load(pid, backend)?; let mut page = (*cached).clone(); // Safety: page is PAGE_SIZE bytes; offset 4..12 is always valid page.get_mut(4..12) - .ok_or_else(|| anyhow!("page too small to write next_leaf"))? + .ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("page too small to write next_leaf") + ) + })? .copy_from_slice(&next_lid.to_le_bytes()); backend.write_page(pid, &page)?; cache.put_dirty(pid, page); @@ -273,7 +315,9 @@ pub fn build_btree( return Ok(( leaf_infos .first() - .ok_or_else(|| anyhow!("leaf_infos unexpectedly empty"))? + .ok_or_else(|| { + err_coded!(ErrorCode::Int049, format!("leaf_infos unexpectedly empty")) + })? .0, next_page, )); @@ -287,7 +331,12 @@ pub fn build_btree( return Ok(( current_level .first() - .ok_or_else(|| anyhow!("current_level unexpectedly empty"))? + .ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("current_level unexpectedly empty") + ) + })? .0, next_page, )); @@ -298,18 +347,24 @@ pub fn build_btree( while i < current_level.len() { let i_start = i; - let first_entry = current_level - .get(i) - .ok_or_else(|| anyhow!("current_level[{i}] out of bounds"))?; + let first_entry = current_level.get(i).ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("current_level[{i}] out of bounds") + ) + })?; let mut child_ids: Vec = vec![first_entry.0]; let mut sep_bytes: Vec> = Vec::new(); let mut sep_data_bytes: usize = 0; i += 1; while i < current_level.len() { - let entry = current_level - .get(i) - .ok_or_else(|| anyhow!("current_level[{i}] out of bounds"))?; + let entry = current_level.get(i).ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("current_level[{i}] out of bounds") + ) + })?; let sep = entry.1.clone(); let projected = INTERNAL_HEADER_SIZE + (child_ids.len() - 1) * 8 @@ -326,7 +381,12 @@ pub fn build_btree( child_ids.push( current_level .get(i) - .ok_or_else(|| anyhow!("current_level[{i}] out of bounds"))? + .ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("current_level[{i}] out of bounds") + ) + })? .0, ); i += 1; @@ -338,7 +398,12 @@ pub fn build_btree( let first_key = current_level .get(i_start) - .ok_or_else(|| anyhow!("current_level[{i_start}] out of bounds"))? + .ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("current_level[{i_start}] out of bounds") + ) + })? .1 .clone(); next_level.push((node_page_id, first_key)); @@ -377,10 +442,12 @@ fn find_leftmost_leaf(root: u64, backend: &dyn StorageBackend, cache: &PageCache let mut page_id = root; loop { let page = cache.get_or_load(page_id, backend)?; - let page_type = page - .first() - .copied() - .ok_or_else(|| anyhow!("empty page at page_id={page_id}"))?; + let page_type = page.first().copied().ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("empty page at page_id={page_id}") + ) + })?; match page_type { PAGE_TYPE_LEAF => return Ok(page_id), PAGE_TYPE_INTERNAL => { @@ -391,10 +458,12 @@ fn find_leftmost_leaf(root: u64, backend: &dyn StorageBackend, cache: &PageCache page_id = read_u64_at(&page[..], INTERNAL_HEADER_SIZE)?; } } - t => anyhow::bail!( - "find_leftmost_leaf: unexpected page type 0x{:02x} at page_id={}", - t, - page_id + t => bail_coded!( + ErrorCode::Int049, + format!( + "find_leftmost_leaf: unexpected page type 0x{:02x} at page_id={}", + t, page_id + ) ), } } @@ -416,10 +485,12 @@ where let mut page_id = root; loop { let page = cache.get_or_load(page_id, backend)?; - let page_type = page - .first() - .copied() - .ok_or_else(|| anyhow!("empty page at page_id={page_id}"))?; + let page_type = page.first().copied().ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("empty page at page_id={page_id}") + ) + })?; match page_type { PAGE_TYPE_LEAF => return Ok(page_id), PAGE_TYPE_INTERNAL => { @@ -436,10 +507,10 @@ where let sep_slice = page .get(sep_offset..sep_offset.saturating_add(sep_length)) .ok_or_else(|| { - anyhow!( + err_coded!(ErrorCode::Int049, format!( "sep slice out of bounds: offset={sep_offset} len={sep_length} page_len={}", page.len() - ) + )) })?; let sep_key: K = postcard::from_bytes(sep_slice)?; @@ -454,10 +525,12 @@ where page_id = rightmost_child; } } - t => anyhow::bail!( - "find_leaf_for_key: unexpected page type 0x{:02x} at page_id={}", - t, - page_id + t => bail_coded!( + ErrorCode::Int049, + format!( + "find_leaf_for_key: unexpected page type 0x{:02x} at page_id={}", + t, page_id + ) ), } } @@ -478,9 +551,12 @@ where let slice = page .get(offset..offset.saturating_add(length)) .ok_or_else(|| { - anyhow!( - "entry slice out of bounds: offset={offset} len={length} page_len={}", - page.len() + err_coded!( + ErrorCode::Int049, + format!( + "entry slice out of bounds: offset={offset} len={length} page_len={}", + page.len() + ) ) })?; let (k, fr): (K, FactRef) = postcard::from_bytes(slice)?; @@ -506,14 +582,19 @@ where loop { let page = cache.get_or_load(leaf_id, backend)?; - let page_type = page - .first() - .copied() - .ok_or_else(|| anyhow!("empty page at page_id={leaf_id}"))?; + let page_type = page.first().copied().ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("empty page at page_id={leaf_id}") + ) + })?; if page_type != PAGE_TYPE_LEAF { - anyhow::bail!( - "stream_all_entries: expected leaf page at page_id={}", - leaf_id + bail_coded!( + ErrorCode::Int049, + format!( + "stream_all_entries: expected leaf page at page_id={}", + leaf_id + ) ); } let next_leaf = read_u64_at(&page[..], 4)?; @@ -551,10 +632,12 @@ where 'outer: loop { let page = cache.get_or_load(leaf_id, backend)?; - let page_type = page - .first() - .copied() - .ok_or_else(|| anyhow!("empty page at page_id={leaf_id}"))?; + let page_type = page.first().copied().ok_or_else(|| { + err_coded!( + ErrorCode::Int049, + format!("empty page at page_id={leaf_id}") + ) + })?; if page_type != PAGE_TYPE_LEAF { bail_coded!(ErrorCode::Stg013, leaf_id); } @@ -598,7 +681,7 @@ impl StorageBackend for MutexStorageBackend { fn read_page(&self, page_id: u64) -> anyhow::Result> { self.0 .lock() - .map_err(|e| anyhow!("MutexStorageBackend lock poisoned: {e}"))? + .map_err(|_| err_coded!(ErrorCode::Int050, "MutexStorageBackend"))? .read_page(page_id) } diff --git a/src/storage/cache.rs b/src/storage/cache.rs index 532017a331..b7fcebd127 100644 --- a/src/storage/cache.rs +++ b/src/storage/cache.rs @@ -15,6 +15,7 @@ //! semantics: frequently accessed pages are unlikely to be evicted but not //! strictly guaranteed MRU. For a 256-page cache this is an excellent tradeoff. +use crate::error::{ErrorCode, err_coded}; use crate::storage::StorageBackend; use anyhow::Result; use std::collections::{HashMap, VecDeque}; @@ -87,7 +88,7 @@ impl PageCache { let inner = self .inner .read() - .map_err(|_| anyhow::anyhow!("cache lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Int050, "cache"))?; // Capacity 0 disables the cache: always read through, no bookkeeping. if inner.capacity == 0 { return Ok(Arc::new(backend.read_page(page_id)?)); @@ -101,7 +102,7 @@ impl PageCache { let mut inner = self .inner .write() - .map_err(|_| anyhow::anyhow!("cache lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Int050, "cache"))?; // Double-check after acquiring write lock (another thread may have loaded it) if let Some(entry) = inner.entries.get(&page_id) { return Ok(entry.data.clone()); @@ -162,7 +163,7 @@ impl PageCache { let mut inner = self .inner .write() - .map_err(|_| anyhow::anyhow!("cache lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Int050, "cache"))?; for (&page_id, entry) in inner.entries.iter_mut() { if entry.dirty { backend.write_page(page_id, &entry.data[..])?; diff --git a/src/storage/mod.rs b/src/storage/mod.rs index 93e3c63bcf..3145504265 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -13,7 +13,7 @@ pub mod index; pub mod packed_pages; pub mod persistent_facts; -use crate::error::{ErrorCode, bail_coded}; +use crate::error::{ErrorCode, bail_coded, err_coded}; use anyhow::Result; /// Read a 4-byte little-endian u32 from `bytes` at `offset`. @@ -21,16 +21,9 @@ fn read_u32_le(bytes: &[u8], offset: usize) -> anyhow::Result { Ok(u32::from_le_bytes( bytes .get(offset..offset + 4) - .ok_or_else(|| { - anyhow::anyhow!( - "header too short: need {}..{}, got {} bytes", - offset, - offset + 4, - bytes.len() - ) - })? + .ok_or_else(|| err_coded!(ErrorCode::Int036, offset, offset + 4, bytes.len()))? .try_into() - .map_err(|_| anyhow::anyhow!("header: slice at {offset} not exactly 4 bytes"))?, + .map_err(|_| err_coded!(ErrorCode::Int037, offset, 4))?, )) } @@ -39,16 +32,9 @@ fn read_u64_le(bytes: &[u8], offset: usize) -> anyhow::Result { Ok(u64::from_le_bytes( bytes .get(offset..offset + 8) - .ok_or_else(|| { - anyhow::anyhow!( - "header too short: need {}..{}, got {} bytes", - offset, - offset + 8, - bytes.len() - ) - })? + .ok_or_else(|| err_coded!(ErrorCode::Int036, offset, offset + 8, bytes.len()))? .try_into() - .map_err(|_| anyhow::anyhow!("header: slice at {offset} not exactly 8 bytes"))?, + .map_err(|_| err_coded!(ErrorCode::Int037, offset, 8))?, )) } @@ -208,7 +194,7 @@ impl FileHeader { magic.copy_from_slice( bytes .get(0..4) - .ok_or_else(|| anyhow::anyhow!("header too short for magic bytes"))?, + .ok_or_else(|| err_coded!(ErrorCode::Int038, "magic bytes"))?, ); if magic != MAGIC_NUMBER { @@ -277,17 +263,17 @@ impl FileHeader { index_checksum: read_u32_le(bytes, 64)?, fact_page_format: *bytes .get(68) - .ok_or_else(|| anyhow::anyhow!("header too short for fact_page_format"))?, + .ok_or_else(|| err_coded!(ErrorCode::Int038, "fact_page_format"))?, _padding: [ *bytes .get(69) - .ok_or_else(|| anyhow::anyhow!("header too short for padding[0]"))?, + .ok_or_else(|| err_coded!(ErrorCode::Int038, "padding[0]"))?, *bytes .get(70) - .ok_or_else(|| anyhow::anyhow!("header too short for padding[1]"))?, + .ok_or_else(|| err_coded!(ErrorCode::Int038, "padding[1]"))?, *bytes .get(71) - .ok_or_else(|| anyhow::anyhow!("header too short for padding[2]"))?, + .ok_or_else(|| err_coded!(ErrorCode::Int038, "padding[2]"))?, ], fact_page_count, header_checksum, @@ -297,7 +283,7 @@ impl FileHeader { /// Validate the header. pub fn validate(&self) -> Result<()> { if self.magic != MAGIC_NUMBER { - anyhow::bail!("Invalid magic number"); + bail_coded!(ErrorCode::Int039); } if self.version < 1 || self.version > FORMAT_VERSION { bail_coded!(ErrorCode::Stg006, self.version, FORMAT_VERSION); diff --git a/src/storage/packed_pages.rs b/src/storage/packed_pages.rs index b5fae80bc3..120568e6db 100644 --- a/src/storage/packed_pages.rs +++ b/src/storage/packed_pages.rs @@ -19,7 +19,7 @@ //! Overflow pages (`page_type = 0x03`) are reserved for future use. //! The `next_page` field is always written as 0 in Phase 6.2. -use crate::error::{ErrorCode, bail_coded}; +use crate::error::{ErrorCode, bail_coded, err_coded}; use crate::graph::types::Fact; use crate::storage::index::FactRef; use crate::storage::{PAGE_SIZE, StorageBackend}; @@ -71,10 +71,9 @@ pub fn pack_facts(facts: &[Fact], start_page_id: u64) -> Result<(Vec>, V // Check if this fact exceeds the maximum slot size. if len > MAX_FACT_BYTES { - anyhow::bail!( - "Fact serialised size {} bytes exceeds maximum slot size {} bytes", - len, - MAX_FACT_BYTES + bail_coded!( + ErrorCode::Int023, + format!("{len} bytes exceeds maximum slot size {MAX_FACT_BYTES} bytes") ); } @@ -99,37 +98,54 @@ pub fn pack_facts(facts: &[Fact], start_page_id: u64) -> Result<(Vec>, V current_page .get_mut(data_offset..data_offset.saturating_add(len)) .ok_or_else(|| { - anyhow::anyhow!( - "packed page too short: data region {}..{} out of bounds", - data_offset, - data_offset.saturating_add(len) + err_coded!( + ErrorCode::Int024, + format!( + "data region {}..{} out of bounds", + data_offset, + data_offset.saturating_add(len) + ) ) })? .copy_from_slice(&serialised); // Write directory entry: offset (u16 LE) | length (u16 LE). // data_offset <= PAGE_SIZE (4096) which fits in u16; len <= MAX_FACT_BYTES < u16::MAX. - let offset_u16 = u16::try_from(data_offset) - .map_err(|_| anyhow::anyhow!("data_offset {} overflows u16", data_offset))?; - let len_u16 = u16::try_from(len) - .map_err(|_| anyhow::anyhow!("serialised fact too large: {} bytes", len))?; + let offset_u16 = u16::try_from(data_offset).map_err(|_| { + err_coded!( + ErrorCode::Int024, + format!("data_offset {data_offset} overflows u16") + ) + })?; + let len_u16 = u16::try_from(len).map_err(|_| { + err_coded!( + ErrorCode::Int024, + format!("serialised fact too large: {len} bytes") + ) + })?; current_page .get_mut(dir_offset..dir_offset.saturating_add(2)) .ok_or_else(|| { - anyhow::anyhow!( - "packed page dir out of bounds at {}..{}", - dir_offset, - dir_offset.saturating_add(2) + err_coded!( + ErrorCode::Int024, + format!( + "dir out of bounds at {}..{}", + dir_offset, + dir_offset.saturating_add(2) + ) ) })? .copy_from_slice(&offset_u16.to_le_bytes()); current_page .get_mut(dir_offset.saturating_add(2)..dir_offset.saturating_add(4)) .ok_or_else(|| { - anyhow::anyhow!( - "packed page dir out of bounds at {}..{}", - dir_offset.saturating_add(2), - dir_offset.saturating_add(4) + err_coded!( + ErrorCode::Int024, + format!( + "dir out of bounds at {}..{}", + dir_offset.saturating_add(2), + dir_offset.saturating_add(4) + ) ) })? .copy_from_slice(&len_u16.to_le_bytes()); @@ -137,7 +153,7 @@ pub fn pack_facts(facts: &[Fact], start_page_id: u64) -> Result<(Vec>, V let page_id = start_page_id.saturating_add( u64::try_from(pages.len()) - .map_err(|_| anyhow::anyhow!("too many pages: overflows u64"))?, + .map_err(|_| err_coded!(ErrorCode::Int024, "too many pages: overflows u64"))?, ); fact_refs.push(FactRef { page_id, @@ -156,30 +172,32 @@ pub fn pack_facts(facts: &[Fact], start_page_id: u64) -> Result<(Vec>, V /// Read a single fact from a packed page at the given slot index. pub fn read_slot(page: &[u8], slot: u16) -> Result { if page.len() < PAGE_SIZE { - anyhow::bail!( - "Page too short: {} bytes (expected {})", - page.len(), - PAGE_SIZE + bail_coded!( + ErrorCode::Int024, + format!( + "Page too short: {} bytes (expected {})", + page.len(), + PAGE_SIZE + ) ); } let page_type = *page .first() - .ok_or_else(|| anyhow::anyhow!("packed page empty"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int024, "packed page empty"))?; if page_type != PAGE_TYPE_PACKED { bail_coded!(ErrorCode::Stg014, format!("{:02x}", page_type)); } let b2 = *page .get(2) - .ok_or_else(|| anyhow::anyhow!("packed page too short for record_count byte 2"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int024, "too short for record_count byte 2"))?; let b3 = *page .get(3) - .ok_or_else(|| anyhow::anyhow!("packed page too short for record_count byte 3"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int024, "too short for record_count byte 3"))?; let record_count = u16::from_le_bytes([b2, b3]); if slot >= record_count { - anyhow::bail!( - "Slot {} out of bounds (page has {} records)", - slot, - record_count + bail_coded!( + ErrorCode::Int024, + format!("Slot {slot} out of bounds (page has {record_count} records)") ); } // dir_base = PACKED_HEADER_SIZE + slot * 4; slot < record_count <= u16::MAX, @@ -188,16 +206,25 @@ pub fn read_slot(page: &[u8], slot: u16) -> Result { let dir_base = PACKED_HEADER_SIZE.saturating_add(slot_usize.saturating_mul(4)); let db0 = *page .get(dir_base) - .ok_or_else(|| anyhow::anyhow!("packed page dir entry {} out of bounds", slot))?; - let db1 = *page - .get(dir_base.saturating_add(1)) - .ok_or_else(|| anyhow::anyhow!("packed page dir entry {} byte 1 out of bounds", slot))?; - let db2 = *page - .get(dir_base.saturating_add(2)) - .ok_or_else(|| anyhow::anyhow!("packed page dir entry {} byte 2 out of bounds", slot))?; - let db3 = *page - .get(dir_base.saturating_add(3)) - .ok_or_else(|| anyhow::anyhow!("packed page dir entry {} byte 3 out of bounds", slot))?; + .ok_or_else(|| err_coded!(ErrorCode::Int024, format!("dir entry {slot} out of bounds")))?; + let db1 = *page.get(dir_base.saturating_add(1)).ok_or_else(|| { + err_coded!( + ErrorCode::Int024, + format!("dir entry {slot} byte 1 out of bounds") + ) + })?; + let db2 = *page.get(dir_base.saturating_add(2)).ok_or_else(|| { + err_coded!( + ErrorCode::Int024, + format!("dir entry {slot} byte 2 out of bounds") + ) + })?; + let db3 = *page.get(dir_base.saturating_add(3)).ok_or_else(|| { + err_coded!( + ErrorCode::Int024, + format!("dir entry {slot} byte 3 out of bounds") + ) + })?; let offset = usize::from(u16::from_le_bytes([db0, db1])); let length = usize::from(u16::from_le_bytes([db2, db3])); if offset.saturating_add(length) > PAGE_SIZE { @@ -206,10 +233,13 @@ pub fn read_slot(page: &[u8], slot: u16) -> Result { let fact: Fact = postcard::from_bytes( page.get(offset..offset.saturating_add(length)) .ok_or_else(|| { - anyhow::anyhow!( - "packed page record {}..{} out of bounds", - offset, - offset.saturating_add(length) + err_coded!( + ErrorCode::Int024, + format!( + "record {}..{} out of bounds", + offset, + offset.saturating_add(length) + ) ) })?, )?; diff --git a/src/storage/persistent_facts.rs b/src/storage/persistent_facts.rs index fdad0923f1..9e116ecede 100644 --- a/src/storage/persistent_facts.rs +++ b/src/storage/persistent_facts.rs @@ -231,9 +231,7 @@ impl PersistentFactStorage { if header.version >= 7 && header.header_checksum != 0 { let computed = compute_header_checksum_from_bytes(&raw_header_bytes); if header.header_checksum != computed { - anyhow::bail!( - "Header checksum mismatch: possible file corruption. Database may be damaged." - ); + bail_coded!(ErrorCode::Int053); } } @@ -422,9 +420,7 @@ impl PersistentFactStorage { let current_header = FileHeader::from_bytes(¤t_header_bytes)?; let computed = compute_header_checksum_from_bytes(¤t_header_bytes); if current_header.header_checksum != computed { - anyhow::bail!( - "Header checksum mismatch: possible file corruption. Database may be damaged." - ); + bail_coded!(ErrorCode::Int053); } } @@ -838,9 +834,7 @@ impl PersistentFactStorage { Ok(mutex) => Ok(mutex .into_inner() .map_err(|_| err_coded!(ErrorCode::Stg016))?), - Err(_) => Err(anyhow::anyhow!( - "into_backend: backend Arc has multiple owners" - )), + Err(_) => Err(err_coded!(ErrorCode::Int047)), } } @@ -903,10 +897,10 @@ impl PersistentFactStorage { backend.write_page(page_id, page_data)?; } let new_pages_len = u64::try_from(new_pages.len()) - .map_err(|_| anyhow::anyhow!("new page count exceeds u64::MAX"))?; + .map_err(|_| err_coded!(ErrorCode::Int048, "new page count exceeds u64::MAX"))?; let new_total_fact_pages = old_fact_page_count .checked_add(new_pages_len) - .ok_or_else(|| anyhow::anyhow!("fact page count overflow"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int048, "fact page count overflow"))?; // Sync fact pages to disk before building indexes on top of them. // Without this, a crash during index build could leave partially-flushed @@ -977,7 +971,7 @@ impl PersistentFactStorage { header.node_count = curr_header .node_count .checked_add(pending_len) - .ok_or_else(|| anyhow::anyhow!("node_count overflow"))?; + .ok_or_else(|| err_coded!(ErrorCode::Int048, "node_count overflow"))?; header.last_checkpointed_tx_count = self.storage.current_tx_count(); header.eavt_root_page = eavt_root; header.aevt_root_page = aevt_root; diff --git a/src/temporal.rs b/src/temporal.rs index cf2396e486..d44fd26508 100644 --- a/src/temporal.rs +++ b/src/temporal.rs @@ -3,7 +3,8 @@ //! Supports UTC ISO 8601 strings only. Timezone offsets are rejected //! to avoid chrono's local timezone handling (GHSA-wcg3-cvx6-7396). -use anyhow::{Result, anyhow}; +use crate::error::{ErrorCode, err_coded}; +use anyhow::Result; use chrono::{DateTime, NaiveDate, TimeZone, Utc}; /// Parse an ISO 8601 UTC string to milliseconds since UNIX epoch. @@ -17,7 +18,8 @@ use chrono::{DateTime, NaiveDate, TimeZone, Utc}; pub fn parse_timestamp(s: &str) -> Result { // Reject timezone offsets explicitly if s.contains('+') || s.get(10..).is_some_and(|rest| rest.contains('-')) { - return Err(anyhow!( + return Err(err_coded!( + ErrorCode::Int004, "timezone offsets are not supported; use UTC (Z) timestamps only. \ chrono's local timezone handling (GHSA-wcg3-cvx6-7396) is avoided by design." )); @@ -25,21 +27,25 @@ pub fn parse_timestamp(s: &str) -> Result { // Try full datetime first if s.contains('T') { - let dt = s - .parse::>() - .map_err(|e| anyhow!("invalid UTC timestamp '{}': {}", s, e))?; + let dt = s.parse::>().map_err(|e| { + err_coded!( + ErrorCode::Int004, + format!("invalid UTC timestamp '{s}': {e}") + ) + })?; return Ok(dt.timestamp_millis()); } // Try date-only (YYYY-MM-DD) let date = s .parse::() - .map_err(|e| anyhow!("invalid date '{}': {}", s, e))?; - let dt = Utc.from_utc_datetime( - &date - .and_hms_opt(0, 0, 0) - .ok_or_else(|| anyhow!("invalid date '{}': could not create midnight UTC", s))?, - ); + .map_err(|e| err_coded!(ErrorCode::Int004, format!("invalid date '{s}': {e}")))?; + let dt = Utc.from_utc_datetime(&date.and_hms_opt(0, 0, 0).ok_or_else(|| { + err_coded!( + ErrorCode::Int004, + format!("invalid date '{s}': could not create midnight UTC") + ) + })?); Ok(dt.timestamp_millis()) } @@ -50,12 +56,8 @@ pub fn parse_timestamp(s: &str) -> Result { /// callers should check for the sentinel before formatting. #[allow(dead_code)] pub fn millis_to_timestamp_string(millis: i64) -> Result { - let dt = DateTime::::from_timestamp_millis(millis).ok_or_else(|| { - anyhow!( - "millisecond value {} is outside the supported datetime range", - millis - ) - })?; + let dt = DateTime::::from_timestamp_millis(millis) + .ok_or_else(|| err_coded!(ErrorCode::Int005, millis))?; Ok(dt.format("%Y-%m-%dT%H:%M:%SZ").to_string()) } diff --git a/tests/error_codes_qry_test.rs b/tests/error_codes_qry_test.rs index 94d8888827..c58d34c2e8 100644 --- a/tests/error_codes_qry_test.rs +++ b/tests/error_codes_qry_test.rs @@ -23,13 +23,15 @@ //! branches) — see that file's "Stream 3: branches unreachable via the //! parser" test group. //! -//! This file also locks in current (INT-000) behavior for two error families -//! that live in this issue's in-scope files but have no documented QRY code: -//! the recursive-rule iteration/derived-fact/result limit family in +//! This file also covers two error families that live in this issue's +//! in-scope files but have no documented QRY code: the recursive-rule +//! iteration/derived-fact/result limit family in //! `src/query/datalog/evaluator.rs` (the "limit/depth-exceeded" and //! "recursion-error" paths), and the runtime aggregate type-mismatch family, -//! which is raised in `src/query/datalog/functions.rs` — not one of this -//! issue's five in-scope files, so it's out of scope for migration here. +//! which is raised in `src/query/datalog/functions.rs`. Both were assigned +//! `INT-0xx` codes (INT-020 and INT-041 respectively) by the #277 step 6 +//! (API+INT) category PR, which audited and coded every remaining uncoded +//! call site crate-wide — see `docs/ERROR_REFERENCE.md`. use minigraf::Minigraf; @@ -57,17 +59,16 @@ fn query_with_rules_unknown_predicate_returns_qry_007() { assert_eq!(err.code(), "QRY-007"); } -// ─── Limit/recursion-error family: no documented QRY code (INT-000) ─────── +// ─── Limit/recursion-error family: no documented QRY code (INT-020) ─────── /// A recursive rule with an artificially tiny per-query `max_derived_facts` /// hits `RecursiveEvaluator::evaluate_recursive_rules`'s "Max derived facts /// per iteration exceeded" branch (src/query/datalog/evaluator.rs). No /// QRY-0xx code is documented for this in ERROR_REFERENCE.md — see the -/// module doc comment above for why. This test locks in that it currently -/// (and, for the scope of this PR, deliberately) surfaces as INT-000 rather -/// than silently succeeding or panicking. +/// module doc comment above for why. #277 step 6 assigned this shared +/// "limit exceeded" family the INT-020 code. #[test] -fn recursive_rule_derived_facts_limit_returns_int000() { +fn recursive_rule_derived_facts_limit_returns_int020() { let db = Minigraf::in_memory().unwrap(); db.execute(r#"(transact [[:a :connected :b] [:b :connected :c] [:c :connected :d]])"#) .unwrap(); @@ -85,7 +86,7 @@ fn recursive_rule_derived_facts_limit_returns_int000() { // rather than treat as a pass. panic!("expected the derived-facts limit to be exceeded"); } - Err(err) => assert_eq!(err.code(), "INT-000"), + Err(err) => assert_eq!(err.code(), "INT-020"), } } @@ -95,15 +96,14 @@ fn recursive_rule_derived_facts_limit_returns_int000() { /// error originates in `apply_builtin_aggregate` /// (src/query/datalog/functions.rs), which is NOT one of this issue's five /// in-scope files (executor.rs, evaluator.rs, optimizer.rs, matcher.rs, -/// magic_sets.rs) — so it is intentionally left uncoded by this PR and -/// currently surfaces as INT-000. Locked in here as a known, documented gap -/// rather than left to silently regress. +/// magic_sets.rs) — so it was intentionally left uncoded by this PR. #277 +/// step 6 (API+INT category PR) later assigned it INT-041. #[test] -fn aggregate_type_mismatch_returns_int000() { +fn aggregate_type_mismatch_returns_int041() { let db = Minigraf::in_memory().unwrap(); db.execute(r#"(transact [[:a :score "high"] [:b :score "low"]])"#) .unwrap(); let result = db.execute(r#"(query [:find (sum ?s) :where [?e :score ?s]])"#); let err = result.expect_err("sum of strings must fail at runtime"); - assert_eq!(err.code(), "INT-000"); + assert_eq!(err.code(), "INT-041"); } From 8677392b2b26ff63b622a1618aaffc6ae3229180 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Wed, 26 Aug 2026 08:58:25 +0530 Subject: [PATCH 2/3] fix: satisfy clippy::useless_format on CI's newer toolchain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI runs clippy 1.98.0, which flags format!("literal") with no interpolation as useless_format; the local toolchain here (1.94.0) doesn't yet catch these. 19 sites in btree.rs/btree_v6.rs — all from this PR's INT-048/INT-049 migration — wrapped a static message in format!() with nothing to interpolate. Switched to .to_string() per clippy's own suggested fix. Part of #277 --- src/storage/btree.rs | 26 +++++++++++++------------- src/storage/btree_v6.rs | 12 ++++++------ 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/src/storage/btree.rs b/src/storage/btree.rs index 857eb9007c..9e4db54e1e 100644 --- a/src/storage/btree.rs +++ b/src/storage/btree.rs @@ -97,7 +97,7 @@ fn write_blob(blob: &[u8], backend: &mut dyn StorageBackend, start_page_id: u64) .min(offset.checked_add(DATA_BYTES_PER_PAGE).ok_or_else(|| { err_coded!( ErrorCode::Int048, - format!("btree write_blob: end offset overflow") + "btree write_blob: end offset overflow".to_string() ) })?); blob.get(offset..end).ok_or_else(|| { @@ -122,14 +122,14 @@ fn write_blob(blob: &[u8], backend: &mut dyn StorageBackend, start_page_id: u64) *page.get_mut(0).ok_or_else(|| { err_coded!( ErrorCode::Int049, - format!("btree: page index 0 out of bounds") + "btree: page index 0 out of bounds".to_string() ) })? = PAGE_TYPE_INDEX; page.get_mut(1..5) .ok_or_else(|| { err_coded!( ErrorCode::Int049, - format!("btree: page slice 1..5 out of bounds") + "btree: page slice 1..5 out of bounds".to_string() ) })? .copy_from_slice(&total_len.to_le_bytes()); @@ -137,21 +137,21 @@ fn write_blob(blob: &[u8], backend: &mut dyn StorageBackend, start_page_id: u64) .ok_or_else(|| { err_coded!( ErrorCode::Int049, - format!("btree: page slice 5..9 out of bounds") + "btree: page slice 5..9 out of bounds".to_string() ) })? .copy_from_slice(&chunk_len.to_le_bytes()); *page.get_mut(9).ok_or_else(|| { err_coded!( ErrorCode::Int049, - format!("btree: page index 9 out of bounds") + "btree: page index 9 out of bounds".to_string() ) })? = is_last; if !chunk.is_empty() { let end = PAGE_HEADER_SIZE.checked_add(chunk.len()).ok_or_else(|| { err_coded!( ErrorCode::Int048, - format!("btree write_blob: data end overflow") + "btree write_blob: data end overflow".to_string() ) })?; page.get_mut(PAGE_HEADER_SIZE..end) @@ -174,7 +174,7 @@ fn write_blob(blob: &[u8], backend: &mut dyn StorageBackend, start_page_id: u64) start_page_id.checked_add(page_offset).ok_or_else(|| { err_coded!( ErrorCode::Int048, - format!("btree write_blob: page_id overflow") + "btree write_blob: page_id overflow".to_string() ) })?, &page, @@ -191,7 +191,7 @@ fn write_blob(blob: &[u8], backend: &mut dyn StorageBackend, start_page_id: u64) start_page_id.checked_add(num_pages_u64).ok_or_else(|| { err_coded!( ErrorCode::Int048, - format!("btree write_blob: final page_id overflow") + "btree write_blob: final page_id overflow".to_string() ) }) } @@ -202,7 +202,7 @@ fn read_blob(backend: &dyn StorageBackend, start_page_id: u64) -> Result let first_byte = *first_page.first().ok_or_else(|| { err_coded!( ErrorCode::Int049, - format!("btree read_blob: first_page index 0 out of bounds") + "btree read_blob: first_page index 0 out of bounds".to_string() ) })?; if first_byte != PAGE_TYPE_INDEX { @@ -221,14 +221,14 @@ fn read_blob(backend: &dyn StorageBackend, start_page_id: u64) -> Result .ok_or_else(|| { err_coded!( ErrorCode::Int049, - format!("btree read_blob: first_page slice 1..5 out of bounds") + "btree read_blob: first_page slice 1..5 out of bounds".to_string() ) })? .try_into() .map_err(|_| { err_coded!( ErrorCode::Int049, - format!("btree read_blob: slice 1..5 not exactly 4 bytes") + "btree read_blob: slice 1..5 not exactly 4 bytes".to_string() ) })?, ) as usize; @@ -258,7 +258,7 @@ fn read_blob(backend: &dyn StorageBackend, start_page_id: u64) -> Result .map_err(|_| { err_coded!( ErrorCode::Int049, - format!("btree read_blob: slice 5..9 not exactly 4 bytes") + "btree read_blob: slice 5..9 not exactly 4 bytes".to_string() ) })?, ) as usize; @@ -290,7 +290,7 @@ fn read_blob(backend: &dyn StorageBackend, start_page_id: u64) -> Result page_id = page_id.checked_add(1).ok_or_else(|| { err_coded!( ErrorCode::Int048, - format!("btree read_blob: page_id overflow") + "btree read_blob: page_id overflow".to_string() ) })?; } diff --git a/src/storage/btree_v6.rs b/src/storage/btree_v6.rs index acada6e0e1..94ceda12f7 100644 --- a/src/storage/btree_v6.rs +++ b/src/storage/btree_v6.rs @@ -141,7 +141,7 @@ fn write_internal_page( })?; let rightmost_child = *child_ids .last() - .ok_or_else(|| err_coded!(ErrorCode::Int049, format!("child_ids is empty")))?; + .ok_or_else(|| err_coded!(ErrorCode::Int049, "child_ids is empty".to_string()))?; let mut page = vec![0u8; PAGE_SIZE]; @@ -245,7 +245,7 @@ pub fn build_btree( let first_key = cur_first_key.take().ok_or_else(|| { err_coded!( ErrorCode::Int049, - format!("BUG: cur_first_key empty when writing leaf page") + "BUG: cur_first_key empty when writing leaf page".to_string() ) })?; leaf_infos.push((next_page, first_key)); @@ -273,7 +273,7 @@ pub fn build_btree( let first_key = cur_first_key.take().ok_or_else(|| { err_coded!( ErrorCode::Int049, - format!("BUG: cur_first_key empty when flushing last leaf page") + "BUG: cur_first_key empty when flushing last leaf page".to_string() ) })?; leaf_infos.push((next_page, first_key)); @@ -302,7 +302,7 @@ pub fn build_btree( .ok_or_else(|| { err_coded!( ErrorCode::Int049, - format!("page too small to write next_leaf") + "page too small to write next_leaf".to_string() ) })? .copy_from_slice(&next_lid.to_le_bytes()); @@ -316,7 +316,7 @@ pub fn build_btree( leaf_infos .first() .ok_or_else(|| { - err_coded!(ErrorCode::Int049, format!("leaf_infos unexpectedly empty")) + err_coded!(ErrorCode::Int049, "leaf_infos unexpectedly empty".to_string()) })? .0, next_page, @@ -334,7 +334,7 @@ pub fn build_btree( .ok_or_else(|| { err_coded!( ErrorCode::Int049, - format!("current_level unexpectedly empty") + "current_level unexpectedly empty".to_string() ) })? .0, From b63ea444a9fe12c59553e1cde2a238f296499b7f Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Wed, 26 Aug 2026 08:58:38 +0530 Subject: [PATCH 3/3] style: cargo fmt --- src/storage/btree_v6.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/storage/btree_v6.rs b/src/storage/btree_v6.rs index 94ceda12f7..5c5a9b9e14 100644 --- a/src/storage/btree_v6.rs +++ b/src/storage/btree_v6.rs @@ -316,7 +316,10 @@ pub fn build_btree( leaf_infos .first() .ok_or_else(|| { - err_coded!(ErrorCode::Int049, "leaf_infos unexpectedly empty".to_string()) + err_coded!( + ErrorCode::Int049, + "leaf_infos unexpectedly empty".to_string() + ) })? .0, next_page,