From 0173bef44c2cc353f46054a525610e54c11a4422 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Sat, 24 Oct 2026 09:53:58 +0530 Subject: [PATCH 1/5] docs(plan): prepared queries in every binding (#181) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Urda7FD9CYYoxdeGGJa11x --- .../plans/2026-10-24-181-prepared-ffi.md | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-24-181-prepared-ffi.md diff --git a/docs/superpowers/plans/2026-10-24-181-prepared-ffi.md b/docs/superpowers/plans/2026-10-24-181-prepared-ffi.md new file mode 100644 index 0000000000..02ad95bb48 --- /dev/null +++ b/docs/superpowers/plans/2026-10-24-181-prepared-ffi.md @@ -0,0 +1,119 @@ +# Prepared queries in every binding (#181) — Plan + +Spec: `docs/superpowers/specs/2026-10-24-prepared-query-ffi-design.md` (merged as #737), called "the spec" below. Every PR targets its repo's `v3` branch and merges with a merge commit. No PR uses a closing keyword: #181 is closed by hand after PR 5. + +| PR | Steps | Repo, base | Branch | +|---|---|---|---| +| 1 | 1–8: codes, `Entity`/`Ref`, `BrowserDb.prepare` (spec §3, §5, §7.4) | minigraf `v3` (+ minigraf-docs `main`) | `feat/181-prepared-core` | +| 2 | 9–10: the UniFFI items in the template (spec §7.1) | minigraf-binding-template `v3` | `feat/181-prepared-ffi` | +| 3 | 11–14, once per binding | minigraf-python, -java, -android, -swift `v3` | `feat/181-prepared-ffi` | +| 4 | 15–16, once per binding | minigraf-node, minigraf-c `v3` | `feat/181-prepared-ffi` | +| 5 | 17 | minigraf-wasm `v3` | `feat/181-prepared-ffi` | +| — | 18: close-out | minigraf `v3` | `docs/181-done` | + +Tests and coverage run on the bench machine first (`source ~/.cargo/env`), the laptop only as a fallback. Each PR gets a Codex review (`codex exec -s read-only ... < /dev/null`) before it is offered for merge. + +## Decisions not fixed by the spec + +1. **Codes are `API-022`, `API-023`, `API-024`**, even if #316's `API-021` has not landed yet. A gap in the registry is allowed: no test requires numbers to be contiguous, and #316's spec has already reserved `API-021`. +2. **The `INT` variants stay in `ErrorCode`** with `#[allow(dead_code)]` and a "deprecated since v3.0.0" comment, as `Stg003`/`Stg004`/`Api013` do. Their registry entries and `ERROR_REFERENCE.md` sections stay, with "(deprecated)" added to the table row and a sentence added to the deprecated-codes paragraph. +3. **The expression slot also accepts `Entity`** (`resolve_val_slot`), as the spec's §3 says. An `Entity(u)` in an expression is `Value::Ref(u)`. +4. **The browser bind reader lives in a new file, `src/browser/binds.rs`**. It holds `fn read_bindings(&JsValue) -> Result, JsValue>` and its helpers. A JS `TypeError` is built with `js_sys::TypeError::new`. `API-017` is `MinigrafError::invalid_argument(..)` rendered by `to_js_error`. +5. **Browser limits.** `BrowserDb.prepare` passes `(DEFAULT_MAX_DERIVED_FACTS, usize::MAX)`, the limits `BrowserDb.query` uses today through `DatalogExecutor::new_with_rules_and_functions`. + +## PR 1 — core (`feat/181-prepared-core`, worktree `.worktrees/181-prepared-core`) + +### Step 1 — this plan +Commit the plan. + +### Step 2 — failing tests for the codes +In `tests/prepared_statements_test.rs`, one test per code. Each asserts `err.code()` and `err.category() == ErrorCategory::Api`, through both `execute` and `query`: +- `API-022` with the missing slot in each position: pattern entity, pattern value, expression, rule argument, `:as-of`, `:valid-at`, inside `not`, `not-join`, `or` and `or-join`. +- `API-023` with an attribute slot at the top level and inside each of `not`, `not-join`, `or` and `or-join`. It is raised by `prepare`. +- `API-024` once per resolver: entity slot given `TxCount`; value slot given `Timestamp`; expression slot given `AnyValidTime`; `:as-of` given `Val`; `:valid-at` given `TxCount`. Check that the message names the slot and position (it has the same text as `INT-035`). + +Update `tests/cursor_test.rs:259` (`INT-033` → `API-022`). Red: the new tests fail on the code. + +### Step 3 — codes +`src/error.rs`: add `Api022`, `Api023` and `Api024` after `Api020`, with registry entries using `INT-033`/`034`/`035`'s templates and `ErrorCategory::Api`. Add them to both exhaustive lists in the tests (the category match near line 2357 and the all-codes array near line 2619). Mark `Int033`–`Int035` deprecated (decision 2). + +`docs/ERROR_REFERENCE.md`: add three rows to the API table and three sections after API-020 (cause, resolution, scenario, in the style of API-017/018). Mark INT-033–035 "(deprecated)" in the table and the deprecated paragraph, and say in each INT section that it is replaced by API-02x from v3.0.0. + +`src/query/datalog/prepared.rs`: switch every `Int033`/`Int034`/`Int035` raise to the new codes. Green: step 2's tests and the registry/doc sync test pass. + +### Step 4 — failing tests for `Entity`/`Ref` +In `tests/prepared_statements_test.rs`, with a fixture where `alice` has `:person/friend` set to `bob`'s entity, check each pair of forms gives the same rows: +- entity slot: `Val(Ref(alice))` vs `Entity(alice)`; +- value slot `[?x :person/friend $f]`: `Entity(bob)` vs `Val(Ref(bob))`; +- rule argument `(friend-of ?x $f)`: `Entity(bob)` vs `Val(Ref(bob))`; +- expression `[(= ?f $f)]`: `Entity(bob)` vs `Val(Ref(bob))`. +Also check that `Val(Integer)` in an entity slot is still `API-024`. Red. + +### Step 5 — `Entity`/`Ref` resolvers +In `resolve_entity_slot`, add an arm `Val(Value::Ref(u))` → `EdnValue::Uuid(u)`. In `resolve_value_slot` and `resolve_val_slot`, add `Entity(u)` → the `Ref`. Update the `BindValue` doc table and drop the "Not valid in rule-invocation argument positions" note. Green. + +### Step 6 — `BrowserDb.prepare` +Write `#[wasm_bindgen_test]` cases in `src/browser/mod.rs` first. They are run in CI by `wasm.yml`; locally, `cargo check`/`clippy --target wasm32-unknown-unknown --features browser` and a `wasm-pack test --headless` run if a browser is available: +- prepare once, then `execute` three times with different plain integers, each giving its rows (#181 acceptance); +- each plain form: `true`, an integer `number`, a fractional `number`, a `bigint`, a string, `null`; +- each typed form: `{type:'integer'|'float'|'string'|'boolean'|'ref'|'keyword'|'null'}`, `{type:'entity'}`, `{type:'txCount'}` and `{type:'timestamp'}` with `bigint` and `number`, and `{type:'anyValidTime'}`; +- `{type:'float', value: 2}` binds a float and `2` binds an integer; +- `query(bindings)` drained, with the same rows as `execute`; +- `undefined` and an unknown object are a `TypeError`; a bad UUID and a negative tx count are rejected with a message starting `[API-017] `; a missing slot is rejected with `[API-022] `; an attribute slot passed to `prepare` with `[API-023] `; +- a prepared query sees a later write (it reads a new snapshot on each `execute`). + +Then `src/browser/binds.rs` (decision 4) and, in `mod.rs`: `BrowserDb::prepare(&self, datalog: &str) -> Result` (parse; `API-005`/`006`/`007` for a non-query, as `Minigraf::prepare`; `prepare_query` with decision 5's limits), and `BrowserPreparedQuery { _db: Rc>, query: PreparedQuery }` with `execute(&self, bindings: JsValue) -> Result` (`query_result_to_json`) and `query(&self, bindings: JsValue) -> Result`. Doc comments with a JS example, as `query` has. + +### Step 7 — docs +- `CHANGELOG.md` v3.0.0. `Added`: `BrowserDb.prepare` and `BrowserPreparedQuery`; `Entity` and `Val(Ref)` accepted in each other's slots. `Breaking changes`: `INT-033`/`034`/`035` → `API-022`/`023`/`024`. +- `CLAUDE.md`: the browser module note (`BrowserDb.prepare`, `binds.rs`), the `prepared.rs` note, the test count. `docs/TEST_COVERAGE.md`: the counts and the new tests. +- `ROADMAP.md`: #181 entry: "core done on `v3`; bindings follow". +- Docs site (`../minigraf-docs`, worktree `.worktrees/181`): `content/tutorial-08-prepared-queries.md` gets a `BrowserDb` example and the new codes; `content/upgrading-to-v3.md` gets the code change. Both wrapped in ``. The docs PR merges after PR 1. + +### Step 8 — verify and raise +On the bench machine: `cargo test`, `cargo test --features test-hooks`, `cargo clippy --all-targets` (and with `--features test-hooks`), coverage gates. Locally: the wasm `check`/`clippy`, `cargo fmt --check`, the release binary size against `v3`. Codex review, then open the PR with spec/plan links and the test counts. Own CI until it is green. + +## PR 2 — template (`minigraf-binding-template`) + +### Step 9 — Rust tests first +In the template's `src/lib.rs` tests: prepare, then execute three times with different `MiniGrafBindValue`s; every variant; `query` drained; `API-022`/`023`/`024` and `API-017` (bad UUID, negative tx count) reach `MiniGrafError::Api`; the database `Arc` dropped before the prepared handle, which still runs. + +### Step 10 — items +Bump the pin to PR 1's merge. Add `MiniGrafBindValue`, `MiniGrafDb::prepare`, `MiniGrafPreparedQuery { db: Arc>, inner: PreparedQuery }` with `execute`/`query` (spec §7.1, §6), and `MiniGrafError::Api { msg }` with `ErrorCategory::Api` mapped to it (spec §5). `at_batch_index` gains the arm. README. + +## PR 3 — UniFFI bindings (python, java, android, swift) + +Once per binding, in this order: python (Tier 1), java, android, swift. Whichever of these and #180's binding PRs lands second rebases onto the other (spec §9). + +### Step 11 — copy +Bump the pin and copy step 10's `src/lib.rs` items and tests from the template. + +### Step 12 — language layer, tests first (spec §4.2) +- **python**: write pytest cases in `tests/test_prepared.py` first (repeated execution, every plain type including `bool` before `int`, every typed form, kwargs and dict, `TypeError`, `MiniGrafError.Api`), then `minigraf/__init__.py`: `Entity`, `TxCount`, `Timestamp`, `ANY_VALID_TIME`, and a `PreparedQuery` wrapper (or functions on the generated class) converting plain values. +- **java**: Kotlin tests (`PreparedTest.kt`) and Java interop tests (`JavaInteropTest.java`) first, then the `Minigraf.kt` extensions and statics. +- **android**: a new `android/src/main/kotlin/.../Minigraf.kt` with the same Kotlin extensions as java (the Java statics are not needed on Android), and Android unit tests next to the existing ones, or a JVM test of the shared source if the module has none. The plan check: run `./gradlew test` in `android/`. +- **swift**: XCTest/`Tests/swift/main.swift` cases first, then `MinigrafKit+Prepared.swift` with `MinigrafBindable` and the extensions. `MiniGrafError.message` gains `.Api`. + +### Step 13 — consumer test +`consumer-test/` gains one prepared query executed twice, with a plain value and a typed value. + +### Step 14 — README, verify, raise +README section (typed and plain forms, lifetime rule). Run the binding's CI-equivalent locally where possible. Codex, PR, own CI. + +## PR 4 — Node and C + +### Step 15 — Node, tests first +Node tests first: repeated execution; every plain form, including the `number`/`bigint`/`2.0` rules; every typed form; `TypeError`s; `API-017`/`022`/`023`/`024`; `prepared.execute` after `db.close()` throws `[API-018] database is closed`; `db.close()` and then reopening the same path while a prepared handle is alive works. Then: `MiniGrafDb` gains `prepared: Mutex>>>>` (dead entries pruned on each `prepare`); `close()` empties every live slot before dropping the database; the `PreparedQuery` napi class; `index.d.ts`; consumer test; README. Check whether an open cursor or fact log blocks reopen after `close()` (spec §6). If it does, file an issue. + +### Step 16 — C, tests first +The C test program first, with the same cases in C form (bindings as JSON, `minigraf_prepared_last_error`). Then: `MiniGrafDb` gains the same weak list; `minigraf_close` empties it; `minigraf_prepare`, `minigraf_prepared_execute`, `minigraf_prepared_query`, `minigraf_prepared_last_error` and `minigraf_prepared_free`; the JSON bind reader (spec §4.2, C rules); regenerate `include/minigraf.h`; consumer test; README. Do the same cursor/fact-log reopen check as in step 15. + +## PR 5 — wasm + +### Step 17 +Bump the pin to PR 1's merge. Browser consumer test: one prepared query executed twice. README section. + +## Close-out + +### Step 18 +`ROADMAP.md` marks #181 done on `v3`. `CHANGELOG.md`'s `Added` lists prepared queries in every binding and `MiniGrafError::Api` (`Breaking changes`). Docs-site `content/tutorial-08-prepared-queries.md` gets an example per binding, and `content/upgrading-to-v3.md` gets `MiniGrafError::Api`. Move every binding's `v3` pin to the latest core `v3` with CI green. Close #181 by hand. From 5c138c4e90605222914aff6f4661c154c932a96e Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Sat, 24 Oct 2026 09:59:12 +0530 Subject: [PATCH 2/5] feat(prepared): bind mistakes are API-022/023/024; Entity and Val(Ref) interchangeable (#181) INT-033/034/035 are deprecated (kept registered). An entity slot takes Val(Ref), and value, expression and rule-argument slots take Entity, so a binding can pass a host UUID without knowing the slot's position. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Urda7FD9CYYoxdeGGJa11x --- docs/ERROR_REFERENCE.md | 54 ++++++++-- src/error.rs | 33 ++++++ src/query/datalog/prepared.rs | 43 ++++---- tests/cursor_test.rs | 2 +- tests/prepared_statements_test.rs | 160 ++++++++++++++++++++++++++++++ 5 files changed, 263 insertions(+), 29 deletions(-) diff --git a/docs/ERROR_REFERENCE.md b/docs/ERROR_REFERENCE.md index 8bd05bbadd..2f909a79a4 100644 --- a/docs/ERROR_REFERENCE.md +++ b/docs/ERROR_REFERENCE.md @@ -222,6 +222,9 @@ with no `CodedError` anywhere in its chain. | API-018 | Call on a closed binding object | Database API | | API-019 | Empty or inverted valid-time window | Database API | | API-020 | Assertion and retraction of one fact in one log-writer transaction | Database API | +| API-022 | Missing bind value for slot | Database API | +| API-023 | Bind slot not permitted in attribute position | Database API | +| API-024 | Bind slot type mismatch | 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 | @@ -255,9 +258,9 @@ with no `CodedError` anywhere in its chain. | 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-033 | Missing bind value for slot (deprecated) | Internal | +| INT-034 | Bind slot not permitted in attribute position (deprecated) | Internal | +| INT-035 | Bind slot type mismatch (deprecated) | 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 | @@ -280,7 +283,7 @@ with no `CodedError` anywhere in its chain. | INT-055 | Rule predicate disappeared during rollback | Internal | | INT-056 | Write to a read-only storage backend | Internal | -Deprecated codes: STG-003 and STG-004 (pre-v7 header sizes) are deprecated as of v3.0.0 and are no longer emitted, because formats v1–v6 are rejected with STG-028 before any header-size check. API-013 (checkpoint while a fact log is open) is deprecated as of v3.0.0 and is no longer emitted, because checkpoints run while fact logs are open. They stay registered and documented, and error codes are never removed or reused. +Deprecated codes: STG-003 and STG-004 (pre-v7 header sizes) are deprecated as of v3.0.0 and are no longer emitted, because formats v1–v6 are rejected with STG-028 before any header-size check. API-013 (checkpoint while a fact log is open) is deprecated as of v3.0.0 and is no longer emitted, because checkpoints run while fact logs are open. INT-033, INT-034 and INT-035 (bind-value mistakes) are deprecated as of v3.0.0 and are no longer emitted: the same mistakes are API-022, API-023 and API-024, since they are the caller's. They stay registered and documented, and error codes are never removed or reused. --- @@ -3370,6 +3373,40 @@ let mut log = src.fact_log(&FactFilter::new())?; **Scenario**: An offline purge copies a database migrated from v2.x through `fact_log()` and `LogWriter`, and one of its transactions retracted and re-asserted a fact. +### API-022 Missing bind value for slot + +**Error text**: `missing bind value for slot '${}'` + +**Cause**: A prepared query was executed (`PreparedQuery::execute` or `query`, or a binding's prepared handle) without a bind value for one of its `$slot`s. The `{}` names the slot. Nothing was read. Before v3.0.0 this was INT-033. + +**Resolution**: +- Pass a bind value for every `$slot` in the query. Bindings for names the query does not use are ignored, so a misspelt name shows up as this error. + +**Scenario**: A query is prepared with `$min-age` and executed with a binding named `min_age`. + +### API-023 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**: `prepare` was given a query with a `$slot` as the attribute of a pattern, at the top level or inside `not`, `not-join`, `or` or `or-join`. The plan depends on the attribute, so it cannot be a parameter. Before v3.0.0 this was INT-034. + +**Resolution**: +- Write the attribute as a keyword. Use bind slots for entities, values, expressions, rule arguments, `:as-of` and `:valid-at`. +- To choose between a few attributes at run time, prepare one query per attribute. + +**Scenario**: A search screen prepares `[?e $field ?v]` to search whichever field the user picked. + +### API-024 Bind slot type mismatch + +**Error text**: `slot '${}' in {} position requires {}, got {}` + +**Cause**: A bind value was of the wrong kind for the position of its slot: an entity position takes `Entity` or `Val(Ref)`; a value, expression or rule-argument position takes `Val` or `Entity`; `:as-of` takes `TxCount` or `Timestamp`; `:valid-at` takes `Timestamp` or `AnyValidTime`. The message names the slot, its position, the kinds it takes and the kind it got. Before v3.0.0 this was INT-035. + +**Resolution**: +- Pass the kind the position takes. `TxCount` and `Timestamp` are only for `:as-of`/`:valid-at`; a number compared in a pattern or expression is a `Val`. + +**Scenario**: `:as-of $tx` is bound to `Val(Integer(5))` instead of `TxCount(5)`. + --- ## INT — Internal Errors @@ -3815,7 +3852,8 @@ window function's row-number position overflowing). **Error text**: `missing bind value for slot '${}'` -**Cause**: `PreparedQuery::execute()` was called without supplying a bind +**Cause**: Deprecated since v3.0.0, and no longer emitted: the same mistake is +API-022. `PreparedQuery::execute()` was called without supplying a bind value for every `$slot` the prepared query declared. **Resolution**: @@ -3825,7 +3863,8 @@ value for every `$slot` the prepared query declared. **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 +**Cause**: Deprecated since v3.0.0, and no longer emitted: the same mistake is +API-023. 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. @@ -3838,7 +3877,8 @@ possible if the attribute itself is a runtime-bound parameter. **Error text**: `slot '${}' in {} position requires {}, got {}` -**Cause**: A bind value supplied to `PreparedQuery::execute()` was of the +**Cause**: Deprecated since v3.0.0, and no longer emitted: the same mistake is +API-024. 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 diff --git a/src/error.rs b/src/error.rs index 57a5d4294a..60207bf157 100644 --- a/src/error.rs +++ b/src/error.rs @@ -258,6 +258,9 @@ pub(crate) enum ErrorCode { Api018, Api019, Api020, + Api022, + Api023, + Api024, Int001, Int002, Int003, @@ -290,8 +293,14 @@ pub(crate) enum ErrorCode { Int030, Int031, Int032, + // INT-033/034/035 are deprecated since v3.0.0: a bind mistake is the + // caller's, so it is API-022/023/024 (#181). Kept so the codes are never + // reused. + #[allow(dead_code)] Int033, + #[allow(dead_code)] Int034, + #[allow(dead_code)] Int035, Int036, Int037, @@ -1533,6 +1542,24 @@ pub(crate) const REGISTRY: &[(ErrorCode, &str, &str, ErrorCategory)] = &[ "one transaction both asserts and retracts the same value of {}; keep only the record that decides it", ErrorCategory::Api, ), + ( + ErrorCode::Api022, + "API-022", + "missing bind value for slot '${}'", + ErrorCategory::Api, + ), + ( + ErrorCode::Api023, + "API-023", + "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::Api, + ), + ( + ErrorCode::Api024, + "API-024", + "slot '${}' in {} position requires {}, got {}", + ErrorCategory::Api, + ), ( ErrorCode::Int001, "INT-001", @@ -2357,6 +2384,9 @@ mod tests { | ErrorCode::Api018 | ErrorCode::Api019 | ErrorCode::Api020 + | ErrorCode::Api022 + | ErrorCode::Api023 + | ErrorCode::Api024 | ErrorCode::Int001 | ErrorCode::Int002 | ErrorCode::Int003 @@ -2619,6 +2649,9 @@ mod tests { ErrorCode::Api018, ErrorCode::Api019, ErrorCode::Api020, + ErrorCode::Api022, + ErrorCode::Api023, + ErrorCode::Api024, ErrorCode::Int001, ErrorCode::Int002, ErrorCode::Int003, diff --git a/src/query/datalog/prepared.rs b/src/query/datalog/prepared.rs index 5108230b79..434d97d0fe 100644 --- a/src/query/datalog/prepared.rs +++ b/src/query/datalog/prepared.rs @@ -22,16 +22,15 @@ use uuid::Uuid; /// /// | Variant | Use in query | /// |---------|-------------| -/// | `Entity` | entity position: `[$slot :attr ?v]` | -/// | `Val` | value position: `[?e :attr $slot]`, expressions | +/// | `Entity` | entity position: `[$slot :attr ?v]`; also a value, expression or rule-argument position, as `Val(Value::Ref(uuid))` | +/// | `Val` | value position: `[?e :attr $slot]`, expressions, rule arguments; `Val(Value::Ref(uuid))` also fills an entity position | /// | `TxCount` | `:as-of $slot` (monotonic counter) | /// | `Timestamp` | `:as-of $slot` (wall-clock ms) or `:valid-at $slot` | /// | `AnyValidTime` | `:valid-at $slot` — disables valid-time filter | #[derive(Debug, Clone)] pub enum BindValue { - /// Fill an entity position `[$slot :attr ?v]` with a UUID. - /// - /// Not valid in rule-invocation argument positions — use `Val(Value::Ref(uuid))` there. + /// Fill an entity position `[$slot :attr ?v]` with a UUID. In a value, + /// expression or rule-argument position it is `Val(Value::Ref(uuid))`. Entity(Uuid), /// Fill a value position `[?e :attr $slot]` or an expression literal. Val(Value), @@ -147,7 +146,7 @@ impl PreparedQuery { for name in &self.slot_names { if !binding_map.contains_key(name.as_str()) { - bail_coded!(ErrorCode::Int033, name); + bail_coded!(ErrorCode::Api022, name); } } @@ -196,7 +195,7 @@ fn validate_clauses_no_attr_slots(clauses: &[WhereClause]) -> Result<()> { match clause { WhereClause::Pattern(p) => { if let AttributeSpec::Real(EdnValue::BindSlot(name)) = &p.attribute { - bail_coded!(ErrorCode::Int034, name); + bail_coded!(ErrorCode::Api023, name); } } WhereClause::Not(inner) => validate_clauses_no_attr_slots(inner)?, @@ -416,43 +415,45 @@ 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(BindValue::Entity(u) | BindValue::Val(Value::Ref(u))) => Ok(EdnValue::Uuid(*u)), Some(other) => bail_coded!( - ErrorCode::Int035, + ErrorCode::Api024, name, "entity", - "Entity", + "Entity or Val(Ref)", bind_value_type_name(other) ), - None => bail_coded!(ErrorCode::Int033, name), + None => bail_coded!(ErrorCode::Api022, 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(BindValue::Entity(u)) => Ok(EdnValue::Uuid(*u)), Some(other) => bail_coded!( - ErrorCode::Int035, + ErrorCode::Api024, name, "value", - "Val", + "Val or Entity", bind_value_type_name(other) ), - None => bail_coded!(ErrorCode::Int033, name), + None => bail_coded!(ErrorCode::Api022, name), } } fn resolve_val_slot(name: &str, bindings: &HashMap<&str, &BindValue>) -> Result { match bindings.get(name) { Some(BindValue::Val(v)) => Ok(v.clone()), + Some(BindValue::Entity(u)) => Ok(Value::Ref(*u)), Some(other) => bail_coded!( - ErrorCode::Int035, + ErrorCode::Api024, name, "expression", - "Val", + "Val or Entity", bind_value_type_name(other) ), - None => bail_coded!(ErrorCode::Int033, name), + None => bail_coded!(ErrorCode::Api022, name), } } @@ -461,13 +462,13 @@ fn resolve_as_of_slot(name: &str, bindings: &HashMap<&str, &BindValue>) -> Resul Some(BindValue::TxCount(n)) => Ok(AsOf::Counter(*n)), Some(BindValue::Timestamp(t)) => Ok(AsOf::Timestamp(*t)), Some(other) => bail_coded!( - ErrorCode::Int035, + ErrorCode::Api024, name, ":as-of", "TxCount or Timestamp", bind_value_type_name(other) ), - None => bail_coded!(ErrorCode::Int033, name), + None => bail_coded!(ErrorCode::Api022, name), } } @@ -476,13 +477,13 @@ fn resolve_valid_at_slot(name: &str, bindings: &HashMap<&str, &BindValue>) -> Re Some(BindValue::Timestamp(t)) => Ok(ValidAt::Timestamp(*t)), Some(BindValue::AnyValidTime) => Ok(ValidAt::AnyValidTime), Some(other) => bail_coded!( - ErrorCode::Int035, + ErrorCode::Api024, name, ":valid-at", "Timestamp or AnyValidTime", bind_value_type_name(other) ), - None => bail_coded!(ErrorCode::Int033, name), + None => bail_coded!(ErrorCode::Api022, name), } } diff --git a/tests/cursor_test.rs b/tests/cursor_test.rs index de322e43c9..b6cdbdea13 100644 --- a/tests/cursor_test.rs +++ b/tests/cursor_test.rs @@ -256,7 +256,7 @@ fn prepared_query_cursor_matches_prepared_execute() { assert_eq!(drain(&mut cursor, 1), expected); } let err = pq.query(&[]).unwrap_err(); - assert_eq!(err.code(), "INT-033", "missing bind value"); + assert_eq!(err.code(), "API-022", "missing bind value"); } #[test] diff --git a/tests/prepared_statements_test.rs b/tests/prepared_statements_test.rs index a8795e5779..a8aa61f09b 100644 --- a/tests/prepared_statements_test.rs +++ b/tests/prepared_statements_test.rs @@ -506,3 +506,163 @@ fn prepared_literal_as_of_and_valid_at_are_kept() { 2 ); } + +// ─── Bind mistakes are API errors (#181) ───────────────────────────────────── + +/// The error of `execute` and of `query` with `binds`, which must be the same code. +fn bind_error( + pq: &minigraf::PreparedQuery, + binds: &[(&str, BindValue)], +) -> minigraf::MinigrafError { + let exec = pq + .execute(binds) + .expect_err("execute must reject the bindings"); + let cursor = pq.query(binds).expect_err("query must reject the bindings"); + assert_eq!(exec.code(), cursor.code(), "execute and query disagree"); + exec +} + +#[test] +fn missing_bind_value_is_api_022_in_every_position() { + let db = Minigraf::in_memory().unwrap(); + db.execute("(transact [[:a :n 1] [:a :m 2]])").unwrap(); + db.execute("(rule [(has-n ?e ?v) [?e :n ?v]])").unwrap(); + for q in [ + "(query [:find ?v :where [$e :n ?v]])", + "(query [:find ?e :where [?e :n $v]])", + "(query [:find ?v :where [?e :n ?v] [(> ?v $t)]])", + "(query [:find ?e :where (has-n ?e $v)])", + "(query [:find ?v :as-of $tx :where [?e :n ?v]])", + "(query [:find ?v :valid-at $d :where [?e :n ?v]])", + "(query [:find ?e :where [?e :n ?v] (not [?e :m $v])])", + "(query [:find ?e :where [?e :n ?v] (not-join [?e] [?e :m $v])])", + "(query [:find ?e :where (or [?e :n $v] [?e :m $v])])", + "(query [:find ?e :where [?e :n ?w] (or-join [?e] [?e :n $v] [?e :m $v])])", + ] { + let pq = db.prepare(q).expect("prepare"); + let err = bind_error(&pq, &[]); + assert_eq!(err.code(), "API-022", "missing bind value"); + assert_eq!(err.category(), minigraf::ErrorCategory::Api); + } +} + +#[test] +fn attribute_slot_is_api_023_in_every_clause() { + let db = Minigraf::in_memory().unwrap(); + for q in [ + "(query [:find ?v :where [?e $a ?v]])", + "(query [:find ?e :where [?e :n ?v] (not [?e $a ?v])])", + "(query [:find ?e :where [?e :n ?v] (not-join [?e] [?e $a 1])])", + "(query [:find ?e :where (or [?e $a 1] [?e :m 1])])", + "(query [:find ?e :where [?e :n ?w] (or-join [?e] [?e :n 1] [?e $a 1])])", + ] { + let err = db.prepare(q).expect_err("attribute slot must be rejected"); + assert_eq!(err.code(), "API-023", "attribute slot"); + assert_eq!(err.category(), minigraf::ErrorCategory::Api); + } +} + +#[test] +fn bind_value_of_the_wrong_kind_is_api_024_for_every_slot_kind() { + let db = Minigraf::in_memory().unwrap(); + db.execute("(transact [[:a :n 1]])").unwrap(); + for (q, slot, bind, position) in [ + ( + "(query [:find ?v :where [$e :n ?v]])", + "e", + BindValue::TxCount(1), + "entity", + ), + ( + "(query [:find ?e :where [?e :n $v]])", + "v", + BindValue::Timestamp(1), + "value", + ), + ( + "(query [:find ?v :where [?e :n ?v] [(> ?v $t)]])", + "t", + BindValue::AnyValidTime, + "expression", + ), + ( + "(query [:find ?v :as-of $tx :where [?e :n ?v]])", + "tx", + BindValue::Val(Value::Integer(1)), + ":as-of", + ), + ( + "(query [:find ?v :valid-at $d :where [?e :n ?v]])", + "d", + BindValue::TxCount(1), + ":valid-at", + ), + ] { + let pq = db.prepare(q).expect("prepare"); + let err = bind_error(&pq, &[(slot, bind)]); + assert_eq!(err.code(), "API-024", "wrong kind of bind value"); + assert_eq!(err.category(), minigraf::ErrorCategory::Api); + let text = err.to_string(); + assert!( + text.contains(&format!("'${slot}'")), + "message names the slot" + ); + assert!( + text.contains(&format!("{position} position")), + "message names the position" + ); + } +} + +// ─── Entity and Val(Ref) are interchangeable (#181) ────────────────────────── + +fn rows(r: QueryResult) -> Vec> { + match r { + QueryResult::QueryResults { mut results, .. } => { + results.sort(); + results + } + _ => panic!("expected QueryResults"), + } +} + +#[test] +fn entity_and_ref_bind_values_fit_each_others_slots() { + let db = Minigraf::in_memory().unwrap(); + let alice = Uuid::new_v5(&Uuid::NAMESPACE_OID, b":alice"); + let bob = Uuid::new_v5(&Uuid::NAMESPACE_OID, b":bob"); + // Friends are stored as refs, so the expression `=` (which compares + // values, unlike a pattern) sees a `Ref` on both sides. + db.execute(&format!( + r#"(transact [[:alice :person/name "Alice"] [:bob :person/name "Bob"] + [:alice :person/friend #uuid "{bob}"] [:carol :person/friend #uuid "{alice}"]])"# + )) + .unwrap(); + db.execute("(rule [(friend-of ?x ?f) [?x :person/friend ?f]])") + .unwrap(); + + for (q, u) in [ + ( + "(query [:find ?name :where [$f :person/name ?name]])", + alice, + ), + ("(query [:find ?x :where [?x :person/friend $f]])", bob), + ("(query [:find ?x :where (friend-of ?x $f)])", bob), + ( + "(query [:find ?x :where [?x :person/friend ?g] [(= ?g $f)]])", + bob, + ), + ] { + let pq = db.prepare(q).expect("prepare"); + let as_entity = rows(pq.execute(&[("f", BindValue::Entity(u))]).unwrap()); + let as_ref = rows(pq.execute(&[("f", BindValue::Val(Value::Ref(u)))]).unwrap()); + assert_eq!(as_entity.len(), 1, "one row"); + assert_eq!(as_entity, as_ref, "Entity and Val(Ref) give the same rows"); + } + + let pq = db + .prepare("(query [:find ?name :where [$f :person/name ?name]])") + .unwrap(); + let err = bind_error(&pq, &[("f", BindValue::Val(Value::Integer(1)))]); + assert_eq!(err.code(), "API-024", "an integer is not an entity"); +} From 4de38c2829c773a5bbc7278b915894c91138c012 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Sat, 24 Oct 2026 10:05:39 +0530 Subject: [PATCH 3/5] feat(browser): BrowserDb.prepare and BrowserPreparedQuery (#181) Bindings are a JS object of slot name to a plain value (boolean, number, bigint, string, null) or a typed {type, value} form. A JS value that is not a bind value is a TypeError; a typed value that does not fit its type is API-017. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Urda7FD9CYYoxdeGGJa11x --- src/browser/binds.rs | 159 +++++++++++++++++++ src/browser/mod.rs | 354 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 513 insertions(+) create mode 100644 src/browser/binds.rs diff --git a/src/browser/binds.rs b/src/browser/binds.rs new file mode 100644 index 0000000000..fa771e9fad --- /dev/null +++ b/src/browser/binds.rs @@ -0,0 +1,159 @@ +//! Bind values from JavaScript for `BrowserPreparedQuery` (#181). +//! +//! A binding is a plain value or a typed form `{ type, value }`: +//! +//! | JavaScript | Bind value | +//! |---|---| +//! | `true` / `false` | `Val(Boolean)` | +//! | a `number` that `Number.isInteger` accepts, a `bigint` | `Val(Integer)` | +//! | any other `number` | `Val(Float)` | +//! | a `string` | `Val(String)` | +//! | `null` | `Val(Null)` | +//! | `{ type: 'string' \| 'integer' \| 'float' \| 'boolean' \| 'ref' \| 'keyword' \| 'null', value }` | `Val` of that type | +//! | `{ type: 'entity', value: uuid }` | `Entity` | +//! | `{ type: 'txCount', value }` | `TxCount` (an integer `>= 0`) | +//! | `{ type: 'timestamp', value }` | `Timestamp` (Unix ms) | +//! | `{ type: 'anyValidTime' }` | `AnyValidTime` | +//! +//! Any other JavaScript value is a `TypeError`. A typed form whose value does +//! not fit its type (a bad UUID, a negative tx count, an integer outside +//! `i64`) is `API-017`. + +use crate::MinigrafError; +use crate::graph::types::Value; +use crate::query::datalog::prepared::BindValue; +use js_sys::{Array, Number, Object, Reflect}; +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +/// The bindings object `bindings` as `(slot name, bind value)` pairs. +/// `undefined` and `null` mean no bindings. +pub(super) fn read_bindings(bindings: &JsValue) -> Result, JsValue> { + if bindings.is_undefined() || bindings.is_null() { + return Ok(Vec::new()); + } + let Some(object) = bindings + .dyn_ref::() + .filter(|_| !Array::is_array(bindings)) + else { + return Err(type_error( + "bindings must be an object of slot name to bind value", + )); + }; + Object::entries(object) + .iter() + .map(|entry| { + let pair: Array = entry.unchecked_into(); + let name = pair.get(0).as_string().unwrap_or_default(); + let value = read_bind_value(&name, &pair.get(1))?; + Ok((name, value)) + }) + .collect() +} + +fn read_bind_value(name: &str, v: &JsValue) -> Result { + if let Some(b) = v.as_bool() { + return Ok(BindValue::Val(Value::Boolean(b))); + } + if v.is_null() { + return Ok(BindValue::Val(Value::Null)); + } + if let Some(s) = v.as_string() { + return Ok(BindValue::Val(Value::String(s))); + } + if v.is_bigint() || v.as_f64().is_some() { + return Ok(BindValue::Val(number(name, v)?)); + } + if v.is_object() + && !Array::is_array(v) + && let Some(kind) = Reflect::get(v, &JsValue::from_str("type"))?.as_string() + && let Some(bind) = read_typed(name, &kind, v)? + { + return Ok(bind); + } + Err(type_error(&format!( + "slot ${name}: a bind value is a boolean, number, bigint, string, null or {{type, value}} object" + ))) +} + +/// A typed form, or `None` if `kind` names no type. +fn read_typed(name: &str, kind: &str, v: &JsValue) -> Result, JsValue> { + let value = Reflect::get(v, &JsValue::from_str("value"))?; + let what = || format!("slot ${name} of type {kind:?}"); + let string = || value.as_string().ok_or_else(|| mismatch(&what())); + Ok(Some(match kind { + "string" => BindValue::Val(Value::String(string()?)), + "keyword" => BindValue::Val(Value::Keyword(string()?)), + "boolean" => BindValue::Val(Value::Boolean( + value.as_bool().ok_or_else(|| mismatch(&what()))?, + )), + "integer" => BindValue::Val(Value::Integer(integer(&what(), &value)?)), + "float" => BindValue::Val(Value::Float( + value.as_f64().ok_or_else(|| mismatch(&what()))?, + )), + "null" => BindValue::Val(Value::Null), + "ref" => BindValue::Val(Value::Ref(uuid(&what(), &string()?)?)), + "entity" => BindValue::Entity(uuid(&what(), &string()?)?), + "txCount" => { + let n = integer(&what(), &value)?; + BindValue::TxCount( + u64::try_from(n).map_err(|_| invalid(&format!("{} {n} is negative", what())))?, + ) + } + "timestamp" => BindValue::Timestamp(integer(&what(), &value)?), + "anyValidTime" => BindValue::AnyValidTime, + _ => return Ok(None), + })) +} + +/// A plain `number` or `bigint`: an integer when it is whole, else a float. +fn number(name: &str, v: &JsValue) -> Result { + if v.is_bigint() || Number::is_integer(v) { + integer(&format!("slot ${name}"), v).map(Value::Integer) + } else { + Ok(Value::Float(v.as_f64().unwrap_or(f64::NAN))) + } +} + +/// A `bigint`, or a `number` that is a whole number, as an `i64`. +fn integer(what: &str, v: &JsValue) -> Result { + if v.is_bigint() { + return i64::try_from(v.clone()) + .map_err(|_| invalid(&format!("{what}: {} is outside i64", big_text(v)))); + } + // -2^63 is exact as an f64, and 2^63 is the first whole f64 past i64::MAX. + const RANGE: std::ops::Range = (i64::MIN as f64)..-(i64::MIN as f64); + match v.as_f64() { + Some(f) if Number::is_integer(v) && RANGE.contains(&f) => { + // Whole and in range, so the cast is exact. + #[allow(clippy::cast_possible_truncation)] + Ok(f as i64) + } + Some(f) if Number::is_integer(v) => Err(invalid(&format!("{what}: {f} is outside i64"))), + _ => Err(mismatch(what)), + } +} + +fn big_text(v: &JsValue) -> String { + js_sys::BigInt::from(v.clone()) + .to_string(10) + .map(String::from) + .unwrap_or_default() +} + +fn uuid(what: &str, s: &str) -> Result { + uuid::Uuid::parse_str(s).map_err(|_| invalid(&format!("{what}: {s:?} is not a UUID"))) +} + +fn mismatch(what: &str) -> JsValue { + invalid(&format!("{what}: the value does not match the type")) +} + +/// `API-017`, as the native bindings report a bad argument. +fn invalid(msg: &str) -> JsValue { + JsValue::from_str(&MinigrafError::invalid_argument(msg).to_string()) +} + +fn type_error(msg: &str) -> JsValue { + js_sys::TypeError::new(msg).into() +} diff --git a/src/browser/mod.rs b/src/browser/mod.rs index df063a45b9..5041b78116 100644 --- a/src/browser/mod.rs +++ b/src/browser/mod.rs @@ -4,6 +4,8 @@ //! feature enabled. It is **not** compatible with Node.js, Deno, Bun, or any //! server-side runtime. For server-side Node.js, use `@minigraf/node` (Phase 8.3). +/// Bind values read from JavaScript for prepared queries. +mod binds; /// Synchronous in-memory page buffer with dirty-page tracking. pub mod buffer; /// Async IndexedDB backend for browser WASM persistence. @@ -15,6 +17,7 @@ use crate::graph::FactStorage; use crate::query::datalog::executor::{DatalogExecutor, QueryResult}; use crate::query::datalog::functions::FunctionRegistry; use crate::query::datalog::parser::parse_datalog_command; +use crate::query::datalog::prepared::{BindValue, PreparedQuery}; use crate::query::datalog::rules::RuleRegistry; use crate::query::datalog::types::DatalogCommand; use crate::storage::persistent_facts::PersistentFactStorage; @@ -166,6 +169,27 @@ impl BrowserDb { }) } + /// Parse and validate a `(query ...)` once, for running many times with + /// different bind values in its `$name` slots. + /// + /// Synchronous. Throws `[API-005]`/`[API-006]`/`[API-007]` for a + /// `transact`, `retract` or `rule`, and `[API-023]` for a slot in an + /// attribute position. + /// + /// ```js + /// const pq = db.prepare('(query [:find ?name :where [?e :age $age] [?e :name ?name]])'); + /// const thirty = JSON.parse(pq.execute({ age: 30 })).results; + /// const forty = JSON.parse(pq.execute({ age: 40n })).results; + /// ``` + #[wasm_bindgen(js_name = prepare)] + pub fn prepare(&self, datalog: &str) -> Result { + let query = self.prepare_inner(datalog).map_err(to_js_error)?; + Ok(BrowserPreparedQuery { + _db: self.inner.clone(), + query, + }) + } + /// Flush all dirty pages to IndexedDB. /// /// Write-through means individual `execute()` calls already flush dirty pages, @@ -283,6 +307,29 @@ impl BrowserDb { } impl BrowserDb { + fn prepare_inner(&self, datalog: &str) -> anyhow::Result { + use crate::error::{ErrorCode, bail_coded}; + + let query = match parse_datalog_command(datalog)? { + DatalogCommand::Query(q) => q, + DatalogCommand::Transact(_) => bail_coded!(ErrorCode::Api005), + DatalogCommand::Retract(_) => bail_coded!(ErrorCode::Api006), + DatalogCommand::Rule(_) => bail_coded!(ErrorCode::Api007), + }; + let inner = self.inner.borrow(); + // The limits `query` runs with (`DatalogExecutor`'s defaults). + crate::query::datalog::prepared::prepare_query( + query, + inner.fact_storage.clone(), + inner.rules.clone(), + inner.functions.clone(), + ( + crate::query::datalog::evaluator::DEFAULT_MAX_DERIVED_FACTS, + usize::MAX, + ), + ) + } + fn query_inner(&self, datalog: &str) -> anyhow::Result { use crate::error::{ErrorCode, bail_coded}; @@ -431,6 +478,61 @@ impl BrowserCursor { } } +// ── BrowserPreparedQuery ──────────────────────────────────────────────────── + +/// A query parsed once by `BrowserDb.prepare`, run with bind values. +/// +/// Bindings are an object of slot name (without the `$`) to bind value: a +/// boolean, a `number` (an integer when `Number.isInteger`, else a float), a +/// `bigint`, a string, `null`, or a typed `{ type, value }` form for a float +/// with no fractional part, a keyword, a ref, an entity, a `txCount`, a +/// `timestamp` or `anyValidTime`. Names the query does not use are ignored. +/// +/// It keeps its database open, and each run reads the database as it is then. +#[wasm_bindgen] +pub struct BrowserPreparedQuery { + /// Keeps the database alive while the prepared query is. + _db: Rc>, + query: PreparedQuery, +} + +#[wasm_bindgen] +impl BrowserPreparedQuery { + /// Run the query with `bindings` and return its result as JSON, encoded + /// like `BrowserDb.execute`'s. Throws a `TypeError` for a binding that is + /// not a bind value, `[API-017]` for a typed value that does not fit its + /// type, `[API-022]` for a missing slot and `[API-024]` for a bind value + /// of the wrong kind. + pub fn execute(&self, bindings: JsValue) -> Result { + let binds = binds::read_bindings(&bindings)?; + self.query + .execute(&as_slice(&binds)) + .map(query_result_to_json) + .map_err(|e| JsValue::from_str(&e.to_string())) + } + + /// Run the query with `bindings` and return a cursor over its rows. The + /// answer is fixed when the cursor opens. Throws as `execute` does. + pub fn query(&self, bindings: JsValue) -> Result { + let binds = binds::read_bindings(&bindings)?; + let cursor = self + .query + .query(&as_slice(&binds)) + .map_err(|e| JsValue::from_str(&e.to_string()))?; + Ok(BrowserCursor { + vars: cursor.vars().to_vec(), + cursor: Some(cursor), + }) + } +} + +fn as_slice(binds: &[(String, BindValue)]) -> Vec<(&str, BindValue)> { + binds + .iter() + .map(|(name, value)| (name.as_str(), value.clone())) + .collect() +} + /// The bytes of every page the last `save()` dirtied, clearing the dirty set. /// A page that cannot be read is an error, never a page silently left out of /// the flush to IndexedDB. @@ -1093,3 +1195,255 @@ mod tests { assert_eq!(count(&db, "(query [:find ?s :where [?e :s ?s]])").await, 0); } } + +#[cfg(all(target_arch = "wasm32", feature = "browser", test))] +mod prepared_tests { + use super::*; + use js_sys::{BigInt, Object, Reflect}; + use wasm_bindgen_test::*; + + wasm_bindgen_test_configure!(run_in_browser); + + /// A JS object with `pairs` as its properties. + fn obj(pairs: &[(&str, JsValue)]) -> JsValue { + let o = Object::new(); + for (k, v) in pairs { + Reflect::set(&o, &JsValue::from_str(k), v).expect("set"); + } + o.into() + } + + /// A typed bind value `{type, value}`. + fn typed(kind: &str, value: Option) -> JsValue { + let mut pairs = vec![("type", JsValue::from_str(kind))]; + if let Some(v) = value { + pairs.push(("value", v)); + } + obj(&pairs) + } + + /// The result rows of a prepared execution. + fn rows(json: &str) -> Vec { + let v: serde_json::Value = serde_json::from_str(json).expect("json"); + v["results"].as_array().expect("results").clone() + } + + fn rejection(r: Result) -> JsValue { + r.expect_err("must reject") + } + + fn starts_with(e: &JsValue, code: &str) -> bool { + e.as_string().is_some_and(|s| s.starts_with(code)) + } + + async fn seeded() -> BrowserDb { + let db = BrowserDb::open_in_memory().expect("open_in_memory"); + db.execute( + r#"(transact [[:a :n 1] [:b :n 2] [:c :n 3] + [:a :s "x"] [:a :f 2.0] [:a :t true] [:a :k :kw] [:a :z nil]])"# + .to_string(), + ) + .await + .expect("transact"); + db + } + + #[wasm_bindgen_test] + async fn prepared_query_runs_again_with_new_bindings() { + let db = seeded().await; + let pq = db + .prepare("(query [:find ?e :where [?e :n $n]])") + .expect("prepare"); + for n in [1.0, 2.0, 3.0] { + let r = pq + .execute(obj(&[("n", JsValue::from_f64(n))])) + .expect("execute"); + assert_eq!(rows(&r).len(), 1, "one entity per value"); + } + let r = pq + .execute(obj(&[("n", JsValue::from_f64(9.0))])) + .expect("execute"); + assert!(rows(&r).is_empty(), "no entity has 9"); + } + + #[wasm_bindgen_test] + async fn every_plain_value_binds() { + let db = seeded().await; + for (attr, value) in [ + (":n", JsValue::from_f64(1.0)), + (":n", BigInt::from(1i64).into()), + (":f", typed("float", Some(JsValue::from_f64(2.0)))), + (":s", JsValue::from_str("x")), + (":t", JsValue::TRUE), + (":z", JsValue::NULL), + ] { + let pq = db + .prepare(&format!("(query [:find ?e :where [?e {attr} $v]])")) + .expect("prepare"); + let r = pq.execute(obj(&[("v", value)])).expect("execute"); + assert_eq!(rows(&r).len(), 1, "the plain or typed value matches"); + } + // A whole-number `number` is an integer, so it does not match the float. + let pq = db + .prepare("(query [:find ?e :where [?e :f $v]])") + .expect("prepare"); + let r = pq + .execute(obj(&[("v", JsValue::from_f64(2.0))])) + .expect("execute"); + assert!(rows(&r).is_empty(), "2 binds an integer"); + let r = pq + .execute(obj(&[("v", JsValue::from_f64(2.5))])) + .expect("execute"); + assert!(rows(&r).is_empty(), "2.5 binds a float that is not stored"); + } + + #[wasm_bindgen_test] + async fn every_typed_value_binds() { + let db = seeded().await; + let a = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, b":a").to_string(); + for (q, value) in [ + ( + "(query [:find ?e :where [?e :n $v]])", + typed("integer", Some(BigInt::from(1i64).into())), + ), + ( + "(query [:find ?e :where [?e :n $v]])", + typed("integer", Some(JsValue::from_f64(1.0))), + ), + ( + "(query [:find ?e :where [?e :s $v]])", + typed("string", Some("x".into())), + ), + ( + "(query [:find ?e :where [?e :t $v]])", + typed("boolean", Some(JsValue::TRUE)), + ), + ( + "(query [:find ?e :where [?e :k $v]])", + typed("keyword", Some(":kw".into())), + ), + ("(query [:find ?e :where [?e :z $v]])", typed("null", None)), + ( + "(query [:find ?x :where [$v :n ?x]])", + typed("entity", Some(a.as_str().into())), + ), + ( + "(query [:find ?x :where [$v :n ?x]])", + typed("ref", Some(a.as_str().into())), + ), + ( + "(query [:find ?x :as-of $v :where [?e :n ?x]])", + typed("txCount", Some(BigInt::from(1i64).into())), + ), + ( + "(query [:find ?x :as-of $v :where [?e :n ?x]])", + typed("txCount", Some(JsValue::from_f64(1.0))), + ), + ( + "(query [:find ?x :valid-at $v :where [:a :n ?x]])", + typed("timestamp", Some(JsValue::from_f64(js_sys::Date::now()))), + ), + ( + "(query [:find ?x :valid-at $v :where [:a :n ?x]])", + typed("anyValidTime", None), + ), + ] { + let pq = db.prepare(q).expect("prepare"); + let r = pq.execute(obj(&[("v", value)])).expect("execute"); + assert!(!rows(&r).is_empty(), "the typed value matches"); + } + } + + #[wasm_bindgen_test] + async fn prepared_cursor_matches_execute() { + let db = seeded().await; + let pq = db + .prepare("(query [:find ?e ?n :where [?e :n ?n] [(>= ?n $min)]])") + .expect("prepare"); + let binds = obj(&[("min", JsValue::from_f64(2.0))]); + let all = rows(&pq.execute(binds.clone()).expect("execute")); + let mut cursor = pq.query(binds).expect("query"); + assert_eq!(cursor.vars(), vec!["?e".to_string(), "?n".to_string()]); + let mut seen = 0; + while let Some(batch) = cursor.next_batch(1).expect("batch") { + seen += serde_json::from_str::>(&batch) + .expect("rows") + .len(); + } + assert_eq!(seen, all.len(), "the cursor returns every row"); + assert_eq!(seen, 2); + } + + #[wasm_bindgen_test] + async fn bad_bindings_are_rejected() { + let db = seeded().await; + let pq = db + .prepare("(query [:find ?e :where [?e :n $n]])") + .expect("prepare"); + for bad in [JsValue::UNDEFINED, obj(&[("type", "nonsense".into())])] { + let e = rejection(pq.execute(obj(&[("n", bad)]))); + assert!(e.is_instance_of::(), "a TypeError"); + } + let e = rejection(pq.execute(JsValue::from_f64(1.0))); + assert!( + e.is_instance_of::(), + "bindings must be an object" + ); + + let entity = db + .prepare("(query [:find ?x :where [$e :n ?x]])") + .expect("prepare"); + let e = + rejection(entity.execute(obj(&[("e", typed("entity", Some("not-a-uuid".into())))]))); + assert!(starts_with(&e, "[API-017] "), "a bad UUID is API-017"); + + let as_of = db + .prepare("(query [:find ?x :as-of $t :where [?e :n ?x]])") + .expect("prepare"); + let e = rejection(as_of.execute(obj(&[( + "t", + typed("txCount", Some(JsValue::from_f64(-1.0))), + )]))); + assert!( + starts_with(&e, "[API-017] "), + "a negative tx count is API-017" + ); + + let e = rejection(pq.execute(obj(&[]))); + assert!(starts_with(&e, "[API-022] "), "a missing slot is API-022"); + let e = pq + .query(obj(&[])) + .map(|_| ()) + .expect_err("query must reject too"); + assert!(starts_with(&e, "[API-022] "), "a missing slot is API-022"); + + let e = db + .prepare("(query [:find ?v :where [?e $a ?v]])") + .map(|_| ()) + .expect_err("attribute slot"); + assert!( + starts_with(&e, "[API-023] "), + "an attribute slot is API-023" + ); + + let e = db + .prepare("(transact [[:a :n 1]])") + .map(|_| ()) + .expect_err("not a query"); + assert!(starts_with(&e, "[API-005] "), "transact is not preparable"); + } + + #[wasm_bindgen_test] + async fn prepared_query_sees_later_writes() { + let db = seeded().await; + let pq = db + .prepare("(query [:find ?e :where [?e :n $n]])") + .expect("prepare"); + let binds = obj(&[("n", JsValue::from_f64(4.0))]); + assert!(rows(&pq.execute(binds.clone()).expect("execute")).is_empty()); + db.execute("(transact [[:d :n 4]])".to_string()) + .await + .expect("transact"); + assert_eq!(rows(&pq.execute(binds).expect("execute")).len(), 1); + } +} From b2f68553aecec89283fecda26a424a101b0e295c Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Sat, 24 Oct 2026 13:06:44 +0530 Subject: [PATCH 4/5] =?UTF-8?q?docs:=20#181=20core=20=E2=80=94=20CHANGELOG?= =?UTF-8?q?,=20ROADMAP,=20CLAUDE.md,=20test=20coverage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Urda7FD9CYYoxdeGGJa11x --- CHANGELOG.md | 3 +++ CLAUDE.md | 6 +++--- ROADMAP.md | 2 +- docs/TEST_COVERAGE.md | 10 ++++++---- 4 files changed, 13 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ca142f693..ecc2781d04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **A fact a rule derives has no metadata** (#548). `:db/valid-from`, `:db/valid-to`, `:db/tx-count` and `:db/tx-id` read from a derived fact (`(reach ?x ?y) [?x :reach ?y] [?x :db/tx-count ?c]`) now bind `nil`, and a constant (`[?x :db/tx-count 1]`) never matches one; a stored fact with the same attribute keeps its own. They used to bind the rule evaluator's working values: the time the query ran, forever, and a counter of its own. `:db/valid-at` still binds the query's valid time. - **A `not` or nested `or` inside an `or` branch sees a variable an expression of the branch binds** (#551). The executor applied a branch's patterns, then its nested `or`s, then its `not`s, then its expressions, so a `not` or nested `or` reading a variable that only an expression of the branch binds saw it unbound. A branch now runs in the order a `:where` does (#625), and the `not` sees the binding. For example, over `[:x :n 1] [:y :n 2] [:z :n 5]`, `[:find ?e :where [?e :n ?v] (or-join [?e ?v] (and [(+ ?v 1) ?w] (not [?f :n ?w])) [?e :n 5])]` returned `:z` (the `not` matched any fact, so the first branch kept no row) and now returns `:y` and `:z`. Only such branches change. - **An unknown predicate is an error when the query opens, wherever it is** (#551). Every predicate a query names, in an `or` branch (of the query or of a rule it evaluates) or a `not` / `not-join` body, is now looked up when the query opens, as top-level predicates and `:find` functions already were (#414): an unknown one fails with `QRY-007` whatever the data. Before, the executor looked it up only when a row reached it. In an `or` branch, a query whose rows never reached the predicate returned an answer, and now fails. In a `not` / `not-join` body the failure was swallowed: the body had no row, so the `not` kept every outer row and the query returned a wrong answer instead of an error. +- **Bind-value mistakes are `API` errors** (#181). A missing bind value, a bind slot in an attribute position and a bind value of the wrong kind for its slot were `INT-033`, `INT-034` and `INT-035`, codes for internal faults, although each is the caller's mistake. They are now `API-022`, `API-023` and `API-024`, with the same messages, from `prepare`, `PreparedQuery::execute` and `PreparedQuery::query`. A caller that matched the `INT` codes must match the new ones. `INT-033`–`INT-035` are deprecated (no longer emitted, still registered, never reused). ### Added @@ -58,6 +59,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Read-only open: `OpenOptions::read_only`** (#429). Opens a database so that nothing done through the handle writes to the `.graph` file or its WAL. The file is locked in shared mode: any number of read-only handles, in this process or others, can hold it at once, and they exclude a read-write open (and it excludes them) with the existing STG-025/STG-026. The handle shows the same data as a read-write open: a WAL left by an earlier session is applied in memory but not checkpointed or deleted, and a format v7 file is read into memory instead of migrated. A missing file is the new `STG-042` (nothing is created). `transact`, `retract`, `begin_write`, `checkpoint` and `rebuild_indexes` fail with the new `API-014`; queries, cursors, `fact_log`, `verify` and rule registration work, and dropping the handle does not checkpoint. `page_cache_size` applies as usual, so a tool can keep the whole file resident. Rust API only for now; the bindings follow. - **Cursor API: `Minigraf::query()` and `PreparedQuery::query()`** (#432). Both return a `Cursor` that hands a query's rows back in batches: `vars()`, `next_batch(max_rows) -> Result, _>`, `close()`, and an iterator over rows. The answer is fixed when the cursor opens, so writes that commit while it is open do not change it. A cursor borrows nothing from the database handle: it can outlive it and move to another thread. For now the answer is still computed when the cursor opens, under the same limits as `execute()`; the API is shaped so the engine can later produce rows as they are pulled without breaking callers. `query()` rejects `transact`, `retract` and `rule` with the new `API-012`, and a query with bind slots with `API-010`. `execute()` is unchanged. Like a fact log, a cursor pins the committed generation it read (#543): checkpoints and `rebuild_indexes()` run while it is open but do not reuse that generation's pages, so on a database taking many writes the file grows by the pages checkpoints replace until the cursor is closed or dropped. `BrowserDb.query()` cursors do the same: the pages they hold keep their bytes in memory and IndexedDB until a later commit after the cursor closes. Rust API only for now; the bindings follow. - **`Minigraf::verify()` and `Minigraf::rebuild_indexes()`** (#373). Page checksums turn a torn or rotted page into an error, but they cannot see a page that is valid and says the wrong thing. `verify()` walks every committed page and returns an `IntegrityReport` with one structured error per finding: an index that holds different facts than EAVT or a different count than the meta page (new `STG-038`), keys out of order or a page reached twice (new `STG-039`), dictionary maps that disagree (new `STG-040`), ids with no dictionary entry (`STG-036`), and leaked, doubly used or wrongly free pages (`STG-035`). It keeps no per-fact state: indexes are compared by an order-independent digest. `rebuild_indexes()` rebuilds EAVT, AEVT, AVET and VAET from an intact index that agrees with another one (or the only intact one), derives the free list again, and commits like a checkpoint, including uncheckpointed writes; a crash at any point leaves the previous checkpoint. If no index can serve as the source, or the dictionary is damaged, it fails with new `STG-041` and writes nothing. Both are Rust API only for now; the bindings follow. +- **`BrowserDb.prepare`** (#181). The browser binding gets prepared queries: `db.prepare(text)` parses and validates a `(query ...)` once and returns a `BrowserPreparedQuery`, whose `execute(bindings)` returns the JSON `execute` returns and whose `query(bindings)` returns a `BrowserCursor`. Bindings are an object of slot name to a plain value (a boolean; a `number`, an integer when `Number.isInteger` accepts it and a float otherwise; a `bigint`; a string; `null`) or a typed `{ type, value }` form for the other kinds (`float` with no fractional part, `keyword`, `ref`, `entity`, `txCount`, `timestamp`, `anyValidTime`). A value that is not a bind value is a `TypeError`, and a typed value that does not fit its type (a bad UUID, a negative tx count) is `API-017`. The other bindings follow. +- **`BindValue::Entity` and `BindValue::Val(Value::Ref(..))` fit each other's slots** (#181). An entity slot (`[$e :attr ?v]`) takes `Val(Value::Ref(uuid))`, and a value, expression or rule-argument slot takes `Entity(uuid)` as the ref. Before, each was `INT-035` in the other's position, and a rule argument needed `Val(Value::Ref(..))`. A binding can now pass a host UUID without knowing where its slot is. ### Fixed diff --git a/CLAUDE.md b/CLAUDE.md index a60373b3ec..540b76966b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -144,7 +144,7 @@ cargo run < demos/demo_negation.txt - `rules.rs`: `RuleRegistry` — thread-safe rule management - `types.rs`: `EdnValue`, `Pattern`, `DatalogQuery`, `AsOf`, `ValidAt`, `WhereClause` (incl. `Not`, `NotJoin`); `PseudoAttr` enum, `AttributeSpec` wrapper - `optimizer.rs`: Selectivity-based join reordering on every build (the `wasm` feature is a deprecated no-op). `reorder()` gates every reordering site; tests turn it off per thread (`set_reorder`, `minigraf::__reorder` under `test-hooks`, #596); `plan_seeded` orders a body with its imported variables counted as bound, `plan_after` orders a rule body's clauses after its delta, each joining on a variable bound before it where one can (#694), and `subplans()` lets tests force the engine's negation bodies and `or` branches hashed or correlated (`set_subplans`, `minigraf::__subplans`, #546) - - `prepared.rs`: `BindValue`, `PreparedQuery` — parse-once/execute-many with named `$slot` bind slots; `prepare_query`, `substitute` + - `prepared.rs`: `BindValue`, `PreparedQuery` — parse-once/execute-many with named `$slot` bind slots; `prepare_query`, `substitute`; `Entity` and `Val(Ref)` fit each other's slots, bind mistakes are `API-022`/`023`/`024` (#181) - `magic_sets.rs`: Magic-sets rewriting for demand-driven recursive rule evaluation (not applied to rules with `not`/`not-join`) 3a. **`src/query/engine/`** — Streaming query engine (#473), runs every query (#551): `plan.rs` (the operator tree of every query, or the executor's error code for it: patterns, expression clauses, `not`/`not-join` and `or`/`or-join`, and rule invocations, read as patterns of their relations (`plan_rules`, #548; a magic-set head constant is `HeadArg::Const`), in `optimizer::plan` order, then the `or`s in text order, then the deferred `not`s; an `or` branch or a `not` body is planned as a `:where` is; a clause list with no pattern first starts from `Seed`; a constant no cell equals is `Term::Never`, a scan that reads nothing; `:as-of` resolved when the query opens (`Snapshot::tx_bound`: a counter bound when `tx_id` rises with `tx_count`, else `TxBound::Timestamp`: committed `tx_count` ranges and pending `tx_id <= t`); a per-fact pseudo-attribute pattern reads the metadata column its source's scan fills (the hidden variable the parser named, #594), and `:db/valid-at` joins as `[e _ _]`; plain `:find` variables, aggregates with `:with`, and window functions, over an aggregate's groups too), `scan.rs` (one pattern over committed key ranges via `CommittedReader::key_source`/`live_keys`, AVET ranges for cross-kind constants, then the pending range by whole runs; one entity per probe for a join), `join.rs` (`IndexNestedLoopJoin` when the pattern's entity is bound, or, under a constant attribute and entity not constant, its value (#721: per outer row the AVET ranges of the values that join-equal it and the attribute's pending facts with its key, read once per query in `IdSpace::probes`; an entity cell needs the keyword naming it, known only where the query made the entity from a keyword (rule heads, magic seeds), else the join becomes the planner's `HashJoin`); `HashJoin` otherwise, and on a relation; `JoinKey`: floats by IEEE `==`, a keyword equals a ref to the entity it names), `filter.rs` (`Filter`/`Bind` and pseudo-attribute steps over batches; a `Bind` on a bound slot keeps the rows where the result is join-equal, #596), `anti.rs` (`AntiJoin`, #546: a body with the same rows for every outer row runs once into a hash set of its imported-variable keys; any other body, or one whose first pattern's entity is imported, runs per outer row from `seed.rs`'s one-row `Seed`, via `Operator::rewind`; never deduplicates), `aggregate.rs` (`Aggregate`, #547: a hash table of groups keyed on cells as `Value`'s `Ord` compares values, one entry when ungrouped; `count`/`count-distinct` on cells, other aggregates on values via `datalog::aggregate::Agg`; groups sorted by value and finished in that order; a float group shows its least value by `value_order`), `window.rs` (`Window`, #547: holds each input row's passed-on cells and its named variables' values, then computes every window with `datalog::aggregate::windows`, the executor's code, and returns the rows in input order), `union.rs`/`distinct.rs` (`Union` and `Distinct`, #546: each `or` branch planned as a `not` body is, hashed into a table or run per outer row; then one row per distinct binding, as the executor's `Value`s compare), `cell.rs`/`batch.rs` (id cells in columnar batches of 1,024), `ids.rs` (DICT and provisional ids, `keyword_eid`), `project.rs` (ids → values for returned rows only), `relation.rs`/`recursive.rs` (#548: rule queries; a relation per evaluated predicate holds its derived rows, a set by `encode_value` identity, appended per round so `Old`/`Delta`/`Full` are ranges; `Recursive` runs each stratum's semi-naive rounds, one run per same-stratum top-level invocation, a rule reading its stratum otherwise run in full every round; scans read derived rows after committed and pending ones, with `nil` metadata), `meter.rs` (#549: one `Meter` per query, shared by every holder of state through a `Held` — hash join build sides, `not`/`or` tables, distinct sets, aggregate groups, window rows, rule relations and their temporaries, `IdSpace`; each entry charged by a per-entry estimate before it is inserted, containers grown with `try_reserve`, released on `rewind`/`close`/drop; over `OpenOptions::query_memory_limit`, or a refused allocation, is `QRY-012`; `Stream::close` drops the operator tree, keeping its counters). `mod.rs`: `Operator` (`next_batch`/`rewind`/`close`/`counters`), `Stream` (the operator tree over an owned `Snapshot`, pulled one batch at a time). `DatalogExecutor::open` / `execute_query` run every query on it: a cursor gets the `Stream` (`Answer::Stream`), `execute` drains it. @@ -162,7 +162,7 @@ cargo run < demos/demo_negation.txt 8. **`src/error.rs`** — Structured error codes: `MinigrafError`, `ErrorCategory`, `ErrorCode` registry (PRS/QRY/STG/WAL/API/INT codes); must match `docs/ERROR_REFERENCE.md`. `MinigrafError::invalid_argument` (API-017) and `MinigrafError::closed` (API-018) exist for language bindings -9. **`src/browser/`** — Browser WASM backend (`browser` feature): `buffer.rs` (`BrowserBufferBackend`, in-memory pages with dirty tracking; free pages a pinned generation may read are withheld from release, `pins::split_released`), `indexeddb.rs` (IndexedDB persistence); `BrowserDb.query` returns a `BrowserCursor` (JSON row batches). Tests here must be `#[wasm_bindgen_test]` (the module only builds for wasm32); `.github/workflows/wasm.yml` runs them in headless browsers, runs the WASI tests under Wasmtime, and lints both wasm targets. New file-backed integration test files need `#![cfg(not(target_arch = "wasm32"))]` +9. **`src/browser/`** — Browser WASM backend (`browser` feature): `buffer.rs` (`BrowserBufferBackend`, in-memory pages with dirty tracking; free pages a pinned generation may read are withheld from release, `pins::split_released`), `indexeddb.rs` (IndexedDB persistence); `BrowserDb.query` returns a `BrowserCursor` (JSON row batches); `BrowserDb.prepare` returns a `BrowserPreparedQuery` (`execute`/`query` with a bindings object, read by `binds.rs`: plain JS values or `{type, value}` forms, #181). Tests here must be `#[wasm_bindgen_test]` (the module only builds for wasm32); `.github/workflows/wasm.yml` runs them in headless browsers, runs the WASI tests under Wasmtime, and lints both wasm targets. New file-backed integration test files need `#![cfg(not(target_arch = "wasm32"))]` ### Data Model @@ -212,7 +212,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are ## Test Coverage -**1716 tests** (1703 passing, 13 ignored; unit + integration + doc). Engine answers once checked by the executor are frozen in `tests/answers/` (#551). +**1720 tests** (1707 passing, 13 ignored; unit + integration + doc). Engine answers once checked by the executor are frozen in `tests/answers/` (#551). See `docs/TEST_COVERAGE.md` for the full per-file breakdown. **Testing conventions** — see the Testing Conventions section below before writing any tests. diff --git a/ROADMAP.md b/ROADMAP.md index 35a09501ea..cd60db2c0c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -103,7 +103,7 @@ Scope — features: - Query profiler (#185) - Set membership predicates (#316) -- `PreparedQuery` over UniFFI (#181) +- Prepared queries in every binding (#181; core and `BrowserDb.prepare` done on `v3`, the other bindings follow) - UDF registration in every binding: the UniFFI ones, C, Node and the browser `BrowserDb` (#180) - `OpenOptions` exposed over UniFFI through `open_with_options`, so embedders can suppress the close-time checkpoint (#322; done on `v3` in every binding with #465) diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index 8de85e9b2a..18d0b50012 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -4,9 +4,9 @@ | | Default features | With `--features test-hooks` | |---|---|---| -| **Passing** | 1,703 | 1,719 | +| **Passing** | 1,707 | 1,723 | | **Ignored** | 13 | 14 | -| **Total** | 1,716 | 1,733 | +| **Total** | 1,720 | 1,737 | **Verified**: 2026-10-24 with `cargo test --quiet`. @@ -318,6 +318,7 @@ These tests compare the database against an independent answer rather than a sin - Unit tests: a batch commits only when a transaction opens past the batch size, never splitting one; `FileBackend::truncate` empties a file. - **Online backup** (#398): runs the online backup from `docs/DURABILITY.md`. It copies a read-write handle with an uncheckpointed transaction through `fact_log` and `LogWriter`, while another thread writes past the automatic checkpoint threshold. The copy verifies clean and holds exactly the records the log returned and the counter read after the log opened; every concurrent write reaches the source's file once the log is dropped. - **Prepared time travel** (#603, `tests/prepared_statements_test.rs`): literal `:as-of` (counter and timestamp), `:valid-at`, `:any-valid-time` and a per-fact pseudo-attribute query through `execute`, a prepared `execute` and a prepared cursor must agree. A `prepared.rs` unit test checks that `substitute` keeps non-slot `:as-of` and `:valid-at`. +- **Bind mistakes and entity bind values** (#181, `tests/prepared_statements_test.rs`): a missing bind value is `API-022` in every slot position (entity, value, expression, rule argument, `:as-of`, `:valid-at`, inside `not`, `not-join`, `or`, `or-join`), an attribute slot is `API-023` from `prepare` at the top level and in each clause kind, and a bind value of the wrong kind is `API-024` for every slot kind, naming the slot and position, through both `execute` and `query`. `Entity` and `Val(Ref)` give the same rows in entity, value, rule-argument and expression slots. - *(v2.x)* **Bind tokens outside prepared queries** (#407): `execute()` and `WriteTransaction::execute()` reject `$slot` bind tokens in every position with `API-010`. - **Binding constructors**: a unit test in `error.rs` checks that `MinigrafError::invalid_argument` and `MinigrafError::closed` give `API-017` and `API-018` with their text. - *(v2.x)* **REPL** (#415): the `run()` test runs in a child process with null stdin, so it no longer hangs when the test runner's stdin is an open non-TTY stream. @@ -449,10 +450,11 @@ These tests compare the database against an independent answer rather than a sin None of these are counted in the summary. The wasm32 targets run in CI (`.github/workflows/wasm.yml`). -- **In a browser** (`wasm-pack test --headless`, Firefox and Chrome): 32 `wasm_bindgen_test` tests. - - Nineteen for `BrowserDb`, including IndexedDB persistence, the cursor, and the flush returning every dirty page and failing on one it cannot read (#470). +- **In a browser** (`wasm-pack test --headless`, Firefox and Chrome): 40 `wasm_bindgen_test` tests. + - Twenty-five for `BrowserDb`, including IndexedDB persistence, the cursor, and the flush returning every dirty page and failing on one it cannot read (#470). - Eleven for `BrowserBufferBackend` (which used `#[test]` and never ran before). - Two checking that IndexedDB page keys accept only whole numbers from 0 to 2^53. +- **`BrowserDb.prepare`** (#181): one prepared query run with three bindings; every plain JS value (boolean, whole and fractional `number`, `bigint`, string, `null`) and every `{type, value}` form; a prepared cursor gives the rows of `execute`; `TypeError` for a non-bind value or non-object bindings, `API-017` for a bad UUID or negative tx count, `API-022`, `API-023` and `API-005`; a later write is seen by the next run. - **`BrowserDb` cursor**: `query()` batches of 1, 7 and 1,000 give the rows of `execute()`; a cursor keeps the answer from when it opened and returns the end after `close()`; a `transact` is `API-012`. - **Page reuse** (#411, #440; five `BrowserDb` tests) - Opening a v7 store written straight into IndexedDB stores a v8 meta page and only the live pages, with nothing written on the next open. From 04f0c7e5297abdf11c13b3cb4177fd7c39d1c340 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Sat, 24 Oct 2026 13:08:00 +0530 Subject: [PATCH 5/5] fix(browser): typed null and anyValidTime take no value; API-024 test (#181) Codex review. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Urda7FD9CYYoxdeGGJa11x --- docs/TEST_COVERAGE.md | 2 +- src/browser/binds.rs | 8 ++++++-- src/browser/mod.rs | 24 ++++++++++++++++++++++++ 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index 18d0b50012..7e64350a45 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -454,7 +454,7 @@ None of these are counted in the summary. The wasm32 targets run in CI (`.github - Twenty-five for `BrowserDb`, including IndexedDB persistence, the cursor, and the flush returning every dirty page and failing on one it cannot read (#470). - Eleven for `BrowserBufferBackend` (which used `#[test]` and never ran before). - Two checking that IndexedDB page keys accept only whole numbers from 0 to 2^53. -- **`BrowserDb.prepare`** (#181): one prepared query run with three bindings; every plain JS value (boolean, whole and fractional `number`, `bigint`, string, `null`) and every `{type, value}` form; a prepared cursor gives the rows of `execute`; `TypeError` for a non-bind value or non-object bindings, `API-017` for a bad UUID or negative tx count, `API-022`, `API-023` and `API-005`; a later write is seen by the next run. +- **`BrowserDb.prepare`** (#181): one prepared query run with three bindings; every plain JS value (boolean, whole and fractional `number`, `bigint`, string, `null`) and every `{type, value}` form; a prepared cursor gives the rows of `execute`; `TypeError` for a non-bind value or non-object bindings, `API-017` for a bad UUID, a negative tx count or a value on `null`/`anyValidTime`, `API-022`, `API-023`, `API-024` (both `execute` and `query`) and `API-005`; a later write is seen by the next run. - **`BrowserDb` cursor**: `query()` batches of 1, 7 and 1,000 give the rows of `execute()`; a cursor keeps the answer from when it opened and returns the end after `close()`; a `transact` is `API-012`. - **Page reuse** (#411, #440; five `BrowserDb` tests) - Opening a v7 store written straight into IndexedDB stores a v8 meta page and only the live pages, with nothing written on the next open. diff --git a/src/browser/binds.rs b/src/browser/binds.rs index fa771e9fad..ba65c7c5e9 100644 --- a/src/browser/binds.rs +++ b/src/browser/binds.rs @@ -15,6 +15,8 @@ //! | `{ type: 'timestamp', value }` | `Timestamp` (Unix ms) | //! | `{ type: 'anyValidTime' }` | `AnyValidTime` | //! +//! `null` and `anyValidTime` take no `value`. +//! //! Any other JavaScript value is a `TypeError`. A typed form whose value does //! not fit its type (a bad UUID, a negative tx count, an integer outside //! `i64`) is `API-017`. @@ -91,7 +93,7 @@ fn read_typed(name: &str, kind: &str, v: &JsValue) -> Result, "float" => BindValue::Val(Value::Float( value.as_f64().ok_or_else(|| mismatch(&what()))?, )), - "null" => BindValue::Val(Value::Null), + "null" if value.is_undefined() => BindValue::Val(Value::Null), "ref" => BindValue::Val(Value::Ref(uuid(&what(), &string()?)?)), "entity" => BindValue::Entity(uuid(&what(), &string()?)?), "txCount" => { @@ -101,7 +103,9 @@ fn read_typed(name: &str, kind: &str, v: &JsValue) -> Result, ) } "timestamp" => BindValue::Timestamp(integer(&what(), &value)?), - "anyValidTime" => BindValue::AnyValidTime, + "anyValidTime" if value.is_undefined() => BindValue::AnyValidTime, + // These two take no value. + "null" | "anyValidTime" => return Err(mismatch(&what())), _ => return Ok(None), })) } diff --git a/src/browser/mod.rs b/src/browser/mod.rs index 5041b78116..c22d224bef 100644 --- a/src/browser/mod.rs +++ b/src/browser/mod.rs @@ -1409,6 +1409,30 @@ mod prepared_tests { "a negative tx count is API-017" ); + for no_value in ["null", "anyValidTime"] { + let e = + rejection(pq.execute(obj(&[("n", typed(no_value, Some(JsValue::from_f64(1.0))))]))); + assert!( + starts_with(&e, "[API-017] "), + "null and anyValidTime take no value" + ); + } + + let wrong = obj(&[("n", typed("txCount", Some(JsValue::from_f64(1.0))))]); + let e = rejection(pq.execute(wrong.clone())); + assert!( + starts_with(&e, "[API-024] "), + "a tx count in a value slot is API-024" + ); + let e = pq + .query(wrong) + .map(|_| ()) + .expect_err("query must reject too"); + assert!( + starts_with(&e, "[API-024] "), + "a tx count in a value slot is API-024" + ); + let e = rejection(pq.execute(obj(&[]))); assert!(starts_with(&e, "[API-022] "), "a missing slot is API-022"); let e = pq