From 0790d1ee42365c67c1b24d50df8ad8de2f205c5f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 19:13:11 +0100 Subject: [PATCH 01/11] cultcache-rs: redb write transaction refuses a second type under a held key (rs-redb-one-record-per-key) Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-rs/CHANGELOG.md | 4 + packages/cultcache-rs/src/lib.rs | 162 ++++++++++++++++++++++++++++- 2 files changed, 165 insertions(+), 1 deletion(-) diff --git a/packages/cultcache-rs/CHANGELOG.md b/packages/cultcache-rs/CHANGELOG.md index af5bbd9e..fd9542f6 100644 --- a/packages/cultcache-rs/CHANGELOG.md +++ b/packages/cultcache-rs/CHANGELOG.md @@ -11,6 +11,10 @@ only in git history. - `CultCache::update_with_attempts` and the conditional `update`: each attempt reads the record from its home store with its content version in one read, applies a function to a copy and commits only over that version, rerunning on a lost race (default five attempts). The result is `CultUpdateResult`, outcome `Updated`, `Declined` (the function returned `None`) or `LostRace`, with the cache's document. Public types `CultStoredRecord`, `CultCommitIf`, `CultUpdateOutcome`, `CultUpdateResult`. - `CacheBackingStore::read(key)` and `commit_if(entry, expected)`, provided methods whose defaults refuse with an error naming the store kind; `SingleFileMessagePackBackingStore` implements both. The content version is the lowercase hex SHA-256 of the record re-encoded as the store file writes it (key, schema id, `stored_at`, payload). It equals the SHA-256 of the record's bytes in the file, and so the C# reference's `tests/vectors/content-version`, whenever the file's MessagePack encodings are minimal, which every runtime's writer produces; a hand-edited file with a non-minimal encoding (for example a `str8` key that fits a fixstr) hashes differently from its slice here. New dependency `sha2` 0.10 and eight new lockfile crates: `sha2`, `digest`, `block-buffer`, `crypto-common`, `generic-array`, `typenum`, `cpufeatures`, `version_check`. +### Fixed + +- The redb stores refuse, inside the write transaction, a write that would put a second type under a key another writer holds (a `SchemaConflictError` naming the key and both types, nothing committed), as the single-file store does; a row under the same schema id and another type name is replaced. Before, a cache that pulled before another writer added a type at the key wrote beside it and every later pull refused the store. + ### Changed - `CultCache::delete::` of a key nothing holds now refuses, as `put` and `is_writable` do, when `T` has no home store ("No backing store is registered…") or when a store carries a foreign record at the key or another registered type holds it (before: `Ok(false)`). diff --git a/packages/cultcache-rs/src/lib.rs b/packages/cultcache-rs/src/lib.rs index 614f7861..40e9b740 100644 --- a/packages/cultcache-rs/src/lib.rs +++ b/packages/cultcache-rs/src/lib.rs @@ -3014,10 +3014,56 @@ fn read_redb_entry( .transpose() } +/// Every row a redb table holds at `key`, whatever its type. Identities sort by their encoded (type, key), and every row of one +/// type shares the prefix `0x92` + msgpack str(type), so the types are walked by skip-scan: read the first row at or after a +/// bound, point-get that type's row at `key`, then continue from the successor of the type's prefix. O(types x log n), not O(n). +fn rows_at_key<'a>(table: &impl ReadableTable<&'a [u8], &'a [u8]>, key: &str) -> Result> { + let mut rows = Vec::new(); + let mut lower = Vec::::new(); + loop { + let first = match table.range::<&[u8]>(lower.as_slice()..)?.next() { + Some(row) => row?.0.value().to_vec(), + None => return Ok(rows), + }; + let (held_type, _): (String, String) = + rmp_serde::from_slice(&first).context("failed to decode redb CultCache identity")?; + let identity = rmp_serde::to_vec(&entry_id_parts(&held_type, key)).context("failed to encode CultCache identity")?; + if let Some(value) = table.get(identity.as_slice())? { + rows.push( + decode_grown(value.value()) + .map_err(opaque_decode_error) + .context("failed to decode redb CultCache envelope")?, + ); + } + let mut prefix = vec![0x92u8]; + prefix.extend(rmp_serde::to_vec(&held_type).context("failed to encode CultCache type")?); + while prefix.last() == Some(&0xFF) { + prefix.pop(); + } + match prefix.last_mut() { + Some(last) => *last += 1, + None => return Ok(rows), + } + lower = prefix; + } +} + +/// The one insert of a redb row, and the store's own judge of one record per key (the rule `settle_one_record_per_key` holds +/// for the single-file store): the write transaction is the lock. A row at the key under another schema id refuses the write +/// as a retype, nothing committed; a row under the same schema id and another type name (a rename) is replaced. fn insert_redb_entry( table: &mut redb::Table<&[u8], &[u8]>, entry: &CultCacheEnvelope, ) -> Result<()> { + for held in rows_at_key(&*table, &entry.key)? { + if held.r#type == entry.r#type { + continue; + } + if schema_identity(&held) != schema_identity(entry) { + return Err(retype_conflict(&held, entry)); + } + table.remove(redb_identity(&held)?.as_slice())?; + } let key = redb_identity(entry)?; let value = rmp_serde::to_vec(entry).context("failed to encode redb CultCache envelope")?; table.insert(key.as_slice(), value.as_slice())?; @@ -4591,7 +4637,7 @@ fn retype_conflict(held: &CultCacheEnvelope, written: &CultCacheEnvelope) -> any /// The commit guard every single-file write passes: a store holds one record per key. Two entries under a key whose schema /// ids differ are a retype and are refused with the key and both types, nothing written. Two under one schema id are one /// record: a written entry replaces the held one it owns (a type renamed under a stable id), the held one being what the file -/// already carries. +/// already carries. The redb stores pass the same rule in `insert_redb_entry`. fn settle_one_record_per_key(entries: &[CultCacheEnvelope], disk: &DiskStore) -> Result> { let arrived: BTreeMap<(String, String), &CultCacheEnvelope> = disk.envelopes.iter().map(|entry| (entry_id(entry), entry)).collect(); let held = |entry: &CultCacheEnvelope| arrived.get(&entry_id(entry)) == Some(&entry); @@ -9226,6 +9272,120 @@ mod tests { Ok(()) } + fn open_redb_cache(path: &Path, owned: Option<&OwnedRedbMessagePackBackingStore>) -> Result { + let mut cache = CultCache::new(); + cache.register_registry(TestEntries)?; + match owned { + Some(handle) => cache.add_generic_backing_store(handle.clone())?, + None => cache.add_generic_backing_store(RedbMessagePackBackingStore::new(path)?)?, + } + cache.pull_all_backing_stores()?; + Ok(cache) + } + + #[test] + fn a_stale_cache_cannot_put_a_second_type_under_a_key_on_redb() -> Result<()> { + let temp = tempfile::tempdir()?; + let owned = OwnedRedbMessagePackBackingStore::new(temp.path().join("owned.db"))?; + for (name, handle) in [("plain", None), ("owned", Some(&owned))] { + let path = temp.path().join("plain.db"); + let mut stale = open_redb_cache(&path, handle)?; + let mut other = open_redb_cache(&path, handle)?; + other.put("k", &Note { title: "n".to_string(), body: "b".to_string() })?; + let refused = stale.put("k", &Settings { theme: "s".to_string(), retries: 1 }).unwrap_err(); + let conflict = refused.downcast_ref::().expect(name); + assert_eq!(conflict.record_key, "k"); + assert_eq!(conflict.schema_names, ["note", "settings"]); + let fresh = open_redb_cache(&path, handle)?; + assert_eq!(fresh.get_required::("k")?.title, "n", "{name}"); + assert!(fresh.get::("k")?.is_none(), "{name}"); + } + Ok(()) + } + + #[test] + fn a_stale_redb_batch_with_a_retype_writes_nothing() -> Result<()> { + let temp = tempfile::tempdir()?; + let owned = OwnedRedbMessagePackBackingStore::new(temp.path().join("owned.db"))?; + for (name, handle) in [("plain", None), ("owned", Some(&owned))] { + let path = temp.path().join("plain.db"); + let mut stale = open_redb_cache(&path, handle)?; + let mut other = open_redb_cache(&path, handle)?; + other.put("k", &Note { title: "n".to_string(), body: "b".to_string() })?; + let clean = stale.prepare_entry("clean", &Settings { theme: "s".to_string(), retries: 1 })?.0; + let retyped = stale.prepare_entry("k", &Settings { theme: "s".to_string(), retries: 1 })?.0; + let refused = stale.put_prepared_batch(vec![clean, retyped]).unwrap_err(); + assert!(refused.downcast_ref::().is_some(), "{name}"); + let fresh = open_redb_cache(&path, handle)?; + assert!(fresh.get::("clean")?.is_none(), "{name}: the clean key is absent"); + assert_eq!(fresh.get_required::("k")?.title, "n", "{name}"); + } + Ok(()) + } + + #[test] + fn a_redb_batch_with_two_schema_ids_at_one_key_is_refused() -> Result<()> { + let temp = tempfile::tempdir()?; + let stores: Vec> = vec![ + Box::new(RedbMessagePackBackingStore::new(temp.path().join("plain.db"))?), + Box::new(OwnedRedbMessagePackBackingStore::new(temp.path().join("owned.db"))?), + ]; + for mut store in stores { + let refused = store + .push_all(&[test_envelope("a", "k", b"1"), test_envelope("b", "k", b"2")], PushAllOptions::default()) + .unwrap_err(); + assert!(refused.downcast_ref::().is_some()); + assert!(store.pull_all()?.is_empty(), "neither row is written"); + } + Ok(()) + } + + #[test] + fn redb_skip_scan_finds_a_row_of_any_type() -> Result<()> { + let temp = tempfile::tempdir()?; + let database = redb::Database::create(temp.path().join("scan.db"))?; + let write = database.begin_write()?; + { + let mut table = write.open_table(REDB_ENVELOPES)?; + for (kind, key) in [("a", "x"), ("a", "y"), ("ab", "x"), ("ab", "z"), ("b", "y"), ("zz", "x"), ("\u{ff}", "x")] { + let row = test_envelope(kind, key, b"p"); + table.insert(redb_identity(&row)?.as_slice(), rmp_serde::to_vec(&row)?.as_slice())?; + } + let mut at = |key: &str| -> Result> { + let mut types: Vec = rows_at_key(&table, key)?.into_iter().map(|row| row.r#type).collect(); + types.sort(); + Ok(types) + }; + assert_eq!(at("x")?, ["a", "ab", "zz", "\u{ff}"]); + assert_eq!(at("y")?, ["a", "b"]); + assert_eq!(at("z")?, ["ab"]); + assert!(at("missing")?.is_empty()); + } + write.commit()?; + Ok(()) + } + + #[test] + fn redb_same_schema_id_rename_replaces() -> Result<()> { + let temp = tempfile::tempdir()?; + let stores: Vec> = vec![ + Box::new(RedbMessagePackBackingStore::new(temp.path().join("plain.db"))?), + Box::new(OwnedRedbMessagePackBackingStore::new(temp.path().join("owned.db"))?), + ]; + for mut store in stores { + let mut old = test_envelope("old", "k", b"1"); + old.schema_id = Some("X".to_string()); + let mut new = test_envelope("new", "k", b"2"); + new.schema_id = Some("X".to_string()); + store.push(&old)?; + store.push(&new)?; + let rows = store.pull_all()?; + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].r#type, "new"); + } + Ok(()) + } + #[test] fn every_store_merges_push_all_and_lands_the_last_of_a_repeated_key() -> Result<()> { let temp = tempfile::tempdir()?; -- 2.47.3 From 1205b9b04d0d49f4a7b4048a1593859fcffec79b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 19:21:29 +0100 Subject: [PATCH 02/11] cultcache-rs: rows_at_key takes a static-keyed table; drop a stray mut Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-rs/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/cultcache-rs/src/lib.rs b/packages/cultcache-rs/src/lib.rs index 40e9b740..6e7831b2 100644 --- a/packages/cultcache-rs/src/lib.rs +++ b/packages/cultcache-rs/src/lib.rs @@ -3017,7 +3017,7 @@ fn read_redb_entry( /// Every row a redb table holds at `key`, whatever its type. Identities sort by their encoded (type, key), and every row of one /// type shares the prefix `0x92` + msgpack str(type), so the types are walked by skip-scan: read the first row at or after a /// bound, point-get that type's row at `key`, then continue from the successor of the type's prefix. O(types x log n), not O(n). -fn rows_at_key<'a>(table: &impl ReadableTable<&'a [u8], &'a [u8]>, key: &str) -> Result> { +fn rows_at_key(table: &impl ReadableTable<&'static [u8], &'static [u8]>, key: &str) -> Result> { let mut rows = Vec::new(); let mut lower = Vec::::new(); loop { @@ -9351,7 +9351,7 @@ mod tests { let row = test_envelope(kind, key, b"p"); table.insert(redb_identity(&row)?.as_slice(), rmp_serde::to_vec(&row)?.as_slice())?; } - let mut at = |key: &str| -> Result> { + let at = |key: &str| -> Result> { let mut types: Vec = rows_at_key(&table, key)?.into_iter().map(|row| row.r#type).collect(); types.sort(); Ok(types) -- 2.47.3 From 02cc7312279f90cb95e46ccaa75df1084dc3d72e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 19:26:00 +0100 Subject: [PATCH 03/11] cultcache-rs: tests that built two types at one redb key now build them directly or use distinct keys Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-rs/src/lib.rs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/packages/cultcache-rs/src/lib.rs b/packages/cultcache-rs/src/lib.rs index 6e7831b2..4a2f974c 100644 --- a/packages/cultcache-rs/src/lib.rs +++ b/packages/cultcache-rs/src/lib.rs @@ -5610,9 +5610,16 @@ mod tests { let (mut stamped, _) = cache.prepare_entry("shared", ¬e_one())?; stamped.schema_id = Some(Settings::TYPE.to_string()); { - let mut store = RedbMessagePackBackingStore::new(&path)?; - store.push(&settings)?; - store.push(&stamped)?; + // Written under the store's own guard this pair is refused, so the foreign state is put in the table directly. + let database = redb::Database::create(&path)?; + let write = database.begin_write()?; + { + let mut table = write.open_table(REDB_ENVELOPES)?; + for row in [&settings, &stamped] { + table.insert(redb_identity(row)?.as_slice(), rmp_serde::to_vec(row)?.as_slice())?; + } + } + write.commit()?; } cache.add_generic_backing_store(RedbMessagePackBackingStore::new(&path)?)?; let error = cache.pull_all_backing_stores().unwrap_err(); @@ -6203,7 +6210,7 @@ mod tests { let temp = tempfile::tempdir()?; let path = temp.path().join("keyed.cc"); let model = test_envelope("model", "shared", b"one"); - let receipt = test_envelope("receipt", "shared", b"two"); + let receipt = test_envelope("receipt", "other", b"two"); { let mut store = RedbMessagePackBackingStore::new(&path)?; store.push(&model)?; @@ -6388,7 +6395,7 @@ mod tests { OwnedRedbMessagePackBackingStore::new(temp.path().join("compact-owned.cc"))?; let old_head = test_envelope("retention", "current", b"one"); let retired_a = test_envelope("claim", "a", b"terminal"); - let retired_b = test_envelope("receipt", "a", b"terminal"); + let retired_b = test_envelope("receipt", "b", b"terminal"); owner.push(&old_head)?; owner.push(&retired_a)?; owner.push(&retired_b)?; -- 2.47.3 From 5e3435f6fb57865dcdc69e434ec53dad226e7300 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:06:10 +0100 Subject: [PATCH 04/11] cultcache-rs: a unique-indexed write onto a moved store is a write conflict that reloads (rs-stale-write-gate) Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-rs/CHANGELOG.md | 3 + packages/cultcache-rs/README.md | 5 + packages/cultcache-rs/src/lib.rs | 453 ++++++++++++++++++-- packages/cultcache-rs/tests/unique_index.rs | 204 ++++++++- 4 files changed, 631 insertions(+), 34 deletions(-) diff --git a/packages/cultcache-rs/CHANGELOG.md b/packages/cultcache-rs/CHANGELOG.md index fd9542f6..a5216284 100644 --- a/packages/cultcache-rs/CHANGELOG.md +++ b/packages/cultcache-rs/CHANGELOG.md @@ -8,15 +8,18 @@ only in git history. ### Added +- `CacheBackingStore::push_all_unchanged(entries)` returning `CultPushUnchanged` (`Committed { stamps }` or `Changed { changed_keys }`), a provided method whose default refuses with an error naming the store kind and `push_all_unchanged`: a custom store keeps compiling and its writes of indexed types are refused until it implements it. The three bundled stores keep what each handle last read or wrote (a clone starts empty). Public `CultCacheWriteConflict { record_keys, changed_keys }`. - `CultCache::update_with_attempts` and the conditional `update`: each attempt reads the record from its home store with its content version in one read, applies a function to a copy and commits only over that version, rerunning on a lost race (default five attempts). The result is `CultUpdateResult`, outcome `Updated`, `Declined` (the function returned `None`) or `LostRace`, with the cache's document. Public types `CultStoredRecord`, `CultCommitIf`, `CultUpdateOutcome`, `CultUpdateResult`. - `CacheBackingStore::read(key)` and `commit_if(entry, expected)`, provided methods whose defaults refuse with an error naming the store kind; `SingleFileMessagePackBackingStore` implements both. The content version is the lowercase hex SHA-256 of the record re-encoded as the store file writes it (key, schema id, `stored_at`, payload). It equals the SHA-256 of the record's bytes in the file, and so the C# reference's `tests/vectors/content-version`, whenever the file's MessagePack encodings are minimal, which every runtime's writer produces; a hand-edited file with a non-minimal encoding (for example a `str8` key that fits a fixstr) hashes differently from its slice here. New dependency `sha2` 0.10 and eight new lockfile crates: `sha2`, `digest`, `block-buffer`, `crypto-common`, `generic-array`, `typenum`, `cpufeatures`, `version_check`. ### Fixed +- A cache whose store changed since it last read it no longer lands a write of a type with a unique index: `put`, `put_envelope`, `put_raw_envelope`, `put_prepared_batch` and `update` check, under the store's own exclusion, that every record is as the cache last read or wrote it, and otherwise write nothing, reload the changed records and return `CultCacheWriteConflict` (naming keys, never values; `update` counts it as a lost attempt and retries), as C# `RefuseWriteIntoMovedStore` does. Before, the judge saw only the cache's image, so a stale cache could write a value another writer already held at another key and every later pull refused the store. The gate also refuses when the other writer changed an unrelated key. Writes of types without an index are unchanged. If the reload fails the cache is refused (`CultCacheLoadRefused`) and the reload error is the conflict's source. - The redb stores refuse, inside the write transaction, a write that would put a second type under a key another writer holds (a `SchemaConflictError` naming the key and both types, nothing committed), as the single-file store does; a row under the same schema id and another type name is replaced. Before, a cache that pulled before another writer added a type at the key wrote beside it and every later pull refused the store. ### Changed +- A redb store that already holds two types at one key (written by a build before the one-record-per-key rule) refuses a write of either held type at that key with `SchemaConflictError`, where it once succeeded; delete one of the two rows (`delete(type, key)` removes that type's row alone), then write. - `CultCache::delete::` of a key nothing holds now refuses, as `put` and `is_writable` do, when `T` has no home store ("No backing store is registered…") or when a store carries a foreign record at the key or another registered type holds it (before: `Ok(false)`). - `is_stored_at_stamp(&str)` (new, public) is the one shape a peer's `storedAt` must parse as, pinned by `tests/vectors/stored-at-stamp` (RFC 3339 `YYYY-MM-DDThh:mm:ss`, a 1 to 9 digit fraction, `Z` or `+hh:mm`/`-hh:mm`; uppercase `T`/`Z`, a real date, seconds 00-59, years 0001-9999), hand-checked because `chrono`'s RFC 3339 reader takes other shapes. `put_raw_envelope` and `put_prepared_batch` refuse a `stored_at` that is not a stamp (before: only a blank one) and mint nothing (variants:ruling:raw-put-without-stamp-refused). - The single-file store's `push`, `push_all` and `commit_if` stamp a replacing write strictly later than the record it replaces at the same key (a staged stamp stands only when it parses and is strictly later; otherwise the stamp is minted as the replaced stamp plus one microsecond, or now if later), with no identical-content exception, as C# does. A stamp with no successor (the replaced stamp is at year 9999's last microsecond) refuses the write and writes nothing, as C# `MintStoredAt` does. `commit_if` replaces only the record of the entry's own type under the key, so a retype is refused as `push` refuses it. The cache holds the stamp the store wrote. The redb stores and the store-level exact-envelope writes (`compare_and_swap_entry` and its family) still write the caller's envelope unchanged. diff --git a/packages/cultcache-rs/README.md b/packages/cultcache-rs/README.md index d52fdea2..986c6cd4 100644 --- a/packages/cultcache-rs/README.md +++ b/packages/cultcache-rs/README.md @@ -444,6 +444,11 @@ A store whose elements hold an id is marked `cultcache.store.v3` by the C# runti - `cache.get_by_index::("callsign", "Lucent-7")`: `#[cultcache(index)]` is unique. Within one type no two records hold one non-blank value of the alias; a put, batch or load that would make two is refused, naming both keys and the alias, and writes nothing. A grouping (faction, kind, status) is not an index: filter `get_all`. + A cache whose store changed since it last read it (another writer added, replaced or removed any record) cannot + check uniqueness against what it has not seen: its write of an indexed type returns `CultCacheWriteConflict` + (`error.downcast_ref`), writes nothing and reloads the changed records; retry the write against them. `update` + retries on its own. Writes of types without an index merge as before. A custom `CacheBackingStore` needs + `push_all_unchanged` for indexed writes, else they are refused. - generated extractors instead of reflection strings 4. **Schema/version metadata** diff --git a/packages/cultcache-rs/src/lib.rs b/packages/cultcache-rs/src/lib.rs index 4a2f974c..b7d21153 100644 --- a/packages/cultcache-rs/src/lib.rs +++ b/packages/cultcache-rs/src/lib.rs @@ -1307,6 +1307,74 @@ pub enum CultCommitIf { Mismatch, } +/// The verdict of [`CacheBackingStore::push_all_unchanged`]: the write landed and carries one stamp per entry (as `push_all` +/// returns), or the store held records this handle had not read as they now are and nothing was written. `changed_keys` are +/// the keys whose record differs from what the handle last read (a record another writer added, replaced or removed), in UTF-16 +/// order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CultPushUnchanged { + Committed { stamps: Vec }, + Changed { changed_keys: Vec }, +} + +/// What one store handle last read or wrote: key -> content version. It decides only whether a gated write may land, never a +/// record's content. A clone starts empty (a clone is another reader), every handle compares equal, and it prints as a count. +#[derive(Default)] +struct LastRead(std::sync::Mutex>); + +impl LastRead { + fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap> { + self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Replaces the whole map with the versions of `entries`: a pull read all of them. + fn set_all(&self, entries: &[CultCacheEnvelope]) { + *self.lock() = entries.iter().map(|entry| (entry.key.clone(), record_version(entry))).collect(); + } + + fn record(&self, entry: &CultCacheEnvelope) { + self.lock().insert(entry.key.clone(), record_version(entry)); + } + + fn forget(&self, key: &str) { + self.lock().remove(key); + } + + /// The keys at which `held` (every record the store holds now) differs from what was last read, in UTF-16 order. + fn changed_keys(&self, held: &[CultCacheEnvelope]) -> Vec { + let read = self.lock(); + let now: BTreeMap<&str, String> = held.iter().map(|entry| (entry.key.as_str(), record_version(entry))).collect(); + let mut changed: Vec = now + .iter() + .filter(|(key, version)| read.get(**key) != Some(*version)) + .map(|(key, _)| (*key).to_string()) + .chain(read.keys().filter(|key| !now.contains_key(key.as_str())).cloned()) + .collect(); + changed.sort_by(|left, right| utf16_cmp(left, right)); + changed + } +} + +impl Clone for LastRead { + fn clone(&self) -> Self { + Self::default() + } +} + +impl PartialEq for LastRead { + fn eq(&self, _: &Self) -> bool { + true + } +} + +impl Eq for LastRead {} + +impl std::fmt::Debug for LastRead { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "LastRead({})", self.lock().len()) + } +} + /// How [`CultCache::update`] ended. `Declined` wrote nothing because `apply` returned `None`; `LostRace` wrote nothing because /// every attempt found the record changed under it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -1397,16 +1465,28 @@ pub trait CacheBackingStore: Send { std::any::type_name::() )) } + + /// [`CacheBackingStore::push_all`] that writes only if every record the store holds is as this handle last read or wrote it, + /// compared under the store's own exclusion. If any differs (a record another writer added, replaced or removed) nothing is + /// written and the keys that moved are returned. A cache needs this for a write of a type with a unique index, whose rule + /// resolves against other records; a store without it refuses such a write. + fn push_all_unchanged(&mut self, _entries: &[CultCacheEnvelope]) -> Result { + Err(anyhow!( + "{} has no push_all_unchanged: a write of a type with a unique index needs push_all_unchanged", + std::any::type_name::() + )) + } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct SingleFileMessagePackBackingStore { path: PathBuf, + last_read: LastRead, } impl SingleFileMessagePackBackingStore { pub fn new(path: impl Into) -> Self { - Self { path: path.into() } + Self { path: path.into(), last_read: LastRead::default() } } pub fn path(&self) -> &Path { @@ -2076,9 +2156,14 @@ fn unique_batch_ids( impl CacheBackingStore for SingleFileMessagePackBackingStore { fn pull_all(&self) -> Result> { if is_absent(&self.path)? && is_absent(&self.lock_path())? { + self.last_read.set_all(&[]); return Ok(Vec::new()); } - self.with_shared_lock(|| self.read_all_unlocked()) + self.with_shared_lock(|| { + let entries = self.read_all_unlocked()?; + self.last_read.set_all(&entries); + Ok(entries) + }) } fn push(&mut self, entry: &CultCacheEnvelope) -> Result { @@ -2090,6 +2175,7 @@ impl CacheBackingStore for SingleFileMessagePackBackingStore { entries.push(entry.clone()); entries.sort_by_key(entry_id); self.write_all_unlocked(&entries)?; + self.last_read.record(&entry); Ok(entry.stored_at) }) } @@ -2120,6 +2206,7 @@ impl CacheBackingStore for SingleFileMessagePackBackingStore { entries.push(entry.clone()); entries.sort_by_key(entry_id); self.write_all_unlocked(&entries)?; + self.last_read.record(&entry); Ok(CultCommitIf::Committed { stored_at: entry.stored_at }) }) } @@ -2128,7 +2215,9 @@ impl CacheBackingStore for SingleFileMessagePackBackingStore { self.with_exclusive_lock(|| { let mut entries = self.read_all_unlocked()?; entries.retain(|candidate| entry_id(candidate) != entry_id(entry)); - self.write_all_unlocked(&entries) + self.write_all_unlocked(&entries)?; + self.last_read.forget(&entry.key); + Ok(()) }) } @@ -2140,26 +2229,46 @@ impl CacheBackingStore for SingleFileMessagePackBackingStore { return Ok(Vec::new()); } - // Of entries sharing a key and a schema id the last one given is the record, whatever their type names (a type - // renamed under a stable id); it replaces the held record under that key and schema id. A second schema id - // under a key reaches the commit guard, which judges the merged store. - let mut merged = self.read_all_unlocked()?; - let mut by_id = BTreeMap::<(String, String), CultCacheEnvelope>::new(); - for entry in entries { - by_id.insert((schema_identity(entry).to_string(), entry.key.clone()), restamped_over(entry, &merged)?); - } - let replaced: BTreeSet<_> = by_id.values().map(entry_id).collect(); - merged.retain(|held| !replaced.contains(&entry_id(held))); - let stamps = entries - .iter() - .map(|entry| by_id[&(schema_identity(entry).to_string(), entry.key.clone())].stored_at.clone()) - .collect(); - merged.extend(by_id.into_values()); - merged.sort_by_key(entry_id); - self.write_all_unlocked(&merged)?; - Ok(stamps) + self.merge_unlocked(entries) }) } + + fn push_all_unchanged(&mut self, entries: &[CultCacheEnvelope]) -> Result { + self.with_exclusive_lock(|| { + let changed_keys = self.last_read.changed_keys(&self.read_all_unlocked()?); + if !changed_keys.is_empty() { + return Ok(CultPushUnchanged::Changed { changed_keys }); + } + Ok(CultPushUnchanged::Committed { stamps: self.merge_unlocked(entries)? }) + }) + } +} + +impl SingleFileMessagePackBackingStore { + /// `push_all`'s write, under the exclusive lock the caller holds. + fn merge_unlocked(&self, entries: &[CultCacheEnvelope]) -> Result> { + // Of entries sharing a key and a schema id the last one given is the record, whatever their type names (a type + // renamed under a stable id); it replaces the held record under that key and schema id. A second schema id + // under a key reaches the commit guard, which judges the merged store. + let mut merged = self.read_all_unlocked()?; + let mut by_id = BTreeMap::<(String, String), CultCacheEnvelope>::new(); + for entry in entries { + by_id.insert((schema_identity(entry).to_string(), entry.key.clone()), restamped_over(entry, &merged)?); + } + let replaced: BTreeSet<_> = by_id.values().map(entry_id).collect(); + merged.retain(|held| !replaced.contains(&entry_id(held))); + let stamps = entries + .iter() + .map(|entry| by_id[&(schema_identity(entry).to_string(), entry.key.clone())].stored_at.clone()) + .collect(); + merged.extend(by_id.values().cloned()); + merged.sort_by_key(entry_id); + self.write_all_unlocked(&merged)?; + for entry in by_id.values() { + self.last_read.record(entry); + } + Ok(stamps) + } } const REDB_ENVELOPES: TableDefinition<&[u8], &[u8]> = TableDefinition::new("cultcache_envelopes"); @@ -2170,6 +2279,7 @@ const REDB_ENVELOPES: TableDefinition<&[u8], &[u8]> = TableDefinition::new("cult #[derive(Clone)] pub struct RedbMessagePackBackingStore { path: PathBuf, + last_read: LastRead, } impl std::fmt::Debug for RedbMessagePackBackingStore { @@ -2191,7 +2301,7 @@ impl RedbMessagePackBackingStore { fs::create_dir_all(parent) .with_context(|| format!("failed to create {}", parent.display()))?; } - let store = Self { path }; + let store = Self { path, last_read: LastRead::default() }; store.with_database(|database| { let write = database.begin_write()?; { @@ -2542,6 +2652,7 @@ struct OwnedRedbInner { pub struct OwnedRedbMessagePackBackingStore { path: PathBuf, inner: Arc, + last_read: LastRead, } impl std::fmt::Debug for OwnedRedbMessagePackBackingStore { @@ -2612,6 +2723,7 @@ impl OwnedRedbMessagePackBackingStore { _owner_lock: owner_lock, file_identity: held_identity, }), + last_read: LastRead::default(), }) } @@ -2916,7 +3028,9 @@ impl CacheBackingStore for OwnedRedbMessagePackBackingStore { fn pull_all(&self) -> Result> { let read = self.inner.database.begin_read()?; let table = read.open_table(REDB_ENVELOPES)?; - read_all_redb(&table) + let entries = read_all_redb(&table)?; + self.last_read.set_all(&entries); + Ok(entries) } fn push(&mut self, entry: &CultCacheEnvelope) -> Result { @@ -2926,6 +3040,7 @@ impl CacheBackingStore for OwnedRedbMessagePackBackingStore { insert_redb_entry(&mut table, entry)?; } write.commit()?; + self.last_read.record(entry); Ok(entry.stored_at.clone()) } @@ -2937,6 +3052,7 @@ impl CacheBackingStore for OwnedRedbMessagePackBackingStore { table.remove(key.as_slice())?; } write.commit()?; + self.last_read.forget(&entry.key); Ok(()) } @@ -2950,8 +3066,37 @@ impl CacheBackingStore for OwnedRedbMessagePackBackingStore { } } write.commit()?; + entries.iter().for_each(|entry| self.last_read.record(entry)); Ok(entries.iter().map(|entry| entry.stored_at.clone()).collect()) } + + fn push_all_unchanged(&mut self, entries: &[CultCacheEnvelope]) -> Result { + push_all_unchanged_redb(&self.inner.database, &self.last_read, entries) + } +} + +/// The gated batch write of both redb stores: the write transaction is the exclusion, the gate reads every row inside it, and a +/// moved store aborts it. +fn push_all_unchanged_redb(database: &Database, last_read: &LastRead, entries: &[CultCacheEnvelope]) -> Result { + unique_batch_ids(entries, "push all")?; + let write = database.begin_write()?; + let changed_keys = { + let mut table = write.open_table(REDB_ENVELOPES)?; + let changed_keys = last_read.changed_keys(&read_all_redb(&table)?); + if changed_keys.is_empty() { + for entry in entries { + insert_redb_entry(&mut table, entry)?; + } + } + changed_keys + }; + if !changed_keys.is_empty() { + write.abort()?; + return Ok(CultPushUnchanged::Changed { changed_keys }); + } + write.commit()?; + entries.iter().for_each(|entry| last_read.record(entry)); + Ok(CultPushUnchanged::Committed { stamps: entries.iter().map(|entry| entry.stored_at.clone()).collect() }) } fn redb_lock_path(path: &Path) -> PathBuf { @@ -3091,7 +3236,9 @@ impl CacheBackingStore for RedbMessagePackBackingStore { self.with_database(|database| { let read = database.begin_read()?; let table = read.open_table(REDB_ENVELOPES)?; - read_all_redb(&table) + let entries = read_all_redb(&table)?; + self.last_read.set_all(&entries); + Ok(entries) }) } @@ -3103,6 +3250,7 @@ impl CacheBackingStore for RedbMessagePackBackingStore { insert_redb_entry(&mut table, entry)?; } write.commit()?; + self.last_read.record(entry); Ok(entry.stored_at.clone()) }) } @@ -3116,6 +3264,7 @@ impl CacheBackingStore for RedbMessagePackBackingStore { table.remove(key.as_slice())?; } write.commit()?; + self.last_read.forget(&entry.key); Ok(()) }) } @@ -3131,9 +3280,14 @@ impl CacheBackingStore for RedbMessagePackBackingStore { } } write.commit()?; + entries.iter().for_each(|entry| self.last_read.record(entry)); Ok(entries.iter().map(|entry| entry.stored_at.clone()).collect()) }) } + + fn push_all_unchanged(&mut self, entries: &[CultCacheEnvelope]) -> Result { + self.with_database(|database| push_all_unchanged_redb(database, &self.last_read, entries)) + } } struct CultCacheStoreRegistration { @@ -3192,6 +3346,58 @@ impl std::fmt::Display for CultCacheLoadRefused { impl std::error::Error for CultCacheLoadRefused {} +/// A write of a type with a unique index refused because its store changed since this cache last read it. Uniqueness resolves +/// against other records, which the cache's image may lack, so nothing was written; the cache reloaded the changed records (its +/// image now holds them) and the write can be retried against what the store holds now. If the reload failed, the cache is +/// refused as any failed pull leaves it, and the reload error is this error's source. Names keys, never values. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CultCacheWriteConflict { + /// The keys this write would have written, in UTF-16 order. + pub record_keys: Vec, + /// The keys whose records differ from what the cache last read, in UTF-16 order. + pub changed_keys: Vec, + reload_failed: bool, +} + +impl std::fmt::Display for CultCacheWriteConflict { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let quoted = |keys: &[String]| keys.iter().map(|key| format!("'{key}'")).collect::>().join(", "); + write!( + formatter, + "The backing store changed since this cache last read it, and it holds a record with a unique index, which resolve against other records; nothing was written. Records this write would have written: {}; records that changed: {}. {}", + quoted(&self.record_keys), + quoted(&self.changed_keys), + if self.reload_failed { + "Reloading them failed, so the cache is refused." + } else { + "The cache reloaded them; retry the write against what the store holds now." + } + ) + } +} + +impl std::error::Error for CultCacheWriteConflict {} + +/// How a landing reaches its home store. +enum LandAs { + /// One record, replacing what is there (`push`). + Record, + /// One record over the record at the given version (`commit_if`; `Some(None)`: over nothing). + Over(Option), + /// Many records, each replacing its own identity and nothing else (`push_all`). + Batch, +} + +/// What a landing found at its home store. +enum Landed { + /// Written; one stamp per record landed. + Stamps(Vec), + /// `LandAs::Over` found another version there; nothing was written. + Mismatch, + /// A gated landing found the store moved; nothing was written and the cache reloaded. + Moved(CultCacheWriteConflict), +} + /// A record a store holds that no registered type claims: carried, never served. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ForeignRecord { @@ -3842,7 +4048,11 @@ impl CultCache { .collect::>() .into_values() .collect(); - let stamps = self.stores[store_index].store.push_all(&landing, PushAllOptions::default())?; + let stamps = match self.land(store_index, &landing, LandAs::Batch)? { + Landed::Stamps(stamps) => stamps, + Landed::Moved(conflict) => return Err(conflict.into()), + Landed::Mismatch => unreachable!("a batch is not written over a version"), + }; if stamps.len() == landing.len() { for (entry, stamp) in landing.iter().zip(stamps) { if chrono::DateTime::parse_from_rfc3339(&stamp).is_ok() @@ -3894,6 +4104,38 @@ impl CultCache { Ok(()) } + /// The one door from the cache to a home store. A landing with an entry of a type that has a projector (a unique index) is + /// gated: its store must still hold what this cache last read, compared under the store's own exclusion by + /// `push_all_unchanged`, because the uniqueness judge only knows the cache's image. A store that moved is not written; the + /// cache reloads and the conflict comes back as `Moved` (a failed reload is the error, the conflict its context). Every + /// other landing reaches the store by its own door. + fn land(&mut self, home: usize, landing: &[CultCacheEnvelope], how: LandAs) -> Result { + if landing.iter().any(|entry| self.projectors.contains_key(&entry.r#type)) { + return match self.stores[home].store.push_all_unchanged(landing)? { + CultPushUnchanged::Committed { stamps } => Ok(Landed::Stamps(stamps)), + CultPushUnchanged::Changed { changed_keys } => { + let mut record_keys: Vec = landing.iter().map(|entry| entry.key.clone()).collect(); + record_keys.sort_by(|left, right| utf16_cmp(left, right)); + record_keys.dedup(); + let conflict = CultCacheWriteConflict { record_keys, changed_keys, reload_failed: false }; + match self.pull_all_backing_stores() { + Ok(()) => Ok(Landed::Moved(conflict)), + Err(error) => Err(error.context(CultCacheWriteConflict { reload_failed: true, ..conflict })), + } + } + }; + } + let store = &mut self.stores[home].store; + match how { + LandAs::Record => Ok(Landed::Stamps(vec![store.push(&landing[0])?])), + LandAs::Over(expected) => Ok(match store.commit_if(&landing[0], expected.as_deref())? { + CultCommitIf::Committed { stored_at } => Landed::Stamps(vec![stored_at]), + CultCommitIf::Mismatch => Landed::Mismatch, + }), + LandAs::Batch => Ok(Landed::Stamps(store.push_all(landing, PushAllOptions::default())?)), + } + } + /// The one landing of a single record, for `put`, `put_envelope`, `put_raw_envelope` and `update`: the global, retype and /// unique judges, then the home store's write, then the install of the stamp the store reports (kept only when it parses /// as RFC 3339, else the entry's own). `expected` is `None` for a blind write; `Some(version)` writes only over the record at @@ -3903,15 +4145,22 @@ impl CultCache { self.refuse_retype(&self.entries, &self.foreign, &entry)?; let change = self.judge_unique(&[&entry])?; if let Some(home) = self.home_index(&entry.r#type)? { - let stored_at = match expected { - None => self.stores[home].store.push(&entry)?, - Some(version) => match self.stores[home].store.commit_if(&entry, version.as_deref())? { - CultCommitIf::Committed { stored_at } => stored_at, - CultCommitIf::Mismatch => return Ok(false), - }, + let how = match expected { + None => LandAs::Record, + Some(version) => LandAs::Over(version), }; - if chrono::DateTime::parse_from_rfc3339(&stored_at).is_ok() { - entry.stored_at = stored_at; + let blind = matches!(how, LandAs::Record); + match self.land(home, std::slice::from_ref(&entry), how)? { + Landed::Stamps(stamps) => { + if let Some(stored_at) = stamps.into_iter().next() + && chrono::DateTime::parse_from_rfc3339(&stored_at).is_ok() + { + entry.stored_at = stored_at; + } + } + Landed::Mismatch => return Ok(false), + Landed::Moved(conflict) if blind => return Err(conflict.into()), + Landed::Moved(_) => return Ok(false), } } self.entries.insert(entry_id(&entry), entry); @@ -9347,6 +9596,144 @@ mod tests { Ok(()) } + #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] + #[cultcache(type = "indexed", schema = "tests.indexed")] + struct Indexed { + #[cultcache(key = 0, index = "Sku")] + sku: String, + } + + #[test] + fn a_store_without_the_door_refuses_indexed_writes() -> Result<()> { + let temp = tempfile::tempdir()?; + let mut cache = CultCache::new(); + cache.register_registry(TestEntries)?; + cache.register_entry_type::()?; + cache.add_generic_backing_store(RefusingBatchStore { + inner: SingleFileMessagePackBackingStore::new(temp.path().join("refusing.cc")), + refuse_batch: Arc::new(AtomicBool::new(false)), + })?; + cache.pull_all_backing_stores()?; + let refused = cache.put("k", &Indexed { sku: "S".to_string() }).unwrap_err(); + assert!(format!("{refused:#}").contains("push_all_unchanged"), "{refused:#}"); + assert!(cache.get::("k")?.is_none()); + cache.put("plain", &Note { title: "t".to_string(), body: "b".to_string() })?; + Ok(()) + } + + fn raw_rows(database: &Database, rows: &[&CultCacheEnvelope]) -> Result<()> { + let write = database.begin_write()?; + { + let mut table = write.open_table(REDB_ENVELOPES)?; + for row in rows { + table.insert(redb_identity(row)?.as_slice(), rmp_serde::to_vec(row)?.as_slice())?; + } + } + write.commit()?; + Ok(()) + } + + /// Both redb stores, each holding `rows` as an older build could have written them (two types at one key). + fn redb_stores_holding(temp: &Path, rows: &[&CultCacheEnvelope]) -> Result>> { + let plain = RedbMessagePackBackingStore::new(temp.join("plain.db"))?; + plain.with_database(|database| raw_rows(database, rows))?; + let owned = OwnedRedbMessagePackBackingStore::new(temp.join("owned.db"))?; + raw_rows(&owned.inner.database, rows)?; + Ok(vec![Box::new(plain), Box::new(owned)]) + } + + #[test] + fn a_row_of_the_same_type_under_another_schema_id_is_overwritten_not_refused() -> Result<()> { + let temp = tempfile::tempdir()?; + let mut old = test_envelope("a", "k", b"old"); + old.schema_id = Some("S1".to_string()); + for mut store in redb_stores_holding(temp.path(), &[&old])? { + let mut restamped = test_envelope("a", "k", b"new"); + restamped.schema_id = Some("S2".to_string()); + store.push(&restamped)?; + assert_eq!(store.pull_all()?, vec![restamped.clone()]); + store.push_all(std::slice::from_ref(&old), PushAllOptions::default())?; + assert_eq!(store.pull_all()?, vec![old.clone()]); + } + Ok(()) + } + + #[test] + fn a_store_holding_two_types_at_a_key_refuses_both_writes_until_one_is_deleted() -> Result<()> { + let temp = tempfile::tempdir()?; + let (a, b) = (test_envelope("a", "k", b"1"), test_envelope("b", "k", b"2")); + for mut store in redb_stores_holding(temp.path(), &[&a, &b])? { + // Neither held type can be rewritten while the other is held there. + for rewrite in [test_envelope("a", "k", b"3"), test_envelope("b", "k", b"3")] { + let refused = store.push(&rewrite).unwrap_err(); + assert!(refused.downcast_ref::().is_some(), "{refused:#}"); + } + assert_eq!(store.pull_all()?.len(), 2, "nothing was written"); + // delete(type, key) removes that type's row alone: the repair path. + store.delete(&b)?; + assert_eq!(store.pull_all()?, vec![a.clone()]); + let rewrite = test_envelope("a", "k", b"3"); + store.push(&rewrite)?; + assert_eq!(store.pull_all()?, vec![rewrite]); + } + Ok(()) + } + + #[test] + fn a_cache_refuses_to_pull_an_owned_redb_store_holding_two_types_at_a_key() -> Result<()> { + let temp = tempfile::tempdir()?; + let owned = OwnedRedbMessagePackBackingStore::new(temp.path().join("owned.db"))?; + let settings = test_envelope("settings", "shared", b"1"); + let mut stamped = test_envelope("note", "shared", b"2"); + stamped.schema_id = Some("settings".to_string()); + raw_rows(&owned.inner.database, &[&settings, &stamped])?; + let mut cache = CultCache::new(); + cache.register_registry(TestEntries)?; + cache.add_generic_backing_store(owned)?; + let error = cache.pull_all_backing_stores().unwrap_err(); + assert_eq!(retype_refusal(&error).record_key, "shared"); + Ok(()) + } + + /// Two writers race two types onto one key of one file: the store's own exclusion lets exactly one in. + #[test] + fn two_writers_racing_two_types_onto_one_key_leave_one_winner() -> Result<()> { + let temp = tempfile::tempdir()?; + let owned = OwnedRedbMessagePackBackingStore::new(temp.path().join("owned.db"))?; + let stores: Vec<(&str, Box Box>)> = vec![ + ("single", Box::new({ + let path = temp.path().join("single.cc"); + move || -> Box { Box::new(SingleFileMessagePackBackingStore::new(&path)) } + })), + ("redb", Box::new({ + let path = temp.path().join("plain.db"); + move || -> Box { Box::new(RedbMessagePackBackingStore::new(&path).unwrap()) } + })), + ("owned", Box::new(move || -> Box { Box::new(owned.clone()) })), + ]; + for (name, open) in &stores { + for round in 0..30 { + let key = format!("k{round}"); + let gate = Arc::new(std::sync::Barrier::new(2)); + let racers: Vec<_> = ["a", "b"] + .into_iter() + .map(|kind| { + let (mut store, gate, key) = (open(), gate.clone(), key.clone()); + std::thread::spawn(move || { + gate.wait(); + store.push(&test_envelope(kind, &key, kind.as_bytes())).is_ok() + }) + }) + .collect(); + let wins = racers.into_iter().map(|racer| racer.join().unwrap()).filter(|won| *won).count(); + assert_eq!(wins, 1, "{name} round {round}"); + let held = open().pull_all()?.into_iter().filter(|row| row.key == key).count(); + assert_eq!(held, 1, "{name} round {round}"); + } + } + Ok(()) + } + #[test] fn redb_skip_scan_finds_a_row_of_any_type() -> Result<()> { let temp = tempfile::tempdir()?; diff --git a/packages/cultcache-rs/tests/unique_index.rs b/packages/cultcache-rs/tests/unique_index.rs index 1e3ea6a2..eadf5c69 100644 --- a/packages/cultcache-rs/tests/unique_index.rs +++ b/packages/cultcache-rs/tests/unique_index.rs @@ -6,7 +6,8 @@ use std::path::{Path, PathBuf}; use cultcache_rs::{ - CultCache, CultCacheEnvelope, CultCacheLoadRefused, CultCacheSoaTable, DatabaseEntry, SingleFileMessagePackBackingStore, + CultCache, CultCacheEnvelope, CultCacheLoadRefused, CultCacheSoaTable, CultCacheWriteConflict, CultUpdateOutcome, + DatabaseEntry, OwnedRedbMessagePackBackingStore, RedbMessagePackBackingStore, SingleFileMessagePackBackingStore, }; use serde::Deserialize; @@ -354,6 +355,207 @@ fn every_write_path_refuses_and_changes_nothing() { assert!(reopened.put("m:x", &multi(Some("zz"), Some("yy"))).is_ok()); } +/// Which store a stale-writer scenario runs on. `Owned` hands every cache a clone of one pinned handle (each clone is another +/// reader). +enum Kind { + Single, + Redb, + Owned(OwnedRedbMessagePackBackingStore), +} + +fn kinds(dir: &Path) -> Vec<(&'static str, Kind)> { + vec![ + ("single", Kind::Single), + ("redb", Kind::Redb), + ("owned", Kind::Owned(OwnedRedbMessagePackBackingStore::new(dir.join("owned.db")).unwrap())), + ] +} + +/// A cache over the kind's store that has pulled it, so its image is what the store holds now. +fn reader(kind: &Kind, dir: &Path) -> CultCache { + let mut cache = CultCache::new(); + cache.register_entry_type::().unwrap(); + cache.register_entry_type::().unwrap(); + match kind { + Kind::Single => cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(dir.join("s.cc"))), + Kind::Redb => cache.add_generic_backing_store(RedbMessagePackBackingStore::new(dir.join("r.db")).unwrap()), + Kind::Owned(owned) => cache.add_generic_backing_store(owned.clone()), + } + .unwrap(); + cache.pull_all_backing_stores().unwrap(); + cache +} + +const CANARY: &str = "canary-value-no-refusal-may-echo"; + +fn conflict_of(error: &anyhow::Error) -> &CultCacheWriteConflict { + error.downcast_ref::().unwrap_or_else(|| panic!("not a write conflict: {error:#}")) +} + +#[test] +fn a_write_onto_a_moved_store_is_a_conflict_and_the_retry_is_refused() { + for kind in ["single", "redb", "owned"] { + let dir = tempfile::tempdir().unwrap(); + let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1; + let mut seed = reader(&kind, dir.path()); + seed.put("a", &unique("base")).unwrap(); + let mut second = reader(&kind, dir.path()); + reader(&kind, dir.path()).put("b", &unique(CANARY)).unwrap(); + + let error = second.put("c", &unique(CANARY)).unwrap_err(); + let conflict = conflict_of(&error); + assert_eq!(conflict.record_keys, ["c"]); + assert_eq!(conflict.changed_keys, ["b"]); + let text = error.to_string(); + assert!(text.contains("unique index") && text.contains("'b'") && text.contains("'c'"), "{text}"); + assert!(!text.contains(CANARY), "the conflict names keys, never values"); + assert!(second.get::("b").unwrap().is_some(), "the moved record is loaded"); + + let retry = error_text(second.put("c", &unique(CANARY))); + assert!(retry.contains('b') && retry.contains('c') && !retry.contains(CANARY), "{retry}"); + let fresh = reader(&kind, dir.path()); + assert!(fresh.get::("b").unwrap().is_some()); + assert!(fresh.get::("c").unwrap().is_none(), "the store never holds the pair"); + } +} + +#[test] +fn a_moved_store_refuses_even_without_a_collision() { + for kind in ["single", "redb", "owned"] { + let dir = tempfile::tempdir().unwrap(); + let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1; + let mut seed = reader(&kind, dir.path()); + seed.put("a", &unique("base")).unwrap(); + let mut second = reader(&kind, dir.path()); + reader(&kind, dir.path()).put("z", &Plain { value: "elsewhere".into() }).unwrap(); + + let error = second.put("c", &unique("fresh")).unwrap_err(); + assert_eq!(conflict_of(&error).changed_keys, ["z"]); + assert!(second.get::("z").unwrap().is_some()); + second.put("c", &unique("fresh")).unwrap(); + assert!(reader(&kind, dir.path()).get::("c").unwrap().is_some()); + } +} + +#[test] +fn every_gated_door_takes_the_gate() { + for kind in ["single", "redb", "owned"] { + let dir = tempfile::tempdir().unwrap(); + let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1; + let mut second = reader(&kind, dir.path()); + let mut other = reader(&kind, dir.path()); + let mut moves = 0; + let mut move_store = |other: &mut CultCache| { + moves += 1; + other.put(&format!("moved{moves}"), &Plain { value: "m".into() }).unwrap(); + }; + + move_store(&mut other); + conflict_of(&second.put("d1", &unique("S1")).unwrap_err()); + second.put("d1", &unique("S1")).unwrap(); + + move_store(&mut other); + let envelope = second.prepare_entry("d2", &unique("S2")).unwrap().0; + conflict_of(&second.put_envelope::(envelope.clone()).unwrap_err()); + second.put_envelope::(envelope).unwrap(); + + move_store(&mut other); + let envelope = second.prepare_entry("d3", &unique("S3")).unwrap().0; + conflict_of(&second.put_raw_envelope(envelope.clone()).unwrap_err()); + second.put_raw_envelope(envelope).unwrap(); + + move_store(&mut other); + let rows = staged(&second, &[("d4", unique("S4"))]); + conflict_of(&second.put_prepared_batch(rows.clone()).unwrap_err()); + second.put_prepared_batch(rows).unwrap(); + + // A batch with one indexed entry among plain ones is gated whole. + move_store(&mut other); + let plain = second.prepare_entry("batch-plain", &Plain { value: "p".into() }).unwrap().0; + let indexed = second.prepare_entry("batch-indexed", &unique("S5")).unwrap().0; + conflict_of(&second.put_prepared_batch(vec![plain.clone(), indexed.clone()]).unwrap_err()); + assert!(reader(&kind, dir.path()).get::("batch-plain").unwrap().is_none(), "nothing of the batch landed"); + second.put_prepared_batch(vec![plain, indexed]).unwrap(); + assert!(reader(&kind, dir.path()).get::("batch-plain").unwrap().is_some()); + } +} + +#[test] +fn an_ungated_write_onto_a_moved_store_still_merges() { + for kind in ["single", "redb", "owned"] { + let dir = tempfile::tempdir().unwrap(); + let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1; + let mut second = reader(&kind, dir.path()); + reader(&kind, dir.path()).put("one", &Plain { value: "1".into() }).unwrap(); + second.put("two", &Plain { value: "2".into() }).unwrap(); + let fresh = reader(&kind, dir.path()); + assert!(fresh.get::("one").unwrap().is_some() && fresh.get::("two").unwrap().is_some()); + } +} + +#[test] +fn update_retries_after_a_moved_store() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("update.cc"); + for (attempts, expected, applied) in [(5, CultUpdateOutcome::Updated, 2), (1, CultUpdateOutcome::LostRace, 1)] { + let _ = std::fs::remove_file(&path); + let mut second = cache_at(&path); + cache_at(&path).put("b", &unique("elsewhere")).unwrap(); + let mut calls = 0; + let result = second + .update_with_attempts::("c", attempts, |_| { + calls += 1; + Some(unique("fresh")) + }) + .unwrap(); + assert_eq!((result.outcome, calls), (expected, applied), "max attempts {attempts}"); + assert_eq!(cache_at(&path).get::("c").unwrap().is_some(), expected == CultUpdateOutcome::Updated); + } +} + +#[test] +fn a_failed_reload_leaves_the_cache_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("reload.cc"); + let mut second = cache_at(&path); + // The other writer holds one value twice through the index-free twin type, so the store no longer loads. + let mut twin = twin_cache_at(&path); + twin.put("item:b", &Twin { sku: "S".into(), category: "c".into() }).unwrap(); + twin.put("item:a", &Twin { sku: "S".into(), category: "c".into() }).unwrap(); + + let error = second.put("c", &unique("fresh")).unwrap_err(); + conflict_of(&error); + assert!(format!("{error:#}").contains("both hold unique index"), "the reload error is the source: {error:#}"); + let next = second.put("d", &unique("other")).unwrap_err(); + assert!(next.downcast_ref::().is_some(), "{next:#}"); +} + +#[test] +fn last_read_follows_this_handles_own_writes() { + for kind in ["single", "redb", "owned"] { + let dir = tempfile::tempdir().unwrap(); + let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1; + let mut cache = reader(&kind, dir.path()); + cache.put("a", &unique("A")).unwrap(); + cache.put("p", &Plain { value: "1".into() }).unwrap(); + cache.put("b", &unique("B")).unwrap(); + cache.put_prepared_batch(staged(&cache, &[("p", Plain { value: "2".into() }), ("c", unique("C"))])).unwrap(); + assert!(cache.delete::("p").unwrap()); + cache.put("d", &unique("D")).unwrap(); + cache.put("a", &unique("A2")).unwrap(); + assert!(cache.delete::("c").unwrap()); + cache.put("e", &unique("C")).unwrap(); + assert_eq!(reader(&kind, dir.path()).get_all_with_keys::().unwrap().len(), 5); + } + // update on the single-file store keeps it current too. + let dir = tempfile::tempdir().unwrap(); + let mut cache = cache_at(&dir.path().join("own-update.cc")); + cache.put("a", &unique("A")).unwrap(); + cache.update::("a", |_| Some(unique("A2"))).unwrap(); + cache.update::("b", |_| Some(unique("B"))).unwrap(); + cache.put("c", &unique("C")).unwrap(); +} + #[test] fn a_batch_is_judged_whole() { let dir = tempfile::tempdir().unwrap(); -- 2.47.3 From a38a2fb6f864fd2bdc2ff2e6820dd2643e5ced35 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:08:22 +0100 Subject: [PATCH 05/11] cultcache-rs: stale-gate test stages its batch by type Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-rs/tests/unique_index.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/cultcache-rs/tests/unique_index.rs b/packages/cultcache-rs/tests/unique_index.rs index eadf5c69..a257e46f 100644 --- a/packages/cultcache-rs/tests/unique_index.rs +++ b/packages/cultcache-rs/tests/unique_index.rs @@ -539,7 +539,9 @@ fn last_read_follows_this_handles_own_writes() { cache.put("a", &unique("A")).unwrap(); cache.put("p", &Plain { value: "1".into() }).unwrap(); cache.put("b", &unique("B")).unwrap(); - cache.put_prepared_batch(staged(&cache, &[("p", Plain { value: "2".into() }), ("c", unique("C"))])).unwrap(); + let mut rows = staged(&cache, &[("p", Plain { value: "2".into() })]); + rows.extend(staged(&cache, &[("c", unique("C"))])); + cache.put_prepared_batch(rows).unwrap(); assert!(cache.delete::("p").unwrap()); cache.put("d", &unique("D")).unwrap(); cache.put("a", &unique("A2")).unwrap(); -- 2.47.3 From d5824a854ca7a11ef16cfc01b06c6892950f9bc6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:13:11 +0100 Subject: [PATCH 06/11] cultcache-rs: correct the own-writes test's count Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-rs/tests/unique_index.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cultcache-rs/tests/unique_index.rs b/packages/cultcache-rs/tests/unique_index.rs index a257e46f..2bd4b530 100644 --- a/packages/cultcache-rs/tests/unique_index.rs +++ b/packages/cultcache-rs/tests/unique_index.rs @@ -547,7 +547,7 @@ fn last_read_follows_this_handles_own_writes() { cache.put("a", &unique("A2")).unwrap(); assert!(cache.delete::("c").unwrap()); cache.put("e", &unique("C")).unwrap(); - assert_eq!(reader(&kind, dir.path()).get_all_with_keys::().unwrap().len(), 5); + assert_eq!(reader(&kind, dir.path()).get_all_with_keys::().unwrap().len(), 4); } // update on the single-file store keeps it current too. let dir = tempfile::tempdir().unwrap(); -- 2.47.3 From 8fbe38bcbc1c260c458fd7b46e4ab1c6ec949f3e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:17:57 +0100 Subject: [PATCH 07/11] cultcache-rs: race test names its store opener type Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-rs/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/cultcache-rs/src/lib.rs b/packages/cultcache-rs/src/lib.rs index b7d21153..c5d84a86 100644 --- a/packages/cultcache-rs/src/lib.rs +++ b/packages/cultcache-rs/src/lib.rs @@ -9700,7 +9700,8 @@ mod tests { fn two_writers_racing_two_types_onto_one_key_leave_one_winner() -> Result<()> { let temp = tempfile::tempdir()?; let owned = OwnedRedbMessagePackBackingStore::new(temp.path().join("owned.db"))?; - let stores: Vec<(&str, Box Box>)> = vec![ + type Opener = Box Box>; + let stores: Vec<(&str, Opener)> = vec![ ("single", Box::new({ let path = temp.path().join("single.cc"); move || -> Box { Box::new(SingleFileMessagePackBackingStore::new(&path)) } -- 2.47.3 From d61216dd62527b4530bf49137e13b6a9ee6c7d68 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:19:36 +0100 Subject: [PATCH 08/11] cultcache-rs: pin removal and UTF-16 order of the moved-store keys Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-rs/tests/unique_index.rs | 23 +++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/packages/cultcache-rs/tests/unique_index.rs b/packages/cultcache-rs/tests/unique_index.rs index 2bd4b530..d1124587 100644 --- a/packages/cultcache-rs/tests/unique_index.rs +++ b/packages/cultcache-rs/tests/unique_index.rs @@ -1025,3 +1025,26 @@ fn registering_without_the_index_releases_the_holders() { cache.put("b", &Twin { sku: "S".into(), category: "x".into() }).unwrap(); assert!(cache.register_entry_type::().is_err(), "the duplicate now written is a held violation"); } + +#[test] +fn a_record_another_writer_removed_or_added_moves_the_store_and_the_keys_come_back_in_utf16_order() { + for kind in ["single", "redb", "owned"] { + let dir = tempfile::tempdir().unwrap(); + let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1; + let mut seed = reader(&kind, dir.path()); + seed.put("a", &Plain { value: "gone soon".into() }).unwrap(); + let mut second = reader(&kind, dir.path()); + let mut other = reader(&kind, dir.path()); + + // A removal alone moves the store. + assert!(other.delete::("a").unwrap()); + assert_eq!(conflict_of(&second.put("c", &unique("fresh")).unwrap_err()).changed_keys, ["a"]); + assert!(second.get::("a").unwrap().is_none(), "the removal is loaded"); + + // Keys sort by UTF-16 code unit: b, then the astral U+10400 (D801 DC00), then U+FF21. + for key in ["\u{ff21}", "\u{10400}", "b"] { + other.put(key, &Plain { value: "x".into() }).unwrap(); + } + assert_eq!(conflict_of(&second.put("c", &unique("fresh")).unwrap_err()).changed_keys, ["b", "\u{10400}", "\u{ff21}"]); + } +} -- 2.47.3 From b38426c57953460947e423aa265ad4e429a0a7e0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:31:17 +0100 Subject: [PATCH 09/11] cultcache-rs: an ungated batch keeps last_read current, pinned Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-rs/tests/unique_index.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/cultcache-rs/tests/unique_index.rs b/packages/cultcache-rs/tests/unique_index.rs index d1124587..18d91f2f 100644 --- a/packages/cultcache-rs/tests/unique_index.rs +++ b/packages/cultcache-rs/tests/unique_index.rs @@ -543,6 +543,8 @@ fn last_read_follows_this_handles_own_writes() { rows.extend(staged(&cache, &[("c", unique("C"))])); cache.put_prepared_batch(rows).unwrap(); assert!(cache.delete::("p").unwrap()); + // An ungated batch is a landing the store records too. + cache.put_prepared_batch(staged(&cache, &[("q", Plain { value: "q".into() })])).unwrap(); cache.put("d", &unique("D")).unwrap(); cache.put("a", &unique("A2")).unwrap(); assert!(cache.delete::("c").unwrap()); -- 2.47.3 From cb2eb9269d829c16666c277813a00a2634d86a10 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:59:50 +0100 Subject: [PATCH 10/11] cultcache-rs: write-conflict accessor reload_failed, Display without a space run, mover-at-same-key and gate-race tests Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-rs/src/lib.rs | 11 +++- packages/cultcache-rs/tests/unique_index.rs | 61 ++++++++++++++++++++- 2 files changed, 70 insertions(+), 2 deletions(-) diff --git a/packages/cultcache-rs/src/lib.rs b/packages/cultcache-rs/src/lib.rs index c5d84a86..e9360b64 100644 --- a/packages/cultcache-rs/src/lib.rs +++ b/packages/cultcache-rs/src/lib.rs @@ -3359,12 +3359,21 @@ pub struct CultCacheWriteConflict { reload_failed: bool, } +impl CultCacheWriteConflict { + /// Whether reloading the changed records failed. When it did, the cache is refused (every write returns + /// `CultCacheLoadRefused` until a pull succeeds) and the reload error is this error's source; otherwise the cache already + /// holds the changed records and the write can be retried. + pub fn reload_failed(&self) -> bool { + self.reload_failed + } +} + impl std::fmt::Display for CultCacheWriteConflict { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let quoted = |keys: &[String]| keys.iter().map(|key| format!("'{key}'")).collect::>().join(", "); write!( formatter, - "The backing store changed since this cache last read it, and it holds a record with a unique index, which resolve against other records; nothing was written. Records this write would have written: {}; records that changed: {}. {}", + "The backing store changed since this cache last read it, and it holds a record with a unique index, which resolve against other records; nothing was written. Records this write would have written: {}; records that changed: {}. {}", quoted(&self.record_keys), quoted(&self.changed_keys), if self.reload_failed { diff --git a/packages/cultcache-rs/tests/unique_index.rs b/packages/cultcache-rs/tests/unique_index.rs index 18d91f2f..f6c67404 100644 --- a/packages/cultcache-rs/tests/unique_index.rs +++ b/packages/cultcache-rs/tests/unique_index.rs @@ -406,7 +406,12 @@ fn a_write_onto_a_moved_store_is_a_conflict_and_the_retry_is_refused() { let conflict = conflict_of(&error); assert_eq!(conflict.record_keys, ["c"]); assert_eq!(conflict.changed_keys, ["b"]); + assert!(!conflict.reload_failed()); let text = error.to_string(); + assert_eq!( + text, + "The backing store changed since this cache last read it, and it holds a record with a unique index, which resolve against other records; nothing was written. Records this write would have written: 'c'; records that changed: 'b'. The cache reloaded them; retry the write against what the store holds now." + ); assert!(text.contains("unique index") && text.contains("'b'") && text.contains("'c'"), "{text}"); assert!(!text.contains(CANARY), "the conflict names keys, never values"); assert!(second.get::("b").unwrap().is_some(), "the moved record is loaded"); @@ -524,7 +529,8 @@ fn a_failed_reload_leaves_the_cache_refused() { twin.put("item:a", &Twin { sku: "S".into(), category: "c".into() }).unwrap(); let error = second.put("c", &unique("fresh")).unwrap_err(); - conflict_of(&error); + assert!(conflict_of(&error).reload_failed()); + assert!(error.to_string().contains("Reloading them failed")); assert!(format!("{error:#}").contains("both hold unique index"), "the reload error is the source: {error:#}"); let next = second.put("d", &unique("other")).unwrap_err(); assert!(next.downcast_ref::().is_some(), "{next:#}"); @@ -1050,3 +1056,56 @@ fn a_record_another_writer_removed_or_added_moves_the_store_and_the_keys_come_ba assert_eq!(conflict_of(&second.put("c", &unique("fresh")).unwrap_err()).changed_keys, ["b", "\u{10400}", "\u{ff21}"]); } } + +#[test] +fn a_mover_that_took_the_same_key_with_another_type_is_a_conflict_not_a_retype_refusal() { + for kind in ["single", "redb", "owned"] { + let dir = tempfile::tempdir().unwrap(); + let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1; + let mut second = reader(&kind, dir.path()); + reader(&kind, dir.path()).put("k", &Plain { value: "first".into() }).unwrap(); + + let error = second.put("k", &unique("S")).unwrap_err(); + assert_eq!(conflict_of(&error).changed_keys, ["k"]); + assert!(second.get::("k").unwrap().is_some(), "the cache reloaded the mover's record"); + let retry = second.put("k", &unique("S")).unwrap_err(); + assert!(retry.downcast_ref::().is_none(), "the retry meets the retype rule: {retry:#}"); + } +} + +/// Two caches that both hold the current image race one value onto two keys through the gate: the store's exclusion lets +/// exactly one in, and the other is a conflict that reloaded. +#[test] +fn two_caches_racing_one_value_through_the_gate_leave_one_holder() { + for kind in ["single", "redb", "owned"] { + let dir = tempfile::tempdir().unwrap(); + let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1; + let mut left = reader(&kind, dir.path()); + let mut right = reader(&kind, dir.path()); + for round in 0..25 { + let value = format!("V{round}"); + let gate = std::sync::Barrier::new(2); + let (won_left, won_right) = std::thread::scope(|scope| { + let run = |cache: &mut CultCache, key: String| { + let (gate, value) = (&gate, &value); + scope.spawn(move || { + gate.wait(); + match cache.put(&key, &unique(value)) { + Ok(_) => true, + Err(error) => { + conflict_of(&error); + false + } + } + }) + }; + let l = run(&mut left, format!("l{round}")); + let r = run(&mut right, format!("r{round}")); + (l.join().unwrap(), r.join().unwrap()) + }); + assert!(won_left ^ won_right, "{round}: exactly one writer lands (left {won_left}, right {won_right})"); + let held = reader(&kind, dir.path()).get_all_with_keys::().unwrap(); + assert_eq!(held.iter().filter(|(_, row)| row.sku == value).count(), 1, "round {round}"); + } + } +} -- 2.47.3 From 17ae70ac07734f0c4b0fcd6aa7a845267e00ab66 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:00:44 +0100 Subject: [PATCH 11/11] cultcache-rs: gate race test spawns its two writers directly Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-rs/tests/unique_index.rs | 25 ++++++++++----------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/packages/cultcache-rs/tests/unique_index.rs b/packages/cultcache-rs/tests/unique_index.rs index f6c67404..b4aa01fa 100644 --- a/packages/cultcache-rs/tests/unique_index.rs +++ b/packages/cultcache-rs/tests/unique_index.rs @@ -1086,21 +1086,20 @@ fn two_caches_racing_one_value_through_the_gate_leave_one_holder() { let value = format!("V{round}"); let gate = std::sync::Barrier::new(2); let (won_left, won_right) = std::thread::scope(|scope| { - let run = |cache: &mut CultCache, key: String| { - let (gate, value) = (&gate, &value); - scope.spawn(move || { - gate.wait(); - match cache.put(&key, &unique(value)) { - Ok(_) => true, - Err(error) => { - conflict_of(&error); - false - } + let (gate, value) = (&gate, &value); + let attempt = move |cache: &mut CultCache, key: String| { + gate.wait(); + match cache.put(&key, &unique(value)) { + Ok(_) => true, + Err(error) => { + conflict_of(&error); + false } - }) + } }; - let l = run(&mut left, format!("l{round}")); - let r = run(&mut right, format!("r{round}")); + let (left, right) = (&mut left, &mut right); + let l = scope.spawn(move || attempt(left, format!("l{round}"))); + let r = scope.spawn(move || attempt(right, format!("r{round}"))); (l.join().unwrap(), r.join().unwrap()) }); assert!(won_left ^ won_right, "{round}: exactly one writer lands (left {won_left}, right {won_right})"); -- 2.47.3