From 45df4cc046d245dfdcefc8c5d7c404544df3de35 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Wed, 21 Oct 2026 11:40:35 +0530 Subject: [PATCH 1/2] fix(browser): BrowserDb errors carry their error code (#673) BrowserDb rejected with the anyhow error's top-level message only ("Unknown command: nosuchcommand"), so the browser API was the one API without structured codes. Every anyhow conversion now goes through to_js_error (MinigrafError::from), so a rejection starts with its code, as on every other API. A browser test checks a parse, query and transact error. Found by the minigraf-wasm consumer test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PtCdzbJMSS1V8qEPaJ4jXz --- CHANGELOG.md | 1 + src/browser/mod.rs | 67 +++++++++++++++++++++++++++------------------- 2 files changed, 41 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 48e10d8634..6df303d50a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **`BrowserDb` errors carry their error code** (#673). The browser API (`@minigraf/browser`) rejected with the error's top-level message only, such as `Unknown command: nosuchcommand`, while every other API reports `[PRS-001] Unknown command: nosuchcommand`. Every `BrowserDb` rejection now goes through `MinigrafError`, so it starts with its code. Host errors that have no code yet (no IndexedDB, an import blob whose length is not a multiple of the page size) are unchanged. - **An `or` branch in a rule body knows the registered predicates** (#548). A rule with `or`/`or-join` evaluated its branches with the built-in functions only, so a predicate registered with `register_predicate` in a branch (`(or [(big? ?v)] [?x :special true])`) was unknown there. Branches now get the database's functions, as the rest of the rule body does. - **A pseudo-attribute in a rule body reads the stored fact** (#661). In a rule without `not`, `not-join`, `or` or `or-join`, `:db/valid-from`, `:db/valid-to`, `:db/tx-count` and `:db/tx-id` read the rule evaluator's working copy of the fact: valid-from was the time the query ran, valid-to forever, and the tx-count and tx-id those of the copy. With `[:a :edge :b]` valid from 2020-01-01 to 2021-01-01, `(rule [(vf ?x ?t) [?x :edge ?y] [?x :db/valid-from ?t]])` returned the query's time for `:a`; it now returns 2020-01-01, as the same pattern in a query body does. Stored data was never affected. Present since v0.15.0; fixed on v2.x too. - **Rule queries with a literal argument return every row** (#608). Magic-sets rewriting restricts a rule to the facts its callers demand, but it took each rule's bound arguments from the first call it saw and assumed every other call matched. A call that did not — the same rule called with free arguments elsewhere in the query, a call inside `or` or `not`, a call from a rule the query calls with free arguments, or a rule-body call whose argument nothing bound yet — either failed with `INT-022` (`(chain ?x :c)` with `(chain ?x ?y) :- (link ?x ?m) (chain ?m ?y)`) or silently returned too few rows (`(link ?x :c) (link ?p ?q)` returned only the `:c` edges for `?p ?q`). A query with both arguments literal next to another rule call also lost its rows. The demand on each rule is now the one every call site supplies, and a rule some call site reads in full is evaluated in full. Present since v1.2.0. diff --git a/src/browser/mod.rs b/src/browser/mod.rs index 820de7e4f9..ba1cf68ea0 100644 --- a/src/browser/mod.rs +++ b/src/browser/mod.rs @@ -57,8 +57,7 @@ impl BrowserDb { // Page cache capacity 0: `BrowserBufferBackend` is already an in-memory // page store, so the LRU cache would only duplicate pages and add // HashMap overhead for zero benefit. See #275. - let pfs = - PersistentFactStorage::new(buffer, 0).map_err(|e| JsValue::from_str(&e.to_string()))?; + let pfs = PersistentFactStorage::new(buffer, 0).map_err(to_js_error)?; let fact_storage = pfs.storage().clone(); Ok(BrowserDb { @@ -84,8 +83,7 @@ impl BrowserDb { let buffer = BrowserBufferBackend::load_pages(existing); // Page cache capacity 0 — see comment in `open_in_memory` above. - let mut pfs = - PersistentFactStorage::new(buffer, 0).map_err(|e| JsValue::from_str(&e.to_string()))?; + let mut pfs = PersistentFactStorage::new(buffer, 0).map_err(to_js_error)?; let fact_storage = pfs.storage().clone(); // Opening may have written pages: a v7 store is migrated to v8 (#411). @@ -117,7 +115,7 @@ impl BrowserDb { /// - Rule: `{"ok": true}` #[wasm_bindgen(js_name = execute)] pub async fn execute(&self, datalog: String) -> Result { - let cmd = parse_datalog_command(&datalog).map_err(|e| JsValue::from_str(&e.to_string()))?; + let cmd = parse_datalog_command(&datalog).map_err(to_js_error)?; // Peek at the discriminant before consuming `cmd`. let is_read = matches!(cmd, DatalogCommand::Query(_) | DatalogCommand::Rule(_)); @@ -131,20 +129,20 @@ impl BrowserDb { inner.functions.clone(), ) .execute(cmd) - .map_err(|e| JsValue::from_str(&e.to_string()))? + .map_err(to_js_error)? }; return Ok(query_result_to_json(result)); } match cmd { DatalogCommand::Transact(tx) => { - let facts = crate::db::Minigraf::materialize_transaction(&tx) - .map_err(|e| JsValue::from_str(&e.to_string()))?; + let facts = + crate::db::Minigraf::materialize_transaction(&tx).map_err(to_js_error)?; self.apply_write(facts, false).await } DatalogCommand::Retract(tx) => { - let facts = crate::db::Minigraf::materialize_retraction(&tx) - .map_err(|e| JsValue::from_str(&e.to_string()))?; + let facts = + crate::db::Minigraf::materialize_retraction(&tx).map_err(to_js_error)?; self.apply_write(facts, true).await } // Handled above; unreachable but required for exhaustiveness. @@ -176,10 +174,7 @@ impl BrowserDb { pub async fn checkpoint(&self) -> Result<(), JsValue> { let (flush, idb) = { let mut inner = self.inner.borrow_mut(); - inner - .pfs - .save() - .map_err(|e| JsValue::from_str(&e.to_string()))?; + inner.pfs.save().map_err(to_js_error)?; ( take_commit_flush(&mut inner)?, inner.idb.as_ref().map(IndexedDbBackend::clone_handle), @@ -208,7 +203,7 @@ impl BrowserDb { let page_count = inner .pfs .with_backend(|b| b.page_count_raw()) - .map_err(|e| JsValue::from_str(&e.to_string()))? + .map_err(to_js_error)? .max(inner.pfs.committed_page_count()); let capacity = usize::try_from(page_count) .ok() @@ -220,7 +215,7 @@ impl BrowserDb { let page = inner .pfs .with_backend(|b| b.export_page(id)) - .map_err(|e| JsValue::from_str(&e.to_string()))?; + .map_err(to_js_error)?; blob.extend_from_slice(&page); } Ok(js_sys::Uint8Array::from(blob.as_slice())) @@ -250,8 +245,7 @@ impl BrowserDb { let mut inner = self.inner.borrow_mut(); let buffer = BrowserBufferBackend::load_pages_all_dirty(pages); // Page cache capacity 0 — see comment in `open_in_memory` above. - let mut new_pfs = PersistentFactStorage::new(buffer, 0) - .map_err(|e| JsValue::from_str(&e.to_string()))?; + let mut new_pfs = PersistentFactStorage::new(buffer, 0).map_err(to_js_error)?; let new_fact_storage = new_pfs.storage().clone(); // Drain dirty set and collect owned page bytes before swapping @@ -333,10 +327,8 @@ impl BrowserDb { // Before allocating: a rejected transaction takes no tx_count // (#435, #436). let tx_id = tx_id_now(); - crate::graph::storage::check_valid_windows(&facts, tx_id) - .map_err(|e| JsValue::from_str(&e.to_string()))?; - crate::graph::storage::check_one_window_per_triple(&facts) - .map_err(|e| JsValue::from_str(&e.to_string()))?; + crate::graph::storage::check_valid_windows(&facts, tx_id).map_err(to_js_error)?; + crate::graph::storage::check_one_window_per_triple(&facts).map_err(to_js_error)?; let tx_count = inner.fact_storage.allocate_tx_count(); let stamped: Vec = facts @@ -355,13 +347,10 @@ impl BrowserDb { inner .fact_storage .load_facts(stamped) - .map_err(|e| JsValue::from_str(&e.to_string()))?; + .map_err(to_js_error)?; inner.pfs.mark_dirty(); - inner - .pfs - .save() - .map_err(|e| JsValue::from_str(&e.to_string()))?; + inner.pfs.save().map_err(to_js_error)?; // Collect dirty pages as owned Vec<(u64, Vec)> — no borrows // escape — and drop the pages this commit freed (#440). @@ -490,6 +479,8 @@ fn take_flush( Ok(Flush { puts, deletes }) } +/// Every error a `BrowserDb` method rejects with goes through this, so the +/// message carries its code (`[PRS-001] ...`), as on every other API (#673). fn to_js_error(e: anyhow::Error) -> JsValue { JsValue::from_str(&crate::MinigrafError::from(e).to_string()) } @@ -571,6 +562,28 @@ mod tests { assert!(take_dirty_pages(&mut pfs).is_err()); } + // #673: a rejection carries the error code, like every other API. + #[wasm_bindgen_test] + async fn execute_errors_carry_their_code() { + let db = BrowserDb::open_in_memory().expect("open_in_memory"); + for (datalog, code) in [ + ("(nosuchcommand [])", "[PRS-"), + ("(query [:find ?x :where [?e :a ?x] [(nosuchfn ?x)]])", "["), + ("(transact [[:a :b]])", "["), + ] { + let err = db + .execute(datalog.to_string()) + .await + .expect_err("invalid command must reject"); + let text = err.as_string().expect("rejection is a string"); + assert!(text.starts_with(code), "rejection has no error code"); + assert!( + text.len() > 10 && text.as_bytes()[4] == b'-' && text.as_bytes()[8] == b']', + "rejection does not start with [XXX-NNN]" + ); + } + } + #[wasm_bindgen_test] async fn in_memory_transact_and_query() { let db = BrowserDb::open_in_memory().expect("open_in_memory"); From 6f893cb977749247d55ebe753bfeb915ac82d23f Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Wed, 21 Oct 2026 11:51:03 +0530 Subject: [PATCH 2/2] test(browser): pin the exact error codes in the #673 test Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PtCdzbJMSS1V8qEPaJ4jXz --- src/browser/mod.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/browser/mod.rs b/src/browser/mod.rs index ba1cf68ea0..df063a45b9 100644 --- a/src/browser/mod.rs +++ b/src/browser/mod.rs @@ -562,24 +562,26 @@ mod tests { assert!(take_dirty_pages(&mut pfs).is_err()); } - // #673: a rejection carries the error code, like every other API. + // #673: a rejection carries the same error code as the native API. #[wasm_bindgen_test] async fn execute_errors_carry_their_code() { let db = BrowserDb::open_in_memory().expect("open_in_memory"); for (datalog, code) in [ - ("(nosuchcommand [])", "[PRS-"), - ("(query [:find ?x :where [?e :a ?x] [(nosuchfn ?x)]])", "["), - ("(transact [[:a :b]])", "["), + ("(nosuchcommand [])", "[PRS-011] "), + ( + "(query [:find ?x :where [?e :a ?x] [(nosuchfn ?x)]])", + "[QRY-007] ", + ), + ("(transact [[:a :b]])", "[PRS-046] "), ] { let err = db .execute(datalog.to_string()) .await .expect_err("invalid command must reject"); let text = err.as_string().expect("rejection is a string"); - assert!(text.starts_with(code), "rejection has no error code"); assert!( - text.len() > 10 && text.as_bytes()[4] == b'-' && text.as_bytes()[8] == b']', - "rejection does not start with [XXX-NNN]" + text.starts_with(code), + "rejection does not start with {code}" ); } }