From caf8cffd4bda37cc91b467ad2b0bdece46141f3c Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Sun, 29 Nov 2026 15:06:48 +0530 Subject: [PATCH] feat(browser): add incomingRefs to BrowserWriteTransaction (#925) BrowserWriteTransaction.incomingRefs(target, maxLinks, maxRecords) exposes the bounded incoming-reference lookup of write transactions (#924) in the browser. It shares db::incoming_refs with the native transactions and returns a plain object discriminated by status, with exact 32-bit budgets. The transaction methods now take shared receivers behind a per-transaction guard, so a user function that calls back into its own transaction gets INT-001 instead of wasm-bindgen's recursive-borrow error. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H2a7QnK1UQ7thygqxPzRfQ --- .github/workflows/wasm.yml | 4 + CHANGELOG.md | 4 + CLAUDE.md | 4 +- README.md | 2 +- ROADMAP.md | 3 +- docs/TEST_COVERAGE.md | 17 +- ...26-11-29-925-incoming-ref-parity-design.md | 185 +++++++++ docs/testing/925-browser-incoming-refs.md | 108 +++++ src/browser/flush_tests.rs | 12 +- src/browser/incoming_tests.rs | 382 ++++++++++++++++++ src/browser/mod.rs | 157 ++++++- src/browser/opfs_tests.rs | 26 +- src/browser/tx_tests.rs | 170 ++++++-- src/db.rs | 58 +-- tests/browser/incoming_refs.ts | 24 ++ 15 files changed, 1058 insertions(+), 98 deletions(-) create mode 100644 docs/superpowers/specs/2026-11-29-925-incoming-ref-parity-design.md create mode 100644 docs/testing/925-browser-incoming-refs.md create mode 100644 src/browser/incoming_tests.rs create mode 100644 tests/browser/incoming_refs.ts diff --git a/.github/workflows/wasm.yml b/.github/workflows/wasm.yml index 3b1faec6e3..b0e3b00820 100644 --- a/.github/workflows/wasm.yml +++ b/.github/workflows/wasm.yml @@ -37,6 +37,10 @@ jobs: run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh - name: wasm-bindgen tests (lib, incl. BrowserDb and IndexedDB) run: wasm-pack test --headless --${{ matrix.browser }} --features browser + - name: Check generated incoming-reference TypeScript declarations + run: | + wasm-pack build --dev --target web --out-dir target/browser-types --features browser + npx --yes --package typescript@5.9.3 tsc --strict --noEmit --target ES2020 --lib ES2020,DOM,ESNext.Disposable --moduleResolution node tests/browser/incoming_refs.ts browser-worker: name: Browser worker tests (headless ${{ matrix.browser }}) diff --git a/CHANGELOG.md b/CHANGELOG.md index 599dc38885..763e347681 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Browser incoming-reference lookup and binding parity** (#925, v3): synchronous `BrowserWriteTransaction.incomingRefs(target, maxLinks, maxRecords)` exposes #924's lookup on in-memory, IndexedDB and OPFS databases. It returns a plain object with a TypeScript `status` union (`complete` with links, or `exhausted` with a budget and no partial list). Budgets are exact integer JS numbers in `0..=2^32-1`; invalid inputs are `[API-017]`, finished/closed handles `[API-018]`. It reads earlier statements and remains available after an IndexedDB flush failure. Native/JVM semantics are unchanged; remaining binding and package parity work is tracked separately in #925. + - **Bounded typed incoming-reference lookup** (#924, v3): `WriteTransaction::incoming_refs` and `OwnedWriteTransaction::incoming_refs` return `IncomingRefs::Complete` or `Exhausted`, with separate links/records budgets and a records-examined count. They read scalar `Value::Ref` links across pending, staged, durable VAET and large working trees, ignore valid time, and never return a partial list. Require a complete result before cascading deletes. No format, WAL, grammar, error-code or browser API change. See [implementation and acceptance evidence](docs/testing/924-incoming-refs.md). - **JVM/WASI nightly lanes** (#858): 14 JVM and 3 WASI routes, pinned runtimes, measured-core/artifact provenance, strict raw-sample reporting and independent histories, live on both branches with the adapter merged in `minigraf-java`. The iOS simulator and Android emulator were qualified against matched Device Farm physical runs and rejected for every case, so no mobile lane is enabled ([report](docs/benchmarks/858-mobile-qualification/REPORT.md)). No runtime, file-format or Rust test inventory change. See [the adapter contract](docs/BINDING_BENCHMARKS.md). @@ -30,6 +32,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **Browser transaction callback reentry** (#925): `incomingRefs`, `execute`, `commit` and `rollback` on the same transaction from its own user function now report `[INT-001]` before lifecycle or argument validation. Previously the existing methods hit wasm-bindgen's recursive-borrow error. The transaction remains usable; `rollback(): void` is unchanged in TypeScript and throws on reentry. + - **Strict UTC timestamps (v3.0.0 behaviour change, #900)**: removed the unmaintained `chrono` dependency (RUSTSEC-2026-0543) without a replacement crate. Accept only `YYYY-MM-DD`, `YYYY-MM-DDTHH:MM:SSZ`, or `YYYY-MM-DDTHH:MM:SS.fZ` with 1–9 ASCII fractional digits, truncated to milliseconds (also before 1970), and years 0000–9999. Newly rejected with INT-004: lowercase `z`, the `UTC` suffix, any whitespace, single-digit fields, one- or two-digit years, negative years, leap seconds, more than nine fractional digits, empty fractions and comma fractions. Offsets, lowercase `t`, missing seconds, five-digit years, invalid calendar/clock fields, non-ASCII digits and trailing characters remain rejected. Formatting keeps whole-second UTC output and returns INT-005 outside the same year range. - **v3 binary-size CI budget**: raise the enforced distribution-binary limit from 1,240 to 1,250 KiB (1,280,000 bytes). Unchanged production source measured 1,242 KiB after CI moved to Rust 1.100.0 and a newer runner image; the additional headroom changes no production code or build settings. diff --git a/CLAUDE.md b/CLAUDE.md index 1407d1fcba..61d01cf2c4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -197,7 +197,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; browser OPFS adds API-026 (unavailable context), API-027 (busy) and STG-048 (failed browser storage operation) -9. **`src/browser/`** — Browser WASM backend (`browser` feature): `backend.rs` (buffer/OPFS dispatch), `opfs.rs` (`OpfsBackend` over an exclusive dedicated-worker sync access handle, one `.graph` file and a 256-page cache; no WAL; sole-valid-meta recovery; crash-atomic import stages `.graph-import`), `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 on the main thread or in workers; atomic puts/deletes, abort/error settlement, STG-048 on failure, ordered flushes and persistent per-handle STG-046 refusal after failure, #894; checkpoint waits for earlier applied writes, close discards unstarted flushes, reads/export retain already-applied memory); `openOpfs(name)` selects OPFS explicitly (Tier 2 in v3.0.0); all modes have synchronous `close()`, invalidating dependents and releasing the OPFS lock, with no save; `BrowserDb.query` returns a `BrowserCursor` (JSON row batches); `BrowserDb.prepare` returns a `BrowserPreparedQuery` (`execute`/`query` with a bindings object; `withMaxDerivedFacts`/`withQueryMemoryLimit`/`withMaxIterations` return a new one, #872; read by `binds.rs`: plain JS values or `{type, value}` forms, #181; a set as `{type: 'set', value: [..]}` or a JS `Set`, #316); `BrowserDb.beginWrite` returns a `BrowserWriteTransaction` (#824: sync `execute` staging through `db::Staged`, `commit()` a `Promise` resolved after the IndexedDB flush, `rollback()`; `BrowserDbInner::tx_open` makes every other read/write call `INT-001`; finished = `API-018`; tests in `tx_tests.rs`); `udfs.rs`: `registerPredicate`/`registerAggregate` (#180; values as `{type, value}` objects, a throw is `QRY-014`; JS values held in a thread-local table, the registry keeps ids). 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): `backend.rs` (buffer/OPFS dispatch), `opfs.rs` (`OpfsBackend` over an exclusive dedicated-worker sync access handle, one `.graph` file and a 256-page cache; no WAL; sole-valid-meta recovery; crash-atomic import stages `.graph-import`), `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 on the main thread or in workers; atomic puts/deletes, abort/error settlement, STG-048 on failure, ordered flushes and persistent per-handle STG-046 refusal after failure, #894; checkpoint waits for earlier applied writes, close discards unstarted flushes, reads/export retain already-applied memory); `openOpfs(name)` selects OPFS explicitly (Tier 2 in v3.0.0); all modes have synchronous `close()`, invalidating dependents and releasing the OPFS lock, with no save; `BrowserDb.query` returns a `BrowserCursor` (JSON row batches); `BrowserDb.prepare` returns a `BrowserPreparedQuery` (`execute`/`query` with a bindings object; `withMaxDerivedFacts`/`withQueryMemoryLimit`/`withMaxIterations` return a new one, #872; read by `binds.rs`: plain JS values or `{type, value}` forms, #181; a set as `{type: 'set', value: [..]}` or a JS `Set`, #316); `BrowserDb.beginWrite` returns a `BrowserWriteTransaction` (#824: sync `execute` staging through `db::Staged`, `commit()` a `Promise` resolved after the IndexedDB flush, `rollback()`; `BrowserDbInner::tx_open` makes every other read/write call `INT-001`; finished = `API-018`; tests in `tx_tests.rs`; #925 adds synchronous `incomingRefs(target, maxLinks, maxRecords)`, a plain-object complete/exhausted TypeScript union with exact 32-bit JS budgets, sharing `db::incoming_refs` with native transactions without `Staged::read_view`; all transaction methods use shared receivers and a per-transaction `RefCell` guard for callback INT-001 before lifecycle/validation; parity and bounded-work tests in `incoming_tests.rs`); `udfs.rs`: `registerPredicate`/`registerAggregate` (#180; values as `{type, value}` objects, a throw is `QRY-014`; JS values held in a thread-local table, the registry keeps ids). 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 @@ -250,7 +250,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are ## Test Coverage -**2213 tests** (2190 active, 23 ignored; unit + integration + example + doc). Browser-only inventory is separate: #894 adds 14 wasm tests (95 main-thread / 128 dedicated-worker tests in total); see `docs/testing/894-idb-flush-recovery.md` for execution results. Engine answers once checked by the executor are frozen in `tests/answers/` (#551). The #924 Rust 1.99.1 dist binary is 1,250,568 bytes (+3,808 from the v3 base), below the 1,280,000-byte gate; [verification and acceptance mapping](docs/testing/924-incoming-refs.md). +**2213 tests** (2190 active, 23 ignored; unit + integration + example + doc). Browser-only inventory is separate: #925 adds eight wasm tests (103 main-thread / 136 dedicated-worker tests in total); see `docs/testing/925-browser-incoming-refs.md` for execution results. Engine answers once checked by the executor are frozen in `tests/answers/` (#551). The #924 Rust 1.99.1 dist binary is 1,250,568 bytes (+3,808 from the v3 base), below the 1,280,000-byte gate; [verification and acceptance mapping](docs/testing/924-incoming-refs.md). See `docs/TEST_COVERAGE.md` for the full per-file breakdown. The #760 deterministic storage suite adds three native unit tests in a separate `--cfg minigraf_shuttle` build, outside the default count. Run only `graph::storage::deterministic::` with that cfg; ordinary unit tests do not enter its scheduler. `deterministic-schedules.yml` runs relevant v3 PRs on Linux/macOS/Windows plus Linux MSRV, and larger nightly/manual searches with replay artifacts. The identical main workflow activates the v3 schedule after both PRs merge. See `docs/testing/deterministic-schedules.md` for scope, controls and findings. diff --git a/README.md b/README.md index 8c43770b78..3f57ddf71a 100644 --- a/README.md +++ b/README.md @@ -292,7 +292,7 @@ See the [Mobile Integration](https://project-minigraf.github.io/minigraf-docs/la ### For WASM / Browser -Published as [`@minigraf/browser`](https://www.npmjs.com/package/@minigraf/browser) on npm (`wasm-pack`). `BrowserDb.open(name)` uses IndexedDB on the main thread or in a worker. From v3.0.0, `await BrowserDb.openOpfs(name)` uses one `.graph` file in OPFS, in a dedicated worker on HTTPS or localhost, with a 256-page cache instead of a whole-file memory buffer. OPFS starts at Tier 2 inside the Tier 1 browser binding; the modes have separate namespaces and never fall back to each other. `close()` is synchronous and releases the database and its lock in every mode. See the [complete module-worker example](https://github.com/project-minigraf/minigraf-wasm/tree/v3#opfs-worker) and [browser durability contract](docs/DURABILITY.md#browser-storage-modes). `BrowserDb.beginWrite()` opens a write transaction (from v3.0.0): `execute` stages and reads back, `await tx.commit()` stores it in IndexedDB or flushes it to OPFS, `rollback()` discards it, and the database's other calls throw `[INT-001]` until it ends. The WASI package is the REPL: each command commits on its own, with no explicit transactions. WASI build (`wasm32-wasip1`) available as [`@minigraf/wasi`](https://www.npmjs.com/package/@minigraf/wasi) on npm and as a GitHub Releases artifact (Wasmtime / Wasmer). See the [Use Cases](https://project-minigraf.github.io/minigraf-docs/latest/use-cases/). The [playground](https://minigraf-playground.vercel.app/) and the [time travel visualizer](https://project-minigraf.github.io/minigraf-visualizer/) are both built on `@minigraf/browser`. +Published as [`@minigraf/browser`](https://www.npmjs.com/package/@minigraf/browser) on npm (`wasm-pack`). `BrowserDb.open(name)` uses IndexedDB on the main thread or in a worker. From v3.0.0, `await BrowserDb.openOpfs(name)` uses one `.graph` file in OPFS, in a dedicated worker on HTTPS or localhost, with a 256-page cache instead of a whole-file memory buffer. OPFS starts at Tier 2 inside the Tier 1 browser binding; the modes have separate namespaces and never fall back to each other. `close()` is synchronous and releases the database and its lock in every mode. See the [complete module-worker example](https://github.com/project-minigraf/minigraf-wasm/tree/v3#opfs-worker) and [browser durability contract](docs/DURABILITY.md#browser-storage-modes). `BrowserDb.beginWrite()` opens a write transaction (from v3.0.0): `execute` stages and reads back, `await tx.commit()` stores it in IndexedDB or flushes it to OPFS, `rollback()` discards it, and the database's other calls throw `[INT-001]` until it ends. `tx.incomingRefs(target, maxLinks, maxRecords)` synchronously returns `{status: 'complete', links, recordsExamined}` or `{status: 'exhausted', budget: 'links' | 'records', recordsExamined}` without partial links. Both budgets are integer JS numbers in `0..=4294967295`; invalid inputs throw `[API-017]`, finished/closed handles `[API-018]`, and callback reentry `[INT-001]`. It includes earlier staged statements and only scalar Ref values (not Keywords, strings or sets), ignoring valid time. Require complete before deleting; retry or abandon on exhausted, which leaves earlier writes staged. The WASI package is the REPL: each command commits on its own, with no explicit transactions or incoming-reference lookup. WASI build (`wasm32-wasip1`) available as [`@minigraf/wasi`](https://www.npmjs.com/package/@minigraf/wasi) on npm and as a GitHub Releases artifact (Wasmtime / Wasmer). See the [Use Cases](https://project-minigraf.github.io/minigraf-docs/latest/use-cases/). The [playground](https://minigraf-playground.vercel.app/) and the [time travel visualizer](https://project-minigraf.github.io/minigraf-visualizer/) are both built on `@minigraf/browser`. ### For Python / Node.js / Java / C diff --git a/ROADMAP.md b/ROADMAP.md index 6e5b4be165..16f322af09 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -73,7 +73,8 @@ Shipped: ## v3.0.0 — File Format v8 and Data Integrity -- Bounded typed incoming references (#924): core Rust transaction APIs implemented, with separate link/record limits, exact scalar Ref matching and target-local access in every storage layer. JVM bindings and the docs site remain separate deliverables. The measurement report shows no median regression above 5% on any of 65 IDs in either round; see [acceptance evidence](docs/testing/924-incoming-refs.md). +- Bounded typed incoming references (#924): core Rust transaction APIs implemented, with separate link/record limits, exact scalar Ref matching and target-local access in every storage layer. The JVM bindings and docs-site deliverables are merged. The measurement report shows no median regression above 5% on any of 65 IDs in either round; see [acceptance evidence](docs/testing/924-incoming-refs.md). +- Incoming-reference binding parity (#925): core browser `BrowserWriteTransaction.incomingRefs` implemented with exact JS budgets, typed complete/exhausted outcomes and callback reentry guards; remaining binding, wasm package and docs-site PRs are separate deliverables. **v3.0.0 supports file format v8 only.** Fixing #287/#371 (`EavtKey`/`AevtKey` carry no value bytes, so same-transaction multi-values collapse) bumps the format from v7 to v8. Support for v1–v6 is dropped at the same time. The v1–v6 → v7 auto-migration code in `persistent_facts.rs` can be removed when cutting this release; a v7→v8 migration replaces it. Any database opened at least once under a v1.x release will already be on v7; there are no known users on older formats. Every other layout change this release needs goes into v8 too, so there is no separate v9. diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index d6348375cc..e3da811ea1 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -2,6 +2,21 @@ ## Coverage Summary +**#925 browser incoming references** adds eight `wasm_bindgen_test` cases: +six in `src/browser/incoming_tests.rs` (generated-JS budget/type boundaries, +in-memory lifecycle, IndexedDB/OPFS reopen and lifecycle, failed-flush reads, +differential parity with `OwnedWriteTransaction`, and 10,000 unrelated staged +or committed facts with independent enumeration counters), and two in +`src/browser/tx_tests.rs` (all four transaction methods reentered through JS +and callback close/free behavior). Browser inventory is **103 main-thread / +136 dedicated-worker** tests. Native inventory remains **2,213 tests** +(2,190 active, 23 ignored). `tests/browser/incoming_refs.ts` checks generated +TypeScript narrowing, required numeric budgets and `rollback(): void` in +`wasm.yml`. The browser and native paths share the same three-layer lookup. +Local Firefox runs pass all 103/136 tests; native default tests, strict native +and browser-library Clippy, formatting and generated TypeScript checks pass. +See [commands, limitations and size measurements](testing/925-browser-incoming-refs.md). + **#924 bounded incoming references**: full native runs on 2026-11-28 with Rust 1.99.1 on Linux x86_64 pass **2,190 tests, 0 failed, 23 ignored** (2,213 total) by default and **2,228 tests, 0 failed, 32 ignored** @@ -823,7 +838,7 @@ None of these are counted in the summary. The wasm32 targets run in CI (`.github - AC13/AC14: `opfs_open_read_bound`, `opfs_cache_residency_bound`, `indexeddb_mode_works_in_a_worker`. - AC3 parity: the worker build runs the existing transaction, prepared-query and UDF suites against OPFS as well as IndexedDB. The main-thread build preserves the existing IndexedDB tests. Worker CI sets `RUSTFLAGS=--cfg minigraf_browser_worker` for Firefox and Chrome. -- **In a browser** (`wasm-pack test --headless`, Firefox and Chrome): 94 `wasm_bindgen_test` tests after #894 (81 inherited plus 13 flush-recovery tests); see the [#894 verification record](testing/894-idb-flush-recovery.md) for actual runs. The final #641 snapshot passed in headless Firefox on the bench; Chrome remains a CI run. +- **In a browser** (`wasm-pack test --headless`, Firefox and Chrome): 103 main-thread and 136 dedicated-worker `wasm_bindgen_test` tests after #925 (95/128 inherited plus eight incoming-reference and reentry cases); see the [#894 verification record](testing/894-idb-flush-recovery.md) for actual runs. The final #641 snapshot passed in headless Firefox on the bench; Chrome remains a CI run. - Three committed-memory-backend input-order fixtures: scalar Sort omission, streaming counts with Boolean/float representatives and mixed numeric group order, and partition windows preserving float edges and numeric group classes (#641). - Twenty-six for `BrowserDb`, including IndexedDB persistence, the default `allow_overrides` list (#869), 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). diff --git a/docs/superpowers/specs/2026-11-29-925-incoming-ref-parity-design.md b/docs/superpowers/specs/2026-11-29-925-incoming-ref-parity-design.md new file mode 100644 index 0000000000..e9ddb09029 --- /dev/null +++ b/docs/superpowers/specs/2026-11-29-925-incoming-ref-parity-design.md @@ -0,0 +1,185 @@ +# Spec — 009-incoming-ref-parity (#925): the #924 incoming-ref lookup in every remaining binding and the browser + +**Mission Type:** code (bindings + a small core browser addition) plus docs, across nine repositories. + +**Base branches:** `project-minigraf/minigraf` **`v3`**; `minigraf-python`, `minigraf-android`, `minigraf-swift`, `minigraf-node`, `minigraf-c`, `minigraf-wasm`, `minigraf-binding-template` **`v3`**; `minigraf-docs` **`main`**. No `main` (v2.x) backport: this is a new feature. minigraf-java needs no PR; it is the reference (`origin/v3` `364ca6c`, PR #29). + +**Deliverables (PRs):** +1. **Core v3**: `BrowserWriteTransaction.incomingRefs`, its wasm-bindgen tests, core docs, and a copy of this spec at `docs/superpowers/specs/2026-11-29-925-incoming-ref-parity-design.md`. +2. **minigraf-python**, 3. **minigraf-android**, 4. **minigraf-swift**, 5. **minigraf-binding-template**: UniFFI lookup, core pin, language surface, tests, README. +6. **minigraf-node**: napi lookup, TypeScript declarations, tests, README. +7. **minigraf-c**: typed C lookup API, regenerated header, tests, README. +8. **minigraf-wasm**: core pin containing PR 1, browser typings, browser consumer test, README, WASI README note. +9. **minigraf-docs**: per-binding and browser examples, WASI note. + +Native binding PRs (2–7) do not depend on PR 1 and may start against core `353bd58b`. PR 8 depends on PR 1's merge. Every PR's final pin is a commit on core `v3` (never a PR-branch-only commit; #824 rule G1). Using one common pin, PR 1's merge commit, for all of PRs 2–8 is allowed and simplest to audit. + +## 1. User Intent + +> /tandemkit:planner #925 + +#925 (v3.0.0): "Expose the #924 incoming-ref lookup in every remaining binding": Python, Android, Swift, Node, C, wasm/WASI where a write transaction exists, and binding-template. Keep the #924 contract: typed target, two explicit budgets, typed complete/exhausted outcome with no partial links and no message parsing needed, and the existing error codes API-017/API-018/INT-001. Each binding pins a core v3 revision containing #924, adds tests with its consumer test, and updates its README. The docs site gets per-binding examples. "Decide here whether [BrowserDb] gets the lookup and in what form. Record the decision in this issue." + +> [Asked whether `BrowserWriteTransaction` gets `incomingRefs` in this mission] Include it. + +Why (from #925): Android shares the JVM Kotlin package from v3.0.0, so Kotlin code calling `incomingRefs` must compile against both artifacts. Python is Tier 1. Every earlier binding feature (#180, #181, #824, #872) shipped to all bindings. Browser WASM is also Tier 1 from v3.0.0 (`PHILOSOPHY.md` on v3, the tier table). + +## 2. Goal + +Every transaction surface a Minigraf user can reach from a language binding offers the same bounded, exact-typed incoming-reference lookup that core and minigraf-java ship. The browser's `BrowserWriteTransaction` is included. The lookup has the #924 semantics: the current write view, scalar Ref only, valid time ignored, two mandatory budgets, and complete or exhausted with no partial list. Callers branch on a typed outcome in their own language. The WASI package stays the auto-commit REPL with no lookup, and says so. + +## 3. Context & Investigation Findings + +Sources: Claude-01, Codex-01. References are `origin/v3` of each repository unless noted. Several local `v3` branches are stale (core local `v3` is `33b4b165c`, before #924), so start every worktree from `origin/v3`. + +### The contract being exposed (core `353bd58be`) +- `src/incoming.rs:6-77`: public `#[non_exhaustive]` `IncomingRefLimits` (two `usize` caps), `IncomingRef {source, attribute}`, `IncomingRefBudget {Links, Records}`, and `IncomingRefs::{Complete{links, records_examined}, Exhausted{budget, records_examined}}`. All are exported at `src/lib.rs:117`. +- `src/db.rs:2394` (`WriteTransaction`) and `:2711` (`OwnedWriteTransaction`) expose `incoming_refs`. `TxState::incoming_refs` (`src/db.rs:2115-2162`) reads three target-local layers in order: committed reader (`incoming_ref_records`, `src/storage/reader.rs:483`), pending (`Snapshot::incoming_pending`, `src/graph/storage.rs:488`) and staged (`Staged.incoming`, maintained at `src/db.rs:2482-2523`). It never builds `Staged::read_view` (`src/db.rs:2528-2544`), which clones every staged fact. +- The full semantics are in `TandemKit/008-incoming-ref-lookup/Spec.md` §4-§5 and in `docs/superpowers/specs/2026-11-28-924-incoming-ref-lookup-design.md`: the definitions of *live link* and *examined record*, AC2-AC15, and the edge cases. **This mission does not change them.** Core already has the semantic, model-based, failed-handle and unrelated-growth tests (`src/db/incoming_tests.rs`). Bindings test marshalling and boundaries, not the whole semantic matrix again. + +### Reference binding: minigraf-java (`364ca6c`, pin `353bd58b`) +- `src/lib.rs:1003-1073`: UniFFI `IncomingRef` record (`source`: canonical lowercase UUID string, `attribute`: string), `IncomingRefBudget` enum, and `IncomingRefs` enum with `records_examined: i64`. Unknown future core variants become an `INT-000` error, never a success-shaped result. +- `src/lib.rs:1165-1179` `incoming_refs(target: String, max_links: i64, max_records: i64)`. **Error precedence:** callback reentry (INT-001, before locking), then finished (API-018), then UUID and budget validation (API-017). Budgets go through `to_usize` (`:79-108`): exact caps, negative or unrepresentable → API-017. **Not** the `to_limit` "huge means unlimited" helper. +- Tests: Rust `src/lib.rs:3126+`, `java/src/test/kotlin/.../TransactionTest.kt`, `java/src/test/java/.../JavaInteropTest.java:181`, `consumer-test/src/test/java/ContractTest.java:181`. README sections: `README.md:41-71`, `java/README.md:320-357`. + +### UniFFI bindings: Python, Android, Swift, template (all pin `32d71ce0`) +- Python, Android and Swift `src/lib.rs` are **byte-identical** to minigraf-java's `src/lib.rs` before #29 (`364ca6c^1`). The template's `src/lib.rs` is identical apart from its 24-line header comment, which says to keep it identical to the others. Their transaction code is at `src/lib.rs:978-1100` (template `:1002-1121`). +- The pin move from `32d71ce0` brings in every core change since. Java went through the same move in #29. +- Python: `minigraf/__init__.py` re-exports from `.minigraf_ffi`, with `__all__` at `:289-327` and the context-manager transaction at `:209-237,280-287`. Tests: `tests/test_transactions.py`, `consumer-test/contract.py`, `consumer-test/readme_sync.py`. CI: `.github/workflows/ci.yml:54-58`. Python integers are unbounded, so values outside `i64` reach UniFFI's lowering before any Rust check. +- Android: `uniffi.toml:6` uses the same Kotlin package as Java (`../minigraf-java/uniffi.toml:4`). `android/.../Transactions.kt` holds the options overload. Installed-AAR test: `consumer-test/tests/contract.kt:165`, run on an emulator in CI. Android ships 32-bit ABIs, so `usize` is 32 bits there. +- Swift: `Sources/MinigrafKit/MinigrafKit+Transactions.swift` has `withWriteTransaction`. Tests: `Tests/swift/main.swift` and `consumer-test/App/Tests/ConsumerTests/ContractTests.swift:118`. CI generates and compiles the Swift bindings (`ci.yml:69-83`). +- Template: language-neutral. `consumer-test/run.sh:45-65` checks exported symbols of the packaged artifact; there is no runnable language SDK. + +### Node (`minigraf-node`, napi-rs, pin `32d71ce0`) +- `src/lib.rs:825-898`: `WriteTransaction { slot: Arc>> }`. Reentry is detected with `try_lock` WouldBlock → INT-001 (`:883-896`); finished → `tx_finished()` (API-018); database `close()` finishes registered transactions. +- `to_limit` (`:25-31`) maps numbers at or above `MAX_SAFE_INTEGER` to `usize::MAX`. That is right for query limits but **wrong** for #924 budgets. +- `index.d.ts` is napi-generated and checked in (`WriteTransaction` at `:260`); `minigraf.d.ts` is hand-written and re-exports and augments it (`package.json` `types`). `package.json` `test` lists the test files explicitly. Tests: `test/transactions.test.mjs`, `consumer-test/contract.cjs:73`. + +### C (`minigraf-c`, cbindgen, pin `32d71ce0`) +- `include/minigraf.h:300-338`: opaque `MiniGrafTx`; `minigraf_tx_execute` returns JSON or NULL plus `minigraf_tx_last_error`; `minigraf_tx_free`; INT-001 on reentry from a user function. `src/lib.rs:1733-1810,1888-1967` has the reentry-before-lock helper and per-transaction last error; `minigraf_close` rolls back registered transactions. +- `ci.yml:36-71` compiles a C smoke test against the header (`tests/c/etl_smoke.c`) and **diffs the header against cbindgen 0.29.2** output. Packaged test: `consumer-test/contract.c:192`. + +### Browser (core `src/browser/mod.rs`) and wasm packaging +- **The issue's premise is stale.** #824 added `BrowserDb.beginWrite()` → `BrowserWriteTransaction` (`:716-728`, `:963-1050`): synchronous `execute(&mut self)`, Promise `commit()`, synchronous `rollback()`. It holds a `crate::db::Staged`, so the #924 staged target index is already maintained. That field is private to `db.rs` (`src/db.rs:2486`), so a small core integration is needed. +- Browser state is `Rc` / `RefCell`, not `Minigraf` (`:56-81,288-305`). Even `openInMemory` uses `PersistentFactStorage` (`:360-368`); OPFS uses the shared committed reader over a worker file backend (`:402-417`). So all three modes have committed, pending and staged layers like native ones, but no WAL and no large-transaction promotion. +- The transaction's query path (`tx_execute`, `:1057-1091`) uses `read_view`. Reusing it would break the bounded-work contract. +- `:109-144` separates admission (closed/busy) from the failed-flush write refusal (`refuse_failed_flush`). While a transaction is open, other `BrowserDb` calls give INT-001 (`:306-316`). +- **Main technical risk:** `execute` takes `&mut self`. If a user function inside a transaction statement calls the *same* transaction object, wasm-bindgen's borrow tracking may throw its own recursive-borrow error before any Rust guard runs. Existing reentry tests (`src/browser/tx_tests.rs:435-475`) call the database, not the transaction. `tx_open` cannot be the guard, since it is true during every legitimate lookup. Codex derived this from the source; nobody has run it yet. The Generator must settle it early through the exported JS. +- `minigraf-wasm/src/lib.rs` is a 4-line re-export of core, so the method must land in **core**. minigraf-wasm pins core `df7e8170`. Browser consumer tests cover Chromium, Firefox and WebKit on Linux and macOS, including OPFS workers (`consumer-test/browser/contract.js`, `opfs-worker.js`; `ci.yml:39-58`). +- WASI: the npm package runs the REPL binary (`wasi-pkg/README.md:27-34`). The #824 maintainer decision (2026-11-10) is auto-commit only, with no transaction commands. WASI packaging checks out `inputs.core-ref` separately (`package.yml:80-88`), which defaults to mutable `v3` (`ci.yml:33`). So the Cargo pin alone does not prove which core the WASI artifact was built from. + +### Docs +- Docs site `content/cookbook-application-workflows.md:318-325` says the lookup is core/JVM only, and the examples are at `:439-477`, inside a v3 `@since` block. Also review `content/architecture.md:224` (browser), `content/use-cases.md`, `content/database-tools.md`, and `content/comparison.md` if it has a transactions or bindings matrix. +- Core `ROADMAP.md:76` still lists the JVM and docs as pending #924 deliverables, though both are merged. + +### Size +- Core gate on v3: 1,280,000 bytes (1,250 KiB), `.github/workflows/binary-size.yml:17`. The browser addition is `browser`-feature only, so the native gate binary should not change; the PR reports it anyway. No wasm size gate exists, so record the browser `.wasm` size before and after without inventing a threshold. + +## 4. Acceptance Criteria + +Test names are suggestions. "Binding" means python, android, swift, template, node or c. "Browser" means `BrowserWriteTransaction`. Lowercase *complete*/*exhausted* refer to the #924 outcomes. + +**Common to every binding and the browser** + +1. **Surface.** The existing transaction object gets the lookup: target entity UUID plus two mandatory budgets (links, records). It returns a typed complete outcome (links, each a canonical lowercase UUID string `source` plus an `attribute` string, and records examined) or a typed exhausted outcome (budget = links or records, records examined, and **no** link list). Callers tell complete, complete-empty, exhausted(links), exhausted(records) and an error apart without parsing JSON or message text. The database object gets no new method. +2. **Semantics equal core.** Each surface returns the core #924 link set for the same statements; the binding converts core's outcome and never re-derives it. Core's own suites already prove the semantic matrix (`src/db/incoming_tests.rs`, model-based, failed-handle), so binding tests prove the marshalling. Tests in each native binding's Rust crate cover at least what minigraf-java's crate tests cover (`incoming_refs_typed_outcomes_and_retry`, `incoming_refs_commit_reopen_and_rollback`, `incoming_refs_invalid_arguments`): two attributes from one source; a Keyword with the same spelling, a UUID-looking String and a `Value::Set` holding the target (all excluded); a staged retraction over committed data (hidden); an unknown target (complete-empty); and canonical lowercase source UUIDs from an uppercase target input. The browser covers the wider list (self-reference, future/expired windows, retract-then-reassert, rejected statement) through AC20's differential test, because the browser path is new core code. Sets are compared, not order. +3. **Budgets are exact caps.** Both are required and non-negative; zero is a real limit; neither has an "unlimited" sentinel or default. With N live links and a sufficient `maxRecords`: `maxLinks = N` → complete; `N-1` → exhausted(links). (With an insufficient `maxRecords`, core returns exhausted(records) first, per #924 AC15; bindings do not change that.) `0,0` on an unknown target → complete-empty with 0 records; `0` records on a target with a link → exhausted(records). Retry with larger budgets gives complete. Records examined never exceeds the records budget. The largest accepted value on a tiny dataset works without proportional allocation. Accepted ranges: + - UniFFI (Python, Android, Swift, template): signed 64-bit arguments, as minigraf-java. Accepted values are 0 through `min(i64::MAX, usize::MAX)`, so 2^63-1 on 64-bit targets and 2^32-1 on 32-bit targets (Android armv7). Negative or above that → API-017. + - C: signed `int64_t` budget arguments with the same accepted range and the same API-017 rule, so a negative value is detectable. + - Node: finite integer `number`s 0 through `Number.MAX_SAFE_INTEGER`. Browser: finite integer `number`s 0 through 2^32-1 (wasm32 `usize`). Fractions, NaN, ±Infinity, negatives and out-of-range values → API-017; `-0` counts as 0. Never truncated, wrapped or saturated. Values at or above `MAX_SAFE_INTEGER` are **not** unlimited (unlike `to_limit`). + - Python: a public-API test passes `2**63` and `-1` and gets API-017 (`MiniGrafError` carrying `[API-017]`), not an `OverflowError` or a silently coerced value. Wrong Python types (e.g. a `str` budget) may keep Python's ordinary `TypeError`. +4. **Errors and precedence.** Invalid UUID → API-017. A finished transaction → API-018, reported before argument validation. A callback from a user function of one of the transaction's own statements → INT-001, before locking or validation, without blocking, deadlocking or panicking. Tests combine them: invalid arguments (including Python's `2**63`) on a finished transaction give API-018, and from a reentrant callback give INT-001. Node/C: after the database's `close()`, the lookup gives API-018. Read, decode and lock errors stay errors; they never become complete-empty or exhausted. An unknown future core outcome or budget variant becomes an error (as Java's INT-000), never a success-shaped result. +5. **Read-only and lifecycle.** Complete, exhausted and API-017 calls leave the transaction open and usable. The lookup stages nothing, takes no `tx_count`, writes no WAL entry, and (browser) starts no flush. Later statements, commit, rollback, scope-form exit (Python `with`, Kotlin `use`, Swift `withWriteTransaction`) and drop/free behave as they did without the lookup. A transaction used from another thread (UniFFI, C) serializes with other calls without deadlock. +6. **Storage paths through the binding** (native bindings): in-memory staging, and file commit → close → reopen, plus rollback leaving the pre-transaction set. Promotion to a large transaction, WAL recovery, failed handles and the model-based check are core paths the binding only forwards; core's suites cover them and keep passing at the chosen pin. They are not repeated in each binding. +7. **Two-level tests.** Each binding has (a) Rust crate tests for AC2-AC6, including the reentry and finished cases (the Java crate's incoming-ref tests and its reentry UDF `CallsItsTx` are the pattern), and (b) language-level tests through the built package or consumer test: complete, complete-empty, both exhaustion reasons, Keyword exclusion, retry, commit → reopen (file), rollback, and finished error. Plus reentry where the language can register a user function. New test files are run by the existing runners (Node's `package.json` `test` lists files explicitly). +8. **Pins and CI.** The final `Cargo.toml` pin is a core `v3` commit containing #924 (and PR 1, for wasm). Every existing CI job of the repository (`ci.yml`, `package.yml`, consumer tests, cbindgen drift, Android emulator, Swift, browser lanes) is green. Anything the pin move breaks is fixed in the same PR and listed in its description. +9. **READMEs** document the signature, accepted budget ranges, outcome branching, scalar-Ref-only and Keyword exclusion, valid time ignored, "require complete before deleting; retry or abandon on exhausted", the error codes, and that exhaustion does not undo earlier staged writes. Any `readme_sync` check passes with the new example. + +**UniFFI-specific** + +10. **Same UniFFI contract as Java.** Python, Android, Swift and the template export the same method, record, enums, field names, argument types, outcome semantics and error precedence as minigraf-java v3. No existing exported API of these bindings changes. (Keeping the shared `src/lib.rs` identical across the five UniFFI repositories, as the template's header asks, is the project convention and is recommended; see §8. It is not an acceptance criterion, and a Java PR is not required to restore it.) +11. **Python** exports the outcome, link and budget types from `minigraf` and lists them in `__all__`. The lookup is callable on the object `begin_write()` returns, inside and outside `with`. +12. **Android** source compatibility: the Kotlin call and outcome branching from minigraf-java's README or consumer test (`tx.incomingRefs(target, maxLinks, maxRecords)`, `IncomingRefs.Complete`/`.Exhausted`, `IncomingRefBudget.LINKS`/`.RECORDS`, `recordsExamined`) compiles and runs unchanged against the AAR in `consumer-test/tests/contract.kt`. +13. **Swift**: the generated enum and record are usable with Swift pattern matching, directly and inside `withWriteTransaction`, in `Tests/swift/main.swift` and the packaged `ContractTests.swift`. +14. **Template**: same Rust surface and tests as the other shims; `consumer-test/run.sh` checks the new exported symbols. No language SDK is invented. + +**Node and browser (shared JS shape)** + +15. **One JS result shape** for Node and the browser: `{ status: 'complete', links: Array<{ source: string, attribute: string }>, recordsExamined: number }` or `{ status: 'exhausted', budget: 'links' | 'records', recordsExamined: number }`. It is a plain object, not a JSON string. The TypeScript declarations (Node `index.d.ts`/`minigraf.d.ts`; the browser's generated typings, augmented if needed) are a discriminated union, so a type-checked consumer narrows on `status`, and reading `links` on the exhausted branch fails to type-check. Each package's consumer test includes a TypeScript-checked snippet, or the equivalent `tsc --noEmit` check over it. + +**C-specific** + +16. **Typed C result, not JSON.** The header offers a lookup on `MiniGrafTx*` that yields a result object or struct the caller reads with typed accessors or fields: outcome kind, budget, records examined, link count, and each link's source UUID and attribute as NUL-terminated strings. The result owns its strings until one documented disposal function frees it; the result stays readable after the transaction is committed, rolled back or freed. Failure returns a distinguishable value (e.g. NULL or -1) with the message in `minigraf_tx_last_error`; a later successful call clears it. NULL handle, NULL target and invalid UTF-8 target are defined (an error, or a documented no-op for NULL handle, following the existing `minigraf_tx_*` convention). Disposal of NULL does nothing. The regenerated `include/minigraf.h` matches cbindgen in CI. `tests/c/etl_smoke.c` (or a new compiled C test run by CI) and `consumer-test/contract.c` exercise complete-empty, complete with links, both exhaustion reasons, invalid UUID, finished, reentry from a user function, and disposal. Callers never free result-owned strings with `minigraf_string_free`. + +**Browser-specific (core PR 1, minigraf-wasm PR 8)** + +17. **Browser surface.** `db.beginWrite().incomingRefs(target, maxLinks, maxRecords)` is synchronous and returns AC15's shape. It sees the transaction's earlier statements and works on in-memory, IndexedDB and OPFS databases, including committed-then-reopened data. A finished transaction or a closed database → `[API-018]`. Existing guards are unchanged: other `BrowserDb` calls during the transaction still give `[INT-001]`; commit durability is still the commit Promise; rollback and free still discard. +18. **Browser reentry through the exported JS.** A JS user function, registered on the `BrowserDb` and running inside one of the transaction's own statements, that calls `incomingRefs`, `execute`, `commit` or `rollback` on the **same** `BrowserWriteTransaction` gets an error whose message starts with `[INT-001]`, without a wasm trap, a wasm-bindgen recursive-borrow error or a hang. The transaction stays open and usable afterwards. Tested in the browser test suite through the generated JS bindings, not only by direct Rust calls. If the existing `execute`/`commit`/`rollback` currently surface a different error here, this mission makes them INT-001 too, since it touches the same guard. The PR names that behaviour change in CHANGELOG. +19. **Failed flush.** After an IndexedDB flush failure (the STG-046 state), a lookup on a new transaction over readable state still answers. It does not go through the failed-flush write refusal (a lookup is a read, as #924 AC8a). Closed stays closed. Tested separately from a rejected statement (`tx_tests.rs` / `flush_tests.rs` patterns). +20. **Browser equals native.** For a fixed list of statement sequences (asserts, retracts, Keyword aliases, sets, future/expired windows, a self-reference, retract-then-reassert, a rejected statement, commits, rollbacks, checkpoints — including every browser case AC2 names), the browser lookup returns the same link sets as an in-memory core `OwnedWriteTransaction::incoming_refs` over the same sequence. Tested with a wasm-bindgen differential test, following the #824 B3 pattern. +21. **Browser boundedness.** At fixed target data and budgets, adding ≥10,000 unrelated facts (scalar facts, Keyword values, and refs to other targets) leaves `recordsExamined` unchanged for staged and for committed browser data. Test-only instrumentation of records enumerated and copied during setup (core's existing #924 instrumentation, or equivalent) is also unchanged, with #924's fixed prefix-end-probe allowance. Lookup setup enumerates, copies or indexes no unrelated facts and does no work proportional to the whole staged set (today's `Staged::read_view` does both, `src/db.rs:2528-2540`). The test may run natively against the same browser code path where wasm timing makes 10,000 facts impractical, as long as the code path is the one `BrowserWriteTransaction` uses. +22. **wasm package.** minigraf-wasm pins a core `v3` commit containing PR 1. `consumer-test/browser/contract.js`, run against the packed package in the existing browser lanes (main thread and OPFS worker), covers complete, both exhaustion reasons, Keyword exclusion, retry, commit → reopen, rollback and finished. The browser TypeScript declarations narrow per AC15. + +**WASI** + +23. **No WASI API.** The REPL gets no new command and no transaction handle. `wasi-pkg/README.md` says the incoming-ref lookup is not available from the REPL (auto-commit, no transactions, #824). It points to Rust compiled for WASI (which has `incoming_refs`) or a transaction-capable binding. Existing WASI tests pass. The PR records the core revision the WASI artifact was built from in validation (because `core-ref` defaults to mutable `v3`), without changing release-tag behaviour. + +**Core, compatibility, size, docs** + +24. **No regressions.** No file-format, WAL, grammar, Datalog, native-API or error-code change. No existing binding API changes, except AC18 if it applies. Core: all tests, clippy and fmt pass, including the wasm32 browser clippy job. Binary size ≤ 1,280,000 bytes, with before/after bytes in PR 1; browser `.wasm` size before/after is recorded in PR 1 or 8. If PR 1 changes native staging or index maintenance (it should not), #924's write-path measurement and its >5% user-acceptance rule apply. +25. **Docs in sync.** + - Core: `CHANGELOG.md` (v3 Unreleased: browser lookup; binding parity note); `CLAUDE.md` (test count; browser module note); `docs/TEST_COVERAGE.md`; `ROADMAP.md` (fix the stale #924 line; add #925); `README.md` if it lists browser transaction methods; rustdoc on the browser method; the spec copy. + - Each binding's README (AC9). + - Docs site: `content/cookbook-application-workflows.md` gets a Python, Kotlin (Android shares the JVM example), Swift, Node, C and browser example in the existing v3 `@since` block, replaces the "core/JVM only" sentence, and adds the WASI note. Check `content/architecture.md`, `use-cases.md`, `database-tools.md` and `comparison.md` and update where they describe binding or browser transactions. The link check passes. + - `docs/ERROR_REFERENCE.md` changes only if an error's meaning changes. +26. **Issue record.** #925 gets a comment recording the decisions: BrowserDb included on `BrowserWriteTransaction` (user, 2026-11-29); WASI excluded (REPL auto-commit, #824); shapes per AC15/AC16. After the last PR merges, #925 gets a closing comment listing all the mission's PRs (nine unless the Generator adds an optional Java PR, §8) and each repository's pinned core commit, and is closed by hand. + +## 5. Edge Cases & Boundaries + +- **Zero records ≠ empty.** An unknown target (absent from every layer) completes with 0 records under `maxRecords = 0`. A target with only dead history may exhaust(records) at 0. +- **Layers cancel.** Committed assertion + staged retraction = no link. Exhausted(links) only after N+1 live links are established in the current view (#924 AC15). Bindings convert core's outcome and never re-derive it. +- **Counts depend on representation.** Checkpoint, promotion and browser flush can change `recordsExamined` for the same links. Cross-binding tests compare sets and the "≤ budget" rule, not exact counts across differently prepared fixtures, except where a single fixture pins them (as Java's test does). +- **Exhaustion keeps earlier writes.** It is not a rollback; scope forms still roll back unless committed. README examples run discovery before staging deletes. +- **32-bit targets.** Android 32-bit ABIs and wasm32 accept at most 2^32-1. A 64-bit-only test value must not be assumed valid everywhere. +- **Python integers** beyond i64 reach UniFFI's lowering first (AC3). +- **C ownership.** A zero-length link list is not failure. Result lifetime is independent of the transaction. Detecting double-free or dangling pointers is not required. +- **Browser has no WAL and no promotion.** Don't copy native WAL or large-transaction requirements onto it. IndexedDB and OPFS keep their distinct persistence rules. +- **Browser during an in-flight commit.** After `commit()` is called the transaction is finished, so the lookup gives `[API-018]`. +- **Test availability.** Android emulator, iOS/macOS Swift, macOS Safari and OPFS lanes run in existing CI runners. A missing local SDK is not a reason to skip a requirement or to claim it passed. + +## 6. Key Decisions + +| Decision | Rationale | +|---|---| +| Include `BrowserWriteTransaction.incomingRefs` (user, 2026-11-29) | The transaction exists since #824 and shares `Staged`'s target index; browser is Tier 1 from v3.0.0. A database-level lookup would lose discover-then-write. | +| WASI excluded, documented | #824 maintainer decision: REPL auto-commit only. Rust on WASI already has the method. | +| Keep minigraf-java's UniFFI contract unchanged; no Java PR required | Android source compatibility; Java is merged and tested. An optional Java PR only if the Generator chooses to keep the shared shim identical after changing it (§8). | +| UniFFI/C budget range = `0..=min(i64::MAX, usize::MAX)` | Signed 64-bit ABI as Java; detects negatives; 32-bit targets are bounded by `usize`. | +| Bindings test marshalling; core proves semantics | Core's suites already cover the semantic matrix; the browser path is new core code, so it gets the wider differential test. | +| Exact caps; no unlimited sentinel in any binding | #924 budgets are explicit; Java uses `to_usize`. Node/browser `to_limit`-style saturation would change meaning. | +| One JS shape for Node and browser, `status` discriminant | Direct JS use plus TypeScript narrowing, no JSON. `number` suffices: counts never exceed the accepted budget. No BigInt overload. | +| C gets a typed owned result, not JSON | #925 requires a typed outcome with no parsing; JSON would need a parser in C. Representation (opaque + accessors, or tagged struct) is the Generator's choice; lifetime and errors are specified. | +| No new error codes | API-017/018, INT-001 and the existing read errors cover everything (#925). | +| Base `v3`, no backport | New v3.0.0 feature. | + +## 7. Out of Scope + +- Cascading delete, referential integrity, DEL7/benchmark pins. +- Any change to #924 semantics, core native API, Datalog, grammar, file format or WAL. +- A database-level lookup on any binding; WASI REPL commands; WASI host exports. +- BigInt budget overloads; multi-target lookup, cursors, `:as-of`/valid-time variants, refs inside sets. +- Shared-shim infrastructure, binding deduplication or unrelated numeric-helper cleanup (beyond AC18 if needed). +- Release tagging and publishing. + +## 8. Possible Directions & Ideas (non-binding) + +- The Java diff (`git -C ../minigraf-java diff 364ca6c^1 364ca6c`) is the model for the UniFFI shims and their tests. Applying its `src/lib.rs` part as-is satisfies AC2's Rust-crate coverage and keeps the five shared shims identical (the project convention). Language-specific checks, such as Python's out-of-i64 budgets, can live in the language wrapper (`minigraf/__init__.py` already adds Python behaviour at `:212-237,278-287`), which keeps the shim shared. If the Generator does change the shared shim, applying the same change to minigraf-java in an extra PR keeps the convention. +- For the browser, a core helper that runs the three-layer walk given the database snapshot and a `&Staged` would let `TxState::incoming_refs` and `BrowserWriteTransaction` share one code path. That would make AC20/AC21 largely follow from core's existing tests. The Generator decides. +- Settle AC18 (the exported-JS reentry behaviour) first: it is the one technical unknown. One option is to check reentry through `Db`'s running state before wasm-bindgen's `&mut` borrow, for example by taking `&self` plus interior mutability for `staged`. +- For C, an opaque `MiniGrafIncomingRefs*` with accessor functions keeps the ABI free to evolve; a tagged struct is also acceptable. +- Order: PR 1 (browser) can run in parallel with PRs 2-7; PR 8 after PR 1 merges; PR 9 last. Use the bench machine for heavy builds (Android/iOS CI runs remotely anyway). +- `test-driven-development` fits the boundary tests; `verification-before-completion` fits the multi-repo CI claims. + +## Open Questions + +None. Codex approved in round 3; planning rounds: Claude-01/Codex-01, Claude-02/Codex-02, Claude-03/Codex-03. diff --git a/docs/testing/925-browser-incoming-refs.md b/docs/testing/925-browser-incoming-refs.md new file mode 100644 index 0000000000..82fd20efd7 --- /dev/null +++ b/docs/testing/925-browser-incoming-refs.md @@ -0,0 +1,108 @@ +# #925 core browser incoming references + +PR 1 only, based on core `353bd58be48dac043fa131305f620324eacbadff`. +The [design](../superpowers/specs/2026-11-29-925-incoming-ref-parity-design.md) +is unchanged. No native public API, storage format, grammar, dependencies or +write-time index maintenance changed. + +## Behavior and acceptance coverage + +`BrowserWriteTransaction.incomingRefs` returns a plain JS object with the +`IncomingRefs` TypeScript discriminated union. The native and browser paths +call the same `db::incoming_refs` helper over a snapshot and borrowed staging. +It walks only the target's committed, pending and staged records, without a +staged read view or failed-flush write admission. + +| Criteria | Evidence | +|---|---| +| AC1–5, AC15, AC17 | `incoming_refs_js_budgets_and_precedence`, `incoming_refs_in_memory_lifecycle`, `incoming_refs_persistent_reopen_and_lifecycle`; generated declaration check in `tests/browser/incoming_refs.ts` | +| AC18 | `transaction_reentry_through_js_is_int001`, `transaction_callback_close_is_busy_and_js_free_discards`; existing database guard and lifecycle tests | +| AC19 | `incoming_refs_after_failed_indexeddb_flush`, separate from rejected-statement coverage | +| AC20 | `incoming_refs_matches_owned_transaction`: fixed statement sequences, canonical UUID strings, exact link sets, ignored valid time, non-Ref exclusions, rejected statements, commits, rollbacks and checkpoints | +| AC21 | `incoming_refs_unrelated_growth_is_bounded`: 10,000 unrelated scalar/Keyword/other-target Ref facts; unchanged records examined and independent enumeration, allowing one committed prefix-end probe | +| AC24–25 | Native suite, browser suites, lint/build/type checks, sizes and synchronized core docs below | + +The persistence helper runs IndexedDB on the main thread and OPFS in the +worker build. The failed-flush case explicitly uses IndexedDB in both builds. +All eight added tests run in both contexts; the native test inventory is unchanged. + +## Test-first findings + +Before changing transaction receivers, the generated-JS reentry regression +failed in Firefox with: + +```text +execute: Error: recursive use of an object detected which would lead to unsafe aliasing in rust +``` + +After adding the per-transaction `RefCell` guard and shared receivers, the +same test advanced through `execute`, `commit` and `rollback`, then failed +because `incomingRefs` did not yet exist. Adding the lookup made all four +methods report `[INT-001]`, with the transaction still usable afterwards. +The test passes the actual JS transaction object to a `js_sys::Function`. + +A subsequent boundary regression passing a non-string UUID target failed +with `Error: expected a string argument, found object` in generated glue. +All three lookup arguments now arrive as uncoerced `JsValue`s and are +validated after reentry and lifecycle checks. Their generated TypeScript +types remain `string, number, number`; `rollback(): void` also remains unchanged. + +## Local verification — 2026-11-29 + +Builds used `CARGO_BUILD_JOBS=4` and offline Cargo resolution. Default compiler: +Rust 1.94.0; size comparison also used installed Rust 1.99.1. No release-mode +tests were run. + +A second run outside the sandbox repeated `wasm-pack test --headless +--firefox --features browser` (103 passed) and the worker build with `--lib` +(136 passed), the strict browser and `wasm32-wasip1` Clippy runs, and the two +commands of the CI declaration step from an empty output directory: +`wasm-pack build --dev --target web --out-dir target/browser-types --features +browser`, then the `tsc` command below. All passed. The `wasm32-wasip1` tests +were not run locally (no Wasmtime). On a second Linux x86_64 host with Rust +1.100.0, `cargo fmt --check`, `cargo build` and `cargo test` passed (2,190 +passed, 0 failed, 23 ignored), and the `dist` binary was 1,254,416 bytes both +at the base and with this change. + +| Command | Result | +|---|---| +| `cargo build --offline` | Pass | +| `cargo test --offline` | 2,190 passed, 0 failed, 23 ignored, including examples and doctests | +| `cargo clippy --offline --all-targets -- -D warnings` | Pass | +| `cargo fmt --check` and `git diff --check` | Pass | +| `cargo clippy --offline --target wasm32-unknown-unknown --features browser -- -D warnings` | Pass | +| `cargo clippy --offline --target wasm32-unknown-unknown --features browser --all-targets` | Fails in the existing native-only `benches/incoming_refs_write.rs`: unavailable `criterion`, `tempfile`, file APIs and consequential type errors. The benchmark and Cargo manifest are unchanged. | +| `cargo test --offline --target wasm32-unknown-unknown --features browser --lib --no-run` | Pass | +| `RUSTFLAGS='--cfg minigraf_browser_worker' cargo build --offline --target wasm32-unknown-unknown --features browser --lib` | Pass | +| `cargo test --offline --target wasm32-unknown-unknown --features browser --lib` with the browser runner | Firefox: 103 passed, 0 failed | +| Same test command with `RUSTFLAGS='--cfg minigraf_browser_worker'` | Firefox worker: 136 passed, 0 failed | +| `tsc --strict --noEmit --target ES2020 --lib ES2020,DOM,ESNext.Disposable --moduleResolution node tests/browser/incoming_refs.ts` | Pass against generated release-library declarations, TypeScript 5.9.3 | + +The runner was cached `wasm-bindgen-test-runner` 0.2.130, with geckodriver +0.36.0 and Firefox 161.0. `CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER` and +`GECKODRIVER` pointed to these binaries; `WASM_BINDGEN_USE_BROWSER=1` and +`WASM_BINDGEN_TEST_ONLY_WEB=1` selected headless browser execution. The worker +run also set `WASM_BINDGEN_TEST_TIMEOUT=180`. Running the local loopback test +server required execution outside the filesystem/network sandbox. +`wasm-pack test` itself could not install into its read-only tooling cache +in the sandbox, so the table's browser rows use the equivalent runner commands. +Chrome and Safari were not run locally; their existing CI lanes remain. + +## Size comparison + +Both native comparisons use `cargo build --offline --profile dist --bin minigraf`. +The Rust 1.99.1 baseline was built from a `git archive` of the base with the +same resolved Cargo lockfile; the package was rebuilt for the changed source. +Browser builds use `cargo build --offline --target wasm32-unknown-unknown +--features browser --release --lib`, then wasm-bindgen 0.2.130 `--target web`. +No wasm-opt pass or new size threshold was applied. + +| Artifact | Before (bytes) | After (bytes) | Delta | +|---|---:|---:|---:| +| Native dist, Rust 1.99.1 | 1,252,144 | 1,252,144 | 0 | +| Native dist, Rust 1.94.0 | 1,289,768 | 1,289,768 | 0 | +| Browser raw `.wasm`, Rust 1.94.0 | 1,741,290 | 1,752,301 | +11,011 | +| Browser wasm-bindgen `_bg.wasm`, Rust 1.94.0 | 1,103,687 | 1,111,681 | +7,994 | + +Rust 1.99.1 meets the 1,280,000-byte native gate. Rust 1.94.0 exceeds it on +both the unchanged base and this change; no native size increase was observed. diff --git a/src/browser/flush_tests.rs b/src/browser/flush_tests.rs index 54e823972b..6f88df8c37 100644 --- a/src/browser/flush_tests.rs +++ b/src/browser/flush_tests.rs @@ -232,7 +232,7 @@ async fn refused(db: &BrowserDb) { "STG-046", ); for nonempty in [false, true] { - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); if nonempty { tx.execute(&write(901, 902)).unwrap(); } @@ -362,7 +362,7 @@ async fn commit_checkpoint_and_smaller_import_fail_atomically() { let fault = Fault::for_db(&db, "abort"); let p = match operation { "commit" => { - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); tx.execute(&write(400, 401)).unwrap(); tx.commit() } @@ -432,7 +432,7 @@ async fn preparation_error_keeps_code_and_fails_handle() { }); let p = match operation { "commit" => { - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); tx.execute(&write(2, 3)).unwrap(); tx.commit() } @@ -462,7 +462,7 @@ async fn overlapping_failure_never_submits_successor() { let before = adapter(&db).load_all_pages().await.unwrap(); let fault = Fault::for_db(&db, "delayed-abort"); let first = if pair.starts_with("commit") { - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); tx.execute(&write(2, 402)).unwrap(); tx.commit() } else if pair.starts_with("import") { @@ -521,7 +521,7 @@ async fn successful_checkpoint_boundary_and_mixed_overlap() { ); let replace = import(&db, Uint8Array::new_with_length(0)); tick().await; - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); tx.execute(&write(600, 602)).unwrap(); let commit = tx.commit(); let retract = execute(&db, "(retract [[:e600 :n 600]])".into()); @@ -548,7 +548,7 @@ async fn close_discards_every_unstarted_flush() { tick().await; let second = match operation { "commit" => { - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); tx.execute(&write(3, 4)).unwrap(); tx.commit() } diff --git a/src/browser/incoming_tests.rs b/src/browser/incoming_tests.rs new file mode 100644 index 0000000000..93ab969518 --- /dev/null +++ b/src/browser/incoming_tests.rs @@ -0,0 +1,382 @@ +//! Browser incoming references (#925): JS boundaries, storage parity and +//! bounded work through the same lookup used by native transactions. + +use super::tests::{fresh_persistent, reopen_persistent, scratch}; +use super::*; +use js_sys::{Function, Reflect}; +use std::collections::BTreeSet; +use wasm_bindgen_futures::JsFuture; +use wasm_bindgen_test::*; + +#[cfg(not(minigraf_browser_worker))] +wasm_bindgen_test_configure!(run_in_browser); +#[cfg(minigraf_browser_worker)] +wasm_bindgen_test_configure!(run_in_dedicated_worker); + +const TARGET: &str = "abcdef01-2345-6789-abcd-ef0123456789"; +const SOURCE: &str = "abcdef02-2345-6789-abcd-ef0123456789"; +const UNKNOWN: &str = "00000000-0000-0000-0000-000000000000"; + +fn statement(verb: &str, attr: &str) -> String { + format!("({verb} [[#uuid \"{SOURCE}\" {attr} #uuid \"{TARGET}\"]])") +} + +fn field(value: &JsValue, name: &str) -> JsValue { + Reflect::get(value, &name.into()).unwrap() +} + +fn lookup(tx: &BrowserWriteTransaction, target: &str, links: u32, records: u32) -> JsValue { + tx.incoming_refs(target.into(), links.into(), records.into()) + .unwrap() +} + +fn links(out: &JsValue) -> BTreeSet<(String, String)> { + assert_eq!( + field(out, "status").as_string().as_deref(), + Some("complete") + ); + js_sys::Array::from(&field(out, "links")) + .iter() + .map(|link| { + ( + field(&link, "source").as_string().unwrap(), + field(&link, "attribute").as_string().unwrap(), + ) + }) + .collect() +} + +fn code(result: Result, expected: &str) { + let Err(error) = result else { + panic!("expected {expected}") + }; + let message = error.as_string().expect("coded error string"); + assert!(message.starts_with(&format!("[{expected}]")), "{message}"); +} + +/// Every numeric and nonnumeric boundary goes through generated glue. In +/// particular, typed f64/u32 arguments would silently coerce some of these. +#[wasm_bindgen_test] +async fn incoming_refs_js_budgets_and_precedence() { + let db = scratch().await; + let tx = db.begin_write().unwrap(); + tx.execute(&statement("transact", ":a")).unwrap(); + tx.execute(&statement("transact", ":b")).unwrap(); + let before = db.inner.borrow().fact_storage.current_tx_count(); + let sequence = db.inner.flush_sequence.get(); + let tx = JsValue::from(tx); + Function::new_with_args( + "tx,target,unknown,source", + r#" + function check(ok, message) { if (!ok) throw message; } + function error(f, code) { + try { f(); } catch (e) { + check(String(e).startsWith('[' + code + ']'), String(e)); return; + } + throw 'expected ' + code; + } + function complete(out, n, records) { + check(Object.getPrototypeOf(out) === Object.prototype, 'plain object'); + check(out.status === 'complete' && out.links.length === n, 'complete'); + check(out.recordsExamined === records, 'record count'); + check(!('budget' in out), 'no budget on complete'); + for (const link of out.links) check(link.source === source, 'canonical source'); + } + function exhausted(out, budget, records) { + check(out.status === 'exhausted' && out.budget === budget, 'exhausted'); + check(!('links' in out), 'no partial links'); + check(out.recordsExamined === records, 'exhausted count'); + } + complete(tx.incomingRefs(target.toUpperCase(), 2, 2), 2, 2); + exhausted(tx.incomingRefs(target, 1, 2), 'links', 2); + exhausted(tx.incomingRefs(target, 2, 1), 'records', 1); + exhausted(tx.incomingRefs(target, 0, 0), 'records', 0); + exhausted(tx.incomingRefs(target, 0, 2), 'links', 2); + complete(tx.incomingRefs(unknown, 0, 0), 0, 0); + complete(tx.incomingRefs(unknown, -0, -0), 0, 0); + complete(tx.incomingRefs(target, 0xffffffff, 0xffffffff), 2, 2); + for (const bad of [-1, -0.5, 0.5, NaN, Infinity, -Infinity, + 0x100000000, Number.MAX_SAFE_INTEGER, Number.MAX_VALUE, + '2', '', null, undefined, true, false, 2n, {}, [], new Number(2), + { valueOf() { throw 'must not coerce'; } }]) { + error(() => tx.incomingRefs(target, bad, 2), 'API-017'); + error(() => tx.incomingRefs(target, 2, bad), 'API-017'); + } + error(() => tx.incomingRefs(target), 'API-017'); + for (const bad of ['invalid', '', null, undefined, 0, {}, Symbol('target')]) { + error(() => tx.incomingRefs(bad, 2, 2), 'API-017'); + } + complete(tx.incomingRefs(target, 2, 2), 2, 2); + tx.execute('(transact [[:still-open :n 1]])'); + tx.rollback(); + error(() => tx.incomingRefs('invalid', -1, NaN), 'API-018'); + error(() => tx.incomingRefs(null, 'invalid', NaN), 'API-018'); + tx.free(); + "#, + ) + .call4( + &JsValue::NULL, + &tx, + &TARGET.into(), + &UNKNOWN.into(), + &SOURCE.into(), + ) + .unwrap(); + assert_eq!(db.inner.borrow().fact_storage.current_tx_count(), before); + assert_eq!(db.inner.flush_sequence.get(), sequence); + let tx = db.begin_write().unwrap(); + assert!(links(&lookup(&tx, TARGET, 0, 0)).is_empty()); +} + +async fn lifecycle(db: BrowserDb, persistent: bool) { + let tx = db.begin_write().unwrap(); + tx.execute(&statement("transact", ":a")).unwrap(); + assert_eq!(links(&lookup(&tx, TARGET, 1, 1)).len(), 1); + code(db.query("(query [:find ?e :where [?e :a _]])"), "INT-001"); + let pending = tx.commit(); + code( + tx.incoming_refs("invalid".into(), (-1).into(), f64::NAN.into()), + "API-018", + ); + JsFuture::from(pending).await.unwrap(); + code( + tx.incoming_refs(TARGET.into(), 1.into(), 1.into()), + "API-018", + ); + let db = if persistent { + reopen_persistent(db).await + } else { + db + }; + let tx = db.begin_write().unwrap(); + assert_eq!( + links(&lookup(&tx, TARGET, 1, 10)), + BTreeSet::from([(SOURCE.into(), ":a".into())]) + ); + tx.execute(&statement("retract", ":a")).unwrap(); + assert!(links(&lookup(&tx, TARGET, 0, 10)).is_empty()); + tx.rollback().unwrap(); + code( + tx.incoming_refs("invalid".into(), (-1).into(), f64::NAN.into()), + "API-018", + ); + let tx = db.begin_write().unwrap(); + assert_eq!(links(&lookup(&tx, TARGET, 1, 10)).len(), 1); + db.close().unwrap(); + code( + tx.incoming_refs("invalid".into(), (-1).into(), f64::NAN.into()), + "API-018", + ); + tx.rollback().unwrap(); +} + +#[wasm_bindgen_test] +async fn incoming_refs_in_memory_lifecycle() { + lifecycle(BrowserDb::open_in_memory().unwrap(), false).await; +} + +/// IndexedDB on the main thread, OPFS in the worker build. +#[wasm_bindgen_test] +async fn incoming_refs_persistent_reopen_and_lifecycle() { + lifecycle(fresh_persistent("incoming-925-lifecycle").await, true).await; +} + +#[wasm_bindgen_test] +async fn incoming_refs_after_failed_indexeddb_flush() { + let name = "incoming-925-failed-flush"; + drop(super::tests::empty_store(name).await); + let db = BrowserDb::open(name).await.unwrap(); + db.execute(statement("transact", ":a")).await.unwrap(); + db.inner.borrow().idb.as_ref().unwrap().db.close(); + code(db.execute(statement("transact", ":b")).await, "STG-048"); + assert!(db.inner.failed_flush.get().is_some()); + let tx = db.begin_write().unwrap(); + let sequence = db.inner.flush_sequence.get(); + let count = db.inner.borrow().fact_storage.current_tx_count(); + assert_eq!(links(&lookup(&tx, TARGET, 2, 10)).len(), 2); + tx.execute(&statement("retract", ":a")).unwrap(); + assert_eq!( + links(&lookup(&tx, TARGET, 1, 10)), + BTreeSet::from([(SOURCE.into(), ":b".into())]) + ); + assert_eq!(db.inner.flush_sequence.get(), sequence); + assert_eq!(db.inner.borrow().fact_storage.current_tx_count(), count); + code(JsFuture::from(tx.commit()).await, "STG-046"); + code( + tx.incoming_refs(TARGET.into(), 2.into(), 10.into()), + "API-018", + ); + db.close().unwrap(); + let db = BrowserDb::open(name).await.unwrap(); + let tx = db.begin_write().unwrap(); + assert_eq!( + links(&lookup(&tx, TARGET, 1, 10)), + BTreeSet::from([(SOURCE.into(), ":a".into())]) + ); +} + +fn compare( + browser: &BrowserWriteTransaction, + native: &mut crate::OwnedWriteTransaction, + target: uuid::Uuid, +) { + for (max_links, max_records) in [(0, 0), (0, 100), (1, 100), (100, 100)] { + let b = lookup( + browser, + &target.to_string().to_uppercase(), + max_links, + max_records, + ); + let n = native + .incoming_refs( + target, + crate::IncomingRefLimits::new(max_links as usize, max_records as usize), + ) + .unwrap(); + assert!(field(&b, "recordsExamined").as_f64().unwrap() <= f64::from(max_records)); + match n { + crate::IncomingRefs::Complete { + links: expected, .. + } => { + let expected = expected + .into_iter() + .map(|l| (l.source.to_string(), l.attribute)) + .collect(); + assert_eq!(links(&b), expected); + } + crate::IncomingRefs::Exhausted { budget, .. } => { + assert_eq!( + field(&b, "status").as_string().as_deref(), + Some("exhausted") + ); + let expected = match budget { + crate::IncomingRefBudget::Links => "links", + crate::IncomingRefBudget::Records => "records", + }; + assert_eq!(field(&b, "budget").as_string().as_deref(), Some(expected)); + assert!(!Reflect::has(&b, &"links".into()).unwrap()); + } + } + } +} + +#[wasm_bindgen_test] +async fn incoming_refs_matches_owned_transaction() { + let target = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, b":target"); + let sequences = [ + vec![format!( + r#"(transact [[#uuid "{SOURCE}" :a #uuid "{target}"] + [#uuid "{SOURCE}" :b #uuid "{target}"] + [:alias :a :target] [:string :a "{target}"] [:set :a #{{#uuid "{target}"}}] + [#uuid "{target}" :self #uuid "{target}"] + [:future :a #uuid "{target}" {{:valid-from "2090-01-01T00:00:00Z"}}] + [:expired :a #uuid "{target}" {{:valid-from "2000-01-01T00:00:00Z" :valid-to "2001-01-01T00:00:00Z"}}]])"# + )], + vec![ + format!(r#"(retract [[#uuid "{SOURCE}" :a #uuid "{target}"]])"#), + format!(r#"(transact [[#uuid "{SOURCE}" :a #uuid "{target}"]])"#), + format!( + r#"(transact [[:rejected :a #uuid "{target}" {{:valid-from "2020-01-01T00:00:00Z"}}] + [:rejected :a #uuid "{target}" {{:valid-from "2021-01-01T00:00:00Z"}}]])"# + ), + format!(r#"(retract [[#uuid "{SOURCE}" :b #uuid "{target}"]])"#), + ], + vec![format!( + r#"(transact [[:rolled-back :a #uuid "{target}"]])"# + )], + vec![], + ]; + let browser = scratch().await; + let native = crate::Minigraf::in_memory().unwrap(); + for (i, statements) in sequences.iter().enumerate() { + let b = browser.begin_write().unwrap(); + let mut n = native.begin_write_owned().unwrap(); + compare(&b, &mut n, target); + for stmt in statements { + let br = b.execute(stmt); + let nr = n.execute(stmt); + assert_eq!(br.is_ok(), nr.is_ok()); + if let Err(e) = nr { + code(br, e.code()); + } + compare(&b, &mut n, target); + compare(&b, &mut n, uuid::Uuid::nil()); + } + if i == 2 { + b.rollback().unwrap(); + n.rollback(); + } else { + JsFuture::from(b.commit()).await.unwrap(); + n.commit().unwrap(); + } + browser.checkpoint().await.unwrap(); + native.checkpoint().unwrap(); + let b = browser.begin_write().unwrap(); + let mut n = native.begin_write_owned().unwrap(); + compare(&b, &mut n, target); + } +} + +#[wasm_bindgen_test] +async fn incoming_refs_unrelated_growth_is_bounded() { + use std::fmt::Write; + for committed in [false, true] { + let mut baseline = None; + for unrelated in [0, 10_000] { + let db = scratch().await; + let tx = db.begin_write().unwrap(); + tx.execute(&statement("transact", ":a")).unwrap(); + tx.execute(&statement("transact", ":b")).unwrap(); + if unrelated > 0 { + let mut stmt = String::from("(transact ["); + for i in 0..unrelated { + let value = match i % 3 { + 0 => i.to_string(), + 1 => ":other".into(), + _ => format!("#uuid \"{UNKNOWN}\""), + }; + write!(stmt, "[:e{i} :unrelated {value}]").unwrap(); + } + stmt.push_str("])"); + tx.execute(&stmt).unwrap(); + } + let tx = if committed { + JsFuture::from(tx.commit()).await.unwrap(); + db.checkpoint().await.unwrap(); + db.begin_write().unwrap() + } else { + tx + }; + // Reset after fixture writes; the first lookup may not build an index. + for _ in 0..2 { + crate::incoming::enumeration(); + let out = lookup(&tx, TARGET, 2, 2); + let (enumerated, ends) = crate::incoming::enumeration(); + assert_eq!(links(&out).len(), 2); + let records = field(&out, "recordsExamined").as_f64().unwrap(); + assert_eq!( + (records, enumerated), + *baseline.get_or_insert((records, enumerated)) + ); + assert_eq!(enumerated, 2); + // The committed prefix may touch one following nonmatching key. + assert!(ends <= usize::from(committed)); + } + for cap in 0..2 { + crate::incoming::enumeration(); + let out = lookup(&tx, TARGET, 2, cap); + let (enumerated, ends) = crate::incoming::enumeration(); + assert_eq!( + field(&out, "budget").as_string().as_deref(), + Some("records") + ); + assert_eq!( + field(&out, "recordsExamined").as_f64(), + Some(f64::from(cap)) + ); + assert_eq!(enumerated, cap as usize); + assert!(ends <= usize::from(committed)); + } + } + } +} diff --git a/src/browser/mod.rs b/src/browser/mod.rs index 7e4399fff0..f8100880f6 100644 --- a/src/browser/mod.rs +++ b/src/browser/mod.rs @@ -14,6 +14,9 @@ pub mod buffer; /// IndexedDB atomicity, settlement and ordered flush regressions (#894). #[cfg(test)] mod flush_tests; +/// Incoming-reference lookup parity and JS boundary tests (#925). +#[cfg(test)] +mod incoming_tests; /// Async IndexedDB backend for browser WASM persistence. pub mod indexeddb; /// OPFS file backend for `BrowserDb.openOpfs` (#441). @@ -723,7 +726,7 @@ impl BrowserDb { let staged = crate::db::Staged::new(inner.fact_storage.current_tx_count()); Ok(BrowserWriteTransaction { db: self.inner.clone(), - staged: Some(staged), + staged: RefCell::new(Some(staged)), }) } } @@ -972,20 +975,36 @@ fn commit_stamped( /// transaction (one `tx_count`) when it is called, and the promise resolves /// once they are stored in IndexedDB. `rollback()`, or freeing the object /// while open, discards them. After either, the transaction is finished: -/// `execute` and `commit` fail with `[API-018]`, and `rollback` does nothing. +/// `execute`, `incomingRefs` and `commit` fail with `[API-018]`, and `rollback` +/// does nothing. Calls back into this transaction from a user function of its +/// own statement fail with `[INT-001]` before lifecycle or argument checks. +/// +/// `incomingRefs(target, maxLinks, maxRecords)` synchronously returns a plain +/// object discriminated by `status`: complete links or an exhausted budget, +/// never a partial list. It reads earlier statements without staging writes, +/// taking a `tx_count` or starting a flush, even after a failed IndexedDB flush. #[wasm_bindgen] pub struct BrowserWriteTransaction { db: Rc, /// `None` once finished. - staged: Option, + staged: RefCell>, } +#[wasm_bindgen(typescript_custom_section)] +const INCOMING_REFS_TYPES: &str = r#" +/** Complete scalar Ref links, or exhaustion without a partial list. */ +export type IncomingRefs = + | { status: 'complete'; links: Array<{ source: string; attribute: string }>; recordsExamined: number } + | { status: 'exhausted'; budget: 'links' | 'records'; recordsExamined: number }; +"#; + #[wasm_bindgen] impl BrowserWriteTransaction { /// Run one Datalog command inside the transaction; see the type's docs. - pub fn execute(&mut self, datalog: &str) -> Result { + pub fn execute(&self, datalog: &str) -> Result { + let mut slot = self.borrow_staged()?; self.db.admit()?; - let Some(staged) = self.staged.as_mut() else { + let Some(staged) = slot.as_mut() else { return Err(finished()); }; let _running = self.db.run(); @@ -994,6 +1013,50 @@ impl BrowserWriteTransaction { .map_err(to_js_error) } + /// Find every live scalar Ref to a UUID in the current write view, ignoring + /// valid time. Keywords, UUID-looking strings and refs inside sets are excluded. + /// Sources are canonical lowercase UUID strings; link order is unspecified. + /// + /// Both budgets must be finite integer JS numbers in `0..=4294967295`; + /// zero (including `-0`) is a real limit, with no unlimited sentinel. + /// Invalid budgets or UUIDs throw `[API-017]`. Reentry from this transaction's + /// user function throws `[INT-001]` first, then finished/closed `[API-018]`, + /// before argument validation. Exhaustion and errors leave staging intact. + /// Require `status === 'complete'` before deleting; otherwise retry with + /// larger budgets or abandon the delete. This read starts no persistence work. + #[wasm_bindgen(js_name = incomingRefs, unchecked_return_type = "IncomingRefs")] + pub fn incoming_refs( + &self, + #[wasm_bindgen(unchecked_param_type = "string")] target: JsValue, + #[wasm_bindgen(js_name = maxLinks, unchecked_param_type = "number")] max_links: JsValue, + #[wasm_bindgen(js_name = maxRecords, unchecked_param_type = "number")] max_records: JsValue, + ) -> Result { + let slot = self.borrow_staged()?; + self.db.admit()?; + let staged = slot.as_ref().ok_or_else(finished)?; + let target = target + .as_string() + .and_then(|text| uuid::Uuid::parse_str(&text).ok()) + .ok_or_else(|| { + to_js_error( + crate::MinigrafError::invalid_argument("target must be a UUID string").into(), + ) + })?; + let limits = crate::IncomingRefLimits::new( + incoming_budget(&max_links)?, + incoming_budget(&max_records)?, + ); + let snapshot = self + .db + .borrow() + .fact_storage + .snapshot() + .map_err(to_js_error)?; + let outcome = + crate::db::incoming_refs(&snapshot, staged, target, limits).map_err(to_js_error)?; + incoming_object(outcome) + } + /// Apply the staged facts as one transaction and store it. The promise /// resolves after the IndexedDB flush, and rejects as a failed flush of /// `BrowserDb.execute` does; in OPFS mode the commit is stored before @@ -1008,11 +1071,15 @@ impl BrowserWriteTransaction { /// /// If `close()` runs before an IndexedDB flush starts, the flush is not /// started and the promise rejects with `[API-018]`. - pub fn commit(&mut self) -> js_sys::Promise { + pub fn commit(&self) -> js_sys::Promise { + let mut slot = match self.borrow_staged() { + Ok(slot) => slot, + Err(e) => return js_sys::Promise::reject(&e), + }; if let Err(e) = self.db.admit() { return js_sys::Promise::reject(&e); } - let Some(staged) = self.staged.take() else { + let Some(staged) = slot.take() else { return js_sys::Promise::reject(&finished()); }; let committed = { @@ -1029,17 +1096,27 @@ impl BrowserWriteTransaction { } /// Discard the staged facts and finish the transaction. Does nothing on a - /// finished one. - pub fn rollback(&mut self) { - if self.staged.take().is_some() { + /// finished one. Throws `[INT-001]` on reentry from its own user function. + pub fn rollback(&self) -> Result<(), JsValue> { + if self.borrow_staged()?.take().is_some() { self.db.borrow_mut().tx_open = false; } + Ok(()) + } +} + +impl BrowserWriteTransaction { + /// Shared receivers let reentry reach this guard through the JS glue. + fn borrow_staged(&self) -> Result>, JsValue> { + self.staged + .try_borrow_mut() + .map_err(|_| to_js_error(err_coded!(ErrorCode::Int001))) } } impl Drop for BrowserWriteTransaction { fn drop(&mut self) { - if self.staged.take().is_some() + if self.staged.get_mut().take().is_some() && let Ok(mut inner) = self.db.try_borrow_mut() { inner.tx_open = false; @@ -1047,6 +1124,64 @@ impl Drop for BrowserWriteTransaction { } } +/// No JS coercion: the numeric cap must fit wasm32 usize exactly. +fn incoming_budget(value: &JsValue) -> Result { + if let Some(n) = value.as_f64() + && n.is_finite() + && n.fract() == 0.0 + && (0.0..=f64::from(u32::MAX)).contains(&n) + { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + return Ok(n as usize); + } + Err(to_js_error( + crate::MinigrafError::invalid_argument( + "incoming-reference budgets must be integer numbers in 0..=4294967295", + ) + .into(), + )) +} + +fn incoming_object(outcome: crate::IncomingRefs) -> Result { + use crate::{IncomingRefBudget, IncomingRefs}; + let out = js_sys::Object::new(); + let records = match outcome { + IncomingRefs::Complete { + links, + records_examined, + } => { + js_sys::Reflect::set(&out, &"status".into(), &"complete".into())?; + let array = js_sys::Array::new(); + for link in links { + let item = js_sys::Object::new(); + js_sys::Reflect::set(&item, &"source".into(), &link.source.to_string().into())?; + js_sys::Reflect::set(&item, &"attribute".into(), &link.attribute.into())?; + array.push(&item); + } + js_sys::Reflect::set(&out, &"links".into(), &array)?; + records_examined + } + IncomingRefs::Exhausted { + budget, + records_examined, + } => { + js_sys::Reflect::set(&out, &"status".into(), &"exhausted".into())?; + let budget = match budget { + IncomingRefBudget::Links => "links", + IncomingRefBudget::Records => "records", + }; + js_sys::Reflect::set(&out, &"budget".into(), &budget.into())?; + records_examined + } + }; + js_sys::Reflect::set( + &out, + &"recordsExamined".into(), + &JsValue::from_f64(records as f64), + )?; + Ok(out.into()) +} + /// `[API-018]`: a call on a finished transaction. fn finished() -> JsValue { JsValue::from_str(&crate::MinigrafError::closed("write transaction").to_string()) diff --git a/src/browser/opfs_tests.rs b/src/browser/opfs_tests.rs index d99aa9556d..dca391c7c9 100644 --- a/src/browser/opfs_tests.rs +++ b/src/browser/opfs_tests.rs @@ -398,9 +398,9 @@ mod worker { let exported = db.export_graph().expect("export"); db.import_graph(exported).await.expect("import"); put(&db, 50..60).await; - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); tx.execute("(transact [[:x :n 1000]])").unwrap(); - tx.rollback(); + tx.rollback().unwrap(); let mine: Vec = entries() .await .into_iter() @@ -470,7 +470,7 @@ mod worker { let mut cursor = db.query("(query [:find ?n :where [?e :n ?n]])").unwrap(); let mut cursor2 = db.query("(query [:find ?n :where [?e :n ?n]])").unwrap(); let pq = db.prepare("(query [:find ?n :where [?e :n ?n]])").unwrap(); - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); tx.execute("(transact [[:t :n 99]])").unwrap(); db.close().expect("close"); db.close().expect("idempotent"); @@ -504,7 +504,7 @@ mod worker { api018(rejection(JsFuture::from(tx.commit()).await)); // Disposal never throws. cursor2.close(); - tx.rollback(); + tx.rollback().unwrap(); drop(tx); } // The OPFS lock is free at once, with the dependents dropped above. @@ -571,7 +571,7 @@ mod worker { .map(JsValue::from) }) }; - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); tx.execute("(transact [[:c :n 1]])").unwrap(); let commit = tx.commit(); db.close().unwrap(); @@ -591,7 +591,7 @@ mod worker { // IndexedDB: a commit whose flush has not started is never flushed. let name = unique("before-close-idb"); let db = BrowserDb::open(&name).await.unwrap(); - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); tx.execute("(transact [[:c :n 1]])").unwrap(); let commit = tx.commit(); db.close().unwrap(); @@ -643,7 +643,7 @@ mod worker { #[wasm_bindgen_test] async fn memory_commit_and_failed_commit_keep_their_own_outcomes_after_close() { let db = BrowserDb::open_in_memory().unwrap(); - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); tx.execute("(transact [[:c :n 1]])").unwrap(); let commit = tx.commit(); db.close().unwrap(); @@ -661,7 +661,7 @@ mod worker { write_after: Some((0, WriteFault::Throw(0))), ..Faults::default() }; - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); tx.execute("(transact [[:bad :n 9]])").unwrap(); let commit = tx.commit(); // Attach a rejection handler before yielding to the browser. @@ -703,7 +703,7 @@ mod worker { }; "#).call2(&JsValue::NULL, &handle, &state).unwrap(); let patch = JsPatch::new(&handle, "transaction", &replacement); - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); tx.execute("(transact [[:c :n 1]])").unwrap(); let commit = tx.commit(); JsFuture::from(js_sys::Promise::resolve(&JsValue::NULL)) @@ -751,7 +751,7 @@ mod worker { let before = db.export_graph().unwrap().to_vec(); let cursor = db.query("(query [:find ?n :where [?e :n ?n]])").unwrap(); let pq = db.prepare("(query [:find ?n :where [?e :n ?n]])").unwrap(); - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); tx.execute("(transact [[:unsaved :n 99]])").unwrap(); if failed_commit { *file(&db).faults.lock().unwrap() = Faults { @@ -818,7 +818,7 @@ mod worker { assert!(msg.contains(text), "{msg}"); let err = rejection(db.execute("(transact [[:e10 :n 10]])".into()).await); assert_eq!(code_of(&err), "STG-046"); - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); tx.execute("(transact [[:e11 :n 11]])").unwrap(); assert_eq!( code_of(&rejection(JsFuture::from(tx.commit()).await)), @@ -1243,7 +1243,7 @@ mod worker { put(&db, 0..3).await; let mut cursor = db.query("(query [:find ?n :where [?e :n ?n]])").unwrap(); let pq = db.prepare("(query [:find ?n :where [?e :n ?n]])").unwrap(); - let mut tx = db.begin_write().unwrap(); + let tx = db.begin_write().unwrap(); let check_database = |code: &str| { assert_eq!( code_of(&rejection(db.query("(query [:find ?n :where [?e :n ?n]])"))), @@ -1317,7 +1317,7 @@ mod worker { "API-018" ); cursor.close(); - tx.rollback(); + tx.rollback().unwrap(); let reopened = open(&name).await; assert_eq!(ns(&reopened).await, vec![0, 1, 2]); reopened.close().unwrap(); diff --git a/src/browser/tx_tests.rs b/src/browser/tx_tests.rs index 67136d2cf0..2f8b5c9ced 100644 --- a/src/browser/tx_tests.rs +++ b/src/browser/tx_tests.rs @@ -42,7 +42,7 @@ fn code_of(e: &JsValue) -> String { .to_string() } -async fn commit(tx: &mut BrowserWriteTransaction) -> Result { +async fn commit(tx: &BrowserWriteTransaction) -> Result { JsFuture::from(tx.commit()).await } @@ -61,7 +61,7 @@ async fn setup() -> BrowserDb { #[wasm_bindgen_test] async fn execute_stages_and_reads_own_writes() { let db = setup().await; - let mut tx = db.begin_write().expect("begin"); + let tx = db.begin_write().expect("begin"); assert_eq!( tx.execute(r#"(transact [[:dave :person/name "Dave"]])"#) .expect("transact"), @@ -88,7 +88,7 @@ async fn execute_stages_and_reads_own_writes() { .execute("(query [:find ?n :where (named ?e ?n)])") .expect("rule query"); assert_eq!(sorted_rows(&ruled).len(), 3, "the rule reads staged facts"); - commit(&mut tx).await.expect("commit"); + commit(&tx).await.expect("commit"); assert_eq!( names(&db).await, vec![r#"["Alice"]"#, r#"["Carol"]"#, r#"["Dave"]"#] @@ -98,7 +98,7 @@ async fn execute_stages_and_reads_own_writes() { #[wasm_bindgen_test] async fn failed_statement_stages_nothing_and_stays_open() { let db = setup().await; - let mut tx = db.begin_write().expect("begin"); + let tx = db.begin_write().expect("begin"); assert_eq!( code_of(&tx.execute("(transact [[:a").unwrap_err()), "PRS-004" @@ -108,7 +108,7 @@ async fn failed_statement_stages_nothing_and_stays_open() { assert_eq!(code_of(&tx.execute(two_windows).unwrap_err()), "API-011"); tx.execute(r#"(transact [[:dave :person/name "Dave"]])"#) .expect("a good statement after the failures"); - commit(&mut tx).await.expect("commit"); + commit(&tx).await.expect("commit"); assert_eq!(names(&db).await.len(), 4, "only the good statement"); let v = db .execute("(query [:find ?e :where [?e :p/v _]])".to_string()) @@ -175,7 +175,7 @@ async fn commit_matches_native_transaction() { let native = crate::Minigraf::in_memory().unwrap(); native.execute(SETUP).unwrap(); - let mut btx = browser.begin_write().expect("begin"); + let btx = browser.begin_write().expect("begin"); let mut ntx = native.begin_write().unwrap(); for stmt in *stmts { let b = outcome(btx.execute(stmt).map_err(|e| code_of(&e))); @@ -186,7 +186,7 @@ async fn commit_matches_native_transaction() { ); assert_eq!(b, n, "sequence {i}: statement outcomes differ"); } - commit(&mut btx).await.expect("browser commit"); + commit(&btx).await.expect("browser commit"); ntx.commit().unwrap(); for check in CHECKS { @@ -215,7 +215,7 @@ async fn commit_is_one_transaction_and_survives_reopen() { let db = fresh_persistent("minigraf-test-tx-commit").await; db.execute(SETUP.to_string()).await.expect("setup"); let before = db.inner.borrow().fact_storage.current_tx_count(); - let mut tx = db.begin_write().expect("begin"); + let tx = db.begin_write().expect("begin"); tx.execute(r#"(transact [[:dave :person/name "Dave"]])"#) .unwrap(); tx.execute(r#"(transact [[:erin :person/name "Erin"]])"#) @@ -255,13 +255,13 @@ async fn rollback_and_drop_discard_and_survive_reopen() { let db = fresh_persistent("minigraf-test-tx-rollback").await; db.execute(SETUP.to_string()).await.expect("setup"); - let mut tx = db.begin_write().expect("begin"); + let tx = db.begin_write().expect("begin"); tx.execute(r#"(transact [[:dave :person/name "Dave"]])"#) .unwrap(); - tx.rollback(); + tx.rollback().unwrap(); assert_eq!(names(&db).await.len(), 3, "rolled back"); - let mut tx = db.begin_write().expect("begin after rollback"); + let tx = db.begin_write().expect("begin after rollback"); tx.execute(r#"(transact [[:erin :person/name "Erin"]])"#) .unwrap(); drop(tx); // as JavaScript's free() does @@ -284,10 +284,10 @@ async fn failed_flush_rejects_like_execute() { .execute(r#"(transact [[:dave :person/name "Dave"]])"#.to_string()) .await; assert_eq!(code_of(&failed_execute.unwrap_err()), "STG-048"); - let mut tx = db.begin_write().expect("begin"); + let tx = db.begin_write().expect("begin"); tx.execute(r#"(transact [[:erin :person/name "Erin"]])"#) .unwrap(); - assert_eq!(code_of(&commit(&mut tx).await.unwrap_err()), "STG-046"); + assert_eq!(code_of(&commit(&tx).await.unwrap_err()), "STG-046"); assert_eq!(names(&db).await.len(), 4, "Erin was never applied"); assert!( tx.execute(NAMES).is_err(), @@ -301,17 +301,15 @@ async fn failed_flush_rejects_like_execute() { #[wasm_bindgen_test] async fn refused_commit_finishes_and_discards() { let db = setup().await; - let mut tx = db.begin_write().expect("begin"); + let tx = db.begin_write().expect("begin"); tx.execute(r#"(transact [[:dave :person/name "Dave"]])"#) .unwrap(); let soon = crate::graph::types::tx_id_now().saturating_add(20); - for f in &mut tx.staged.as_mut().unwrap().pending_facts { + for f in &mut tx.staged.borrow_mut().as_mut().unwrap().pending_facts { f.valid_to = soon.cast_signed(); } while crate::graph::types::tx_id_now() <= soon {} - let err = commit(&mut tx) - .await - .expect_err("window ends before commit"); + let err = commit(&tx).await.expect_err("window ends before commit"); assert_eq!(code_of(&err), "API-019"); assert_eq!(names(&db).await.len(), 3, "nothing committed"); assert_eq!(code_of(&tx.execute(NAMES).unwrap_err()), "API-018"); @@ -321,14 +319,14 @@ async fn refused_commit_finishes_and_discards() { async fn empty_and_query_only_transactions() { let db = setup().await; let before = db.inner.borrow().fact_storage.current_tx_count(); - let mut tx = db.begin_write().expect("begin"); - commit(&mut tx).await.expect("empty commit"); - let mut tx = db.begin_write().expect("begin"); + let tx = db.begin_write().expect("begin"); + commit(&tx).await.expect("empty commit"); + let tx = db.begin_write().expect("begin"); tx.execute(NAMES).unwrap(); - commit(&mut tx).await.expect("query-only commit"); - let mut tx = db.begin_write().expect("begin"); + commit(&tx).await.expect("query-only commit"); + let tx = db.begin_write().expect("begin"); tx.execute(NAMES).unwrap(); - tx.rollback(); + tx.rollback().unwrap(); assert_eq!(db.inner.borrow().fact_storage.current_tx_count(), before); } @@ -376,7 +374,7 @@ async fn database_calls_are_int001_while_open() { let db = setup().await; let pq = db.prepare(NAMES).expect("prepare"); let mut cursor = db.query(NAMES).expect("cursor before begin"); - let mut tx = db.begin_write().expect("begin"); + let tx = db.begin_write().expect("begin"); tx.execute(r#"(transact [[:dave :person/name "Dave"]])"#) .unwrap(); for (name, code) in guarded(&db, &pq, true).await { @@ -384,14 +382,14 @@ async fn database_calls_are_int001_while_open() { } let rows = cursor.next_batch(10).expect("cursor").expect("rows"); assert_eq!(sorted_rows(&format!(r#"{{"results":{rows}}}"#)).len(), 3); - commit(&mut tx).await.expect("commit"); + commit(&tx).await.expect("commit"); // After the commit everything works. for (name, code) in guarded(&db, &pq, false).await { assert_eq!(code, None, "{name} after the commit"); } // After a rollback and a drop too. - db.begin_write().expect("begin").rollback(); + db.begin_write().expect("begin").rollback().unwrap(); drop(db.begin_write().expect("begin")); assert_eq!(names(&db).await.len(), 4); } @@ -399,17 +397,17 @@ async fn database_calls_are_int001_while_open() { #[wasm_bindgen_test] async fn finished_transaction_is_api018() { let db = setup().await; - let mut tx = db.begin_write().expect("begin"); - commit(&mut tx).await.expect("commit"); + let tx = db.begin_write().expect("begin"); + commit(&tx).await.expect("commit"); assert_eq!(code_of(&tx.execute(NAMES).unwrap_err()), "API-018"); - assert_eq!(code_of(&commit(&mut tx).await.unwrap_err()), "API-018"); - tx.rollback(); // does nothing + assert_eq!(code_of(&commit(&tx).await.unwrap_err()), "API-018"); + tx.rollback().unwrap(); // does nothing - let mut tx = db.begin_write().expect("begin"); - tx.rollback(); - tx.rollback(); + let tx = db.begin_write().expect("begin"); + tx.rollback().unwrap(); + tx.rollback().unwrap(); assert_eq!(code_of(&tx.execute(NAMES).unwrap_err()), "API-018"); - assert_eq!(code_of(&commit(&mut tx).await.unwrap_err()), "API-018"); + assert_eq!(code_of(&commit(&tx).await.unwrap_err()), "API-018"); // A finished transaction no longer guards the database. assert_eq!(names(&db).await.len(), 3); } @@ -417,10 +415,10 @@ async fn finished_transaction_is_api018() { #[wasm_bindgen_test] async fn rules_stay_after_rollback() { let db = setup().await; - let mut tx = db.begin_write().expect("begin"); + let tx = db.begin_write().expect("begin"); tx.execute("(rule [(named ?e ?n) [?e :person/name ?n]])") .unwrap(); - tx.rollback(); + tx.rollback().unwrap(); let r = db .execute("(query [:find ?n :where (named ?e ?n)])".to_string()) .await @@ -451,7 +449,7 @@ async fn user_function_calling_the_database_inside_a_transaction() { .expect("make the predicate"); db.register_predicate(name, predicate).expect("register"); } - let mut tx = db.begin_write().expect("begin"); + let tx = db.begin_write().expect("begin"); for (name, _) in calls { let q = format!("(query [:find ?n :where [?e :person/name ?n] [({name} ?n)]])"); let e = tx.execute(&q).expect_err("a call back into the database"); @@ -464,6 +462,100 @@ async fn user_function_calling_the_database_inside_a_transaction() { } tx.execute(r#"(transact [[:dave :person/name "Dave"]])"#) .expect("still usable"); - commit(&mut tx).await.expect("commit"); + commit(&tx).await.expect("commit"); assert_eq!(names(&db).await.len(), 4); } + +/// Reentry must pass through wasm-bindgen's transaction wrapper, not a Rust +/// reference: an exclusive receiver otherwise fails in the generated glue. +#[wasm_bindgen_test] +async fn transaction_reentry_through_js_is_int001() { + for method in ["execute", "commit", "rollback", "incomingRefs"] { + let db = setup().await; + let state = js_sys::Object::new(); + let predicate = js_sys::Function::new_with_args( + "state,method", + r#"return () => { + try { + const result = method === 'incomingRefs' + ? state.tx.incomingRefs(null, 'invalid', NaN) + : method === 'execute' ? state.tx.execute('invalid') + : state.tx[method](); + state.result = Promise.resolve(result).then( + () => 'unexpected success', e => String(e)); + } catch (e) { state.result = Promise.resolve(String(e)); } + return true; + }"#, + ) + .call2(&JsValue::NULL, &state, &method.into()) + .unwrap(); + db.register_predicate("reenter?", predicate).unwrap(); + let tx = JsValue::from(db.begin_write().unwrap()); + let run = js_sys::Function::new_with_args( + "tx,state", + r#"state.tx = tx; + tx.execute('(query [:find ?n :where [?e :person/name ?n] [(reenter? ?n)] :limit 1])'); + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject('reentry hung'), 1500); + state.result.then(value => { clearTimeout(timer); resolve(value); }, + error => { clearTimeout(timer); reject(error); }); + });"#, + ); + let result = run.call2(&JsValue::NULL, &tx, &state).unwrap(); + let message = JsFuture::from(result.unchecked_into::()) + .await + .unwrap() + .as_string() + .unwrap(); + assert!(message.starts_with("[INT-001]"), "{method}: {message}"); + let finish = js_sys::Function::new_with_args( + "tx", + "tx.execute('(transact [[:after :n 1]])'); return tx.commit();", + ); + JsFuture::from( + finish + .call1(&JsValue::NULL, &tx) + .unwrap() + .unchecked_into::(), + ) + .await + .unwrap(); + js_sys::Function::new_with_args("tx", "tx.free()") + .call1(&JsValue::NULL, &tx) + .unwrap(); + assert_eq!(db.inner.borrow().fact_storage.current_tx_count(), 2); + } +} + +#[wasm_bindgen_test] +async fn transaction_callback_close_is_busy_and_js_free_discards() { + let db = setup().await; + let other = JsValue::from(BrowserDb { + inner: db.inner.clone(), + }); + let predicate = js_sys::Function::new_with_args( + "db", + r#"return () => { + try { db.close(); } catch (e) { + if (String(e).startsWith('[API-027]')) return true; + throw e; + } + throw 'close unexpectedly succeeded'; + }"#, + ) + .call1(&JsValue::NULL, &other) + .unwrap(); + db.register_predicate("closes?", predicate).unwrap(); + let tx = JsValue::from(db.begin_write().unwrap()); + js_sys::Function::new_with_args( + "tx", + r#"tx.execute('(transact [[:discard :person/name "Discard"]])'); + tx.execute('(query [:find ?n :where [?e :person/name ?n] [(closes? ?n)]])'); + tx.free();"#, + ) + .call1(&JsValue::NULL, &tx) + .unwrap(); + assert_eq!(names(&db).await.len(), 3); + drop(db.begin_write().unwrap()); + db.close().unwrap(); +} diff --git a/src/db.rs b/src/db.rs index e50450db6d..45d4faa1df 100644 --- a/src/db.rs +++ b/src/db.rs @@ -2132,30 +2132,7 @@ impl TxState { }; #[cfg(target_arch = "wasm32")] let _ = ctx; - let mut lookup = crate::incoming::Lookup::new(limits); - if let Some(reader) = &snapshot.committed { - let done = reader.incoming_ref_records( - target, - lookup.remaining(), - &mut |e, a, tx, asserted| { - lookup.charge(); - lookup.record(e, a, tx, asserted); - }, - )?; - if !done { - return Ok(lookup.finish(false)); - } - } - lookup.next_layer(); - if !snapshot.incoming_pending(target, &mut lookup)? { - return Ok(lookup.finish(false)); - } - lookup.next_layer(); - let done = self - .staged - .incoming - .visit(target, &self.staged.pending_facts, &mut lookup); - Ok(lookup.finish(done)) + incoming_refs(&snapshot, &self.staged, target, limits) } /// The state a query inside the transaction reads (#550 spec §7): for a @@ -2489,6 +2466,39 @@ pub(crate) struct Staged { next_pending_tx_id: TxId, } +/// Walk only the target's committed, pending and staged records. Native and +/// browser transactions share this path without constructing a staged read view. +pub(crate) fn incoming_refs( + snapshot: &Snapshot, + staged: &Staged, + target: crate::EntityId, + limits: crate::IncomingRefLimits, +) -> Result { + let mut lookup = crate::incoming::Lookup::new(limits); + if let Some(reader) = &snapshot.committed { + let done = reader.incoming_ref_records( + target, + lookup.remaining(), + &mut |e, a, tx, asserted| { + lookup.charge(); + lookup.record(e, a, tx, asserted); + }, + )?; + if !done { + return Ok(lookup.finish(false)); + } + } + lookup.next_layer(); + if !snapshot.incoming_pending(target, &mut lookup)? { + return Ok(lookup.finish(false)); + } + lookup.next_layer(); + let done = staged + .incoming + .visit(target, &staged.pending_facts, &mut lookup); + Ok(lookup.finish(done)) +} + impl Staged { /// Nothing staged, on a store whose last `tx_count` is `current_tx_count`. pub(crate) fn new(current_tx_count: u64) -> Self { diff --git a/tests/browser/incoming_refs.ts b/tests/browser/incoming_refs.ts new file mode 100644 index 0000000000..4cd2451666 --- /dev/null +++ b/tests/browser/incoming_refs.ts @@ -0,0 +1,24 @@ +// Checked against wasm-bindgen's generated declarations by wasm.yml. +import type { BrowserWriteTransaction, IncomingRefs } from '../../target/browser-types/minigraf'; + +declare const tx: BrowserWriteTransaction; +const result: IncomingRefs = tx.incomingRefs('abcdef01-2345-6789-abcd-ef0123456789', 10, 100); +const records: number = result.recordsExamined; +if (result.status === 'complete') { + const links: Array<{ source: string; attribute: string }> = result.links; + // @ts-expect-error Complete results have no exhausted budget. + result.budget; + void links; +} else { + const budget: 'links' | 'records' = result.budget; + // @ts-expect-error Exhausted results never contain partial links. + result.links; + void budget; +} +// @ts-expect-error Both numeric budgets are required. +tx.incomingRefs('abcdef01-2345-6789-abcd-ef0123456789', 10); +// @ts-expect-error Budgets are numbers, without string coercion. +tx.incomingRefs('abcdef01-2345-6789-abcd-ef0123456789', '10', 100); +const rolledBack: void = tx.rollback(); +void records; +void rolledBack;