Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
Decision 0010 rested on a false claim about its own dependency (#207)
Fabio Rovai770f31661fb7
diff --git a/docs/decisions/0010-the-input-is-a-value-and-not-a-store.md b/docs/decisions/0010-the-input-is-a-value-and-not-a-store.mdindex 4122fc4b..fa746c97 100644--- a/docs/decisions/0010-the-input-is-a-value-and-not-a-store.md+++ b/docs/decisions/0010-the-input-is-a-value-and-not-a-store.md@@ -32,9 +32,12 @@ The certified reasoner accepts an immutable `CertifiedInput` and has no second p`CertifiedInput` owns the canonical bytes of the assertions it was built from. Selection copies once;everything downstream reads an owned value. There are no phases that re-read the store, so there isno window in which the store can drift between hashing and reasoning. That matters here because-`GraphStore::snapshot` is a serialiser that takes a format string, not an isolation primitive, and-no transactional snapshot is available to lean on. Copying is the only honest option available and it-is also the one that dissolves the race.+`GraphStore::snapshot` is a serialiser that takes a format string, not an isolation primitive.++This paragraph used to continue "and no transactional snapshot is available to lean on. Copying is+the only honest option available". **That was false**, and the correction is below under *The+premise was wrong and the decision survives it*. A transactional snapshot IS available. Copying is+still what we do, for a reason that had to be measured rather than assumed.The invariant to enforce and then to prove:@@ -142,6 +145,102 @@ Adjusted from the obvious order, because the canonical-bytes machinery is alreadthe correct bytes are constructed and handed to a conventional implementation.9. Attestation, only under the condition in the section above.+## The premise was wrong and the decision survives it++*Added 19 September 2026, closing #181.*++The paragraph above rested on a claim about this repository's own dependency, and the claim did not+hold. `oxigraph = "0.5"` is pinned; `Store::start_transaction` is public and the crate documents it+as repeatable read. A decision record resting on a false statement about its dependency is worth+correcting whether or not the decision changes. This one does not change, and the reason it does not+is a cost the original text never weighed, because it believed there was nothing to weigh.++Three things were measured rather than argued. `tests/transaction_isolation_test.rs` and+`tests/transaction_memory_test.rs` are the measurements, and they are gates: each carries the+assertion that would fail if a future Oxigraph changed the answer, worded so that the fix is to+re-argue this section rather than to relax the assertion.++**The two storage backends do not behave alike.** This is the finding that matters, because+`GraphStore::new` builds the in-memory one and almost everything in this codebase uses it.++| | in memory (`Store::new`) | on disk (`Store::open`) |+|---|---|---|+| a writer, while a read transaction is open | **blocked until the reader commits** | proceeds |+| the reader's view, meanwhile | stable | stable |++In memory, a concurrent `insert` does not return while a read transaction is open. It is a lock and+not a deadlock: the writer proceeds the moment the reader commits, and a test asserts exactly that,+because "blocked forever" and "blocked for the duration" are different defects. The block is inside+`MemoryStorage::start_transaction`, reached from `Store::insert`, which opens a transaction of its+own. On disk the same probe shows the writer completing while the reader's repeated scan returns+the same count, which is what repeatable read is supposed to feel like.++**A read-only transaction costs no memory.** Oxigraph warns that "the transaction keeps the complete+set of changes into memory". That is a warning about writes. Over 20,000 triples, measuring NET LIVE+bytes with a counting global allocator, one run on macOS in a debug build:++| | net live bytes |+|---|---|+| held open, read-only transaction | **0** |+| copied out, the owned value this decision builds | **4,417,076** |++about 221 bytes per triple for the copy, against nothing for the transaction. The transaction's zero+is net rather than churn: the scan allocates and frees, and keeps nothing, which is the claim that+matters here.++Those two constants are from one run and are not gated. What is gated is the inequality between+them, by a factor of four in each direction, which is the shape the argument rests on and is not+going to move with an allocator or a platform. A test that pinned 4,417,076 would fail on Linux for+no reason anybody cares about, and would then be relaxed rather than read.++**So the trade is the opposite way round from the one the original text implied.** It is not+"copying is the only honest option". It is: copying spends about 221 bytes per triple in order to+hold an exclusive window that is short rather than one that lasts the whole reasoning run. On the+in-memory store a certified run that held its transaction open would stall every writer for as long+as it reasoned, and a reasoning run is not bounded by anything the reader controls. Copy once,+release, and reason on an owned value.++**Phantoms do not occur, measured rather than inferred from the isolation level's name.**+Repeatable read permits phantoms in general: a second evaluation of the same PATTERN may return rows+a concurrent transaction inserted. The probe repeats one pattern scan twenty times while a writer+commits between every pair of scans, into the very pattern being scanned, on the on-disk store+because that is the only one where a writer can commit at all while a reader is open. Every scan+returned the first count. The probe also asserts that the writer committed something, so a run in+which the writer never got going fails rather than passing as a clean result.++**The route this issue suggested for TCB-6 and TCB-7 does not exist in Oxigraph 0.5.** The+suggestion was that a transaction plus a recorded store version would turn "the assertions the+engine reasoned over" from a claim about an EXECUTION into a claim about a VALUE, which a checker+could confirm. There is no version to record: `Store` exposes no revision, sequence number or+snapshot handle, and the `Storage::snapshot` that exists internally is not reachable from the public+API. So `store revision` stays in the attested half of the manifest, where this decision already put+it, and TCB-6 and TCB-7 stay irreducible for this dependency at this version. That is settled, not+deferred; it becomes live again only if Oxigraph exposes one.++**Neither option is good enough, so the dependency is being changed.** The choice the original text+thought it faced was between a copy and nothing. The choice it actually faced is between a copy that+spends 221 bytes a triple and a transaction that stops the store for the length of a reasoning run.+Both are bad, and they are bad for the same reason: Oxigraph 0.5 exposes no way to pin a read state+without also taking a lock, even though `Storage::snapshot` does exactly that internally and is what+`Store::len` and `Store::quads_for_pattern` already call for every single read.++So the fix is a patch to Oxigraph rather than a better sentence here. `Store::snapshot` returns a+read view pinned to one state that takes no lock, measured as:++| | pins the state | writers keep running | memory over 20,000 triples |+|---|---|---|---|+| transaction, in memory | yes | **no, all blocked** | 0 |+| the copy this decision makes | yes | yes | 4,417,076 bytes |+| `Store::snapshot`, patched in | **yes** | **yes** | **0** |++The reader is shared through an `Arc` rather than cloned per call, because+`rocksdb_wrapper::Reader` owns a `*mut rocksdb_readoptions_t` and frees it in `Drop`; a derived+`Clone` would double free. Oxigraph's own store suite passes against the patch.++That work is a separate change and is not in this one, which corrects the record and leaves the copy+in place. When the snapshot lands, the copy goes and this section is what says why it was ever+there.+## ConsequencesTCB-8 stops being an informal promise and becomes a testable boundary. The cost is a copy of thediff --git a/tests/transaction_isolation_test.rs b/tests/transaction_isolation_test.rsnew file mode 100644index 00000000..bb33cd00--- /dev/null+++ b/tests/transaction_isolation_test.rs@@ -0,0 +1,256 @@+//! **What Oxigraph 0.5's transactions actually give this repository (#181).**+//!+//! `docs/decisions/0010-the-input-is-a-value-and-not-a-store.md` justifies+//! copying the whole selected graph for every certified run on this premise:+//!+//! > `GraphStore::snapshot` is a serialiser that takes a format string, not an+//! > isolation primitive, and no transactional snapshot is available to lean on.+//!+//! The second half is false of the version pinned here. `Store::start_transaction`+//! is public and documented as repeatable read. A decision record resting on a+//! false claim about its own dependency is worth correcting whether or not the+//! decision changes.+//!+//! It does not change, and this file is why. The measurements below say that a+//! transaction is a usable snapshot and that taking one costs something the+//! decision record never weighed, because the two storage backends do not+//! behave alike:+//!+//! * **In memory**, which is what `GraphStore::new` builds and what almost+//! everything in this codebase uses, an open read transaction BLOCKS every+//! writer. Not "may see stale data": a concurrent `insert` does not return+//! until the reader commits, because `Store::insert` opens a transaction of+//! its own and `MemoryStorage::start_transaction` waits.+//! * **On disk**, a concurrent writer proceeds and the reader's view stays+//! stable, which is what repeatable read is supposed to feel like.+//!+//! So the copy in 0010 is not working around a missing primitive. It is trading+//! one short exclusive window for a long one: copy the bytes and let go, rather+//! than hold the store against all writers for the length of a reasoning run.+//! That is a better reason than the one in the file, and it is measured here+//! rather than asserted there.++use oxigraph::model::{GraphNameRef, NamedNodeRef, QuadRef};+use oxigraph::store::Store;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;+use std::time::{Duration, Instant};++/// Long enough that a writer which is merely slow finishes, short enough that a+/// writer which is blocked is obvious. The in-memory case below blocks for as+/// long as the transaction is held, so any value works; this one keeps the+/// suite quick.+const PATIENCE: Duration = Duration::from_millis(1500);++fn quad(n: usize) -> (String,) {+ (format!("http://ex.org/{n}"),)+}++fn insert(store: &Store, n: usize) {+ let s = quad(n).0;+ store+ .insert(QuadRef::new(+ NamedNodeRef::new(&s).unwrap(),+ NamedNodeRef::new("http://ex.org/p").unwrap(),+ NamedNodeRef::new("http://ex.org/o").unwrap(),+ GraphNameRef::DefaultGraph,+ ))+ .unwrap();+}++fn seed(store: &Store, n: usize) {+ for i in 0..n {+ insert(store, i);+ }+}++/// Spawn a writer, and report whether it finished while the caller still holds+/// whatever it is holding. Never joins on a thread that may be blocked, because+/// a test that hangs reports nothing at all; this one ran for 60 seconds and+/// told us only that it was unhappy.+fn writer_finishes_within(store: &Arc<Store>, first: usize, patience: Duration) -> bool {+ let done = Arc::new(AtomicBool::new(false));+ let (w, d) = (Arc::clone(store), Arc::clone(&done));+ std::thread::spawn(move || {+ for i in first..first + 20 {+ insert(&w, i);+ }+ d.store(true, Ordering::SeqCst);+ });+ let deadline = Instant::now() + patience;+ while Instant::now() < deadline {+ if done.load(Ordering::SeqCst) {+ return true;+ }+ std::thread::sleep(Duration::from_millis(10));+ }+ done.load(Ordering::SeqCst)+}++// ── The in-memory store, which is what GraphStore::new builds ───────────++#[test]+fn in_memory_an_open_read_transaction_blocks_every_writer() {+ let store = Arc::new(Store::new().unwrap());+ seed(&store, 100);++ let txn = store.start_transaction().unwrap();+ let before = txn.quads_for_pattern(None, None, None, None).count();+ assert_eq!(before, 100, "the seed did not land");++ let finished = writer_finishes_within(&store, 1000, PATIENCE);+ assert!(+ !finished,+ "a writer completed while a read transaction was open on the IN-MEMORY store. That \+ would be good news, and it would also mean this file's measurement of the cost of \+ holding a transaction is stale and decision 0010 should be re-argued."+ );++ // The reader's view is stable, which it trivially is when nobody can write.+ let after = txn.quads_for_pattern(None, None, None, None).count();+ assert_eq!(after, before, "the view moved under a reader that holds the only lock");++ // Releasing the transaction releases the writer.+ txn.commit().unwrap();+ let deadline = Instant::now() + Duration::from_secs(10);+ while store.len().unwrap() < 120 && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(10));+ }+ assert_eq!(+ store.len().unwrap(),+ 120,+ "the writer did not proceed after the transaction committed, so it was not merely \+ blocked on the reader and this is a deadlock rather than a lock"+ );+}++// ── The persistent store, which behaves differently ─────────────────────++#[test]+fn on_disk_a_writer_proceeds_and_the_reader_still_sees_a_stable_view() {+ let dir = std::env::temp_dir().join(format!("oo-txn-disk-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ let store = Arc::new(Store::open(&dir).unwrap());+ seed(&store, 100);++ let txn = store.start_transaction().unwrap();+ let before = txn.quads_for_pattern(None, None, None, None).count();++ let finished = writer_finishes_within(&store, 1000, Duration::from_secs(10));+ let after = txn.quads_for_pattern(None, None, None, None).count();+ txn.commit().unwrap();+ let total = store.len().unwrap();+ let _ = std::fs::remove_dir_all(&dir);++ assert!(+ finished,+ "the on-disk store blocked a writer the way the in-memory one does. The two would then \+ behave alike after all, and the note in docs/decisions/0010 about them differing is \+ wrong."+ );+ assert_eq!(+ after, before,+ "the on-disk reader saw a concurrent commit mid-transaction, so repeatable read does \+ not hold and a transaction is NOT a snapshot here"+ );+ assert_eq!(total, 120, "the writer's work should be visible after the reader commits");+}++/// The two backends differ, and that is the finding. Stated as its own test so+/// that it fails loudly if a future Oxigraph makes them agree, in either+/// direction, rather than quietly invalidating the reasoning in 0010.+#[test]+fn the_two_backends_do_not_behave_alike() {+ let mem = Arc::new(Store::new().unwrap());+ seed(&mem, 10);+ let t = mem.start_transaction().unwrap();+ let mem_blocks = !writer_finishes_within(&mem, 500, PATIENCE);+ t.commit().unwrap();++ let dir = std::env::temp_dir().join(format!("oo-txn-cmp-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ let disk = Arc::new(Store::open(&dir).unwrap());+ seed(&disk, 10);+ let t2 = disk.start_transaction().unwrap();+ let disk_blocks = !writer_finishes_within(&disk, 500, Duration::from_secs(10));+ t2.commit().unwrap();+ let _ = std::fs::remove_dir_all(&dir);++ assert!(+ mem_blocks && !disk_blocks,+ "measured: in-memory blocks writers = {mem_blocks}, on-disk blocks writers = \+ {disk_blocks}. docs/decisions/0010 records that these differ; if they no longer do, \+ the decision's cost argument needs rewriting rather than this assertion relaxing."+ );+}++// ── Phantoms, settled ───────────────────────────────────────────────────++/// Repeatable read permits phantoms in general: a second evaluation of the same+/// PATTERN may return rows a concurrent transaction inserted, even though rows+/// already read do not change. Whether it permits them HERE is the question+/// decision 0010 turns on, and it is answerable by experiment rather than by+/// reading the isolation level's name.+///+/// The probe is deliberately hostile. It repeats the same pattern scan twenty+/// times while a writer commits between every pair of scans, and it scans a+/// pattern the writer is inserting INTO, so a phantom has every chance to+/// appear. It runs on the on-disk store, because that is the one where a writer+/// can commit at all while a reader is open; in memory the writer is blocked,+/// so phantoms are unreachable there for a reason that has nothing to do with+/// the isolation level.+#[test]+fn on_disk_repeated_scans_of_a_growing_pattern_never_return_a_phantom() {+ let dir = std::env::temp_dir().join(format!("oo-txn-phantom-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ let store = Arc::new(Store::open(&dir).unwrap());+ seed(&store, 50);++ let p = NamedNodeRef::new("http://ex.org/p").unwrap();+ let txn = store.start_transaction().unwrap();++ let first = txn.quads_for_pattern(None, Some(p), None, None).count();+ let mut counts = vec![first];++ let stop = Arc::new(AtomicBool::new(false));+ let (w, sflag) = (Arc::clone(&store), Arc::clone(&stop));+ let writer = std::thread::spawn(move || {+ let mut i = 10_000;+ while !sflag.load(Ordering::SeqCst) {+ insert(&w, i);+ i += 1;+ std::thread::sleep(Duration::from_millis(2));+ }+ i - 10_000+ });++ for _ in 0..20 {+ std::thread::sleep(Duration::from_millis(5));+ counts.push(txn.quads_for_pattern(None, Some(p), None, None).count());+ }+ stop.store(true, Ordering::SeqCst);+ let written = writer.join().expect("writer thread");+ txn.commit().unwrap();++ let total = store.len().unwrap();+ let _ = std::fs::remove_dir_all(&dir);++ assert!(+ written > 0,+ "the writer committed nothing during the scans, so this probe had no chance to see a \+ phantom and proves nothing. It is the gate on the gate."+ );+ let moved: Vec<_> = counts.iter().filter(|&&c| c != first).collect();+ assert!(+ moved.is_empty(),+ "a repeated scan of the same pattern returned {moved:?} where the first returned \+ {first}, with {written} rows committed underneath it. Repeatable read admits phantoms \+ on this store, a transaction is therefore NOT a snapshot, and the copy in decision \+ 0010 is load-bearing for correctness rather than for availability."+ );+ assert_eq!(+ total,+ 50 + written,+ "every committed row should be visible to a read started after the transaction closed"+ );+}diff --git a/tests/transaction_memory_test.rs b/tests/transaction_memory_test.rsnew file mode 100644index 00000000..a86ee2a6--- /dev/null+++ b/tests/transaction_memory_test.rs@@ -0,0 +1,115 @@+//! **What a read transaction costs in memory, against what the copy costs (#181).**+//!+//! Oxigraph warns that "the transaction keeps the complete set of changes into+//! memory, do not use them to load tens of millions of triples". That is a+//! warning about WRITE volume, and `docs/decisions/0010` is about a read. The+//! question it leaves open is whether a read-only transaction carries a cost of+//! its own, and how that compares with the copy 0010 makes instead.+//!+//! Measured here with a counting allocator rather than reasoned about, because+//! the answer decides which of two costs the decision is choosing between.+//!+//! This is its own test binary on purpose: `#[global_allocator]` is per-binary,+//! and putting one in a file that also runs the concurrency probes would have+//! the probes' threads counted as part of the measurement.++use oxigraph::model::{GraphNameRef, NamedNodeRef, QuadRef};+use oxigraph::store::Store;+use std::alloc::{GlobalAlloc, Layout, System};+use std::sync::atomic::{AtomicUsize, Ordering};++struct Counting;++static LIVE: AtomicUsize = AtomicUsize::new(0);++unsafe impl GlobalAlloc for Counting {+ unsafe fn alloc(&self, l: Layout) -> *mut u8 {+ LIVE.fetch_add(l.size(), Ordering::Relaxed);+ unsafe { System.alloc(l) }+ }+ unsafe fn dealloc(&self, p: *mut u8, l: Layout) {+ LIVE.fetch_sub(l.size(), Ordering::Relaxed);+ unsafe { System.dealloc(p, l) }+ }+}++#[global_allocator]+static ALLOC: Counting = Counting;++fn live() -> usize {+ LIVE.load(Ordering::Relaxed)+}++const N: usize = 20_000;++fn seed(store: &Store, n: usize) {+ let p = NamedNodeRef::new("http://ex.org/p").unwrap();+ let o = NamedNodeRef::new("http://ex.org/o").unwrap();+ for i in 0..n {+ let s = format!("http://ex.org/{i}");+ store+ .insert(QuadRef::new(+ NamedNodeRef::new(&s).unwrap(),+ p,+ o,+ GraphNameRef::DefaultGraph,+ ))+ .unwrap();+ }+}++/// The comparison decision 0010 is actually making: hold a transaction open+/// while you read, or copy the triples out and let go.+#[test]+fn a_read_only_transaction_costs_far_less_memory_than_the_copy() {+ let store = Store::new().unwrap();+ seed(&store, N);++ // (a) Hold a transaction and scan it. Nothing is written, so the change+ // set the vendor's warning is about should stay empty.+ let base = live();+ let txn = store.start_transaction().unwrap();+ let mut seen = 0usize;+ for q in txn.quads_for_pattern(None, None, None, None) {+ let _ = q.unwrap();+ seen += 1;+ }+ let held = live().saturating_sub(base);+ txn.commit().unwrap();+ assert_eq!(seen, N, "the scan did not see the whole store");++ // (b) The copy: the owned value 0010 builds, as three Strings per triple,+ // which is the shape `GraphStore::all_triples` produces.+ let base2 = live();+ let mut owned: Vec<(String, String, String)> = Vec::new();+ for q in store.iter() {+ let q = q.unwrap();+ owned.push((+ q.subject.to_string(),+ q.predicate.to_string(),+ q.object.to_string(),+ ));+ }+ let copied = live().saturating_sub(base2);+ assert_eq!(owned.len(), N);++ println!("triples {N}");+ println!("held open, read-only txn {held} bytes");+ println!("copied out, owned value {copied} bytes");+ println!("ratio copy:txn {:.1}x", copied as f64 / held.max(1) as f64);++ assert!(+ copied > held * 4,+ "the copy ({copied} bytes) is not materially more expensive than holding a read-only \+ transaction ({held} bytes) over {N} triples. If that is now true, decision 0010 is \+ paying memory for no isolation it could not get more cheaply, and the trade in it \+ should be re-argued rather than this assertion relaxed."+ );+ // The point of the first number: a read-only transaction does not+ // accumulate a change set, so the vendor's warning is about writes.+ assert!(+ held < copied / 4,+ "a read-only transaction held {held} bytes over {N} triples, which is not the flat \+ cost the vendor's warning implies for a transaction that writes nothing"+ );+}