From 24c27c915933a95172f3acd60fd30c31d2f915d4 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Sat, 28 Nov 2026 10:48:24 +0530 Subject: [PATCH 1/5] feat(db): add bounded incoming-reference lookup to write transactions (#924) WriteTransaction and OwnedWriteTransaction gain incoming_refs, which returns every live scalar reference to an entity, ignoring valid time, or an explicit exhausted outcome when a links or records budget is exceeded. Pending and staged facts keep target-keyed positions, and durable and large-transaction data are walked by VAET prefix, so the work depends only on the target's own history. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H2a7QmsdjnGhRdBSbw6GB7 --- CHANGELOG.md | 2 + CLAUDE.md | 7 +- Cargo.toml | 4 + README.md | 12 + ROADMAP.md | 2 + benches/incoming_refs_write.rs | 124 ++++ docs/TEST_COVERAGE.md | 34 +- ...26-11-28-924-incoming-ref-lookup-design.md | 157 +++++ docs/testing/924-incoming-refs.md | 122 ++++ src/db.rs | 150 ++++- src/db/incoming_tests.rs | 536 ++++++++++++++++++ src/graph/storage.rs | 101 +++- src/incoming.rs | 255 +++++++++ src/lib.rs | 8 + src/storage/backend/file.rs | 6 + src/storage/btree.rs | 1 - src/storage/fault.rs | 15 +- src/storage/mod.rs | 15 + src/storage/persistent_facts/large_tx.rs | 22 +- src/storage/reader.rs | 99 ++++ tests/incoming_refs_test.rs | 535 +++++++++++++++++ tests/owned_tx_test.rs | 30 + 22 files changed, 2206 insertions(+), 31 deletions(-) create mode 100644 benches/incoming_refs_write.rs create mode 100644 docs/superpowers/specs/2026-11-28-924-incoming-ref-lookup-design.md create mode 100644 docs/testing/924-incoming-refs.md create mode 100644 src/db/incoming_tests.rs create mode 100644 src/incoming.rs create mode 100644 tests/incoming_refs_test.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cddf756c7..599dc38885 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 +- **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). - **OPFS-backed `BrowserDb` persistence and explicit close** (#441). `await BrowserDb.openOpfs(name)` opens one `.graph` file through an exclusive sync access handle in a dedicated worker on a secure origin. It uses the default 256-page cache, reads pages on demand and commits by copy-on-write with data/meta flushes, without a WAL or a whole-file buffer. IndexedDB `open(name)` now also works in workers. The two modes have independent namespaces and no automatic fallback. OPFS starts at Tier 2 within the Tier 1 browser binding. All modes gain synchronous, idempotent `close()`, which saves nothing, discards an open transaction, invalidates dependents and immediately releases an OPFS lock. OPFS import admits an empty blob, a nonempty v8 image with a selectable meta and complete, verified contents (an empty v8 image included), or a supported v7 image that migrates completely, and rejects anything else (such as a torn or zero-filled initial image) before replacing anything; it validates the whole image, stages and publishes the complete old or new database across interruption, and invalidates earlier cursors/prepared queries after publication. Exports after interrupted initial creation fill an absent second meta slot with zeros and still propagate failed reads of existing pages. OPFS recovery accepts the sole valid meta; unlike native recovery this can silently fall back after later meta rot. A failed commit is unconfirmed (it may be stored), leaves reads working, and refuses later writes with STG-046 until reopen. New registered errors API-026 (unavailable OPFS context), API-027 (busy database) and STG-048 (browser operation and exception name); lock contention is STG-026. No file-format change or new crate dependency. See [durability](docs/DURABILITY.md#browser-storage-modes) and [measurement status](docs/benchmarks/441-opfs/README.md). diff --git a/CLAUDE.md b/CLAUDE.md index f076eb6ed4..384676880c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -139,6 +139,7 @@ cargo run < demos/demo_negation.txt ### Module Structure 1. **`src/graph/`** — EAV fact store with bi-temporal support + - Pending facts maintain EAVT/AEVT and `RefPositions` (#924), a standard `HashMap>` containing only scalar-ref positions. `push`/`extend` maintain it for writes and WAL replay; checkpoint publication replaces it with the pending store. `Staged` maintains the same structure at statement acceptance and clears it on promotion. Lookup never builds an index or copies unrelated facts. - `types.rs`: `Fact`, `Value`, `EntityId`, `TxId`, `VALID_TIME_FOREVER` - `storage.rs`: `FactStorage` — in-memory store, `snapshot()` → `Snapshot` (committed reader + pin + pending prefix, and a `WriteTransaction`'s staged facts read with the pending ones as one store, #550; every query/cursor/log read goes through one), `transact_batch`, `retract`, `get_facts_as_of`, `get_facts_valid_at`, `net_asserted_facts`, `get_facts_by_entity_attribute_indexed`; `Snapshot::has_pending` probes only its captured pending/staged source range for input-order proofs (#641) @@ -147,7 +148,7 @@ cargo run < demos/demo_negation.txt - `backend/file.rs`: Single `.graph` file backend (4KB pages, cross-platform) - `backend/memory.rs`: In-memory backend for testing - `backend/fault_inject.rs`: `FaultInjectingBackend` — injects I/O errors for durability tests (test builds only) - - `fault.rs`: thread-local fault plan (test builds only, #390) — EIO, torn/short writes, sticky ENOSPC, failed fsync with or without lost writes, at the k-th write or sync of `FileBackend`, the WAL and `sync_parent_dir`; driven by `src/fault_matrix.rs` + - `fault.rs`: thread-local fault plan (test builds only, #390) — page-read EIO, write EIO, torn/short writes, sticky ENOSPC, failed fsync with or without lost writes, at the k-th write or sync of `FileBackend`, the WAL and `sync_parent_dir`; driven by `src/fault_matrix.rs` - `index.rs`: pending (uncheckpointed) EAVT/AEVT keys over UUIDs and strings, `encode_value`; `index/verification.rs`: Kani proofs of `encode_value` (`#[cfg(kani)]`, #627) - `keys.rs`: byte-comparable v8 keys (FDB integers, value tags, `tx↓`, FOREVER), DICT keys, `MAX_VALUE_BYTES`, `MAX_IDENT_BYTES`; sets (#316): tag `0x08`, element encoding (`set_elements`: each element's key encoding, sorted) inline up to 64 bytes, else `LongSet` in a value page, `decode_set`, `set_bytes_bound` (the WAL's id-free size bound); pure scalar decoders preserve INT-049 errors (#693). `keys/verification.rs` proves encoder order and scalar decoder round trips/malformed bounds with Kani (`#[cfg(kani)]`, #627, #693); `keys/legacy_verification.rs` compares the old and new readers in tests. `kani.yml` runs proofs on key PRs and nightly. - `node.rs`: prefix-compressed leaf and shortest-separator internal node codecs @@ -186,7 +187,7 @@ cargo run < demos/demo_negation.txt 5. **`src/repl.rs`** — Interactive REPL; TTY-aware (suppresses prompts/banner for piped input) -6. **`src/db.rs`** — Public API: `Minigraf::open/execute/query/fact_log/prepare/begin_write/begin_write_with/begin_write_owned/begin_write_owned_with/checkpoint/save/verify/rebuild_indexes`, `WriteTransaction`, `OwnedWriteTransaction` (#824: `Send + 'static`, holds a `Minigraf` clone; the write lock is `Mutex` + `Condvar`, `WriteSlot::owned` makes every other writer wait in `Inner::lock_write`; `TxOwner` records its begin thread per database, and `refuse_reentry` gives `INT-001` there as the thread-local flag does for `WriteTransaction`, and each owned statement sets that flag on the thread running it (`RunningHere`); both kinds share `TxState`, and small staging is `Staged`, which `BrowserWriteTransaction` uses too), `TxOptions` (#871: one transaction's `synchronous` and `chunk_facts`; `None` = the database value; the WAL writer keeps no mode, each append gets its transaction's; no effect on a large transaction, whose WAL guard is always synced), `IntegrityReport`, `OpenOptions::page_cache_size`, `OpenOptions::read_only` (#429: shared lock, nothing written, writes are `API-014`), `OpenOptions::query_memory_limit` (#549: `QRY-012`, off by default), `OpenOptions::transaction_chunk_facts` (#550), `OpenOptions::max_iterations` (#861: rounds per stratum, default 1,000,000), `OpenOptions::allow_overrides` (#869: which query keywords may override settings, `API-025`; see `docs/CONFIGURATION.md`) +6. **`src/db.rs`** — Public API: `Minigraf::open/execute/query/fact_log/prepare/begin_write/begin_write_with/begin_write_owned/begin_write_owned_with/checkpoint/save/verify/rebuild_indexes`, `WriteTransaction`, `OwnedWriteTransaction` (#824: `Send + 'static`, holds a `Minigraf` clone; the write lock is `Mutex` + `Condvar`, `WriteSlot::owned` makes every other writer wait in `Inner::lock_write`; `TxOwner` records its begin thread per database, and `refuse_reentry` gives `INT-001` there as the thread-local flag does for `WriteTransaction`, and each owned statement sets that flag on the thread running it (`RunningHere`); both kinds share `TxState`, and small staging is `Staged`, which `BrowserWriteTransaction` uses too), `incoming_refs` on both transaction types (#924: complete-or-exhausted scalar Ref links, independent link/record caps, any valid window; `src/incoming.rs` holds types, target-position lists and visibility reduction; no `Staged::read_view`; promotion filters staging in place and rebuilds target positions only on failure, failed statement finalization retains completed roots for lookup; query-only staged snapshots omit the target index), `TxOptions` (#871: one transaction's `synchronous` and `chunk_facts`; `None` = the database value; the WAL writer keeps no mode, each append gets its transaction's; no effect on a large transaction, whose WAL guard is always synced), `IntegrityReport`, `OpenOptions::page_cache_size`, `OpenOptions::read_only` (#429: shared lock, nothing written, writes are `API-014`), `OpenOptions::query_memory_limit` (#549: `QRY-012`, off by default), `OpenOptions::transaction_chunk_facts` (#550), `OpenOptions::max_iterations` (#861: rounds per stratum, default 1,000,000), `OpenOptions::allow_overrides` (#869: which query keywords may override settings, `API-025`; see `docs/CONFIGURATION.md`) - `src/overrides.rs`: `Overridable` (`DEFAULTS`, `keyword`; `QueryMemoryLimit` not in `DEFAULTS`, #870; `MaxIterations` in it, #861) and `check_overrides`, called after parsing at every query entry point (`BrowserDb` uses `DEFAULTS`) - `src/cursor.rs`: `Cursor` / `Batch` — owned, `Send` cursor returned by `Minigraf::query` and `PreparedQuery::query` (#432); pulls engine queries one internal batch at a time (`close`/drop stops the work; a read error after some rows comes on the next call), other queries computed at open; holds a `Snapshot` (one state of the store, its committed generation pinned, #543) until dropped - `src/fact_log.rs`: `FactLog` / `FactFilter` / `FactRecord` / `FactOrder` — every fact version streamed by `Minigraf::fact_log` (#430): tx order (multi-pass, bounded window) or storage order, key-level filters; an open log pins the committed generation (`storage::pins`), so checkpoints run but do not reuse its pages (`API-013` deprecated, #543) @@ -249,7 +250,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are ## Test Coverage -**2181 tests** (2158 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). +**2211 tests** (2188 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). 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/Cargo.toml b/Cargo.toml index 0bc20d5dc0..7fa1ae2d56 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -95,6 +95,10 @@ uuid = { version = "1.0", features = ["v4", "js"] } name = "minigraf_bench" harness = false +[[bench]] +name = "incoming_refs_write" +harness = false + # `cargo test` runs the envelope harness's unit tests (the -irregular fixture, #551). [[example]] name = "perf_envelope" diff --git a/README.md b/README.md index cb1cb70dc8..8c43770b78 100644 --- a/README.md +++ b/README.md @@ -158,6 +158,18 @@ let mut tx = db.begin_write()?; tx.execute(r#"(transact [[:alice :person/age 31]])"#)?; tx.commit()?; +// v3: bounded incoming scalar Ref links, including future/expired assertions. +// Require Complete before staging a cascading delete; Exhausted has no links. +use minigraf::{IncomingRefLimits, IncomingRefs}; +let mut tx = db.begin_write()?; +let target = uuid::Uuid::nil(); +match tx.incoming_refs(target, IncomingRefLimits::new(100, 10_000))? { + IncomingRefs::Complete { links, .. } => { /* inspect every link before deleting */ } + IncomingRefs::Exhausted { budget, .. } => { /* retry or abandon the delete */ } + _ => { /* future outcomes */ } +} +tx.rollback(); + // Owned transaction — Send + 'static, so it can live in an object or move to // another thread; every language binding's transaction is one let mut tx = db.begin_write_owned()?; diff --git a/ROADMAP.md b/ROADMAP.md index df1da98ff6..1b12c3b017 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -73,6 +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. Bench-machine comparison is pending; see [acceptance evidence](docs/testing/924-incoming-refs.md). + **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. This was the GitHub milestone named “2.0” before v2.0.0 used that version number for the kernel-locking and structured-error-code breaking changes; it was consequently renumbered to v3.0.0. It is developed on the long-lived `v3` branch; every v3 pull request targets `v3` and `main` is left untouched. At the first v3 release the current `main` is copied to a `v2` branch and `v3` becomes the new `main`. diff --git a/benches/incoming_refs_write.rs b/benches/incoming_refs_write.rs new file mode 100644 index 0000000000..0627f1d841 --- /dev/null +++ b/benches/incoming_refs_write.rs @@ -0,0 +1,124 @@ +#![allow( + clippy::expect_used, + clippy::indexing_slicing, + clippy::panic, + clippy::unwrap_used +)] +//! #924 write-cost controls. Uses only public APIs present on the v3 base. +//! Copy this file and its Cargo.toml bench entry to the base for comparison. + +use criterion::{BatchSize, BenchmarkId, Criterion, SamplingMode, criterion_group, criterion_main}; +use minigraf::{Minigraf, OpenOptions, TxOptions}; +use std::fmt::Write; +use std::hint::black_box; +use std::path::PathBuf; +use std::time::Duration; + +fn command(start: usize, end: usize) -> String { + let mut text = String::from("(transact ["); + for i in start..end { + let target = uuid::Uuid::from_u128(1 + u128::try_from(i % 16).unwrap()); + write!(text, "[:source{i} :ref #uuid \"{target}\"]").unwrap(); + } + text.push_str("])"); + text +} + +fn file() -> (Minigraf, tempfile::TempDir, PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("refs.graph"); + let db = Minigraf::open_with_options( + &path, + OpenOptions::default().wal_checkpoint_threshold(usize::MAX), + ) + .unwrap(); + (db, dir, path) +} + +fn bench_ref_writes(c: &mut Criterion) { + let mut group = c.benchmark_group("incoming_ref_writes"); + group.sample_size(30); + group.sampling_mode(SamplingMode::Flat); + group.warm_up_time(Duration::from_secs(1)); + group.measurement_time(Duration::from_secs(3)); + for n in [1_000, 10_000] { + let all = command(0, n); + group.bench_with_input(BenchmarkId::new("pending", n), &n, |b, _| { + b.iter_batched( + || Minigraf::in_memory().unwrap(), + |db| { + black_box(db.execute(black_box(&all)).unwrap()); + db + }, + BatchSize::PerIteration, + ); + }); + group.bench_with_input(BenchmarkId::new("staged", n), &n, |b, _| { + b.iter_batched( + || Minigraf::in_memory().unwrap().begin_write_owned().unwrap(), + |mut tx| { + black_box(tx.execute(black_box(&all)).unwrap()); + tx + }, + BatchSize::PerIteration, + ); + }); + group.bench_with_input(BenchmarkId::new("wal_recovery", n), &n, |b, _| { + b.iter_batched_ref( + || { + let (db, dir, path) = file(); + db.execute(&all).unwrap(); + drop(db); // usize::MAX retains the WAL on the base and branch. + assert!(path.with_extension("graph.wal").exists()); + (None::, dir, path) + }, + |(opened, _, path)| { + *opened = Some(black_box( + Minigraf::open_with_options( + path, + OpenOptions::default().wal_checkpoint_threshold(usize::MAX), + ) + .unwrap(), + )); + }, + BatchSize::PerIteration, + ); + }); + group.bench_with_input(BenchmarkId::new("checkpoint", n), &n, |b, _| { + b.iter_batched_ref( + || { + let f = file(); + f.0.execute(&all).unwrap(); + f + }, + |(db, _, _)| { + db.checkpoint().unwrap(); + black_box(()) + }, + BatchSize::PerIteration, + ); + }); + let first = command(0, n / 2); + let second = command(n / 2, n); + group.bench_with_input(BenchmarkId::new("promotion", n), &n, |b, _| { + b.iter_batched_ref( + || { + let (db, dir, _) = file(); + // Include a pending ref range in the promotion's first chunk. + db.execute(&command(n, n + 16)).unwrap(); + let mut tx = db + .begin_write_owned_with(TxOptions::new().chunk_facts(n - 1)) + .unwrap(); + tx.execute(&first).unwrap(); + (tx, dir) + }, + |(tx, _)| black_box(tx.execute(black_box(&second)).unwrap()), + BatchSize::PerIteration, + ); + }); + } + group.finish(); +} + +criterion_group!(benches, bench_ref_writes); +criterion_main!(benches); diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index 62917d5235..a471d5dc5b 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -2,6 +2,28 @@ ## Coverage Summary +**#924 bounded incoming references**: full offline native `cargo test` on +2026-11-28 passes **2,188 tests, 0 failures, 23 ignored** (2,211 total), with +`CARGO_BUILD_JOBS=4` and `RUST_TEST_THREADS=4`. This adds 30 active tests: +`src/db/incoming_tests.rs` has ten (fault-injected STG-046/WAL-007 reads, +legacy ties/budgets, 100,000 unrelated facts in all four representations, +independent history-enumeration bounds, unchanged non-ref batch capacity, +failed promotion/chunk/finalization visibility, setup-work instrumentation, +and allocation reuse with last-statement/tied-retraction precedence after stamping); +`src/graph/storage.rs` adds two tests for counted pending extension and omission +of the unused incoming index in query-only snapshots; +`src/incoming.rs` has one capacity-accounting test; `src/storage/reader.rs` +has one malformed/missing VAET test; `tests/incoming_refs_test.rs` has 14 +(including the crash-child entrypoint, proptest model and exact-set promotion); the owned +transaction suite has one new cross-thread/guard case (17 total); and the API +has one new rustdoc test. The library suite passes 1,268 with eight ignored. +Build, strict native all-target Clippy, fmt, browser wasm Clippy and WASI Clippy +all pass offline. The Rust 1.99.1 distribution binary is 1,250,568 bytes +(+3,808 from the v3 base), below the unchanged 1,280,000-byte gate. +No browser tests or ignored tests were added. +See the [AC-to-test mapping, memory accounting and binary/benchmark evidence](testing/924-incoming-refs.md). + + **#900 strict UTC timestamps**: `src/temporal.rs` has 13 tests (seven added), including all 328 frozen chrono 0.4.45 vectors in `src/temporal/chrono_vectors.rs`, whole-second vector round trips, strict syntax @@ -40,14 +62,16 @@ tests. The distribution binary is **1,270,880 bytes** (+16 bytes), below the failures, one-line existing crash-harness Clippy correction, and unverified lanes are documented in the [PR 1 evidence](testing/894-idb-flush-recovery.md). -| | Default features | With `--features test-hooks` | +| | Default features (#924 run) | `test-hooks` (pre-#924 inventory) | |---|---|---| -| **Active** | 2,158 | 2,196 | +| **Active** | 2,188 | 2,196 | | **Ignored** | 23 | 32 | -| **Total** | 2,181 | 2,228 | +| **Total** | 2,211 | 2,228 | -Counts above are the current Cargo test inventory (active versus ignored), -including #900, #441, #777, #789, #781, #794, #795, #837, #865, #869, #870, #861, #863, #871, #872 and #824 (Linux). Verification results below identify which suites ran. +Default counts above come from the completed #924 Linux run, including unit, +integration, example and doc tests. The test-hooks column preserves the last +pre-#924 inventory; that full feature suite was not rerun for #924. Verification +results below identify which earlier suites ran. **#441 verification (2026-11-14)**: the full native default suite passes (2,149 active, 23 ignored), including the grammar verifier and eight new diff --git a/docs/superpowers/specs/2026-11-28-924-incoming-ref-lookup-design.md b/docs/superpowers/specs/2026-11-28-924-incoming-ref-lookup-design.md new file mode 100644 index 0000000000..ecadf196a8 --- /dev/null +++ b/docs/superpowers/specs/2026-11-28-924-incoming-ref-lookup-design.md @@ -0,0 +1,157 @@ +# Spec — 008-incoming-ref-lookup (#924): bounded typed incoming-reference lookup in v3 write transactions + +**Mission Type:** code (plus API docs in three repos) + +**Base branches:** `project-minigraf/minigraf` **`v3`**; `project-minigraf/minigraf-java` **`v3`**; `project-minigraf/minigraf-docs` `main`. No `main` (v2.x) backport: this is a new feature, not a data-integrity fix. + +**Deliverables (PRs):** +1. Core PR on `v3` — API, implementation, tests, in-repo docs, a copy of this spec at `docs/superpowers/specs/2026-11-28-924-incoming-ref-lookup-design.md`. +2. minigraf-java PR on `v3` — binding method, tests, README, core pin bumped to the core PR's merge commit (opened or finalised after PR 1 merges). +3. minigraf-docs PR — v3-scoped docs (``). + +## 1. User Intent + +> #924: add a bounded typed incoming-reference lookup on the v3 write transaction. v3.0.0 is required for the LDBC SNB benchmark (JNI DEL7). Cover the small-write pending path, the large-write working tree, the durable VAET path and WAL-recovered data. It needs two budgets: one on the links returned and one on the records examined, with an explicit exhausted outcome. Include the Kotlin/JVM binding exposure DEL7 needs. + +> [Binding scope, after the Planner found that the benchmark's JNI bridge (`snb_minigraf`) calls core Rust directly] Core plus minigraf-java, matching what DEL7 needs. + +> [Valid time] Any valid window — every ref asserted at the current transaction time, including future-dated and expired ones. Safest for a cascading delete, since none are left dangling. Differs from a default query. + +## 2. Goal + +A cascading delete (LDBC SNB Interactive v2 DEL7) must find every live typed reference **to** an entity — across attributes it did not anticipate — inside the same write transaction that will apply the delete, and must be able to refuse the delete when discovery cannot finish cheaply. Today the only route is an unbound-attribute query that falls back to a whole-EAVT scan and whose `:limit` does not bound work. Add a read-only lookup on both Rust write-transaction types and on the JVM transaction object that, given a target entity UUID, returns the complete set of live incoming `(source entity, attribute)` pairs, or an explicit *exhausted* outcome when either a links budget or a records-examined budget would be exceeded. Its record enumeration must depend only on the target's own incoming history — no scan, copy or re-index proportional to unrelated facts (bounded index navigation, whose depth may grow with the tree, is allowed) — in every place the transaction's facts can live: durable VAET, pending (uncheckpointed, including WAL-recovered), staged (small transaction), and large-transaction working trees. + +## 3. Context & Investigation Findings + +All core references are `v3` @ `33b4b165c`. minigraf-java references are `origin/v3` @ `0a2d4d65` (core pin still `32d71ce0`); start the binding work from that or a later `origin/v3`, not an older local branch. Sources: Claude-01, Codex-01..03. + +### Issue and caller +- #924 (milestone v3.0.0) and ldbc-benchmarks #17 ("Bounded JNI delete prerequisite") list the required behaviour: exact typed Ref, no Keyword alias, unknown target → empty without dictionary mutation, staged retractions shadow older assertions, WAL-recovered data included, both budgets, distinct exhausted outcome, no whole-index fallback, overflow detected before mutation. +- The benchmark's JNI lane loads its own Rust crate (`ldbc-benchmarks/crates/snb-minigraf/src/bridge.rs`) which calls `db.begin_write()` (borrowed `WriteTransaction`, `examples/support/deep_delete.rs:33`). minigraf-java (`MiniGrafWriteTransaction`, UniFFI/JNA over `OwnedWriteTransaction`, `minigraf-java/src/lib.rs:1003-1096`) is the published JVM surface. Both are in scope per the user. The benchmark repo's core pin stays unchanged by this mission. + +### Why a query cannot do this +- `src/query/engine/scan.rs:745-764`: `[?e ?a ]` with unbound entity and attribute scans EAVT from the empty prefix; pending shadow setup is built first. `:limit` caps rows, not work. +- `scan.rs:~690`: query value matching treats a Keyword and a Ref to its entity as equal in some positions (#744); this lookup must not. A generic query is therefore not a valid oracle for tests. +- `src/db.rs:1245-1250`: `fact_log` refuses use during an active write. + +### Transaction read state +- `TxState` (`db.rs:2008-2022`) is shared by `WriteTransaction` and `OwnedWriteTransaction`: `staged: Staged` while small, `large: Option` once large (native file databases only). +- `TxState::read_snapshot` (`db.rs:2115-2128`): large → `OnDiskReader` over working trees (`persistent_facts/large_tx.rs:213-227`, own dictionary cache; contains committed + pending + finished statements, and `with_committed` empties the pending/staged view, `graph/storage.rs:372-383`); small → database snapshot + `with_staged(staged.read_view())`. +- A transaction becomes large only on a file database (`db.rs:2070-2081`). **In-memory transactions never become large**, so their staged set is unbounded. +- `Staged::read_view` (`db.rs:2428-2439`) clones every staged fact and `Snapshot::with_staged` (`graph/storage.rs:362-370`) rebuilds a full `PendingStore` from them **per read** — O(staged) setup that would make any lookup built on it linear in unrelated staged data. +- Promotion to large (`db.rs:2135-2175`), rejected statements, rollback and retry must leave no stale lookup state. + +### Pending store +- `PendingStore` (`graph/storage.rs:59-129`) holds uncheckpointed facts with `Indexes` of **EAVT and AEVT only** (`storage/index.rs:194-212`; the "four indexes" comment at `storage.rs:167-169` is stale). No target-keyed pending access exists. `push`, `extend`, `of`, `load_facts` (`:845-855`, used by WAL replay at `db.rs:932-961`) and checkpoint publication (`:1002-1031`) are all insertion/lifecycle points. +- An in-memory database has `committed: None` (`storage.rs:689`): every fact is pending for its lifetime. +- #762 (bbtree pending indexes) is v3.next; this mission must not depend on it. + +### Durable and large paths +- VAET key = `target eid ‖ attr iid ‖ source eid ‖ tx↓ ‖ vf ‖ vt ‖ asserted`, only for scalar `KeyValue::Ref` (`storage/keys.rs:779-812`). Keywords and sets never get VAET keys. No key-format change is needed. +- `KeySource::live_keys` / `OnDiskReader::live_walk` (`storage/mod.rs:555-574`, `storage/reader.rs:138-296`): `max` bounds **emitted** keys at triple boundaries; dead triples cost visits without counting; legacy winning groups can buffer several windows; seek-after-8-skips helps one long history but not many distinct dead triples. `LogSource::walk` rejects VAET (`reader.rs:441-453`). +- Durable and large paths use the same reader type; source UUIDs and attribute idents must be decoded through the selected reader's dictionary (a source or attribute first written in the large working tree is absent from the committed dictionary). +- `Dict::eid_of` (`storage/dict.rs:128-132`) is a read-only lookup. Absence in the committed dictionary says nothing about pending/staged data. + +### Visibility rules to reuse +- Per triple `(e, a, v)`, the newest transaction decides; within it a tied retraction beats assertions; earlier windows never reappear (`graph/storage.rs:1067-1089`; #435/#477; design `2026-10-07-write-validation-and-statement-order-design.md` §1). Across layers, staged > pending > committed (`scan.rs:765-775` shadowing). Within one transaction, the last statement that wrote a triple decides (`db.rs:2443-2448`, `keep_last_statement`). +- Because the user chose "any valid window", valid-time filtering does **not** apply, so the staged `now` / `VALID_FROM_USE_TX_TIME` subtleties (`db.rs:2428-2439`, `storage.rs:362-368`) do not affect the result. + +### JVM binding +- `minigraf-java/src/lib.rs:1020-1096`: `MiniGrafWriteTransaction` wraps `Mutex>`; finished → `API-018`; callback reentry is refused (`INT-001`) before the mutex (`:1040-1074`); counts are signed `i64`, bad counts/UUIDs → `API-017` (`:75-109`); Ref payloads are UUID strings (`:280-332`). +- Core pin is `32d71ce0` (`Cargo.toml:17-20`); the binding needs a pin containing the feature, and the bump brings in every core change since (bindings' CI must stay green). +- Tests: `java/src/test/kotlin/.../TransactionTest.kt`, `java/src/test/java/.../JavaInteropTest.java`, `consumer-test/`. Generated Kotlin is a build artifact. + +### Budgets and size +- Binary-size gate on v3 is **1,250 KiB** (`.github/workflows/binary-size.yml:17`, 1,280,000 bytes; `PHILOSOPHY.md:126`). `TandemKit/Planner.md`'s 1,230 KiB is stale. +- Last error codes on v3: API-027, QRY-015, STG-048. No new code is expected. + +## 4. Acceptance Criteria + +Test names are suggestions; equivalent tests are fine. "Live" and "examined record" are defined in §5. + +**Core API (Rust)** +1. **Both transaction forms.** `WriteTransaction` and `OwnedWriteTransaction` expose the same lookup (proposed `incoming_refs(target: EntityId, limits: IncomingRefLimits)`) with the same receiver style as `execute`, returning `Result`. It is available on every target where those types compile (native and WASI `wasm32`); `BrowserDb` is excluded. New public types are exported from the crate root and are `#[non_exhaustive]`; external code can still build the limits (constructor or builder, Generator's choice) — shown by a rustdoc example or an external integration test that constructs limits, calls the lookup and matches both outcomes. +2. **Outcome shape.** The outcome is either *complete* — every live link plus the number of records examined — or *exhausted* — which budget (links or records) and the records examined so far, with **no link list**. Exhausted is distinguishable from complete-empty and from an error without parsing text. Test: `incoming_refs_outcomes_are_distinct`. +3. **Exact typed results.** With several sources, several inbound attributes (including one the caller does not name), a self-reference, a same-spelling Keyword value, a UUID-looking String, a `Value::Set` containing the target's Ref and non-Ref values on the same attributes, the result is exactly the scalar-Ref links. Run on in-memory and file databases. Test: `incoming_refs_exact_types_and_attributes`. +4. **Unique pairs.** Each `(source, attribute)` appears once regardless of duplicate statements, history or several surviving legacy windows; two attributes from one source are two links. Tests: `incoming_refs_unique_pairs`, `incoming_refs_legacy_ties`. +5. **Valid time ignored (user decision).** A ref whose newest version is an assertion with a future `valid_from`, or a `valid_to` already in the past, **is** returned; a ref whose newest version is a retraction is not, whatever the windows. A newer assertion with an expired window still shadows an older one (no double-count, no resurrection). Test: `incoming_refs_any_valid_window`. +6. **Current write view.** Inside one transaction: a staged assertion is visible to a later lookup; a staged retraction hides a committed, pending or earlier-staged assertion; retract-then-reassert is visible; the last statement wins per triple; a rejected statement (e.g. API-011) contributes nothing. Tests: `incoming_refs_statement_order`, `incoming_refs_rejected_statement`. +7. **Unknown and dangling targets.** A UUID never seen anywhere → complete, zero links, and the transaction's later commit, `checkpoint`, reopen and `verify()` behave as if the lookup never ran (no dictionary id allocated in the committed or working dictionary). A target referenced only by pending or staged facts, or with no facts of its own, is found. Tests: `incoming_refs_unknown_target`, `incoming_refs_pending_only_target`, `incoming_refs_dangling_target`. +8. **Read-only and retryable.** Complete and exhausted lookups stage nothing, write no WAL entry, take no `tx_count`, cause no promotion or checkpoint, and leave the transaction usable; a retry with larger budgets, further writes, commit, rollback and drop behave as without the lookup. Core `commit`/`rollback` keep consuming the transaction (`db.rs:2610-2650`), so there is no finished Rust object to call; API-018 applies only to the JVM wrapper (AC17). Tests: `incoming_refs_read_only_and_retryable`, `incoming_refs_exhaustion_then_rollback`. +8a. **Failed handles: a lookup is a read.** A prior checkpoint failure (later writes STG-046) or WAL-append failure (later writes WAL-007) does not by itself make the lookup fail with STG-046 or WAL-007 — as queries keep working in that state (`db.rs:1391-1399`; `refuse_if_failed` at `db.rs:704-719` guards writes only). The lookup stays subject to its own budgets and returns the I/O, decode and lock errors its own reads hit; it need not fail or succeed together with a query, which reads different indexes. Existing query behaviour and rollback availability are unchanged. Test (fault-injected, distinct from an API-011 rejected statement): `incoming_refs_on_failed_handle` — in each failure state, with readable data and sufficient budgets, the result equals the independent exact-typed, any-valid-time oracle. + +**Storage coverage (each layer, same expected sets)** +9. **Durable VAET:** committed + checkpointed, and after close/reopen. **Pending:** committed, not checkpointed. **WAL-recovered:** a child process commits and exits without checkpoint (as `tests/wal_test.rs:700-722` does); after reopen the links are returned, a small transaction can retract a recovered link (hidden), and after a forced promotion to large it stays hidden. **Large working tree:** a file transaction forced large with a small `TxOptions::chunk_facts`, including links asserted/retracted in earlier statements, sources/attributes first created inside the large transaction, and a lookup before and after promotion returning the same set. **In-memory database:** pending + staged. **Rollback:** a new transaction sees the pre-transaction set; **commit:** same set before/after checkpoint and reopen. Tests: `incoming_refs_checkpoint_reopen`, `incoming_refs_wal_recovery`, `incoming_refs_recovered_then_promoted`, `incoming_refs_promotion`, `incoming_refs_rollback`. +10. **Model-based check.** A proptest over random sequences of assert/retract statements, commits, rollbacks, checkpoints, reopens and forced promotions on a small universe (a few sources, attributes, targets, Keyword aliases) compares every lookup with an independent exact-typed, any-valid-time model (not a Datalog query). Test: `incoming_refs_model` (may live beside `tests/model_based_test.rs`). + +**Budgets** +11. **Links budget boundary.** Given a sufficient `max_records`, with N live links: `max_links = N` → complete with N; `N − 1` → exhausted(links); `0` with no links → complete-empty; `0` with one link → exhausted(links). Huge caps (`usize::MAX`) work without allocating to the cap or overflowing. Tests: `incoming_refs_exact_link_cap`, `incoming_refs_link_overflow`, `incoming_refs_zero_and_huge_limits`. +12. **Records budget.** The lookup never examines more than `max_records` records in total across all layers; `records_examined` in either outcome is ≤ `max_records`. If it cannot establish the complete set within the budget it returns exhausted(records), including mid-way through one triple's version group. Tests: `incoming_refs_budget_shared_across_layers`, `incoming_refs_legacy_group_budget`. +13. **History exhaustion.** A target with zero or few live links but ≥1,000 distinct retracted or superseded incoming pairs, with `max_records` well below that, returns exhausted(records) — in pending, durable and large-working-tree representations. Separately, one pair with a long history (≥1,000 versions, newest an assertion): on a fixed fixture and representation, first take a **complete** run with a generous `max_records`, and let B be its `records_examined`; then the same lookup with `max_records = B` is complete and correct, and with `max_records = B − 1` it is exhausted(records) or complete-and-correct (an implementation may adapt its traversal to the budget; B need not be minimal). Skipping old versions by seek is allowed but not required. In every low-budget history test, no uncharged processing or materialisation of the target's records happens before exhaustion (checked by AC14's independent counter). Tests: `incoming_refs_dead_pairs_exhaust`, `incoming_refs_one_pair_long_history`. +14. **Independence from unrelated data.** At fixed target data (e.g. 3 live links) and fixed budgets, adding 100,000 unrelated facts — scalar facts, Keyword values, and refs to other targets — leaves `records_examined` exactly unchanged, in each of: durable, pending, staged (in-memory database, one transaction), and large working tree. Independently of the public count, test-only instrumentation (mechanism is the Generator's choice, e.g. `cfg(test)` or the `test-hooks` feature) counts the actual records the lookup enumerates, copies or indexes in **every** representation — index entries advanced over in durable and working-tree VAET (whether or not they match the target), and pending/staged facts touched during setup — and it too stays unchanged when the unrelated facts are added, for the first lookup in a transaction as well as repeats — except for a fixed number of prefix-end probes per participating range (e.g. reading the one successor key of another target that now sorts after this target's range, where before the range ended at end-of-index), which the instrumentation reports separately or allows explicitly. No enumeration continues past the target range and nothing grows with the number of unrelated facts. The fixture covers both the end-of-index and the non-matching-successor case. Bounded tree routing and page decoding may change with tree shape and are not asserted equal. Test: `incoming_refs_unrelated_growth`. +15. **Exhaustion precedence.** Exhausted(links) is reported only after N+1 distinct live links have been established; otherwise a lookup that runs out of records reports exhausted(records). Never a partial list. + +**Owned transaction** +16. A lookup works after moving an `OwnedWriteTransaction` to another thread; concurrent readers still see only their committed snapshot; existing reentry/thread guards (INT-001) are unchanged. Tests extend `tests/owned_tx_test.rs` (`owned_incoming_refs_cross_thread` and guard cases). + +**JVM binding (minigraf-java `v3`)** +17. `MiniGrafWriteTransaction` exposes the lookup (proposed `incomingRefs(target: String, maxLinks: Long, maxRecords: Long)`) returning a typed outcome (complete with links + records examined / exhausted with budget + records examined) and typed links (`source` canonical UUID string, `attribute` string). Invalid UUID, negative or unrepresentable budgets → API-017; finished transaction → API-018; callback reentry → INT-001 without blocking. Java callers distinguish outcomes without JSON or message parsing. +18. Kotlin (`TransactionTest.kt`) and plain Java (`JavaInteropTest.java`) tests cover complete, complete-empty, both exhaustion reasons, Keyword exclusion, retry with larger budgets, commit/reopen, rollback, finished-transaction and reentry errors. The packaged `consumer-test` calls the API from the built jar. Native shim `cargo test`, Gradle build and every existing CI job pass with the bumped core pin. + +**Compatibility, size, performance, docs** +19. No file-format, WAL, grammar or Datalog change; no existing public API changes; the golden-file corpus, model-based, WAL, crash and owned-transaction suites pass; all existing tests pass; clippy and fmt clean (including the wasm32 lint job). +20. Binary size stays within the **1,250 KiB** gate (the PR reports before/after bytes). +21. Write-path cost of any new maintained pending/staged target structure is measured on the bench machine against the v3 base. The measured set includes (a) the existing insert/transaction, WAL-replay and checkpoint benchmarks as controls (they write integer values: `benches/minigraf_bench.rs:105-212`, `benches/minigraf_bench/chunked_transactions.rs`), and (b) timed workloads whose measured operation writes `Value::Ref` facts — pending insertion, small-transaction staging, WAL recovery, and checkpoint/promotion where the new structure is involved — using an existing fixture if one writes refs, else a small new bench. The PR's measurement report names each workload ID and scale, the statistic (median), base and branch numbers, and pending-store memory per ref fact. A median regression above 5% on any of them is reported to the user and needs their acceptance before the PR is marked ready. +22. Docs in sync: `CHANGELOG.md` (v3 Unreleased: new API), `CLAUDE.md` (test count, module notes for any new pending structure, fix the stale "four indexes" wording if touched), `docs/TEST_COVERAGE.md`, `ROADMAP.md` (#924), `README.md` (if it lists transaction methods), rustdoc on the API (semantics, both budgets, exhaustion, "require complete before deleting", scalar-Ref only, valid time ignored); minigraf-java `README.md` / `java/README.md`; docs site `content/database-tools.md` or `content/cookbook-application-workflows.md` (usage) and `content/architecture.md` (pending target access), all under ``. `docs/ERROR_REFERENCE.md` only if an error meaning changes. + +## 5. Edge Cases & Boundaries + +### Definitions +- **Live link** — a pair `(source, attribute)` such that, in the transaction's current view (staged over pending over committed; or the working trees when large), the newest version of the triple `(source, attribute, Value::Ref(target))` is an assertion. Valid-time windows are ignored. Only stored facts; rule-derived facts are not links. Only a top-level `Value::Ref` — not a Keyword with the same spelling, not a String, not a Ref inside a `Value::Set`. +- **Examined record** — one stored fact version (index entry or pending/staged fact) belonging to the target's range that the lookup inspects, in any layer, whether it turns out live, superseded or retracted; charged when inspected, including lookahead used to detect overflow or settle a version group. Tree navigation, dictionary lookups and the prefix-end check are not records, but must not hide a scan: AC14's independent enumeration counter checks every representation. Beyond a fixed number of prefix-end probes per range, advancing over an index entry outside the target's range is enumeration, not navigation. Every inspected record of the target's own history, and lookahead used to settle a target version group, is charged to the budget. Versions skipped by an index seek without inspection are not charged. The budget is one total across all layers. +- **Records examined counts may differ** between representations (pending vs checkpointed vs working tree) for the same logical data; results must not. + +### Boundaries +- `max_links = 0` / `max_records = 0` are real limits, not "unlimited". `max_records = 0` gives complete-empty only when emptiness is known without inspecting a record (e.g. the target is absent from every layer's dictionary/index); otherwise exhausted(records). +- Exactly `max_records` examined and the set is complete → complete. Never examine `max_records + 1`. +- No arithmetic overflow at `usize::MAX`; no allocation proportional to a requested cap. +- Result order is **unspecified**; tests compare sets. + +### Transaction and lifecycle +- The lookup sees every earlier completed statement of the transaction, not a begin-time snapshot. +- Exhaustion does not undo the caller's own staged writes; the guarantee is that the lookup itself mutates nothing. DEL7 is expected to run discovery before staging its deletes. +- Cache warming is allowed; dictionary id allocation, WAL writes and staged changes are not. +- I/O, decode and lock errors are errors — never an empty complete or an exhausted outcome, never a partial list. +- Rejected statements, promotion, rollback, retry after exhaustion, checkpoint publication and WAL replay must leave any auxiliary lookup state consistent with the facts. + +## 6. Key Decisions + +| Decision | Rationale | +|---|---| +| Dedicated method, not a query-planner change | Needs an exhausted outcome and a work budget; Datalog `=` treats Keyword≈Ref (#744); planner changes would not meet the bound for staged/pending data. | +| Any valid window (user) | Cascading delete must not leave future-dated or expired-but-asserted refs dangling. Differs from a default query; documented. | +| Complete-or-exhausted batch, no partial links, no cursor | DEL7 needs a complete set before deleting; a cursor adds lifetime and continuation semantics nobody asked for. Retry with larger budgets instead. | +| Outcome enum, not error codes | Exhaustion is an expected outcome, not a failure; no new error code. | +| `records_examined` public | Lets the benchmark record bounded-visit evidence; tests assert it. | +| Scalar Ref only | Matches VAET; sets of refs would need another index. | +| Order unspecified | DEL7 doesn't need it; avoids a sort contract. | +| Pending/staged need maintained target-local access | Only way to meet AC14 for in-memory and pending data; cost measured (AC21), independent of #762. | +| Core + minigraf-java only (user) | DEL7 uses core directly; minigraf-java is the published JVM surface. Other bindings (Python, Android, Swift, Node, C, WASI REPL, browser) are not in this mission. | +| Base `v3`, no backport | New feature in the v3.0.0 milestone. | + +## 7. Out of Scope + +- Cascading delete itself, referential-integrity enforcement, relationship allowlists. +- DEL7 integration, benchmark pin changes, reference comparison, qualification. +- Datalog/grammar/planner changes, `:limit` semantics, AVET work (#518), pending-index redesign (#762). +- `:as-of` / chosen valid-time variants, multi-target lookup, continuation tokens, refs inside sets. +- Other bindings and `BrowserDb`; binding-template (unless the Generator finds the template must change for the Java binding to build — then report it). +- A database-level (non-transaction) lookup. + +## 8. Possible Directions & Ideas (non-binding) + +- The durable and large paths can share one VAET walk over `OnDiskReader`; `live_walk` (`reader.rs:156`) shows the triple/tx-group logic but counts only emitted keys. +- For pending and staged data, a target-keyed index maintained alongside EAVT/AEVT (ref facts only) is one option; another is keeping staged facts in a persistent indexed store instead of rebuilding per read. Either must survive promotion, rollback and checkpoint publication. +- `tests/model_based_test.rs` and `tests/reference_model/` show the existing model-based pattern; `tests/wal_test.rs:700-722` the child-process crash pattern; `tests/owned_tx_test.rs` the owned-transaction pattern. +- Measure on the bench machine (`benches/minigraf_bench.rs`); bench profile is opt-level z, so compare base vs branch on the same profile. +- The `test-driven-development` skill fits the budget/boundary tests. diff --git a/docs/testing/924-incoming-refs.md b/docs/testing/924-incoming-refs.md new file mode 100644 index 0000000000..24c3b96995 --- /dev/null +++ b/docs/testing/924-incoming-refs.md @@ -0,0 +1,122 @@ +# #924 core incoming references + +Scope: deliverable 1 of the [approved spec](../superpowers/specs/2026-11-28-924-incoming-ref-lookup-design.md), based on `73388aec5` on `v3`. JVM bindings and the docs site are separate repositories. No format, WAL, grammar, Datalog or error-code changes. + +## Design + +`IncomingRefLimits::new(max_links, max_records)` is constructible by downstream code. Both write transaction forms expose `incoming_refs(&mut self, target, limits)`. `IncomingRef`, `IncomingRefLimits`, `IncomingRefs` and `IncomingRefBudget` are non-exhaustive crate-root exports. `IncomingRef::new` also permits external link construction. + +- Pending: `RefPositions`, a standard randomly seeded `HashMap>`, records scalar-ref positions during `PendingStore::push` and `extend`. WAL replay uses the same insertion path. Query-only stores built by `Snapshot::with_staged` omit this unused index. A checkpoint publishes a new empty pending store together with its committed reader. +- Small staged transactions: the same position structure is maintained when an accepted statement is staged. Lookup borrows the facts directly, including in-memory transactions of unbounded size. It never calls `Staged::read_view`. Rejected statements add nothing. Successful promotion releases the staged facts and index. Promotion filters the staged vector in place with the existing last-statement mask before the writer stamps one transaction counter. It reuses the vector and retained facts without cloning. A failed staged-chunk write retains those facts and rebuilds their target positions, accounting for filtering or writer reordering; lookup uses committed/pending storage plus the completed staged statements. Only the error path rebuilds the index. Rollback/drop discard the transaction. +- Durable and large working trees: a dedicated raw VAET walk seeks the target prefix, checks only that prefix before charging, then decodes one version at a time. It uses the selected reader's dictionary, including new working-tree entities and attributes. Neither `live_keys` nor a buffered version-group reader is used. Tree-page decoding is bounded navigation; a single nonmatching successor probe is counted separately. A failed large-statement chunk restores its statement base. If finalization fails while reading the claims tree, lookup retains the completed statements’ roots and dictionary; their held pages remain allocated. Existing query readers still select the working roots. Commit remains refused with STG-046. +- Visibility: a per-lookup map retains the newest `(layer, tx_count, asserted)` per `(source, attribute)`, with tied retractions winning. Staged beats pending, which beats committed. It examines all target history rather than seeking past old versions. Only after all participating ranges finish are live links established and the links cap checked. Consequently, records exhaustion can precede links exhaustion even when some inspected assertions might eventually survive. No partial list escapes. Temporary state follows inspected distinct pairs, never a requested cap. + +The test-only enumeration counter counts actual lookup advances as well as general staged copying, pending-store construction/extension, range copies and pending scans. These sites compile only for tests or `test-hooks`, independently of public `records_examined`. + +The lookup does not write, allocate dictionary IDs, promote, checkpoint or take a transaction counter. Write-failure flags are not checked on this read. Lock, read and decode errors propagate. Valid time is ignored; keywords, strings, sets and rule-derived facts are excluded. + +## Acceptance mapping + +Names below are executable tests; combined names cover several closely related criteria. + +| AC | Tests / evidence | +|---|---| +| 1 | `incoming_refs_external_types_and_large_read_only`, API rustdoc, `owned_incoming_refs_cross_thread_and_guards` | +| 2 | `incoming_refs_outcomes_are_distinct` | +| 3 | `incoming_refs_exact_types_and_attributes` (memory, pending and durable) | +| 4–5 | `incoming_refs_unique_pairs_and_any_valid_window`, `incoming_refs_legacy_ties_and_group_budget` | +| 6 | `incoming_refs_statement_order_rejected_statement_and_promotion` (memory and file), `incoming_refs_model`, `incoming_refs_promotion_filters_before_stamping` (allocation reuse, both statement orders and tied retractions after stamping), the three failed-statement tests in AC8a | +| 7 | `incoming_refs_unknown_pending_only_dangling_and_checkpoint_reopen`, `incoming_refs_external_types_and_large_read_only`, statement/promotion test | +| 8 | `incoming_refs_read_only_retryable_exhaustion_rollback_and_drop`, `incoming_refs_external_types_and_large_read_only` | +| 8a | `incoming_refs_on_failed_handle` (fault-injected STG-046 and WAL-007; borrowed and owned); `incoming_refs_failed_promotion_keeps_completed_statements` (earlier assertion and retraction), `incoming_refs_failed_large_statement_keeps_completed_statements` (every chunk-write fault ordinal), `incoming_refs_failed_end_statement_keeps_completed_statements` (claims-tree read failure) | +| 9 | `incoming_refs_wal_recovery_and_recovered_then_promoted` (actual crashing child, implicit and explicit commits), `incoming_refs_promotion_exact_set` (before/after promotion, new source/attribute and retraction after promotion, exact set before commit); checkpoint/reopen, statement/promotion, rollback/drop and model tests | +| 10 | `incoming_refs_model`: 32 proptest cases, up to 79 operations, independent exact-typed set model; asserts/retracts, aliases, commit/rollback, checkpoint/reopen and low promotion thresholds | +| 11 | `incoming_refs_exact_link_cap_overflow_zero_and_huge_limits` | +| 12 | `incoming_refs_budget_shared_across_layers`, `incoming_refs_legacy_ties_and_group_budget` | +| 13 | `incoming_refs_dead_pairs_exhaust_and_one_pair_long_history`, `incoming_refs_history_enumeration_is_bounded` | +| 14 | `incoming_refs_unrelated_growth`: 100,000 mixed unrelated facts, all four layers, first and repeated calls; independent enumeration and separate successor probes; history and legacy budget tests independently check low-budget counts; `incoming_refs_setup_work_is_counted`, `incoming_refs_pending_extend_work_is_counted`, `incoming_refs_query_snapshot_skips_target_index` | +| 15 | outcome, shared-layer budget and external large read-only tests; reduction establishes links only after all ranges finish | +| 16 | `owned_incoming_refs_cross_thread_and_guards`, existing `owned_tx_guards_begin_thread`, `owned_tx_user_function_off_the_begin_thread`, `owned_tx_other_thread_query_reads_committed` | +| 19 | `incoming_refs_read_errors_remain_errors`; full native suite, golden/model/WAL/crash/owned suites, fmt and native/browser/WASI Clippy | +| 20 | Distribution binary measurements below | +| 21, Rust half | Standalone `incoming_refs_write` benchmark below; `incoming_refs_position_memory` capacity accounting; bench-machine timing comparison pending | +| 22, in-repo half | API rustdoc, CHANGELOG, CLAUDE, TEST_COVERAGE, ROADMAP and README | + +## Ref write-cost benchmarks + +`benches/incoming_refs_write.rs` uses only APIs present on the base. To compare, copy that file and its `[[bench]]` Cargo entry onto the base in a disposable directory. No production source from this branch is needed. Statements contain `#uuid` values, which the parser stores as scalar `Value::Ref`. + +New IDs, each at `1000` and `10000` facts: + +- `incoming_ref_writes/pending/{scale}`: in-memory insertion, including the pending position index. +- `incoming_ref_writes/staged/{scale}`: staging in an owned in-memory transaction. +- `incoming_ref_writes/wal_recovery/{scale}`: open and replay a retained Ref WAL. +- `incoming_ref_writes/checkpoint/{scale}`: publish a checkpoint over pending refs. +- `incoming_ref_writes/promotion/{scale}`: a second Ref statement crosses the chunk threshold; includes pending refs and earlier staged refs in promotion. + +The harness uses 30 samples with flat sampling, one second of warmup and a three-second measurement target per ID (Criterion may extend this for slow operations). Command construction, fixture creation, and handle teardown are outside the timed operation. Run the same profile/toolchain on base and branch; report Criterion's **median** for each ID and percent change. A regression above 5% requires user acceptance before readiness. + +```sh +CARGO_BUILD_JOBS=4 cargo bench --offline --bench incoming_refs_write -- --list +CARGO_BUILD_JOBS=4 cargo bench --offline --bench incoming_refs_write +# Existing integer controls (all existing scales): +CARGO_BUILD_JOBS=4 cargo bench --offline --bench minigraf_bench -- '^insert/' +CARGO_BUILD_JOBS=4 cargo bench --offline --bench minigraf_bench -- '^insert_file/' +CARGO_BUILD_JOBS=4 cargo bench --offline --bench minigraf_bench -- '^open/wal_replay/' +CARGO_BUILD_JOBS=4 cargo bench --offline --bench minigraf_bench -- '^checkpoint/' +``` + +Integer control IDs include `insert/{single_fact,batch_100,explicit_tx}/{1k,10k,100k,1m}`, their `insert_file` equivalents, `open/wal_replay/{1k,10k,100k}`, `checkpoint/{1k,10k,100k,1m}`, `checkpoint/after_1_fact/{10k,100k,1m}`, `checkpoint/after_100k_facts/{10k,100k}`, and `insert_file/chunked/{execute,retract,write_tx}/{65535,65537}`. Use `--list` on the existing harness for its authoritative inventory and any additional controls selected by these filters. + +Base/branch timing medians and the >5% decision remain for the separate bench machine. + +## Added pending-store memory + +`incoming_refs_position_memory` measures retained capacities at 10,000 scalar-ref facts on x86_64. The same representation is used for staged facts. The pre-existing facts, duplicate-check set and EAVT/AEVT indexes are unchanged; this table is the **additional** pending-store memory introduced by #924, not total database RSS. + +| Distinct targets | Added capacity bytes | Bytes per Ref fact | +|---:|---:|---:| +| 1 | 131,300 | 13.1300 | +| 16 (benchmark distribution) | 132,448 | 13.2448 | +| 10,000 (one ref per target) | 751,808 | 75.1808 | + +Derivation: `size_of::()` (48 bytes) + hash-table buckets × (`size_of::<(EntityId, Vec)>()` (40) + one control byte) + 16 control-tail bytes + the sum of vector capacities × 8-byte positions. Bucket count is the next power of two of the measured map capacity. This accounts for capacity slack but excludes allocator metadata/rounding; it describes the installed standard-library implementation, not a portable allocation contract. Each singleton target reserves one position rather than Vec's default four. Logical position storage is eight bytes per Ref plus per-target overhead. Non-Ref facts add no entries or heap allocation; the empty map is one fixed 48-byte field per store/transaction. `incoming_refs_non_ref_staging_keeps_batch_capacity` also verifies that staging retains the original batch reservation. + +Reproduce the capacity report without running timing benchmarks: + +```sh +CARGO_BUILD_JOBS=4 cargo test --offline --lib incoming_refs_position_memory -- --nocapture +``` + +Total allocator/RSS measurements and write-time medians remain for the bench machine. No allocator instrumentation was added to the library. + +## Verification (2026-11-28) + +All Cargo commands ran offline with `CARGO_BUILD_JOBS=4`; the final test run also set `RUST_TEST_THREADS=4`. No release-mode tests or timing benchmarks were run. Both wasm targets were installed. + +| Command | Result | +|---|---| +| `cargo build --offline` | Pass | +| `cargo test --offline` | **2,188 passed, 0 failed, 23 ignored** (2,211 total); 402.58 seconds | +| `cargo clippy --offline --all-targets -- -D warnings` | Pass | +| `cargo fmt --check` | Pass | +| `cargo clippy --offline --target wasm32-unknown-unknown --features browser -- -D warnings` | Pass | +| `cargo clippy --offline --target wasm32-wasip1 -- -D warnings` | Pass | +| Base-only source plus the new benchmark: `cargo check --offline --bench incoming_refs_write` | Pass | +| `cargo build --offline --profile dist` (Rust 1.94.0) | Build passes; size exceeds gate on both base and branch | +| `cargo +1.99.1 build --offline --profile dist` | Pass; size below gate | + +The library suite is 1,268 passed / eight ignored. The incoming-reference integration file is 14 passed; owned transactions are 17 passed. Fourteen focused incoming-reference unit tests pass. The full run includes the existing golden-file, model, WAL, crash and transaction suites; ignored cases remain ignored. The new API rustdoc passes. + +The complete `--features test-hooks` suite, wasm runtime tests, JVM bindings and docs-site builds were not run. Ordinary unit tests exercise the test-only enumeration sites. + +## Distribution binary size + +The workflow builds the native x86_64 Linux CLI with `cargo build --profile dist` (release's full LTO, opt-level z, one codegen unit, stripped symbols). The unchanged limit is **1,280,000 bytes (1,250 KiB)**. Base is `73388aec5`; base and branch use the same compiler and separate build directories. + +| Installed compiler | Base bytes | Branch bytes | Growth | Gate | +|---|---:|---:|---:|---| +| Rust 1.94.0 (local default) | 1,284,448 | 1,288,240 | +3,792 | Both exceed | +| Rust 1.99.1 | 1,246,760 | 1,250,568 | +3,808 | Both pass | + +The gate is satisfied with the installed newer toolchain. CI's exact Rust 1.100 toolchain is unavailable locally; that exact build remains unverified. diff --git a/src/db.rs b/src/db.rs index ef887316cb..e50450db6d 100644 --- a/src/db.rs +++ b/src/db.rs @@ -2112,6 +2112,52 @@ impl TxState { } } + fn incoming_refs( + &self, + ctx: &WriteContext, + inner: &Inner, + target: crate::EntityId, + limits: crate::IncomingRefLimits, + ) -> Result { + let snapshot = inner.fact_storage.snapshot()?; + #[cfg(not(target_arch = "wasm32"))] + let snapshot = if let (Some(tx), WriteContext::File { pfs, .. }) = (&self.large, ctx) { + if self.staged.pending_facts.is_empty() { + snapshot.with_committed(pfs.large_incoming_reader(tx)) + } else { + snapshot + } + } else { + snapshot + }; + #[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)) + } + /// The state a query inside the transaction reads (#550 spec §7): for a /// large transaction its working trees, which hold every committed and /// pending fact and its finished statements; otherwise the database with @@ -2159,17 +2205,28 @@ impl TxState { // synced whatever the transaction's mode (#871). Minigraf::open_wal(wal, db_path, pfs.generation())?; let mut tx = pfs.begin_large(tx_id)?; - let mut staged: Vec = std::mem::take(&mut self.staged.pending_facts) - .into_iter() - .zip(keep) - .filter_map(|(f, k)| k.then_some(f)) - .collect(); - let written = if staged.is_empty() { + // Reduce before stamping: the newest statements must still win when + // all retained records receive the same tx_count. + let mut keep = keep.into_iter(); + self.staged + .pending_facts + .retain(|_| keep.next() == Some(true)); + drop(keep); + let written = if self.staged.pending_facts.is_empty() { Ok(()) } else { - pfs.write_staged_chunk(&mut tx, &mut staged) + pfs.write_staged_chunk(&mut tx, &mut self.staged.pending_facts) }; - drop(staged); + self.staged.incoming = crate::incoming::RefPositions::default(); + if written.is_ok() { + self.staged.pending_facts = Vec::new(); + } else { + // Filtering and the writer may change positions; rebuild only + // after failure, for reads of the completed staged statements. + for (pos, fact) in self.staged.pending_facts.iter().enumerate() { + self.staged.incoming.insert(fact, pos); + } + } // After a failure the transaction stays open: `commit` refuses it // (STG-046), and a rollback or drop discards it. self.large = Some(tx); @@ -2305,6 +2362,45 @@ impl<'a> WriteTransaction<'a> { .map_err(MinigrafError::from) } + /// Find every live stored scalar [`Value::Ref`] to `target` in this write + /// view. The newest transaction wins per triple; tied retractions win, + /// and the last staged statement wins. Valid time is ignored, including + /// future and expired assertions. Keywords, strings, sets and derived + /// facts are excluded. Result order is unspecified. + /// + /// `max_links` bounds distinct live pairs; `max_records` bounds inspected + /// versions across all layers, including retractions and superseded + /// versions. Zero is a real limit. Exhaustion returns no partial list; + /// require [`crate::IncomingRefs::Complete`] before staging a cascading + /// delete. Retry with larger limits or abandon the delete on exhaustion. + /// This read stages nothing, takes no transaction counter and does not + /// promote or checkpoint. Failed write handles remain readable. + /// + /// # Errors + /// Returns any lock, I/O or decoding error encountered by the lookup. + /// + /// ``` + /// use minigraf::{Minigraf, IncomingRefLimits, IncomingRefs}; + /// let db = Minigraf::in_memory().unwrap(); + /// let mut tx = db.begin_write().unwrap(); + /// let target = uuid::Uuid::nil(); + /// match tx.incoming_refs(target, IncomingRefLimits::new(100, 1000)).unwrap() { + /// IncomingRefs::Complete { links, .. } => assert!(links.is_empty()), + /// IncomingRefs::Exhausted { .. } => { /* retry or abandon delete */ } + /// _ => { /* future outcomes */ } + /// } + /// tx.rollback(); + /// ``` + pub fn incoming_refs( + &mut self, + target: crate::EntityId, + limits: crate::IncomingRefLimits, + ) -> Result { + self.state + .incoming_refs(&self.guard.ctx, self.inner, target, limits) + .map_err(MinigrafError::from) + } + /// This transaction's chunk size after the clamp, for tests. #[cfg(test)] pub(crate) fn chunk(&self) -> usize { @@ -2386,6 +2482,7 @@ impl<'a> WriteTransaction<'a> { pub(crate) struct Staged { /// Facts buffered in this transaction (not yet committed to FactStorage). pub(crate) pending_facts: Vec, + incoming: crate::incoming::RefPositions, /// Synthetic tx_count assigned to the next staged write batch. next_pending_tx_count: u64, /// Synthetic tx_id seed used to keep staged writes monotonic. @@ -2397,6 +2494,7 @@ impl Staged { pub(crate) fn new(current_tx_count: u64) -> Self { Staged { pending_facts: Vec::new(), + incoming: crate::incoming::RefPositions::default(), next_pending_tx_count: current_tx_count.saturating_add(1), next_pending_tx_id: crate::graph::types::tx_id_now(), } @@ -2412,11 +2510,13 @@ impl Staged { let staged_tx_id = self.next_tx_id(); let staged_tx_count = self.next_pending_tx_count; - self.pending_facts.extend(facts.into_iter().map(|mut fact| { + self.pending_facts.reserve(facts.len()); + for mut fact in facts { fact.tx_id = staged_tx_id; fact.tx_count = staged_tx_count; - fact - })); + self.incoming.insert(&fact, self.pending_facts.len()); + self.pending_facts.push(fact); + } self.next_pending_tx_id = staged_tx_id.saturating_add(1); self.next_pending_tx_count = self.next_pending_tx_count.saturating_add(1); @@ -2426,6 +2526,8 @@ impl Staged { /// default `valid_from` stays the sentinel until the commit stamps it; /// reads see it as the fact's own staged tx_id. pub(crate) fn read_view(&self) -> Vec { + #[cfg(any(test, feature = "test-hooks"))] + crate::incoming::enumerated_many(self.pending_facts.len()); self.pending_facts .iter() .cloned() @@ -2599,6 +2701,29 @@ impl OwnedWriteTransaction { .map_err(MinigrafError::from) } + /// Bounded incoming scalar references, with exactly the visibility, + /// valid-time, exhaustion and read-only semantics of + /// [`WriteTransaction::incoming_refs`]. Require a complete result before + /// deleting. May run on any thread; both budgets apply across all layers. + /// + /// # Errors + /// Returns read errors, or `API-001` if the write mutex is poisoned. + pub fn incoming_refs( + &mut self, + target: crate::EntityId, + limits: crate::IncomingRefLimits, + ) -> Result { + let inner = &self.db.inner; + let slot = inner + .write_lock + .lock() + .map_err(|_| MinigrafError::from(err_coded!(ErrorCode::Api001)))?; + let _running = RunningHere::enter(); + self.state + .incoming_refs(&slot.ctx, inner, target, limits) + .map_err(MinigrafError::from) + } + /// Commit this transaction atomically, as [`WriteTransaction::commit`] /// does, and release the write lock. A commit that fails rolls the /// transaction back. @@ -4024,3 +4149,6 @@ mod wasi_tests { } } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod incoming_tests; diff --git a/src/db/incoming_tests.rs b/src/db/incoming_tests.rs new file mode 100644 index 0000000000..f47a11b7a4 --- /dev/null +++ b/src/db/incoming_tests.rs @@ -0,0 +1,536 @@ +use super::*; +use crate::storage::fault::{self, Fault}; +use crate::{IncomingRefBudget, IncomingRefLimits, IncomingRefs}; + +fn target() -> uuid::Uuid { + uuid::Uuid::from_u128(9) +} +fn assert_one(out: IncomingRefs) { + assert!( + matches!(out, IncomingRefs::Complete { links, .. } if links.len() == 1 && links[0].attribute == ":a" && links[0].source == uuid::Uuid::from_u128(1)) + ); +} + +#[test] +fn incoming_refs_on_failed_handle() { + for checkpoint in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let db = Minigraf::open(dir.path().join("failed.graph")).unwrap(); + db.execute(&format!( + "(transact [[#uuid \"{}\" :a #uuid \"{}\"]])", + uuid::Uuid::from_u128(1), + target() + )) + .unwrap(); + fault::arm(Fault::Torn(9), 0); + let failed = if checkpoint { + db.checkpoint().map(|_| QueryResult::Ok) + } else { + db.execute("(transact [[:b :n 2]])") + }; + fault::disarm(); + assert!(failed.is_err()); + assert_eq!( + db.execute("(transact [[:b :n 3]])").unwrap_err().code(), + if checkpoint { "STG-046" } else { "WAL-007" } + ); + let mut tx = db.begin_write().unwrap(); + assert_one( + tx.incoming_refs(target(), IncomingRefLimits::new(10, 10)) + .unwrap(), + ); + assert!(matches!( + tx.incoming_refs(target(), IncomingRefLimits::new(10, 0)) + .unwrap(), + IncomingRefs::Exhausted { + budget: IncomingRefBudget::Records, + records_examined: 0 + } + )); + tx.execute("(query [:find ?e :where [?e :a ?v]])").unwrap(); + tx.rollback(); + let mut tx = db.begin_write_owned().unwrap(); + assert_one( + tx.incoming_refs(target(), IncomingRefLimits::new(10, 10)) + .unwrap(), + ); + tx.rollback(); + } +} + +#[test] +fn incoming_refs_legacy_ties_and_group_budget() { + for durable in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let db = Minigraf::open(dir.path().join("legacy.graph")).unwrap(); + let mut facts = Vec::new(); + for source in 1..=2 { + for window in 0..5 { + let mut f = Fact::new( + uuid::Uuid::from_u128(source), + ":a".into(), + Value::Ref(target()), + 100, + ); + f.tx_count = 1; + f.valid_from = window; + f.valid_to = window + 1; + f.asserted = source == 1 || window != 4; + facts.push(f); + } + } + db.inner.fact_storage.load_facts(facts).unwrap(); + if durable { + db.checkpoint().unwrap(); + } + let mut tx = db.begin_write().unwrap(); + for cap in 0..10 { + crate::incoming::enumeration(); + let out = tx + .incoming_refs(target(), IncomingRefLimits::new(10, cap)) + .unwrap(); + assert!( + matches!(out, IncomingRefs::Exhausted { budget: IncomingRefBudget::Records, records_examined } if records_examined == cap) + ); + assert_eq!(crate::incoming::enumeration().0, cap); + } + assert_one( + tx.incoming_refs(target(), IncomingRefLimits::new(1, 10)) + .unwrap(), + ); + } +} + +#[test] +fn incoming_refs_unrelated_growth() { + use std::fmt::Write; + for layer in 0..4 { + let mut baseline = None; + for unrelated in [0, 100_000] { + let dir = tempfile::tempdir().unwrap(); + let db = if layer < 2 { + Minigraf::in_memory().unwrap() + } else { + Minigraf::open_with_options( + dir.path().join("growth.graph"), + OpenOptions::default().wal_checkpoint_threshold(usize::MAX), + ) + .unwrap() + }; + let mut target_command = String::from("(transact ["); + for source in 1..=3 { + write!( + target_command, + "[#uuid \"{}\" :a #uuid \"{}\"]", + uuid::Uuid::from_u128(source), + target() + ) + .unwrap(); + } + target_command.push_str("])"); + let mut command = String::from("(transact ["); + for i in 0..unrelated { + let value = match i % 3 { + 0 => i.to_string(), + 1 => ":other".into(), + _ => format!("#uuid \"{}\"", uuid::Uuid::from_u128(10_000_000)), + }; + write!(command, "[:e{i} :unrelated {value}]").unwrap(); + } + command.push_str("])"); + if layer != 1 && layer != 3 { + db.execute(&target_command).unwrap(); + if unrelated != 0 { + db.execute(&command).unwrap(); + } + if layer == 2 { + db.checkpoint().unwrap(); + } + } + let mut tx = db + .begin_write_with(TxOptions::new().chunk_facts(if layer == 3 { + 2 + } else { + 1_000_000 + })) + .unwrap(); + if layer == 1 || layer == 3 { + tx.execute(&target_command).unwrap(); + if layer == 3 { + tx.state.chunk_facts = 65_536; + } + if unrelated != 0 { + tx.execute(&command).unwrap(); + } + } + // The first call must not build an index or copy unrelated staged facts. + for _ in 0..2 { + crate::incoming::enumeration(); + let out = tx + .incoming_refs(target(), IncomingRefLimits::new(3, 3)) + .unwrap(); + let IncomingRefs::Complete { + links, + records_examined, + } = out + else { + panic!("expected complete"); + }; + assert_eq!(links.len(), 3); + let (enumerated, ends) = crate::incoming::enumeration(); + assert_eq!(enumerated, 3); + assert_eq!(records_examined, *baseline.get_or_insert(records_examined)); + assert_eq!(ends, usize::from(layer >= 2 && unrelated != 0)); + } + for cap in 0..3 { + crate::incoming::enumeration(); + assert!( + matches!(tx.incoming_refs(target(), IncomingRefLimits::new(3, cap)).unwrap(), IncomingRefs::Exhausted { budget: IncomingRefBudget::Records, records_examined } if records_examined == cap) + ); + assert_eq!(crate::incoming::enumeration().0, cap); + } + } + } +} + +#[test] +fn incoming_refs_history_enumeration_is_bounded() { + for layer in 0..4 { + for one_pair in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let db = if layer < 2 { + Minigraf::in_memory().unwrap() + } else { + Minigraf::open(dir.path().join("bounded.graph")).unwrap() + }; + let facts: Vec<_> = (0..1000) + .map(|i| { + let mut f = Fact::new( + uuid::Uuid::from_u128(if one_pair { 1 } else { i + 1 }), + ":a".into(), + Value::Ref(target()), + 100, + ); + f.tx_count = u64::try_from(i + 1).unwrap(); + f.asserted = one_pair && i == 999; + f + }) + .collect(); + if layer != 1 { + db.inner.fact_storage.load_facts(facts.clone()).unwrap(); + db.inner.fact_storage.restore_tx_counter().unwrap(); + } + if layer == 2 { + db.checkpoint().unwrap(); + } + let mut tx = db + .begin_write_with(TxOptions::new().chunk_facts(1)) + .unwrap(); + if layer == 1 { + for f in facts { + tx.state.staged.stage(vec![f]); + } + } + if layer == 3 { + tx.execute("(transact [[:x :n 1] [:y :n 2]])").unwrap(); + } + crate::incoming::enumeration(); + assert!(matches!( + tx.incoming_refs(target(), IncomingRefLimits::new(10, 20)) + .unwrap(), + IncomingRefs::Exhausted { + budget: IncomingRefBudget::Records, + records_examined: 20 + } + )); + assert_eq!(crate::incoming::enumeration().0, 20); + } + } +} + +#[test] +fn incoming_refs_non_ref_staging_keeps_batch_capacity() { + let mut staged = Staged::new(0); + let facts = (0..1000) + .map(|i| Fact::new(uuid::Uuid::from_u128(i), ":n".into(), Value::Integer(1), 0)) + .collect(); + staged.stage(facts); + assert_eq!(staged.pending_facts.capacity(), 1000); +} + +fn ref_statement(asserted: bool, source: u128, attr: &str) -> String { + format!( + "({} [[#uuid \"{}\" {attr} #uuid \"{}\"]])", + if asserted { "transact" } else { "retract" }, + uuid::Uuid::from_u128(source), + target() + ) +} + +fn incoming_set(tx: &mut WriteTransaction<'_>) -> std::collections::BTreeSet<(uuid::Uuid, String)> { + match tx + .incoming_refs(target(), IncomingRefLimits::new(100, 1000)) + .unwrap() + { + IncomingRefs::Complete { links, .. } => { + links.into_iter().map(|l| (l.source, l.attribute)).collect() + } + _ => panic!("expected complete links"), + } +} + +#[test] +fn incoming_refs_failed_promotion_keeps_completed_statements() { + for asserted in [true, false] { + let dir = tempfile::tempdir().unwrap(); + let db = Minigraf::open(dir.path().join("promotion-failure.graph")).unwrap(); + if !asserted { + db.execute(&ref_statement(true, 1, ":a")).unwrap(); + db.checkpoint().unwrap(); + } + let mut tx = db + .begin_write_with(TxOptions::new().chunk_facts(2)) + .unwrap(); + tx.execute(&ref_statement(asserted, 1, ":a")).unwrap(); + tx.execute(&ref_statement(true, 7, ":z")).unwrap(); + let expected = incoming_set(&mut tx); + // WAL header succeeds, then the first staged-chunk page write fails. + fault::arm(Fault::Eio, 1); + let failure = tx.execute(&ref_statement(true, 2, ":rejected")); + let site = fault::disarm(); + assert!(failure.is_err()); + assert_eq!(site, Some(fault::Site::PageWrite)); + assert!( + incoming_set(&mut tx) == expected, + "completed staged statements survive failed promotion" + ); + assert_eq!(tx.commit().unwrap_err().code(), "STG-046"); + } +} + +#[test] +fn incoming_refs_failed_large_statement_keeps_completed_statements() { + let run = |at| { + let dir = tempfile::tempdir().unwrap(); + let db = Minigraf::open(dir.path().join("statement-failure.graph")).unwrap(); + let mut tx = db + .begin_write_with(TxOptions::new().chunk_facts(2)) + .unwrap(); + tx.execute(&ref_statement(true, 1, ":a")).unwrap(); + tx.execute(&ref_statement(true, 7, ":z")).unwrap(); + tx.execute("(transact [[:promote :n 1]])").unwrap(); + let expected = incoming_set(&mut tx); + let mut command = ref_statement(false, 1, ":a"); + command.truncate(command.len() - 2); + for source in 10..16 { + command.push_str(&format!( + "[#uuid \"{}\" :rejected #uuid \"{}\"]", + uuid::Uuid::from_u128(source), + target() + )); + } + command.push_str("])"); + fault::arm(Fault::Eio, at); + let result = tx.execute(&command); + let writes = fault::count(); + fault::disarm(); + if at != u64::MAX { + assert!(result.is_err()); + assert!( + incoming_set(&mut tx) == expected, + "a failed chunk contributes no links or retractions" + ); + assert_eq!(tx.commit().unwrap_err().code(), "STG-046"); + } else { + result.unwrap(); + } + writes + }; + let writes = run(u64::MAX); + assert!(writes > 1); + for at in 0..writes { + run(at); + } +} + +#[test] +fn incoming_refs_setup_work_is_counted() { + let db = Minigraf::in_memory().unwrap(); + db.execute(&ref_statement(true, 1, ":a")).unwrap(); + db.execute("(transact [[:other :n 1]])").unwrap(); + let mut tx = db.begin_write().unwrap(); + tx.execute(&ref_statement(true, 2, ":b")).unwrap(); + tx.execute("(transact [[:staged :n 2]])").unwrap(); + crate::incoming::enumeration(); + let staged = tx.state.staged.read_view(); + assert!( + crate::incoming::enumeration().0 >= staged.len(), + "staged cloning must be counted" + ); + crate::incoming::enumeration(); + let snapshot = db + .inner + .fact_storage + .snapshot() + .unwrap() + .with_staged(staged); + assert!( + crate::incoming::enumeration().0 >= 2, + "staged reindexing must be counted" + ); + crate::incoming::enumeration(); + let all = snapshot.pending_range(0, usize::MAX).unwrap(); + assert!( + crate::incoming::enumeration().0 >= all.len(), + "range copies must be counted" + ); + crate::incoming::enumeration(); + let all = snapshot + .pending_records(crate::storage::Scan::All, &crate::storage::TxBound::All) + .unwrap(); + assert!( + crate::incoming::enumeration().0 >= all.len(), + "pending scans must be counted" + ); + crate::incoming::enumeration(); + let all = db.inner.fact_storage.get_pending_facts(); + assert!( + crate::incoming::enumeration().0 >= all.len(), + "whole-store copies must be counted" + ); +} + +#[test] +fn incoming_refs_failed_end_statement_keeps_completed_statements() { + let dir = tempfile::tempdir().unwrap(); + let db = Minigraf::open_with_options( + dir.path().join("end-failure.graph"), + OpenOptions::default().page_cache_size(0), + ) + .unwrap(); + let mut tx = db + .begin_write_with(TxOptions::new().chunk_facts(1)) + .unwrap(); + tx.execute(&ref_statement(true, 1, ":a")).unwrap(); + tx.execute(&ref_statement(true, 7, ":z")).unwrap(); + let expected = incoming_set(&mut tx); + // Execute a full chunk, then fail the claims-tree read at statement end. + // These are the same three phases TxState::write_statement calls. + let (WriteContext::File { pfs, .. }, Some(large)) = + (&mut tx.guard.ctx, tx.state.large.as_mut()) + else { + panic!("expected large transaction"); + }; + pfs.begin_statement(large); + let mut facts = vec![ + Fact::retract( + uuid::Uuid::from_u128(1), + ":a".into(), + Value::Ref(target()), + large.tx_id(), + ), + Fact::new( + uuid::Uuid::from_u128(2), + ":rejected".into(), + Value::Ref(target()), + large.tx_id(), + ), + ]; + assert!(pfs.write_large_chunk(large, &mut facts).is_ok()); + fault::arm(Fault::ReadEio, 0); + let ended = pfs.end_statement(large, true); + assert_eq!(fault::disarm(), Some(fault::Site::PageRead)); + assert!(ended.is_err()); + assert!( + incoming_set(&mut tx) == expected, + "failed finalization must not expose its chunk" + ); + assert_eq!(tx.commit().unwrap_err().code(), "STG-046"); +} + +#[test] +fn incoming_refs_promotion_filters_before_stamping() { + fn strings<'a>(facts: impl Iterator) -> Vec<*const u8> { + let mut pointers = Vec::new(); + for f in facts { + pointers.push(f.attribute.as_ptr()); + if let Value::String(s) = &f.value { + pointers.push(s.as_ptr()); + } + } + pointers.sort_unstable(); + pointers + } + + for fail in [true, false] { + let dir = tempfile::tempdir().unwrap(); + let db = Minigraf::open(dir.path().join("promotion-stamping.graph")).unwrap(); + db.execute(&ref_statement(true, 2, ":removed")).unwrap(); + db.checkpoint().unwrap(); + let mut tx = db + .begin_write_with(TxOptions::new().chunk_facts(9)) + .unwrap(); + for asserted in [true, false, true] { + tx.execute(&ref_statement(asserted, 1, ":kept")).unwrap(); + } + for asserted in [false, true, false] { + tx.execute(&ref_statement(asserted, 2, ":removed")).unwrap(); + } + // Legacy tied records in the latest statement retain both versions; + // stamping them must keep the retraction's precedence. + tx.state.staged.stage(vec![ + Fact::new( + uuid::Uuid::from_u128(3), + ":tied".into(), + Value::Ref(target()), + 0, + ), + Fact::retract( + uuid::Uuid::from_u128(3), + ":tied".into(), + Value::Ref(target()), + 0, + ), + ]); + tx.execute("(transact [[:text :payload \"retained string allocation\"]])") + .unwrap(); + let expected = + std::collections::BTreeSet::from([(uuid::Uuid::from_u128(1), ":kept".to_string())]); + assert!(incoming_set(&mut tx) == expected); + let facts = &tx.state.staged.pending_facts; + let allocation = facts.as_ptr(); + let capacity = facts.capacity(); + let retained_strings = strings( + facts + .iter() + .zip(last_statement_mask(facts)) + .filter_map(|(f, keep)| keep.then_some(f)), + ); + if fail { + fault::arm(Fault::Eio, 1); + } + let result = tx.execute("(transact [[:promote :n 1]])"); + if fail { + assert_eq!(fault::disarm(), Some(fault::Site::PageWrite)); + assert!(result.is_err()); + let facts = &tx.state.staged.pending_facts; + assert_eq!(facts.len(), 5, "only the latest statements survive"); + assert!(facts.as_ptr() == allocation, "reuse the staged vector"); + assert_eq!(facts.capacity(), capacity); + assert!( + strings(facts.iter()) == retained_strings, + "do not clone strings" + ); + assert!(facts.iter().all(|f| f.tx_count == 2)); + assert!(incoming_set(&mut tx) == expected); + assert_eq!(tx.commit().unwrap_err().code(), "STG-046"); + } else { + result.unwrap(); + assert!(tx.state.staged.pending_facts.is_empty()); + assert!(incoming_set(&mut tx) == expected); + tx.commit().unwrap(); + let mut tx = db.begin_write().unwrap(); + assert!(incoming_set(&mut tx) == expected); + } + } +} diff --git a/src/graph/storage.rs b/src/graph/storage.rs index 94dff76b5d..ca7ca7770e 100644 --- a/src/graph/storage.rs +++ b/src/graph/storage.rs @@ -65,6 +65,7 @@ struct PendingStore { /// fact sets (e.g. 1M-fact benchmark setup). keys: HashSet, indexes: Indexes, + incoming: crate::incoming::RefPositions, /// The first position whose fact's `tx_count` or `tx_id` is below the /// previous fact's, or whose `tx_id` differs from it within one /// `tx_count`; `usize::MAX` if none (#551 plan, decision 6). Before it, @@ -78,6 +79,7 @@ impl PendingStore { facts: Vec::with_capacity(capacity), keys: HashSet::new(), indexes: Indexes::new(), + incoming: crate::incoming::RefPositions::default(), first_irregular: usize::MAX, } } @@ -88,6 +90,12 @@ impl PendingStore { /// Append `fact` unless it is already here; returns whether it was added. fn push(&mut self, fact: Fact) -> bool { + self.push_indexed::(fact) + } + + fn push_indexed(&mut self, fact: Fact) -> bool { + #[cfg(any(test, feature = "test-hooks"))] + crate::incoming::enumerated_many(1); if !self.keys.insert(pending_key(&fact)) { return false; } @@ -96,6 +104,9 @@ impl PendingStore { { self.first_irregular = self.facts.len(); } + if INCOMING { + self.incoming.insert(&fact, self.facts.len()); + } self.indexes.insert(&fact, self.facts.len()); self.facts.push(fact); true @@ -106,7 +117,7 @@ impl PendingStore { fn of(facts: Vec) -> Self { let mut store = PendingStore::empty(facts.len()); for fact in facts { - store.push(fact); + store.push_indexed::(fact); } store } @@ -114,6 +125,8 @@ impl PendingStore { /// Append `facts` without the duplicate check (fresh writes: each has a /// new tx_count, so none can repeat a stored one). fn extend(&mut self, facts: Vec) { + #[cfg(any(test, feature = "test-hooks"))] + crate::incoming::enumerated_many(facts.len()); let base = self.facts.len(); for (i, fact) in facts.iter().enumerate() { let prev = match i.checked_sub(1) { @@ -124,6 +137,7 @@ impl PendingStore { self.first_irregular = base + i; } self.keys.insert(pending_key(fact)); + self.incoming.insert(fact, base + i); self.indexes.insert(fact, base + i); } self.facts.extend(facts); @@ -164,9 +178,9 @@ struct FactData { /// /// # Storage Model (Phase 3-6) /// -/// This is a simple in-memory store using `Vec` plus four covering -/// indexes (EAVT, AEVT, AVET, VAET). For persistence, see `PersistentFactStorage` -/// which wraps this with a "load all, save all" strategy. +/// Pending facts use `Vec`, EAVT/AEVT indexes and target-keyed positions +/// for scalar refs. `PersistentFactStorage` checkpoints them into four +/// durable covering indexes (EAVT, AEVT, AVET, VAET). /// /// # Examples /// ```ignore @@ -248,10 +262,15 @@ impl<'a> PendingView<'a> { fn extend(&self, from: usize, to: usize, out: &mut Vec) { let to = to.min(self.total()); let first = self.p.facts.get(from.min(self.len)..to.min(self.len)); + #[cfg(any(test, feature = "test-hooks"))] + crate::incoming::enumerated_many(first.map_or(0, <[Fact]>::len)); out.extend_from_slice(first.unwrap_or(&[])); if let Some(s) = self.staged { let (from, to) = (from.saturating_sub(self.len), to.saturating_sub(self.len)); - out.extend_from_slice(s.facts.get(from.min(to)..to).unwrap_or(&[])); + let facts = s.facts.get(from.min(to)..to).unwrap_or(&[]); + #[cfg(any(test, feature = "test-hooks"))] + crate::incoming::enumerated_many(facts.len()); + out.extend_from_slice(facts); } } @@ -284,6 +303,8 @@ fn merged<'a, K: Ord + 'a>( pending: impl Iterator, staged: Option>, ) -> impl Iterator { + #[cfg(any(test, feature = "test-hooks"))] + let pending = pending.inspect(|_| crate::incoming::enumerated_many(1)); let mut a = pending .filter(move |&(_, &pos)| pos < len) .map(|(k, &pos)| (k, pos)) @@ -291,7 +312,11 @@ fn merged<'a, K: Ord + 'a>( let mut b = staged .into_iter() .flatten() - .map(move |(k, &pos)| (k, pos.saturating_add(len))) + .map(move |(k, &pos)| { + #[cfg(any(test, feature = "test-hooks"))] + crate::incoming::enumerated_many(1); + (k, pos.saturating_add(len)) + }) .peekable(); std::iter::from_fn(move || match (a.peek(), b.peek()) { (Some((ka, _)), Some((kb, _))) if kb < ka => b.next(), @@ -362,6 +387,8 @@ impl Snapshot { /// This snapshot with `facts` staged after its pending ones (#550 spec /// §7), its `now` raised to the newest of their `tx_id`s. pub(crate) fn with_staged(mut self, facts: Vec) -> Self { + #[cfg(any(test, feature = "test-hooks"))] + crate::incoming::enumerated_many(facts.len()); if let Some(newest) = facts.iter().map(|f| f.tx_id.cast_signed()).max() { self.now = self.now.max(newest); self.staged = Some(Arc::new(PendingStore::of(facts))); @@ -458,6 +485,19 @@ impl Snapshot { self.now } + pub(crate) fn incoming_pending( + &self, + target: EntityId, + lookup: &mut crate::incoming::Lookup, + ) -> Result { + let pending = self.read_pending()?; + let facts = pending + .facts + .get(..self.pending_len) + .unwrap_or(&pending.facts); + Ok(pending.incoming.visit(target, facts, lookup)) + } + fn read_pending(&self) -> Result> { self.pending .read() @@ -941,6 +981,8 @@ impl FactStorage { pub(crate) fn get_pending_facts(&self) -> Vec { let d = self.data.read().unwrap_or_else(|e| e.into_inner()); let p = d.pending.read().unwrap_or_else(|e| e.into_inner()); + #[cfg(any(test, feature = "test-hooks"))] + crate::incoming::enumerated_many(p.facts.len()); p.facts.clone() } @@ -1246,6 +1288,8 @@ pub(crate) fn check_valid_windows(facts: &[Fact], tx_id: TxId) -> Result<()> { /// The pending fact at `pos`, as indexed by `PendingStore::indexes`. fn pending_fact(p: &PendingStore, pos: usize) -> Result { + #[cfg(any(test, feature = "test-hooks"))] + crate::incoming::enumerated_many(1); p.facts .get(pos) .cloned() @@ -1455,6 +1499,51 @@ impl FactStorage { #[cfg(test)] mod tests { + #[test] + fn incoming_refs_query_snapshot_skips_target_index() { + let target = EntityId::from_u128(9); + let facts = vec![Fact::new( + EntityId::from_u128(1), + ":a".into(), + Value::Ref(target), + 1, + )]; + let storage = FactStorage::new(); + let snapshot = storage.snapshot().unwrap().with_staged(facts); + let staged = snapshot.staged.as_ref().unwrap(); + let mut lookup = crate::incoming::Lookup::new(crate::IncomingRefLimits::new(10, 10)); + assert!(staged.incoming.visit(target, &staged.facts, &mut lookup)); + assert_eq!( + lookup.remaining(), + 10, + "query-only stores need no target index" + ); + assert_eq!( + snapshot + .pending_records(crate::storage::Scan::All, &TxBound::All) + .unwrap() + .len(), + 1 + ); + } + + #[test] + fn incoming_refs_pending_extend_work_is_counted() { + let facts = vec![Fact::new( + EntityId::from_u128(1), + ":n".into(), + Value::Integer(1), + 1, + )]; + let mut store = PendingStore::empty(0); + crate::incoming::enumeration(); + store.extend(facts); + assert!( + crate::incoming::enumeration().0 >= 1, + "non-ref indexing is work too" + ); + } + use super::*; fn fact_at(i: u128, tx_count: u64, tx_id: u64) -> Fact { diff --git a/src/incoming.rs b/src/incoming.rs new file mode 100644 index 0000000000..ca44e219dd --- /dev/null +++ b/src/incoming.rs @@ -0,0 +1,255 @@ +//! Bounded scalar-reference discovery for write transactions. + +use crate::graph::types::{EntityId, Fact, Value}; +use std::collections::HashMap; + +/// Work limits for an incoming-reference lookup. Zero is a real limit. +#[derive(Clone, Copy, Debug)] +#[non_exhaustive] +pub struct IncomingRefLimits { + /// Maximum number of distinct live links in a complete result. + pub max_links: usize, + /// Maximum fact versions inspected across all storage layers, including + /// retractions, superseded versions and lookahead. + pub max_records: usize, +} + +impl IncomingRefLimits { + /// Set both limits. Neither limit reserves memory in advance. + pub const fn new(max_links: usize, max_records: usize) -> Self { + Self { + max_links, + max_records, + } + } +} + +/// One stored scalar `Value::Ref` pointing to the requested target. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct IncomingRef { + /// Entity containing the reference. + pub source: EntityId, + /// Attribute containing the reference. + pub attribute: String, +} + +impl IncomingRef { + /// Construct one typed incoming link. + pub fn new(source: EntityId, attribute: String) -> Self { + Self { source, attribute } + } +} + +/// The limit that prevented a complete result. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum IncomingRefBudget { + /// More than `max_links` distinct live links were established. + Links, + /// The complete set could not be established within `max_records`. + Records, +} + +/// A complete incoming-reference set, or exhaustion with no partial list. +/// Require `Complete` before staging a cascading delete; on exhaustion, +/// retry with larger limits or abandon the delete. +#[derive(Clone, Debug)] +#[non_exhaustive] +pub enum IncomingRefs { + /// Every live scalar reference, ignoring valid time. Order is unspecified. + Complete { + /// Distinct `(source, attribute)` pairs. + links: Vec, + /// Stored fact versions inspected across all layers. + records_examined: usize, + }, + /// Discovery could not finish within a limit. Contains no links. + Exhausted { + /// The exhausted limit. + budget: IncomingRefBudget, + /// Stored fact versions inspected, never above `max_records`. + records_examined: usize, + }, +} + +/// Positions only: no cloned facts, attributes or values. Empty for scalar +/// properties, keywords and sets; populated at write time, never at lookup. +#[derive(Default)] +pub(crate) struct RefPositions(HashMap>); + +impl RefPositions { + pub(crate) fn insert(&mut self, fact: &Fact, pos: usize) { + #[cfg(any(test, feature = "test-hooks"))] + enumerated_many(1); + if let Value::Ref(target) = fact.value { + self.0 + .entry(target) + .or_insert_with(|| Vec::with_capacity(1)) + .push(pos); + } + } + + pub(crate) fn visit(&self, target: EntityId, facts: &[Fact], lookup: &mut Lookup) -> bool { + if let Some(positions) = self.0.get(&target) { + let len = positions.partition_point(|&pos| pos < facts.len()); + let take = len.min(lookup.remaining()); + for &pos in positions.iter().take(take) { + lookup.charge(); + enumerated(); + if let Some(f) = facts.get(pos) { + lookup.record(f.entity, f.attribute.clone(), f.tx_count, f.asserted); + } + } + return take == len; + } + true + } +} + +pub(crate) struct Lookup { + limits: IncomingRefLimits, + examined: usize, + layer: u8, + winners: HashMap<(EntityId, String), (u8, u64, bool)>, +} + +impl Lookup { + pub(crate) fn new(limits: IncomingRefLimits) -> Self { + Self { + limits, + examined: 0, + layer: 0, + winners: HashMap::new(), + } + } + + pub(crate) fn next_layer(&mut self) { + self.layer += 1; + } + + pub(crate) fn remaining(&self) -> usize { + self.limits.max_records - self.examined + } + + pub(crate) fn charge(&mut self) -> bool { + if self.remaining() == 0 { + return false; + } + self.examined += 1; + true + } + + pub(crate) fn record(&mut self, source: EntityId, attribute: String, tx: u64, asserted: bool) { + let candidate = (self.layer, tx, asserted); + let winner = self.winners.entry((source, attribute)).or_insert(candidate); + if (candidate.0, candidate.1) > (winner.0, winner.1) { + *winner = candidate; + } else if (candidate.0, candidate.1) == (winner.0, winner.1) { + winner.2 &= asserted; + } + } + + pub(crate) fn finish(self, complete: bool) -> IncomingRefs { + let exhausted = |budget| IncomingRefs::Exhausted { + budget, + records_examined: self.examined, + }; + if !complete { + return exhausted(IncomingRefBudget::Records); + } + let mut links = Vec::new(); + for ((source, attribute), (_, _, asserted)) in self.winners { + if asserted { + if links.len() == self.limits.max_links { + return exhausted(IncomingRefBudget::Links); + } + links.push(IncomingRef { source, attribute }); + } + } + IncomingRefs::Complete { + links, + records_examined: self.examined, + } + } +} + +#[cfg(any(test, feature = "test-hooks"))] +thread_local! { + static ENUMERATION: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) }; +} + +#[cfg(any(test, feature = "test-hooks"))] +pub(crate) fn enumerated_many(count: usize) { + ENUMERATION.with(|n| { + let (records, ends) = n.get(); + n.set((records + count, ends)); + }); +} + +// Separate from budget accounting: called at the actual fact/key access sites. +pub(crate) fn enumerated() { + #[cfg(any(test, feature = "test-hooks"))] + ENUMERATION.with(|n| { + let (records, ends) = n.get(); + n.set((records + 1, ends)); + }); +} + +pub(crate) fn prefix_end() { + #[cfg(any(test, feature = "test-hooks"))] + ENUMERATION.with(|n| { + let (records, ends) = n.get(); + n.set((records, ends + 1)); + }); +} + +#[cfg(any(test, feature = "test-hooks"))] +pub(crate) fn enumeration() -> (usize, usize) { + ENUMERATION.with(|n| n.replace((0, 0))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn incoming_refs_position_memory() { + for targets in [1, 16, 10_000] { + let mut index = RefPositions::default(); + for i in 0..10_000 { + let fact = Fact::new( + EntityId::nil(), + ":a".into(), + Value::Ref(EntityId::from_u128(i % targets)), + 0, + ); + index.insert(&fact, usize::try_from(i).unwrap()); + } + // Raw capacity estimate, excluding allocator metadata: std's + // hash table uses power-of-two buckets plus control bytes. + let buckets = index.0.capacity().next_power_of_two(); + let bytes = std::mem::size_of::() + + buckets * (std::mem::size_of::<(EntityId, Vec)>() + 1) + + 16 + + index + .0 + .values() + .map(|v| v.capacity() * std::mem::size_of::()) + .sum::(); + println!( + "ref positions: targets={targets}, facts=10000, capacity bytes={bytes}, bytes/ref={}", + bytes as f64 / 10_000.0 + ); + if targets == 10_000 { + assert!(index.0.values().all(|v| v.capacity() == 1)); + } + } + let mut index = RefPositions::default(); + index.insert( + &Fact::new(EntityId::nil(), ":a".into(), Value::Integer(1), 0), + 0, + ); + assert_eq!(index.0.capacity(), 0); + } +} diff --git a/src/lib.rs b/src/lib.rs index d8712ece9b..a2f0fdc4fd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -87,6 +87,7 @@ pub mod fact_log; #[cfg(all(test, not(target_arch = "wasm32")))] mod fault_matrix; pub(crate) mod graph; +mod incoming; /// Build a new database from explicit fact records: [`LogWriter`]. #[cfg(not(target_arch = "wasm32"))] pub mod log_writer; @@ -113,6 +114,7 @@ pub use db::{ WriteTransaction, }; pub use error::{ErrorCategory, MinigrafError}; +pub use incoming::{IncomingRef, IncomingRefBudget, IncomingRefLimits, IncomingRefs}; pub use overrides::Overridable; pub use query::datalog::functions::UdfError; pub use repl::Repl; @@ -206,3 +208,9 @@ pub use query::datalog::optimizer::{Subplans, SubplansGuard}; pub fn __subplans(mode: Subplans) -> SubplansGuard { query::datalog::optimizer::set_subplans(mode) } + +/// Take and reset incoming-lookup enumeration counts (records, prefix-end probes). +#[cfg(feature = "test-hooks")] +pub fn __incoming_enumeration() -> (usize, usize) { + incoming::enumeration() +} diff --git a/src/storage/backend/file.rs b/src/storage/backend/file.rs index 75dd140769..61a8d2c8c4 100644 --- a/src/storage/backend/file.rs +++ b/src/storage/backend/file.rs @@ -473,6 +473,12 @@ impl StorageBackend for FileBackend { } fn read_page(&self, page_id: u64) -> Result> { + #[cfg(test)] + if let crate::storage::fault::Action::Fail(e) = + crate::storage::fault::on(crate::storage::fault::Site::PageRead) + { + return Err(e.into()); + } if page_id >= self.page_count { bail_coded!( ErrorCode::Int049, diff --git a/src/storage/btree.rs b/src/storage/btree.rs index d135492941..79456a5a28 100644 --- a/src/storage/btree.rs +++ b/src/storage/btree.rs @@ -674,7 +674,6 @@ impl<'a> LeafCursor<'a> { /// The next entry in key order without moving past it, or `None` past /// the last one. - #[cfg(not(target_arch = "wasm32"))] pub(crate) fn peek_ref(&mut self) -> Result> { loop { if self.done { diff --git a/src/storage/fault.rs b/src/storage/fault.rs index 0fbd1fec66..4b2f576acd 100644 --- a/src/storage/fault.rs +++ b/src/storage/fault.rs @@ -1,8 +1,8 @@ //! Test-only fault plan for the file and WAL I/O paths (#390). //! -//! Every write and sync that reaches the disk through `FileBackend`, the WAL +//! Every page read, write and sync through `FileBackend`, the WAL //! writer and `sync_parent_dir` asks [`on`] first. With a plan armed on the -//! calling thread, the `at`-th call of the plan's kind (writes or syncs, +//! calling thread, the `at`-th call of the plan's kind (reads, writes or syncs, //! counted from 0) fails the way [`Fault`] says. A [`Fault::Enospc`] plan //! keeps failing every later write too, like a full disk. With no plan //! armed, [`on`] returns [`Action::Proceed`] and the call runs as usual. @@ -16,6 +16,8 @@ use std::io; /// Where an I/O call happens. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Site { + /// `FileBackend::read_page` (cache misses only). + PageRead, /// `FileBackend::write_page`. PageWrite, /// `FileBackend::sync`. @@ -44,6 +46,8 @@ impl Site { /// How the chosen call fails. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Fault { + /// A page read fails with EIO. + ReadEio, /// The write fails with EIO and writes nothing. Eio, /// The write stores its first `n` bytes, then fails with EIO: a short @@ -63,9 +67,12 @@ pub(crate) enum Fault { impl Fault { fn targets(self, site: Site) -> bool { match self { + Fault::ReadEio => site == Site::PageRead, Fault::Eio | Fault::Torn(_) => site.is_write(), Fault::Enospc => site.is_write() && site != Site::WalRemove, - Fault::SyncEio | Fault::SyncLost => !site.is_write(), + Fault::SyncEio | Fault::SyncLost => { + matches!(site, Site::PageSync | Site::WalSync | Site::DirSync) + } } } } @@ -147,7 +154,7 @@ pub(crate) fn on(site: Site) -> Action { } plan.tripped = Some(site); match plan.fault { - Fault::Eio | Fault::SyncEio => Action::Fail(eio()), + Fault::ReadEio | Fault::Eio | Fault::SyncEio => Action::Fail(eio()), Fault::Torn(bytes) => Action::Tear(bytes), Fault::Enospc => Action::Fail(io::Error::from(io::ErrorKind::StorageFull)), Fault::SyncLost => Action::Lose, diff --git a/src/storage/mod.rs b/src/storage/mod.rs index dcc040c702..fc12261a99 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -370,6 +370,21 @@ impl Default for LegacyHeaderV7 { /// query layer uses; results are in index order (eid, then iid), not insertion /// order. pub trait CommittedReader: Send + Sync { + /// Visit at most `max` raw scalar-ref versions for `target`. Returns + /// whether the range ended. No net-assert buffering or value lookahead. + #[doc(hidden)] + fn incoming_ref_records( + &self, + _target: crate::graph::types::EntityId, + _max: usize, + _visit: &mut dyn FnMut(crate::graph::types::EntityId, String, u64, bool), + ) -> Result { + Err(crate::error::err_coded!( + crate::error::ErrorCode::Int019, + "reader has no incoming-reference access" + )) + } + /// Every committed fact (an EAVT scan). #[cfg(test)] fn all_facts(&self) -> Result>; diff --git a/src/storage/persistent_facts/large_tx.rs b/src/storage/persistent_facts/large_tx.rs index a7b47905bd..bee34ebc38 100644 --- a/src/storage/persistent_facts/large_tx.rs +++ b/src/storage/persistent_facts/large_tx.rs @@ -46,6 +46,8 @@ pub(crate) struct LargeTx { written: bool, /// The running statement's base, in a `WriteTransaction` (plan decision 33). stmt: Option, + /// Completed statements retained if releasing a statement base fails. + incoming_base: Option, } /// A statement's base (spec §5.1, plan decision 28): what a failed statement @@ -131,6 +133,7 @@ impl PersistentFactStorage { pending_len: 0, written: false, stmt: None, + incoming_base: None, }; // No fact joins the pending store while the write lock is held, so // these are the facts the commit publishes. Their own tx_counts and @@ -191,6 +194,7 @@ impl PersistentFactStorage { }; let since = tx.alloc.end_base(); if ok { + tx.incoming_base = Some(base.work); let claims = { let backend = self.lock()?; btree::tree_pages(base.claims, &*backend, &self.page_cache) @@ -200,6 +204,7 @@ impl PersistentFactStorage { tx.alloc.release(id); } tx.written |= base.wrote; + tx.incoming_base = None; } else { tx.work = base.work; tx.freed.truncate(base.freed_len); @@ -216,12 +221,27 @@ impl PersistentFactStorage { /// learns an id that is not committed. Unpinned: nothing frees a working /// page while the transaction holds the write lock. pub(crate) fn large_reader(&self, tx: &LargeTx) -> Arc { + self.large_reader_at(tx, tx.work) + } + + pub(crate) fn large_incoming_reader( + &self, + tx: &LargeTx, + ) -> Arc { + self.large_reader_at(tx, tx.incoming_base.unwrap_or(tx.work)) + } + + fn large_reader_at( + &self, + tx: &LargeTx, + work: MetaPage, + ) -> Arc { Arc::new(crate::storage::reader::OnDiskReader::new( self.backend.clone(), self.page_cache.clone(), &MetaPage { last_checkpointed_tx_count: tx.tx_count, - ..tx.work + ..work }, )) } diff --git a/src/storage/reader.rs b/src/storage/reader.rs index 09ba6f1ab2..433216fbf9 100644 --- a/src/storage/reader.rs +++ b/src/storage/reader.rs @@ -480,6 +480,51 @@ impl LogSource for OnDiskReader { } impl CommittedReader for OnDiskReader { + fn incoming_ref_records( + &self, + target: EntityId, + max: usize, + visit: &mut dyn FnMut(EntityId, String, u64, bool), + ) -> Result { + if self.vaet_root == 0 { + return Ok(true); + } + let mut dict = self.dict(); + let Some(eid) = dict.eid_of(&target)? else { + return Ok(true); + }; + let prefix = keys::entity_prefix(eid); + let mut cursor = + LeafCursor::new(self.vaet_root, Some(&prefix), &self.backend, &self.cache)?; + let mut examined = 0; + loop { + // Only the target prefix is checked before charging. In particular, + // do not decode the next version to settle the preceding group. + match cursor.peek_ref()? { + None => return Ok(true), + Some((key, _)) if !key.starts_with(&prefix) => { + crate::incoming::prefix_end(); + return Ok(true); + } + Some(_) => {} + } + if examined == max { + return Ok(false); + } + examined += 1; + if let Some((key, _)) = cursor.next_ref()? { + crate::incoming::enumerated(); + let fact = KeyFact::decode(Index::Vaet, key)?; + visit( + dict.uuid_of(fact.e)?, + dict.name_of(fact.a)?, + fact.tx_count, + fact.asserted, + ); + } + } + } + fn log_source(&self) -> Option<&dyn LogSource> { Some(self) } @@ -713,3 +758,57 @@ mod uuid_batch_tests { } } } + +#[cfg(test)] +mod incoming_tests { + use super::*; + use crate::storage::backend::memory::MemoryBackend; + use crate::storage::btree::build_btree; + use crate::storage::page::PageAllocator; + + #[test] + fn incoming_refs_read_errors_remain_errors() { + let target = EntityId::from_u128(9); + let mut backend = MemoryBackend::new(); + let cache = Arc::new(PageCache::new(0)); + let mut alloc = PageAllocator::new(Vec::new(), 2, 1); + let mut meta = MetaPage::empty(1); + meta.dict_root = build_btree( + vec![(keys::dict_uuid_key(&target), keys::uint_bytes(1))], + &mut backend, + &cache, + &mut alloc, + ) + .unwrap(); + // The target prefix exists, but the rest of this fact is malformed. + meta.vaet_root = build_btree( + vec![(keys::entity_prefix(1), Vec::new())], + &mut backend, + &cache, + &mut alloc, + ) + .unwrap(); + let backend = Arc::new(Mutex::new(backend)); + let reader = OnDiskReader::new(backend.clone(), cache.clone(), &meta); + let mut visits = 0; + assert!( + !reader + .incoming_ref_records(target, 0, &mut |_, _, _, _| visits += 1) + .unwrap() + ); + let err = reader + .incoming_ref_records(target, 1, &mut |_, _, _, _| visits += 1) + .unwrap_err(); + assert_eq!(crate::MinigrafError::from(err).code(), "INT-049"); + assert_eq!(visits, 0); + // An unavailable VAET page is an error even with an otherwise readable DICT. + meta.vaet_root = alloc.next_append() + 100; + let reader = OnDiskReader::new(backend, cache, &meta); + assert!( + reader + .incoming_ref_records(target, 10, &mut |_, _, _, _| visits += 1) + .is_err() + ); + assert_eq!(visits, 0); + } +} diff --git a/tests/incoming_refs_test.rs b/tests/incoming_refs_test.rs new file mode 100644 index 0000000000..2d22e5eeb0 --- /dev/null +++ b/tests/incoming_refs_test.rs @@ -0,0 +1,535 @@ +#![cfg(test)] +#![cfg(not(target_arch = "wasm32"))] + +use minigraf::{ + IncomingRefBudget, IncomingRefLimits, IncomingRefs, Minigraf, OpenOptions, TxOptions, +}; +use std::collections::BTreeSet; +use uuid::Uuid; +mod common; + +fn id(n: u128) -> Uuid { + Uuid::from_u128(n) +} +fn statement(asserted: bool, source: u128, attr: &str, target: u128) -> String { + format!( + "({} [[#uuid \"{}\" {attr} #uuid \"{}\"]])", + if asserted { "transact" } else { "retract" }, + id(source), + id(target) + ) +} +fn complete(out: IncomingRefs) -> (BTreeSet<(Uuid, String)>, usize) { + match out { + IncomingRefs::Complete { + links, + records_examined, + } => ( + links.into_iter().map(|l| (l.source, l.attribute)).collect(), + records_examined, + ), + _ => panic!("expected complete incoming references"), + } +} +fn lookup(db: &Minigraf, target: u128) -> (BTreeSet<(Uuid, String)>, usize) { + complete( + db.begin_write() + .unwrap() + .incoming_refs(id(target), IncomingRefLimits::new(usize::MAX, usize::MAX)) + .unwrap(), + ) +} +fn exhausted(out: IncomingRefs, expected: IncomingRefBudget, cap: usize) { + match out { + IncomingRefs::Exhausted { + budget, + records_examined, + } => { + assert_eq!(budget, expected); + assert!(records_examined <= cap); + } + _ => panic!("expected exhaustion without links"), + } +} +fn database(file: bool, path: &std::path::Path) -> Minigraf { + if file { + Minigraf::open_with_options( + path, + OpenOptions::default().wal_checkpoint_threshold(usize::MAX), + ) + .unwrap() + } else { + Minigraf::in_memory().unwrap() + } +} + +#[test] +fn incoming_refs_exact_types_and_attributes() { + for file in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let db = database(file, &dir.path().join("types.graph")); + let target = Uuid::new_v5(&Uuid::NAMESPACE_OID, b":target"); + db.execute(&format!("(transact [[#uuid \"{}\" :a #uuid \"{target}\"] [#uuid \"{}\" :b #uuid \"{target}\"] [#uuid \"{target}\" :self #uuid \"{target}\"] [:alias :a :target] [:string :a \"{target}\"] [:set :a #{{#uuid \"{target}\"}}] [:integer :a 1]])", id(1), id(2))).unwrap(); + for checkpoint in [false, true] { + if checkpoint && file { + db.checkpoint().unwrap(); + } + let (links, _) = lookup(&db, target.as_u128()); + assert!( + links + == BTreeSet::from([ + (id(1), ":a".into()), + (id(2), ":b".into()), + (target, ":self".into()) + ]) + ); + } + } +} + +#[test] +fn incoming_refs_outcomes_are_distinct() { + let db = Minigraf::in_memory().unwrap(); + assert!(lookup(&db, 9).0.is_empty()); + db.execute(&statement(true, 1, ":a", 9)).unwrap(); + let mut tx = db.begin_write().unwrap(); + exhausted( + tx.incoming_refs(id(9), IncomingRefLimits::new(0, 10)) + .unwrap(), + IncomingRefBudget::Links, + 10, + ); + exhausted( + tx.incoming_refs(id(9), IncomingRefLimits::new(10, 0)) + .unwrap(), + IncomingRefBudget::Records, + 0, + ); + assert_eq!( + complete( + tx.incoming_refs(id(9), IncomingRefLimits::new(1, 1)) + .unwrap() + ) + .0 + .len(), + 1 + ); +} + +#[test] +fn incoming_refs_unique_pairs_and_any_valid_window() { + for file in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let db = database(file, &dir.path().join("windows.graph")); + for (source, from, to) in [ + (1, "2000", "2001"), + (2, "2998", "2999"), + (1, "2002", "2003"), + ] { + db.execute(&format!("(transact [[#uuid \"{}\" :a #uuid \"{}\" {{:valid-from \"{from}-01-01T00:00:00Z\" :valid-to \"{to}-01-01T00:00:00Z\"}}]])", id(source), id(9))).unwrap(); + } + db.execute(&statement(true, 1, ":b", 9)).unwrap(); + db.execute(&statement(true, 1, ":b", 9)).unwrap(); + db.execute(&statement(false, 2, ":a", 9)).unwrap(); + if file { + db.checkpoint().unwrap(); + } + assert!(lookup(&db, 9).0 == BTreeSet::from([(id(1), ":a".into()), (id(1), ":b".into())])); + } +} + +#[test] +fn incoming_refs_statement_order_rejected_statement_and_promotion() { + for file in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let db = database(file, &dir.path().join("order.graph")); + db.execute(&statement(true, 1, ":a", 9)).unwrap(); + if file { + db.checkpoint().unwrap(); + } + db.execute(&statement(true, 2, ":a", 9)).unwrap(); + let mut tx = db + .begin_write_with(TxOptions::new().chunk_facts(4)) + .unwrap(); + let limits = IncomingRefLimits::new(10, 100); + for source in [1, 2, 3] { + tx.execute(&statement(false, source, ":a", 9)).unwrap(); + } + assert!( + complete(tx.incoming_refs(id(9), limits).unwrap()) + .0 + .is_empty() + ); + tx.execute(&statement(true, 3, ":a", 9)).unwrap(); + let before = complete(tx.incoming_refs(id(9), limits).unwrap()).0; + tx.execute("(transact [[:unrelated :n 1]])").unwrap(); + assert!(complete(tx.incoming_refs(id(9), limits).unwrap()).0 == before); + let bad = format!( + "(transact [[#uuid \"{}\" :bad #uuid \"{}\" {{:valid-from \"2000-01-01T00:00:00Z\"}}] [#uuid \"{}\" :bad #uuid \"{}\" {{:valid-from \"2001-01-01T00:00:00Z\"}}]])", + id(4), + id(9), + id(4), + id(9) + ); + assert_eq!(tx.execute(&bad).unwrap_err().code(), "API-011"); + assert!(complete(tx.incoming_refs(id(9), limits).unwrap()).0 == before); + tx.execute(&statement(true, 5, ":new-attribute", 9)) + .unwrap(); + tx.commit().unwrap(); + assert_eq!(lookup(&db, 9).0.len(), 2); + } +} + +#[test] +fn incoming_refs_unknown_pending_only_dangling_and_checkpoint_reopen() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("reopen.graph"); + let db = database(true, &path); + let before = std::fs::read(&path).unwrap(); + { + let mut tx = db.begin_write().unwrap(); + assert!( + complete( + tx.incoming_refs(id(999), IncomingRefLimits::new(0, 0)) + .unwrap() + ) + .0 + .is_empty() + ); + tx.commit().unwrap(); + } + assert!(std::fs::read(&path).unwrap() == before); + db.execute(&statement(true, 1, ":a", 9)).unwrap(); + assert_eq!(lookup(&db, 9).0.len(), 1); + db.checkpoint().unwrap(); + let expected = lookup(&db, 9).0; + drop(db); + let db = Minigraf::open(&path).unwrap(); + assert!(lookup(&db, 9).0 == expected); + db.verify().unwrap(); +} + +#[test] +fn incoming_refs_read_only_retryable_exhaustion_rollback_and_drop() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("readonly.graph"); + let db = database(true, &path); + db.execute(&statement(true, 1, ":a", 9)).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + let wal = std::fs::read(path.with_extension("graph.wal")).unwrap(); + for rollback in [false, true] { + let mut tx = db + .begin_write_with(TxOptions::new().chunk_facts(1)) + .unwrap(); + tx.execute(&statement(false, 1, ":a", 9)).unwrap(); + exhausted( + tx.incoming_refs(id(9), IncomingRefLimits::new(0, 0)) + .unwrap(), + IncomingRefBudget::Records, + 0, + ); + assert!( + complete( + tx.incoming_refs(id(9), IncomingRefLimits::new(10, 10)) + .unwrap() + ) + .0 + .is_empty() + ); + assert!(std::fs::read(&path).unwrap() == bytes); + assert!(std::fs::read(path.with_extension("graph.wal")).unwrap() == wal); + if rollback { + tx.rollback(); + } + } + assert_eq!(lookup(&db, 9).0.len(), 1); + let mut tx = db.begin_write().unwrap(); + tx.incoming_refs(id(9), IncomingRefLimits::new(0, 10)) + .unwrap(); + tx.execute(&statement(true, 2, ":b", 9)).unwrap(); + tx.commit().unwrap(); + let counts: BTreeSet<_> = db + .fact_log(&minigraf::FactFilter::new()) + .unwrap() + .map(|r| r.unwrap().tx_count) + .collect(); + assert_eq!(counts, BTreeSet::from([1, 2])); +} + +#[test] +fn incoming_refs_exact_link_cap_overflow_zero_and_huge_limits() { + let db = Minigraf::in_memory().unwrap(); + for i in 1..=3 { + db.execute(&statement(true, i, ":a", 9)).unwrap(); + } + let mut tx = db.begin_write().unwrap(); + for cap in [3, usize::MAX] { + assert_eq!( + complete( + tx.incoming_refs(id(9), IncomingRefLimits::new(cap, usize::MAX)) + .unwrap() + ) + .0 + .len(), + 3 + ); + } + for cap in [0, 2] { + exhausted( + tx.incoming_refs(id(9), IncomingRefLimits::new(cap, usize::MAX)) + .unwrap(), + IncomingRefBudget::Links, + usize::MAX, + ); + } + assert!( + complete( + tx.incoming_refs(id(999), IncomingRefLimits::new(0, 0)) + .unwrap() + ) + .0 + .is_empty() + ); + exhausted( + tx.incoming_refs(id(9), IncomingRefLimits::new(0, 0)) + .unwrap(), + IncomingRefBudget::Records, + 0, + ); +} + +#[test] +fn incoming_refs_budget_shared_across_layers() { + let dir = tempfile::tempdir().unwrap(); + let db = database(true, &dir.path().join("layers.graph")); + db.execute(&statement(true, 1, ":a", 9)).unwrap(); + db.checkpoint().unwrap(); + db.execute(&statement(false, 1, ":a", 9)).unwrap(); + let mut tx = db.begin_write().unwrap(); + tx.execute(&statement(true, 1, ":a", 9)).unwrap(); + for cap in 0..3 { + exhausted( + tx.incoming_refs(id(9), IncomingRefLimits::new(1, cap)) + .unwrap(), + IncomingRefBudget::Records, + cap, + ); + } + assert_eq!( + complete( + tx.incoming_refs(id(9), IncomingRefLimits::new(1, 3)) + .unwrap() + ) + .1, + 3 + ); +} + +#[test] +fn incoming_refs_dead_pairs_exhaust_and_one_pair_long_history() { + for one_pair in [false, true] { + for layer in 0..3 { + let dir = tempfile::tempdir().unwrap(); + let db = database(layer != 0, &dir.path().join("history.graph")); + for i in 0..1000 { + db.execute(&statement( + if one_pair { i == 999 } else { false }, + if one_pair { 1 } else { i + 1 }, + ":a", + 2000, + )) + .unwrap(); + } + if layer == 1 { + db.checkpoint().unwrap(); + } + let mut tx = db + .begin_write_with(TxOptions::new().chunk_facts(1)) + .unwrap(); + if layer == 2 { + tx.execute("(transact [[:x :n 1] [:y :n 2]])").unwrap(); + } + exhausted( + tx.incoming_refs(id(2000), IncomingRefLimits::new(10, 20)) + .unwrap(), + IncomingRefBudget::Records, + 20, + ); + let (expected, b) = complete( + tx.incoming_refs(id(2000), IncomingRefLimits::new(10, 10000)) + .unwrap(), + ); + assert_eq!(expected.len(), usize::from(one_pair)); + assert!( + complete( + tx.incoming_refs(id(2000), IncomingRefLimits::new(10, b)) + .unwrap() + ) + .0 == expected + ); + match tx + .incoming_refs(id(2000), IncomingRefLimits::new(10, b - 1)) + .unwrap() + { + IncomingRefs::Complete { links, .. } => assert_eq!(links.len(), expected.len()), + out => exhausted(out, IncomingRefBudget::Records, b - 1), + } + } + } +} + +#[test] +fn incoming_refs_wal_recovery_and_recovered_then_promoted() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("wal.graph"); + common::run_crashing_child( + &path, + 1000, + &[&statement(true, 1, ":a", 9)], + common::CrashTx::Explicit, + ); + let other = dir.path().join("implicit.graph"); + common::run_crashing_child( + &other, + 1000, + &[&statement(true, 1, ":a", 9)], + common::CrashTx::Implicit, + ); + assert_eq!(lookup(&database(true, &other), 9).0.len(), 1); + let db = database(true, &path); + assert_eq!(lookup(&db, 9).0.len(), 1); + let mut tx = db + .begin_write_with(TxOptions::new().chunk_facts(1)) + .unwrap(); + tx.execute(&statement(false, 1, ":a", 9)).unwrap(); + assert!( + complete( + tx.incoming_refs(id(9), IncomingRefLimits::new(10, 10)) + .unwrap() + ) + .0 + .is_empty() + ); + tx.execute("(transact [[:x :n 1]])").unwrap(); + assert!( + complete( + tx.incoming_refs(id(9), IncomingRefLimits::new(10, 10)) + .unwrap() + ) + .0 + .is_empty() + ); + tx.rollback(); + assert_eq!(lookup(&db, 9).0.len(), 1); +} + +use proptest::prelude::*; +proptest! { + #![proptest_config(ProptestConfig::with_cases(32))] + #[test] + fn incoming_refs_model(ops in prop::collection::vec((0u8..10, 1u128..5, 0usize..2, 8u128..11), 1..80)) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("model.graph"); + let mut db = database(true, &path); + let mut committed = BTreeSet::new(); + let mut model = committed.clone(); + let mut tx = db.begin_write_owned_with(TxOptions::new().chunk_facts(5)).unwrap(); + for (op, source, attr, target) in ops { + let attr = [":a", ":b"][attr]; + match op { + 0..=3 => { tx.execute(&statement(true, source, attr, target)).unwrap(); model.insert((source, attr, target)); } + 4 => { tx.execute(&statement(false, source, attr, target)).unwrap(); model.remove(&(source, attr, target)); } + 5 => { tx.execute(&format!("(transact [[#uuid \"{}\" {attr} :{}]])", id(source), id(target))).unwrap(); } + 6 => { tx.commit().unwrap(); committed = model.clone(); tx = db.begin_write_owned_with(TxOptions::new().chunk_facts(5)).unwrap(); } + 7 => { tx.rollback(); model = committed.clone(); tx = db.begin_write_owned().unwrap(); } + 8 | 9 => { + tx.commit().unwrap(); committed = model.clone(); db.checkpoint().unwrap(); + if op == 9 { drop(db); db = database(true, &path); } + tx = db.begin_write_owned_with(TxOptions::new().chunk_facts(1)).unwrap(); + } + _ => unreachable!(), + } + for t in 8..11 { + let got = complete(tx.incoming_refs(id(t), IncomingRefLimits::new(100, 10000)).unwrap()).0; + let expected = model.iter().filter(|(_,_,target)| *target == t).map(|(s,a,_)| (id(*s), (*a).to_string())).collect(); + prop_assert!(got == expected); + } + } + } +} + +#[test] +fn incoming_refs_external_types_and_large_read_only() { + let constructed = minigraf::IncomingRef::new(id(1), ":a".into()); + assert!(constructed.source == id(1)); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("large-read.graph"); + let db = database(true, &path); + let mut tx = db + .begin_write_with(TxOptions::new().chunk_facts(1)) + .unwrap(); + tx.execute(&statement(true, 1, ":a", 9)).unwrap(); + tx.execute(&statement(true, 2, ":b", 9)).unwrap(); + let before = std::fs::read(&path).unwrap(); + let wal = std::fs::read(path.with_extension("graph.wal")).unwrap(); + let count = db.current_tx_count(); + assert!( + complete( + tx.incoming_refs(id(999), IncomingRefLimits::new(0, 0)) + .unwrap() + ) + .0 + .is_empty() + ); + exhausted( + tx.incoming_refs(id(9), IncomingRefLimits::new(0, 1)) + .unwrap(), + IncomingRefBudget::Records, + 1, + ); + assert_eq!( + complete( + tx.incoming_refs(id(9), IncomingRefLimits::new(2, 10)) + .unwrap() + ) + .0 + .len(), + 2 + ); + assert!(std::fs::read(&path).unwrap() == before); + assert!(std::fs::read(path.with_extension("graph.wal")).unwrap() == wal); + assert_eq!(db.current_tx_count(), count); + tx.commit().unwrap(); + db.checkpoint().unwrap(); + db.verify().unwrap(); + drop(db); + assert_eq!(lookup(&Minigraf::open(&path).unwrap(), 9).0.len(), 2); +} + +#[test] +fn incoming_refs_promotion_exact_set() { + let dir = tempfile::tempdir().unwrap(); + let db = database(true, &dir.path().join("promotion-set.graph")); + db.execute(&statement(true, 1, ":committed", 9)).unwrap(); + db.checkpoint().unwrap(); + let mut tx = db + .begin_write_with(TxOptions::new().chunk_facts(2)) + .unwrap(); + tx.execute(&statement(true, 2, ":staged", 9)).unwrap(); + tx.execute("(transact [[:filler :n 1]])").unwrap(); + let limits = IncomingRefLimits::new(10, 100); + let before = complete(tx.incoming_refs(id(9), limits).unwrap()).0; + assert!(before == BTreeSet::from([(id(1), ":committed".into()), (id(2), ":staged".into())])); + tx.execute("(transact [[:promote :n 2]])").unwrap(); + assert!(complete(tx.incoming_refs(id(9), limits).unwrap()).0 == before); + tx.execute(&statement(true, 3, ":created-after-promotion", 9)) + .unwrap(); + tx.execute(&statement(false, 1, ":committed", 9)).unwrap(); + let expected = BTreeSet::from([ + (id(2), ":staged".into()), + (id(3), ":created-after-promotion".into()), + ]); + assert!(complete(tx.incoming_refs(id(9), limits).unwrap()).0 == expected); + tx.commit().unwrap(); + assert!(lookup(&db, 9).0 == expected); +} diff --git a/tests/owned_tx_test.rs b/tests/owned_tx_test.rs index 0b194e7517..64217bf611 100644 --- a/tests/owned_tx_test.rs +++ b/tests/owned_tx_test.rs @@ -699,3 +699,33 @@ fn owned_tx_user_function_off_the_begin_thread() { } const NAMES_Q: &str = "(query [:find ?n :where [?e :person/name ?n]])"; + +#[test] +fn owned_incoming_refs_cross_thread_and_guards() { + use minigraf::{IncomingRefLimits, IncomingRefs}; + let db = Minigraf::in_memory().unwrap(); + let target = uuid::Uuid::from_u128(9); + let mut tx = db.begin_write_owned().unwrap(); + tx.execute(&format!("(transact [[:source :ref #uuid \"{target}\"]])")) + .unwrap(); + assert_eq!( + db.execute("(query [:find ?e :where [?e :ref ?v]])") + .unwrap_err() + .code(), + "INT-001" + ); + let reader = db.clone(); + let tx = thread::spawn(move || { + assert!(rows(&reader).is_empty()); + let out = tx + .incoming_refs(target, IncomingRefLimits::new(10, 10)) + .unwrap(); + assert!(matches!(out, IncomingRefs::Complete { links, .. } if links.len() == 1)); + tx + }) + .join() + .unwrap(); + assert_eq!(db.begin_write().err().unwrap().code(), "INT-001"); + tx.commit().unwrap(); + assert_eq!(rows(&db).len(), 1); +} From 72bc20baa05b9cb780fcde511992241b528913b7 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Sat, 28 Nov 2026 12:46:22 +0530 Subject: [PATCH 2/5] docs(testing): record incoming-reference write-cost measurements (#924) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H2a7QmsdjnGhRdBSbw6GB7 --- ROADMAP.md | 2 +- docs/TEST_COVERAGE.md | 14 ++--- docs/testing/924-incoming-refs.md | 100 ++++++++++++++++++++++++++---- 3 files changed, 95 insertions(+), 21 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 1b12c3b017..6e5b4be165 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -73,7 +73,7 @@ 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. Bench-machine comparison is pending; 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. 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). **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 a471d5dc5b..6f50150a94 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -62,16 +62,16 @@ tests. The distribution binary is **1,270,880 bytes** (+16 bytes), below the failures, one-line existing crash-harness Clippy correction, and unverified lanes are documented in the [PR 1 evidence](testing/894-idb-flush-recovery.md). -| | Default features (#924 run) | `test-hooks` (pre-#924 inventory) | +| | Default features (#924 run) | `test-hooks` (#924 run) | |---|---|---| -| **Active** | 2,188 | 2,196 | +| **Active** | 2,188 | 2,226 | | **Ignored** | 23 | 32 | -| **Total** | 2,211 | 2,228 | +| **Total** | 2,211 | 2,258 | -Default counts above come from the completed #924 Linux run, including unit, -integration, example and doc tests. The test-hooks column preserves the last -pre-#924 inventory; that full feature suite was not rerun for #924. Verification -results below identify which earlier suites ran. +Both columns come from the completed #924 runs on the same committed code with +Rust 1.99.1 on Linux x86_64, including unit, integration, example and doc tests; +both suites had zero failures. Verification results below identify which earlier +suites ran. **#441 verification (2026-11-14)**: the full native default suite passes (2,149 active, 23 ignored), including the grammar verifier and eight new diff --git a/docs/testing/924-incoming-refs.md b/docs/testing/924-incoming-refs.md index 24c3b96995..50cd99d680 100644 --- a/docs/testing/924-incoming-refs.md +++ b/docs/testing/924-incoming-refs.md @@ -39,11 +39,13 @@ Names below are executable tests; combined names cover several closely related c | 16 | `owned_incoming_refs_cross_thread_and_guards`, existing `owned_tx_guards_begin_thread`, `owned_tx_user_function_off_the_begin_thread`, `owned_tx_other_thread_query_reads_committed` | | 19 | `incoming_refs_read_errors_remain_errors`; full native suite, golden/model/WAL/crash/owned suites, fmt and native/browser/WASI Clippy | | 20 | Distribution binary measurements below | -| 21, Rust half | Standalone `incoming_refs_write` benchmark below; `incoming_refs_position_memory` capacity accounting; bench-machine timing comparison pending | +| 21, Rust half | Criterion median comparison below: no regression above 5% on any of 65 IDs in either round; `incoming_refs_position_memory` capacity accounting | | 22, in-repo half | API rustdoc, CHANGELOG, CLAUDE, TEST_COVERAGE, ROADMAP and README | ## Ref write-cost benchmarks +The comparison measures Criterion medians for base `73388aec5` versus the branch. Method: Linux x86_64, Rust 1.99.1, bench profile; base and branch ran side by side with CPU/memory pinning, swapped between the two rounds (r1, r2); the base used the same `incoming_refs_write` bench copied onto it; controls selected with the filter `^(insert|insert_file|checkpoint)/|^open/wal_replay/`. + `benches/incoming_refs_write.rs` uses only APIs present on the base. To compare, copy that file and its `[[bench]]` Cargo entry onto the base in a disposable directory. No production source from this branch is needed. Statements contain `#uuid` values, which the parser stores as scalar `Value::Ref`. New IDs, each at `1000` and `10000` facts: @@ -68,7 +70,75 @@ CARGO_BUILD_JOBS=4 cargo bench --offline --bench minigraf_bench -- '^checkpoint/ Integer control IDs include `insert/{single_fact,batch_100,explicit_tx}/{1k,10k,100k,1m}`, their `insert_file` equivalents, `open/wal_replay/{1k,10k,100k}`, `checkpoint/{1k,10k,100k,1m}`, `checkpoint/after_1_fact/{10k,100k,1m}`, `checkpoint/after_100k_facts/{10k,100k}`, and `insert_file/chunked/{execute,retract,write_tx}/{65535,65537}`. Use `--list` on the existing harness for its authoritative inventory and any additional controls selected by these filters. -Base/branch timing medians and the >5% decision remain for the separate bench machine. +No median regression exceeds 5% on any of the 65 IDs in either round. The largest increase is **+4.01%** (`insert/explicit_tx/10k`, r1). This in-memory explicit-transaction insert control increases at all four scales in both rounds: +2.9% to +4.0% at 1k, 10k and 1m, and +0.63% / +1.01% at 100k. The largest ref-workload increase is **+2.36%** (`incoming_ref_writes/staged/1000`, r1). The largest decrease is **-7.45%** (`open/wal_replay/10k`, r2). + +| Workload ID | Base r1 | Branch r1 | Change r1 | Base r2 | Branch r2 | Change r2 | +|---|---:|---:|---:|---:|---:|---:| +| `incoming_ref_writes/checkpoint/1000` | 3.294 ms | 3.283 ms | -0.32% | 3.318 ms | 3.375 ms | +1.74% | +| `incoming_ref_writes/checkpoint/10000` | 35.54 ms | 35.6 ms | +0.18% | 35.4 ms | 36.17 ms | +2.16% | +| `incoming_ref_writes/pending/1000` | 3.72 ms | 3.661 ms | -1.60% | 3.716 ms | 3.671 ms | -1.20% | +| `incoming_ref_writes/pending/10000` | 40.99 ms | 41.47 ms | +1.16% | 40.82 ms | 41.21 ms | +0.94% | +| `incoming_ref_writes/promotion/1000` | 6.981 ms | 6.893 ms | -1.26% | 6.993 ms | 6.905 ms | -1.26% | +| `incoming_ref_writes/promotion/10000` | 67.66 ms | 66.77 ms | -1.32% | 68.15 ms | 66.94 ms | -1.77% | +| `incoming_ref_writes/staged/1000` | 2.484 ms | 2.542 ms | +2.36% | 2.474 ms | 2.532 ms | +2.32% | +| `incoming_ref_writes/staged/10000` | 26.14 ms | 26.59 ms | +1.71% | 26.19 ms | 26.62 ms | +1.65% | +| `incoming_ref_writes/wal_recovery/1000` | 4.059 ms | 4.117 ms | +1.41% | 4.088 ms | 4.18 ms | +2.25% | +| `incoming_ref_writes/wal_recovery/10000` | 45.56 ms | 46.49 ms | +2.05% | 45.9 ms | 46.83 ms | +2.03% | +| `checkpoint/100k` | 377.8 ms | 378.2 ms | +0.10% | 380.3 ms | 380.7 ms | +0.09% | +| `checkpoint/10k` | 28.53 ms | 28.62 ms | +0.30% | 28.66 ms | 28.7 ms | +0.12% | +| `checkpoint/1k` | 2.843 ms | 2.765 ms | -2.74% | 2.774 ms | 2.77 ms | -0.15% | +| `checkpoint/1m` | 5.126 s | 5.079 s | -0.92% | 5.071 s | 5.103 s | +0.63% | +| `checkpoint/after_100k_facts/100k` | 1.461 s | 1.459 s | -0.14% | 1.47 s | 1.481 s | +0.78% | +| `checkpoint/after_100k_facts/10k` | 1.41 s | 1.403 s | -0.44% | 1.421 s | 1.41 s | -0.78% | +| `checkpoint/after_1_fact/100k` | 504 µs | 504.1 µs | +0.02% | 505.3 µs | 512.8 µs | +1.48% | +| `checkpoint/after_1_fact/10k` | 472.3 µs | 464.1 µs | -1.73% | 466.4 µs | 467.8 µs | +0.30% | +| `checkpoint/after_1_fact/1m` | 531.5 µs | 526 µs | -1.04% | 532.7 µs | 534.2 µs | +0.27% | +| `checkpoint/set_storage/inline_unique/10k` | 38.88 ms | 38.82 ms | -0.15% | 39.1 ms | 38.79 ms | -0.80% | +| `checkpoint/set_storage/long_repeated/10k` | 93.61 ms | 93.17 ms | -0.47% | 93.03 ms | 93.9 ms | +0.94% | +| `checkpoint/set_storage/long_unique/10k` | 112.8 ms | 112.1 ms | -0.63% | 112.2 ms | 112.3 ms | +0.02% | +| `checkpoint/storage_v3/multivalue_inline_unique/10k` | 27.1 ms | 26.84 ms | -0.97% | 27.29 ms | 26.91 ms | -1.39% | +| `checkpoint/storage_v3/multivalue_long_repeated/10k` | 38.34 ms | 37.88 ms | -1.20% | 38.24 ms | 38.24 ms | -0.01% | +| `checkpoint/storage_v3/multivalue_long_unique/10k` | 58.82 ms | 58.12 ms | -1.19% | 58.45 ms | 58.45 ms | +0.01% | +| `checkpoint/storage_v3/rebuild_damaged_avet/100k_history` | 510.3 ms | 509.3 ms | -0.20% | 512.2 ms | 513.9 ms | +0.33% | +| `checkpoint/storage_v3/verify/100k_history` | 254.8 ms | 251.6 ms | -1.23% | 254.5 ms | 253.7 ms | -0.34% | +| `insert/batch_100/100k` | 455.1 µs | 463.4 µs | +1.81% | 455.5 µs | 462.5 µs | +1.53% | +| `insert/batch_100/10k` | 412.8 µs | 409.7 µs | -0.77% | 413.6 µs | 417.5 µs | +0.94% | +| `insert/batch_100/1k` | 395.4 µs | 397.1 µs | +0.45% | 402.7 µs | 400.7 µs | -0.49% | +| `insert/batch_100/1m` | 410.7 µs | 409.6 µs | -0.27% | 414.8 µs | 413.8 µs | -0.24% | +| `insert/explicit_tx/100k` | 5.619 µs | 5.654 µs | +0.63% | 5.603 µs | 5.66 µs | +1.01% | +| `insert/explicit_tx/10k` | 4.922 µs | 5.119 µs | +4.01% | 4.973 µs | 5.166 µs | +3.88% | +| `insert/explicit_tx/1k` | 4.914 µs | 5.058 µs | +2.93% | 4.942 µs | 5.114 µs | +3.47% | +| `insert/explicit_tx/1m` | 4.861 µs | 5.044 µs | +3.77% | 4.905 µs | 5.1 µs | +3.98% | +| `insert/single_fact/100k` | 5.019 µs | 4.983 µs | -0.71% | 4.941 µs | 4.995 µs | +1.10% | +| `insert/single_fact/10k` | 4.473 µs | 4.52 µs | +1.05% | 4.516 µs | 4.552 µs | +0.79% | +| `insert/single_fact/1k` | 4.374 µs | 4.409 µs | +0.81% | 4.37 µs | 4.353 µs | -0.37% | +| `insert/single_fact/1m` | 4.243 µs | 4.35 µs | +2.52% | 4.34 µs | 4.427 µs | +2.02% | +| `insert_file/batch_100/100k` | 430.2 µs | 428.2 µs | -0.45% | 429.8 µs | 426.9 µs | -0.69% | +| `insert_file/batch_100/10k` | 423.5 µs | 424.5 µs | +0.24% | 427.3 µs | 424.7 µs | -0.60% | +| `insert_file/batch_100/1k` | 423.3 µs | 424.8 µs | +0.35% | 424.6 µs | 428.7 µs | +0.97% | +| `insert_file/batch_100/1m` | 442.5 µs | 427.4 µs | -3.42% | 427.5 µs | 426.7 µs | -0.18% | +| `insert_file/chunked/execute/65535` | 305.4 ms | 307.1 ms | +0.55% | 306.2 ms | 305.5 ms | -0.24% | +| `insert_file/chunked/execute/65537` | 343.4 ms | 339.9 ms | -1.01% | 336.3 ms | 341.9 ms | +1.66% | +| `insert_file/chunked/retract/65535` | 268.4 ms | 271.3 ms | +1.09% | 267.1 ms | 270.8 ms | +1.37% | +| `insert_file/chunked/retract/65537` | 542.3 ms | 538.5 ms | -0.70% | 535.7 ms | 544 ms | +1.54% | +| `insert_file/chunked/statement_rollback/65537` | 350.4 ms | 353.5 ms | +0.90% | 348.9 ms | 356.9 ms | +2.30% | +| `insert_file/chunked/write_tx/65535` | 346.6 ms | 345.9 ms | -0.20% | 339.1 ms | 348.5 ms | +2.75% | +| `insert_file/chunked/write_tx/65537` | 469 ms | 473.6 ms | +0.97% | 473.6 ms | 464 ms | -2.04% | +| `insert_file/explicit_tx/100k` | 7.34 µs | 7.27 µs | -0.96% | 7.081 µs | 7.167 µs | +1.21% | +| `insert_file/explicit_tx/10k` | 7.347 µs | 7.238 µs | -1.48% | 7.112 µs | 7.156 µs | +0.62% | +| `insert_file/explicit_tx/1k` | 7.385 µs | 7.232 µs | -2.07% | 7.114 µs | 7.146 µs | +0.45% | +| `insert_file/explicit_tx/1m` | 7.22 µs | 7.26 µs | +0.56% | 7.075 µs | 7.189 µs | +1.62% | +| `insert_file/set_storage/inline_unique/10k` | 68.58 ms | 69.13 ms | +0.81% | 68.78 ms | 69.44 ms | +0.96% | +| `insert_file/set_storage/long_repeated/10k` | 251.6 ms | 254.5 ms | +1.15% | 251.5 ms | 252.9 ms | +0.57% | +| `insert_file/set_storage/long_unique/10k` | 252.8 ms | 254.1 ms | +0.53% | 252.7 ms | 253.9 ms | +0.48% | +| `insert_file/set_storage/scalar/10k` | 39.51 ms | 39.98 ms | +1.20% | 39.33 ms | 40.43 ms | +2.80% | +| `insert_file/single_fact/100k` | 6.301 µs | 6.364 µs | +1.00% | 6.219 µs | 6.341 µs | +1.96% | +| `insert_file/single_fact/10k` | 6.367 µs | 6.505 µs | +2.17% | 6.376 µs | 6.462 µs | +1.35% | +| `insert_file/single_fact/1k` | 6.417 µs | 6.459 µs | +0.66% | 6.403 µs | 6.5 µs | +1.51% | +| `insert_file/single_fact/1m` | 6.293 µs | 6.384 µs | +1.46% | 6.272 µs | 6.367 µs | +1.52% | +| `open/wal_replay/100k` | 300.9 ms | 301.9 ms | +0.33% | 300 ms | 302.6 ms | +0.89% | +| `open/wal_replay/10k` | 33.41 µs | 32.85 µs | -1.68% | 34.44 µs | 31.88 µs | -7.45% | +| `open/wal_replay/1k` | 28.89 µs | 27.87 µs | -3.51% | 29.19 µs | 28.44 µs | -2.58% | ## Added pending-store memory @@ -88,27 +158,31 @@ Reproduce the capacity report without running timing benchmarks: CARGO_BUILD_JOBS=4 cargo test --offline --lib incoming_refs_position_memory -- --nocapture ``` -Total allocator/RSS measurements and write-time medians remain for the bench machine. No allocator instrumentation was added to the library. +Total allocator/RSS usage was not measured. No allocator instrumentation was added to the library. ## Verification (2026-11-28) -All Cargo commands ran offline with `CARGO_BUILD_JOBS=4`; the final test run also set `RUST_TEST_THREADS=4`. No release-mode tests or timing benchmarks were run. Both wasm targets were installed. +Verification on the same committed code with Rust 1.99.1 on Linux x86_64: | Command | Result | |---|---| -| `cargo build --offline` | Pass | -| `cargo test --offline` | **2,188 passed, 0 failed, 23 ignored** (2,211 total); 402.58 seconds | -| `cargo clippy --offline --all-targets -- -D warnings` | Pass | +| `cargo build` | Pass | +| `cargo test` | **2,188 passed, 0 failed, 23 ignored** (2,211 total) | +| `cargo test --features test-hooks` | **2,226 passed, 0 failed, 32 ignored** (2,258 total) | +| `cargo clippy --all-targets -- -D warnings` | Pass | +| `cargo clippy --all-targets --features test-hooks -- -D warnings` | Pass | | `cargo fmt --check` | Pass | -| `cargo clippy --offline --target wasm32-unknown-unknown --features browser -- -D warnings` | Pass | -| `cargo clippy --offline --target wasm32-wasip1 -- -D warnings` | Pass | -| Base-only source plus the new benchmark: `cargo check --offline --bench incoming_refs_write` | Pass | -| `cargo build --offline --profile dist` (Rust 1.94.0) | Build passes; size exceeds gate on both base and branch | -| `cargo +1.99.1 build --offline --profile dist` | Pass; size below gate | +| `cargo clippy --target wasm32-unknown-unknown --features browser -- -D warnings` | Pass | +| `cargo clippy --target wasm32-wasip1 -- -D warnings` | Pass | +| WASI tests on `wasm32-wasip1` under wasmtime 33.0.0 | **1,232 passed, 0 failed, 7 ignored** | +| `wasm-pack` headless Firefox browser tests | Pass: 95 library tests plus the integration targets | +| `cargo build --profile dist` | Pass: **1,250,600 bytes**, below the 1,280,000-byte gate; build path differs from the table's 1,250,568-byte measurement below | + +The earlier base-only source check with the new benchmark, `cargo check --offline --bench incoming_refs_write`, also passed. The library suite is 1,268 passed / eight ignored. The incoming-reference integration file is 14 passed; owned transactions are 17 passed. Fourteen focused incoming-reference unit tests pass. The full run includes the existing golden-file, model, WAL, crash and transaction suites; ignored cases remain ignored. The new API rustdoc passes. -The complete `--features test-hooks` suite, wasm runtime tests, JVM bindings and docs-site builds were not run. Ordinary unit tests exercise the test-only enumeration sites. +Chrome and Safari browser runs and CI's Rust 1.100 size build were not run for this repository. Ordinary unit tests exercise the test-only enumeration sites. ## Distribution binary size From 5ac1bb3ac924509551c753af649dd980809395d8 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Sat, 28 Nov 2026 14:28:22 +0530 Subject: [PATCH 3/5] test(db): cover unknown incoming-reference targets on a populated database (#924) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H2a7QmsdjnGhRdBSbw6GB7 --- CLAUDE.md | 2 +- docs/TEST_COVERAGE.md | 31 ++++++----- docs/testing/924-incoming-refs.md | 17 ++++-- tests/incoming_refs_test.rs | 93 +++++++++++++++++++++++++++++++ 4 files changed, 123 insertions(+), 20 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 384676880c..02518c36e3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -250,7 +250,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are ## Test Coverage -**2211 tests** (2188 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). +**2212 tests** (2189 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). 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/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index 6f50150a94..e869f5a7a8 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -2,9 +2,9 @@ ## Coverage Summary -**#924 bounded incoming references**: full offline native `cargo test` on -2026-11-28 passes **2,188 tests, 0 failures, 23 ignored** (2,211 total), with -`CARGO_BUILD_JOBS=4` and `RUST_TEST_THREADS=4`. This adds 30 active tests: +**#924 bounded incoming references**: full native `cargo test` on +2026-11-28 passes **2,189 tests, 0 failures, 23 ignored** (2,212 total). +This adds 31 active tests: `src/db/incoming_tests.rs` has ten (fault-injected STG-046/WAL-007 reads, legacy ties/budgets, 100,000 unrelated facts in all four representations, independent history-enumeration bounds, unchanged non-ref batch capacity, @@ -13,12 +13,16 @@ and allocation reuse with last-statement/tied-retraction precedence after stampi `src/graph/storage.rs` adds two tests for counted pending extension and omission of the unused incoming index in query-only snapshots; `src/incoming.rs` has one capacity-accounting test; `src/storage/reader.rs` -has one malformed/missing VAET test; `tests/incoming_refs_test.rs` has 14 -(including the crash-child entrypoint, proptest model and exact-set promotion); the owned +has one malformed/missing VAET test; `tests/incoming_refs_test.rs` has 15 +(including the crash-child entrypoint, proptest model, exact-set +promotion and unknown-target lookup with a populated committed dictionary); the owned transaction suite has one new cross-thread/guard case (17 total); and the API has one new rustdoc test. The library suite passes 1,268 with eight ignored. -Build, strict native all-target Clippy, fmt, browser wasm Clippy and WASI Clippy -all pass offline. The Rust 1.99.1 distribution binary is 1,250,568 bytes +Strict native all-target Clippy with and without `test-hooks`, fmt, and +`incoming_refs_model` with `PROPTEST_CASES=500` pass. The earlier build, +browser/WASI Clippy, WASI/Firefox tests, distribution-size and benchmark results +predate the test-only change, which is excluded from wasm32 builds and changes +no production source. The Rust 1.99.1 distribution binary is 1,250,568 bytes (+3,808 from the v3 base), below the unchanged 1,280,000-byte gate. No browser tests or ignored tests were added. See the [AC-to-test mapping, memory accounting and binary/benchmark evidence](testing/924-incoming-refs.md). @@ -64,14 +68,15 @@ are documented in the [PR 1 evidence](testing/894-idb-flush-recovery.md). | | Default features (#924 run) | `test-hooks` (#924 run) | |---|---|---| -| **Active** | 2,188 | 2,226 | +| **Passed** | 2,189 | 2,227 | +| **Failed** | 0 | 0 | | **Ignored** | 23 | 32 | -| **Total** | 2,211 | 2,258 | +| **Total** | 2,212 | 2,259 | -Both columns come from the completed #924 runs on the same committed code with -Rust 1.99.1 on Linux x86_64, including unit, integration, example and doc tests; -both suites had zero failures. Verification results below identify which earlier -suites ran. +Both columns come from the completed #924 runs on the working tree including +the incoming-reference test changes, with Rust 1.99.1 on Linux x86_64, including +unit, integration, example and doc tests; both suites had zero failures. +Verification results below identify which earlier suites ran. **#441 verification (2026-11-14)**: the full native default suite passes (2,149 active, 23 ignored), including the grammar verifier and eight new diff --git a/docs/testing/924-incoming-refs.md b/docs/testing/924-incoming-refs.md index 50cd99d680..e0093c60d8 100644 --- a/docs/testing/924-incoming-refs.md +++ b/docs/testing/924-incoming-refs.md @@ -26,11 +26,11 @@ Names below are executable tests; combined names cover several closely related c | 3 | `incoming_refs_exact_types_and_attributes` (memory, pending and durable) | | 4–5 | `incoming_refs_unique_pairs_and_any_valid_window`, `incoming_refs_legacy_ties_and_group_budget` | | 6 | `incoming_refs_statement_order_rejected_statement_and_promotion` (memory and file), `incoming_refs_model`, `incoming_refs_promotion_filters_before_stamping` (allocation reuse, both statement orders and tied retractions after stamping), the three failed-statement tests in AC8a | -| 7 | `incoming_refs_unknown_pending_only_dangling_and_checkpoint_reopen`, `incoming_refs_external_types_and_large_read_only`, statement/promotion test | +| 7 | `incoming_refs_unknown_target_with_populated_dictionary` (committed dictionary/VAET plus pending facts, small and promoted transactions, zero/large limits, unchanged file/WAL bytes and counters, empty commit, reopen integrity and exact known links), `incoming_refs_unknown_pending_only_dangling_and_checkpoint_reopen`, `incoming_refs_external_types_and_large_read_only`, statement/promotion test | | 8 | `incoming_refs_read_only_retryable_exhaustion_rollback_and_drop`, `incoming_refs_external_types_and_large_read_only` | | 8a | `incoming_refs_on_failed_handle` (fault-injected STG-046 and WAL-007; borrowed and owned); `incoming_refs_failed_promotion_keeps_completed_statements` (earlier assertion and retraction), `incoming_refs_failed_large_statement_keeps_completed_statements` (every chunk-write fault ordinal), `incoming_refs_failed_end_statement_keeps_completed_statements` (claims-tree read failure) | | 9 | `incoming_refs_wal_recovery_and_recovered_then_promoted` (actual crashing child, implicit and explicit commits), `incoming_refs_promotion_exact_set` (before/after promotion, new source/attribute and retraction after promotion, exact set before commit); checkpoint/reopen, statement/promotion, rollback/drop and model tests | -| 10 | `incoming_refs_model`: 32 proptest cases, up to 79 operations, independent exact-typed set model; asserts/retracts, aliases, commit/rollback, checkpoint/reopen and low promotion thresholds | +| 10 | `incoming_refs_model`: 32 proptest cases by default, `PROPTEST_CASES` overrides; up to 79 operations, independent exact-typed set model; asserts/retracts, aliases, commit/rollback, checkpoint/reopen and low promotion thresholds | | 11 | `incoming_refs_exact_link_cap_overflow_zero_and_huge_limits` | | 12 | `incoming_refs_budget_shared_across_layers`, `incoming_refs_legacy_ties_and_group_budget` | | 13 | `incoming_refs_dead_pairs_exhaust_and_one_pair_long_history`, `incoming_refs_history_enumeration_is_bounded` | @@ -162,13 +162,18 @@ Total allocator/RSS usage was not measured. No allocator instrumentation was add ## Verification (2026-11-28) -Verification on the same committed code with Rust 1.99.1 on Linux x86_64: +Verification with Rust 1.99.1 on Linux x86_64. The full native suites, native +Clippy, fmt and 500-case model results include the incoming-reference test +changes. The build, WASI, Firefox, wasm Clippy, distribution-size and benchmark +results predate that test-only change, which is excluded from wasm32 builds and +changes no production source. | Command | Result | |---|---| | `cargo build` | Pass | -| `cargo test` | **2,188 passed, 0 failed, 23 ignored** (2,211 total) | -| `cargo test --features test-hooks` | **2,226 passed, 0 failed, 32 ignored** (2,258 total) | +| `cargo test` | **2,189 passed, 0 failed, 23 ignored** (2,212 total) | +| `cargo test --features test-hooks` | **2,227 passed, 0 failed, 32 ignored** (2,259 total) | +| `PROPTEST_CASES=500 cargo test --test incoming_refs_test incoming_refs_model` | Pass | | `cargo clippy --all-targets -- -D warnings` | Pass | | `cargo clippy --all-targets --features test-hooks -- -D warnings` | Pass | | `cargo fmt --check` | Pass | @@ -180,7 +185,7 @@ Verification on the same committed code with Rust 1.99.1 on Linux x86_64: The earlier base-only source check with the new benchmark, `cargo check --offline --bench incoming_refs_write`, also passed. -The library suite is 1,268 passed / eight ignored. The incoming-reference integration file is 14 passed; owned transactions are 17 passed. Fourteen focused incoming-reference unit tests pass. The full run includes the existing golden-file, model, WAL, crash and transaction suites; ignored cases remain ignored. The new API rustdoc passes. +The library suite is 1,268 passed / eight ignored. The incoming-reference integration file is 15 passed; owned transactions are 17 passed. Fourteen focused incoming-reference unit tests pass. The full run includes the existing golden-file, model, WAL, crash and transaction suites; ignored cases remain ignored. The new API rustdoc passes. Chrome and Safari browser runs and CI's Rust 1.100 size build were not run for this repository. Ordinary unit tests exercise the test-only enumeration sites. diff --git a/tests/incoming_refs_test.rs b/tests/incoming_refs_test.rs index 2d22e5eeb0..96c9db6b8c 100644 --- a/tests/incoming_refs_test.rs +++ b/tests/incoming_refs_test.rs @@ -209,6 +209,97 @@ fn incoming_refs_unknown_pending_only_dangling_and_checkpoint_reopen() { db.verify().unwrap(); } +#[test] +fn incoming_refs_unknown_target_with_populated_dictionary() { + for large in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("unknown.graph"); + let wal_path = path.with_extension("graph.wal"); + let db = database(true, &path); + for (source, attr, target) in [(1, ":a", 9), (2, ":b", 9), (3, ":a", 10)] { + db.execute(&statement(true, source, attr, target)).unwrap(); + } + db.execute("(transact [[:property :n 42]])").unwrap(); + db.checkpoint().unwrap(); + db.execute(&statement(true, 4, ":c", 9)).unwrap(); + db.execute(&statement(true, 5, ":d", 10)).unwrap(); + let count = db.current_tx_count(); + let before = std::fs::read(&path).unwrap(); + let wal_before = std::fs::read(&wal_path).unwrap(); + let mut tx = db + .begin_write_with(TxOptions::new().chunk_facts(1)) + .unwrap(); + if large { + // Two facts cross the threshold and populate the working trees. + tx.execute("(transact [[:filler-a :n 1] [:filler-b :n 2]])") + .unwrap(); + assert!(std::fs::read(&path).unwrap() != before); + } + // Promotion may write pages; only lookup itself must leave them intact. + let bytes = std::fs::read(&path).unwrap(); + let wal = std::fs::read(&wal_path).unwrap(); + if !large { + assert!(bytes == before); + assert!(wal == wal_before); + } + for limits in [ + IncomingRefLimits::new(0, 0), + IncomingRefLimits::new(usize::MAX, usize::MAX), + ] { + let (links, examined) = complete(tx.incoming_refs(id(999), limits).unwrap()); + assert!(links.is_empty()); + assert_eq!(examined, 0); + assert!(std::fs::read(&path).unwrap() == bytes); + assert!(std::fs::read(&wal_path).unwrap() == wal); + assert_eq!(db.current_tx_count(), count); + } + if large { + tx.rollback(); + } else { + tx.commit().unwrap(); + assert!(std::fs::read(&path).unwrap() == bytes); + assert!(std::fs::read(&wal_path).unwrap() == wal); + } + assert_eq!(db.current_tx_count(), count); + let bytes = std::fs::read(&path).unwrap(); + let wal = std::fs::read(&wal_path).unwrap(); + db.begin_write().unwrap().commit().unwrap(); + assert!(std::fs::read(&path).unwrap() == bytes); + assert!(std::fs::read(&wal_path).unwrap() == wal); + assert_eq!(db.current_tx_count(), count); + db.checkpoint().unwrap(); + drop(db); + + let db = database(true, &path); + let report = db.verify().unwrap(); + assert!(report.is_ok()); + assert_eq!(report.facts, 6); + assert_eq!(db.current_tx_count(), count); + assert!( + lookup(&db, 9).0 + == BTreeSet::from([ + (id(1), ":a".into()), + (id(2), ":b".into()), + (id(4), ":c".into()) + ]) + ); + assert!(lookup(&db, 10).0 == BTreeSet::from([(id(3), ":a".into()), (id(5), ":d".into())])); + let (links, examined) = lookup(&db, 999); + assert!(links.is_empty()); + assert_eq!(examined, 0); + // The public fact log exposes neither an entity nor a ref for the unknown ID. + let records: Vec<_> = db + .fact_log(&minigraf::FactFilter::new()) + .unwrap() + .map(|record| record.unwrap()) + .collect(); + assert_eq!(records.len(), 6); + assert!(records.iter().all(|record| { + record.entity != id(999) && record.value != minigraf::Value::Ref(id(999)) + })); + } +} + #[test] fn incoming_refs_read_only_retryable_exhaustion_rollback_and_drop() { let dir = tempfile::tempdir().unwrap(); @@ -424,6 +515,8 @@ fn incoming_refs_wal_recovery_and_recovered_then_promoted() { } use proptest::prelude::*; + +// More cases: PROPTEST_CASES=500 cargo test --test incoming_refs_test incoming_refs_model proptest! { #![proptest_config(ProptestConfig::with_cases(32))] #[test] From 126a041753b9edb7acc5564a7d83d07465bdc971 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Sat, 28 Nov 2026 18:13:14 +0530 Subject: [PATCH 4/5] test(db): cover the default incoming-reference reader and compare locked files portably (#924) Exercise the default CommittedReader method, which no test executed and which left src/storage/mod.rs below its coverage floor. Windows file locks are mandatory, so the incoming-reference tests compare the open database's length there and its exact bytes elsewhere. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H2a7QmsdjnGhRdBSbw6GB7 --- CLAUDE.md | 2 +- docs/TEST_COVERAGE.md | 39 ++++++++++++++++------------ docs/testing/924-incoming-refs.md | 31 +++++++++++++++------- src/graph/storage.rs | 16 ++++++++++++ tests/incoming_refs_test.rs | 43 +++++++++++++++++++++---------- 5 files changed, 89 insertions(+), 42 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 02518c36e3..1407d1fcba 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -250,7 +250,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are ## Test Coverage -**2212 tests** (2189 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: #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). 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/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index e869f5a7a8..a59d91270b 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -2,27 +2,35 @@ ## Coverage Summary -**#924 bounded incoming references**: full native `cargo test` on -2026-11-28 passes **2,189 tests, 0 failures, 23 ignored** (2,212 total). -This adds 31 active tests: +**#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** +(2,260 total) with `test-hooks`. Both runs include the new default-reader test +and precede the Windows-only test helper, which behaves identically on +non-Windows. This adds 32 active tests: `src/db/incoming_tests.rs` has ten (fault-injected STG-046/WAL-007 reads, legacy ties/budgets, 100,000 unrelated facts in all four representations, independent history-enumeration bounds, unchanged non-ref batch capacity, failed promotion/chunk/finalization visibility, setup-work instrumentation, and allocation reuse with last-statement/tied-retraction precedence after stamping); -`src/graph/storage.rs` adds two tests for counted pending extension and omission -of the unused incoming index in query-only snapshots; +`src/graph/storage.rs` adds three tests for counted pending extension, omission +of the unused incoming index in query-only snapshots, and the default reader +error (`incoming_refs_default_reader_returns_int019_without_visiting`, asserting +INT-019 and no visitor calls); `src/incoming.rs` has one capacity-accounting test; `src/storage/reader.rs` has one malformed/missing VAET test; `tests/incoming_refs_test.rs` has 15 (including the crash-child entrypoint, proptest model, exact-set promotion and unknown-target lookup with a populated committed dictionary); the owned transaction suite has one new cross-thread/guard case (17 total); and the API -has one new rustdoc test. The library suite passes 1,268 with eight ignored. +has one new rustdoc test. The library count is 1,269 passed with eight ignored. Strict native all-target Clippy with and without `test-hooks`, fmt, and -`incoming_refs_model` with `PROPTEST_CASES=500` pass. The earlier build, -browser/WASI Clippy, WASI/Firefox tests, distribution-size and benchmark results -predate the test-only change, which is excluded from wasm32 builds and changes -no production source. The Rust 1.99.1 distribution binary is 1,250,568 bytes +`incoming_refs_model` with `PROPTEST_CASES=500` pass. Coverage using the +coverage-gates workflow's nightly-2026-10-01, cargo-llvm-cov 0.9.1 and `--branch` +passes every per-module gate; `src/storage/mod.rs` has **85.82% line coverage** +(84% floor) and **93.33% branch coverage** (92% floor). +The earlier build, WASI, Firefox, wasm Clippy, distribution-size and benchmark +results predate the later test-only changes; no production source has changed +since. Windows was not run. The Rust 1.99.1 distribution binary is 1,250,568 bytes (+3,808 from the v3 base), below the unchanged 1,280,000-byte gate. No browser tests or ignored tests were added. See the [AC-to-test mapping, memory accounting and binary/benchmark evidence](testing/924-incoming-refs.md). @@ -66,17 +74,14 @@ tests. The distribution binary is **1,270,880 bytes** (+16 bytes), below the failures, one-line existing crash-harness Clippy correction, and unverified lanes are documented in the [PR 1 evidence](testing/894-idb-flush-recovery.md). -| | Default features (#924 run) | `test-hooks` (#924 run) | +| | Default features (#924) | `test-hooks` (#924) | |---|---|---| -| **Passed** | 2,189 | 2,227 | +| **Passed** | 2,190 | 2,228 | | **Failed** | 0 | 0 | | **Ignored** | 23 | 32 | -| **Total** | 2,212 | 2,259 | +| **Total** | 2,213 | 2,260 | -Both columns come from the completed #924 runs on the working tree including -the incoming-reference test changes, with Rust 1.99.1 on Linux x86_64, including -unit, integration, example and doc tests; both suites had zero failures. -Verification results below identify which earlier suites ran. +Both completed runs include unit, integration, example and doc tests. **#441 verification (2026-11-14)**: the full native default suite passes (2,149 active, 23 ignored), including the grammar verifier and eight new diff --git a/docs/testing/924-incoming-refs.md b/docs/testing/924-incoming-refs.md index e0093c60d8..20a2286c6a 100644 --- a/docs/testing/924-incoming-refs.md +++ b/docs/testing/924-incoming-refs.md @@ -26,7 +26,7 @@ Names below are executable tests; combined names cover several closely related c | 3 | `incoming_refs_exact_types_and_attributes` (memory, pending and durable) | | 4–5 | `incoming_refs_unique_pairs_and_any_valid_window`, `incoming_refs_legacy_ties_and_group_budget` | | 6 | `incoming_refs_statement_order_rejected_statement_and_promotion` (memory and file), `incoming_refs_model`, `incoming_refs_promotion_filters_before_stamping` (allocation reuse, both statement orders and tied retractions after stamping), the three failed-statement tests in AC8a | -| 7 | `incoming_refs_unknown_target_with_populated_dictionary` (committed dictionary/VAET plus pending facts, small and promoted transactions, zero/large limits, unchanged file/WAL bytes and counters, empty commit, reopen integrity and exact known links), `incoming_refs_unknown_pending_only_dangling_and_checkpoint_reopen`, `incoming_refs_external_types_and_large_read_only`, statement/promotion test | +| 7 | `incoming_refs_unknown_target_with_populated_dictionary` (committed dictionary/VAET plus pending facts, small and promoted transactions, zero/large limits, unchanged main-file bytes (length on Windows), WAL bytes and counters, empty commit, reopen integrity and exact known links), `incoming_refs_unknown_pending_only_dangling_and_checkpoint_reopen`, `incoming_refs_external_types_and_large_read_only`, statement/promotion test | | 8 | `incoming_refs_read_only_retryable_exhaustion_rollback_and_drop`, `incoming_refs_external_types_and_large_read_only` | | 8a | `incoming_refs_on_failed_handle` (fault-injected STG-046 and WAL-007; borrowed and owned); `incoming_refs_failed_promotion_keeps_completed_statements` (earlier assertion and retraction), `incoming_refs_failed_large_statement_keeps_completed_statements` (every chunk-write fault ordinal), `incoming_refs_failed_end_statement_keeps_completed_statements` (claims-tree read failure) | | 9 | `incoming_refs_wal_recovery_and_recovered_then_promoted` (actual crashing child, implicit and explicit commits), `incoming_refs_promotion_exact_set` (before/after promotion, new source/attribute and retraction after promotion, exact set before commit); checkpoint/reopen, statement/promotion, rollback/drop and model tests | @@ -37,7 +37,7 @@ Names below are executable tests; combined names cover several closely related c | 14 | `incoming_refs_unrelated_growth`: 100,000 mixed unrelated facts, all four layers, first and repeated calls; independent enumeration and separate successor probes; history and legacy budget tests independently check low-budget counts; `incoming_refs_setup_work_is_counted`, `incoming_refs_pending_extend_work_is_counted`, `incoming_refs_query_snapshot_skips_target_index` | | 15 | outcome, shared-layer budget and external large read-only tests; reduction establishes links only after all ranges finish | | 16 | `owned_incoming_refs_cross_thread_and_guards`, existing `owned_tx_guards_begin_thread`, `owned_tx_user_function_off_the_begin_thread`, `owned_tx_other_thread_query_reads_committed` | -| 19 | `incoming_refs_read_errors_remain_errors`; full native suite, golden/model/WAL/crash/owned suites, fmt and native/browser/WASI Clippy | +| 19 | `incoming_refs_read_errors_remain_errors`, `incoming_refs_default_reader_returns_int019_without_visiting` (MockReader inherits the default, INT-019, visitor never called); full native suite, golden/model/WAL/crash/owned suites, fmt and native/browser/WASI Clippy | | 20 | Distribution binary measurements below | | 21, Rust half | Criterion median comparison below: no regression above 5% on any of 65 IDs in either round; `incoming_refs_position_memory` capacity accounting | | 22, in-repo half | API rustdoc, CHANGELOG, CLAUDE, TEST_COVERAGE, ROADMAP and README | @@ -162,17 +162,24 @@ Total allocator/RSS usage was not measured. No allocator instrumentation was add ## Verification (2026-11-28) -Verification with Rust 1.99.1 on Linux x86_64. The full native suites, native -Clippy, fmt and 500-case model results include the incoming-reference test -changes. The build, WASI, Firefox, wasm Clippy, distribution-size and benchmark -results predate that test-only change, which is excluded from wasm32 builds and -changes no production source. +Full native runs on Linux x86_64 with Rust 1.99.1 include the new default-reader +test and precede the Windows-only test helper, which behaves identically on +non-Windows. Native all-target Clippy with and without `test-hooks` and fmt pass. +Coverage using the coverage-gates workflow's nightly-2026-10-01, +cargo-llvm-cov 0.9.1 and `--branch` passes every per-module gate: +`src/storage/mod.rs` has **85.82% line coverage** (84% floor) and +**93.33% branch coverage** (92% floor). + +The build, WASI, Firefox, wasm Clippy, distribution-size and benchmark results +predate the later test-only changes; no production source has changed since. +Open main-file checks compare length on Windows because its mandatory lock +prevents reading through a second handle. Windows was not run. | Command | Result | |---|---| | `cargo build` | Pass | -| `cargo test` | **2,189 passed, 0 failed, 23 ignored** (2,212 total) | -| `cargo test --features test-hooks` | **2,227 passed, 0 failed, 32 ignored** (2,259 total) | +| `cargo test` | **2,190 passed, 0 failed, 23 ignored** (2,213 total) | +| `cargo test --features test-hooks` | **2,228 passed, 0 failed, 32 ignored** (2,260 total) | | `PROPTEST_CASES=500 cargo test --test incoming_refs_test incoming_refs_model` | Pass | | `cargo clippy --all-targets -- -D warnings` | Pass | | `cargo clippy --all-targets --features test-hooks -- -D warnings` | Pass | @@ -185,7 +192,11 @@ changes no production source. The earlier base-only source check with the new benchmark, `cargo check --offline --bench incoming_refs_write`, also passed. -The library suite is 1,268 passed / eight ignored. The incoming-reference integration file is 15 passed; owned transactions are 17 passed. Fourteen focused incoming-reference unit tests pass. The full run includes the existing golden-file, model, WAL, crash and transaction suites; ignored cases remain ignored. The new API rustdoc passes. +The library has 1,269 passed and eight ignored; incoming-reference integration +tests have 15 passed and owned transactions have 17 passed. The full runs +include the default-reader INT-019/no-visitor test, the existing golden-file, +model, WAL, crash and transaction suites, and the new API rustdoc; ignored cases +remain ignored. Chrome and Safari browser runs and CI's Rust 1.100 size build were not run for this repository. Ordinary unit tests exercise the test-only enumeration sites. diff --git a/src/graph/storage.rs b/src/graph/storage.rs index ca7ca7770e..8aa4407a89 100644 --- a/src/graph/storage.rs +++ b/src/graph/storage.rs @@ -2259,6 +2259,22 @@ mod tests { } } + #[test] + fn incoming_refs_default_reader_returns_int019_without_visiting() { + use crate::storage::CommittedReader; + + let reader = MockReader(Vec::new()); + let mut visited = false; + let err = reader + .incoming_ref_records(uuid::Uuid::from_u128(1), 1, &mut |_, _, _, _| { + visited = true; + }) + .unwrap_err(); + + assert_eq!(crate::error::MinigrafError::from(err).code(), "INT-019"); + assert!(!visited, "unsupported reader must not call the visitor"); + } + #[test] fn committed_and_pending_facts_combine_in_every_lookup() { let (e, other) = (uuid::Uuid::from_u128(1), uuid::Uuid::from_u128(2)); diff --git a/tests/incoming_refs_test.rs b/tests/incoming_refs_test.rs index 96c9db6b8c..c15ae49322 100644 --- a/tests/incoming_refs_test.rs +++ b/tests/incoming_refs_test.rs @@ -8,6 +8,19 @@ use std::collections::BTreeSet; use uuid::Uuid; mod common; +fn main_file_state(path: &std::path::Path) -> impl PartialEq { + // Windows locks are mandatory: a second handle cannot read the open database. + // Compare its length there, and exact bytes elsewhere. The WAL is not locked. + #[cfg(windows)] + { + std::fs::metadata(path).unwrap().len() + } + #[cfg(not(windows))] + { + std::fs::read(path).unwrap() + } +} + fn id(n: u128) -> Uuid { Uuid::from_u128(n) } @@ -185,7 +198,7 @@ fn incoming_refs_unknown_pending_only_dangling_and_checkpoint_reopen() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("reopen.graph"); let db = database(true, &path); - let before = std::fs::read(&path).unwrap(); + let before = main_file_state(&path); { let mut tx = db.begin_write().unwrap(); assert!( @@ -198,7 +211,7 @@ fn incoming_refs_unknown_pending_only_dangling_and_checkpoint_reopen() { ); tx.commit().unwrap(); } - assert!(std::fs::read(&path).unwrap() == before); + assert!(main_file_state(&path) == before); db.execute(&statement(true, 1, ":a", 9)).unwrap(); assert_eq!(lookup(&db, 9).0.len(), 1); db.checkpoint().unwrap(); @@ -224,7 +237,7 @@ fn incoming_refs_unknown_target_with_populated_dictionary() { db.execute(&statement(true, 4, ":c", 9)).unwrap(); db.execute(&statement(true, 5, ":d", 10)).unwrap(); let count = db.current_tx_count(); - let before = std::fs::read(&path).unwrap(); + let before = main_file_state(&path); let wal_before = std::fs::read(&wal_path).unwrap(); let mut tx = db .begin_write_with(TxOptions::new().chunk_facts(1)) @@ -233,13 +246,15 @@ fn incoming_refs_unknown_target_with_populated_dictionary() { // Two facts cross the threshold and populate the working trees. tx.execute("(transact [[:filler-a :n 1] [:filler-b :n 2]])") .unwrap(); - assert!(std::fs::read(&path).unwrap() != before); + // Changed pages need not change file length, so this proof needs bytes. + #[cfg(not(windows))] + assert!(main_file_state(&path) != before); } // Promotion may write pages; only lookup itself must leave them intact. - let bytes = std::fs::read(&path).unwrap(); + let state = main_file_state(&path); let wal = std::fs::read(&wal_path).unwrap(); if !large { - assert!(bytes == before); + assert!(state == before); assert!(wal == wal_before); } for limits in [ @@ -249,7 +264,7 @@ fn incoming_refs_unknown_target_with_populated_dictionary() { let (links, examined) = complete(tx.incoming_refs(id(999), limits).unwrap()); assert!(links.is_empty()); assert_eq!(examined, 0); - assert!(std::fs::read(&path).unwrap() == bytes); + assert!(main_file_state(&path) == state); assert!(std::fs::read(&wal_path).unwrap() == wal); assert_eq!(db.current_tx_count(), count); } @@ -257,14 +272,14 @@ fn incoming_refs_unknown_target_with_populated_dictionary() { tx.rollback(); } else { tx.commit().unwrap(); - assert!(std::fs::read(&path).unwrap() == bytes); + assert!(main_file_state(&path) == state); assert!(std::fs::read(&wal_path).unwrap() == wal); } assert_eq!(db.current_tx_count(), count); - let bytes = std::fs::read(&path).unwrap(); + let state = main_file_state(&path); let wal = std::fs::read(&wal_path).unwrap(); db.begin_write().unwrap().commit().unwrap(); - assert!(std::fs::read(&path).unwrap() == bytes); + assert!(main_file_state(&path) == state); assert!(std::fs::read(&wal_path).unwrap() == wal); assert_eq!(db.current_tx_count(), count); db.checkpoint().unwrap(); @@ -306,7 +321,7 @@ fn incoming_refs_read_only_retryable_exhaustion_rollback_and_drop() { let path = dir.path().join("readonly.graph"); let db = database(true, &path); db.execute(&statement(true, 1, ":a", 9)).unwrap(); - let bytes = std::fs::read(&path).unwrap(); + let state = main_file_state(&path); let wal = std::fs::read(path.with_extension("graph.wal")).unwrap(); for rollback in [false, true] { let mut tx = db @@ -327,7 +342,7 @@ fn incoming_refs_read_only_retryable_exhaustion_rollback_and_drop() { .0 .is_empty() ); - assert!(std::fs::read(&path).unwrap() == bytes); + assert!(main_file_state(&path) == state); assert!(std::fs::read(path.with_extension("graph.wal")).unwrap() == wal); if rollback { tx.rollback(); @@ -563,7 +578,7 @@ fn incoming_refs_external_types_and_large_read_only() { .unwrap(); tx.execute(&statement(true, 1, ":a", 9)).unwrap(); tx.execute(&statement(true, 2, ":b", 9)).unwrap(); - let before = std::fs::read(&path).unwrap(); + let before = main_file_state(&path); let wal = std::fs::read(path.with_extension("graph.wal")).unwrap(); let count = db.current_tx_count(); assert!( @@ -589,7 +604,7 @@ fn incoming_refs_external_types_and_large_read_only() { .len(), 2 ); - assert!(std::fs::read(&path).unwrap() == before); + assert!(main_file_state(&path) == before); assert!(std::fs::read(path.with_extension("graph.wal")).unwrap() == wal); assert_eq!(db.current_tx_count(), count); tx.commit().unwrap(); From 166c9c42c246a68aff90e70246f3a59a3b2c24c6 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Sat, 28 Nov 2026 18:46:05 +0530 Subject: [PATCH 5/5] docs(testing): record the CI results for the incoming-reference lookup (#924) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H2a7QmsdjnGhRdBSbw6GB7 --- docs/TEST_COVERAGE.md | 10 ++++++++-- docs/testing/924-incoming-refs.md | 15 +++++++++++---- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index a59d91270b..d6348375cc 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -28,9 +28,15 @@ Strict native all-target Clippy with and without `test-hooks`, fmt, and coverage-gates workflow's nightly-2026-10-01, cargo-llvm-cov 0.9.1 and `--branch` passes every per-module gate; `src/storage/mod.rs` has **85.82% line coverage** (84% floor) and **93.33% branch coverage** (92% floor). -The earlier build, WASI, Firefox, wasm Clippy, distribution-size and benchmark +The earlier local build, WASI, Firefox, wasm Clippy, distribution-size and benchmark results predate the later test-only changes; no production source has changed -since. Windows was not run. The Rust 1.99.1 distribution binary is 1,250,568 bytes +since. CI at commit `126a04175` passed all 28 checks, including build/test on +`ubuntu-latest`, `macos-latest` and `windows-latest` (all 15 incoming-reference +integration tests pass on Windows); browser tests in headless Chrome and Firefox +(main thread and worker) and Safari (main thread and dedicated worker); WASI +tests on Wasmtime; wasm32 and wasip1 Clippy; per-module coverage gates; MSRV 1.89; +and the distribution binary size check on Rust 1.100.1: **1,225 KiB**, below the +**1,250 KiB** limit. The local Rust 1.99.1 distribution binary is 1,250,568 bytes (+3,808 from the v3 base), below the unchanged 1,280,000-byte gate. No browser tests or ignored tests were added. See the [AC-to-test mapping, memory accounting and binary/benchmark evidence](testing/924-incoming-refs.md). diff --git a/docs/testing/924-incoming-refs.md b/docs/testing/924-incoming-refs.md index 20a2286c6a..882f3cde2c 100644 --- a/docs/testing/924-incoming-refs.md +++ b/docs/testing/924-incoming-refs.md @@ -170,10 +170,11 @@ cargo-llvm-cov 0.9.1 and `--branch` passes every per-module gate: `src/storage/mod.rs` has **85.82% line coverage** (84% floor) and **93.33% branch coverage** (92% floor). -The build, WASI, Firefox, wasm Clippy, distribution-size and benchmark results +The local build, WASI, Firefox, wasm Clippy, distribution-size and benchmark results predate the later test-only changes; no production source has changed since. Open main-file checks compare length on Windows because its mandatory lock -prevents reading through a second handle. Windows was not run. +prevents reading through a second handle. CI at commit `126a04175` passed all +15 incoming-reference integration tests on Windows. | Command | Result | |---|---| @@ -198,7 +199,13 @@ include the default-reader INT-019/no-visitor test, the existing golden-file, model, WAL, crash and transaction suites, and the new API rustdoc; ignored cases remain ignored. -Chrome and Safari browser runs and CI's Rust 1.100 size build were not run for this repository. Ordinary unit tests exercise the test-only enumeration sites. +CI at commit `126a04175` passed all 28 checks, including build/test on +`ubuntu-latest`, `macos-latest` and `windows-latest`; browser tests in headless +Chrome and Firefox (main thread and worker) and Safari (main thread and +dedicated worker); WASI tests on Wasmtime; wasm32 and wasip1 Clippy; per-module +coverage gates; MSRV 1.89; and the distribution binary size check on Rust +1.100.1 (**1,225 KiB**, below the **1,250 KiB** limit). Ordinary unit tests +exercise the test-only enumeration sites. ## Distribution binary size @@ -209,4 +216,4 @@ The workflow builds the native x86_64 Linux CLI with `cargo build --profile dist | Rust 1.94.0 (local default) | 1,284,448 | 1,288,240 | +3,792 | Both exceed | | Rust 1.99.1 | 1,246,760 | 1,250,568 | +3,808 | Both pass | -The gate is satisfied with the installed newer toolchain. CI's exact Rust 1.100 toolchain is unavailable locally; that exact build remains unverified. +The gate is satisfied with the installed newer toolchain. CI at commit `126a04175` also passed the distribution binary size check on Rust 1.100.1: **1,225 KiB**, below the **1,250 KiB** limit.