From 734005d7bb8e6cbefad6f9e761dfabb7b585dbf4 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, 44 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 016e8e9717..452f6f4dcf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,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. - **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. - **A fact with more than four elements is rejected** (#649). `transact` read a fact's 4th element as its optional valid-time map and ignored everything after it, so `[[:alice :person/age 1 {} 99 :junk]]` stored `[:alice :person/age 1]` and dropped the rest without an error; two facts run together by a misplaced bracket lost one. A fact of more than four elements now fails with the new `PRS-108`, numbered as in v3.0.0, and the transaction writes nothing. A fact of five or more elements whose 4th is not a map now gets `PRS-108` instead of `PRS-047`. Present since v0.4.0. diff --git a/src/browser/mod.rs b/src/browser/mod.rs index a7d80ca3b0..81e010da54 100644 --- a/src/browser/mod.rs +++ b/src/browser/mod.rs @@ -54,8 +54,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 { @@ -80,8 +79,7 @@ impl BrowserDb { let buffer = BrowserBufferBackend::load_pages(existing); // Page cache capacity 0 — see comment in `open_in_memory` above. - 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 { @@ -104,7 +102,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(_)); @@ -118,20 +116,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. @@ -147,10 +145,7 @@ impl BrowserDb { pub async fn checkpoint(&self) -> Result<(), JsValue> { let (dirty_pages, has_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)?; let pages = take_dirty_pages(&mut inner.pfs)?; (pages, inner.idb.is_some()) }; @@ -175,14 +170,14 @@ impl BrowserDb { let page_count = inner .pfs .with_backend(|b| b.page_count_raw()) - .map_err(|e| JsValue::from_str(&e.to_string()))? as usize; + .map_err(to_js_error)? as usize; let mut blob = Vec::with_capacity(page_count * crate::storage::PAGE_SIZE); for id in 0..page_count as u64 { let page = inner .pfs .with_backend(|b| b.read_page_raw(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())) @@ -212,8 +207,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 inner. @@ -271,13 +265,10 @@ impl BrowserDb { inner .fact_storage .load_facts(stamped.iter().cloned()) - .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 let dirty_pages = take_dirty_pages(&mut inner.pfs)?; @@ -319,7 +310,13 @@ fn take_dirty_pages( .map(|id| b.read_page_raw(id).map(|d| (id, d))) .collect::>>() }) - .map_err(|e| JsValue::from_str(&crate::MinigrafError::from(e).to_string())) + .map_err(to_js_error) +} + +/// 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()) } fn query_result_to_json(result: QueryResult) -> String { @@ -389,6 +386,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 5052b77d0e2e1612dbb722f62519669578dbcce3 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Wed, 21 Oct 2026 11:53:41 +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 81e010da54..3f94178745 100644 --- a/src/browser/mod.rs +++ b/src/browser/mod.rs @@ -386,24 +386,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}" ); } }