FFFF feat(db): add bounded incoming-reference lookup to write transactions (#924) by adityamukho · Pull Request #926 · project-minigraf/minigraf · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<name>.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).
Expand Down
7 changes: 4 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<EntityId, Vec<usize>>` 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)

Expand All @@ -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
Expand Down Expand Up @@ -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<WriteSlot>` + `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<WriteSlot>` + `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)
Expand Down Expand Up @@ -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).
**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.
Expand Down
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()?;
Expand Down
2 changes: 2 additions & 0 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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.

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`.
Expand Down
124 changes: 124 additions & 0 deletions benches/incoming_refs_write.rs
Original file line number Diff line number Diff line change
@@ -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::<Minigraf>, 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);
Loading
Loading
0