From 9fc4bdda6a8620f846b58e89ddf476f4676d3e89 Mon Sep 17 00:00:00 2001 From: Eureka Date: Fri, 27 Nov 2026 19:40:32 +0000 Subject: [PATCH 1/2] cultcache-py: map payloads decode under msgpack's pure-Python fallback (#180) --- packages/cultcache-py/CHANGELOG.md | 4 +++ .../src/cultcache_py/documents.py | 6 +++-- .../cultcache-py/tests/test_payload_codec.py | 27 +++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/packages/cultcache-py/CHANGELOG.md b/packages/cultcache-py/CHANGELOG.md index 738be0b0..3319863f 100644 --- a/packages/cultcache-py/CHANGELOG.md +++ b/packages/cultcache-py/CHANGELOG.md @@ -7,6 +7,10 @@ - Breaking: `define_document_type` writes and reads MessagePack payloads by default (`cultlib-gaps:ruling:py-msgpack-default`); it wrote JSON until 0.3. A definition's `payload_codec` (`PayloadCodec`, with `MESSAGEPACK_PAYLOAD_CODEC` and `JSON_PAYLOAD_CODEC` exported) owns its payload format, replacing the `payload_encoder` and `payload_decoder` parameters and fields, so no definition carries a second author of the format. A store written by 0.3 or earlier holds JSON: define its types with `payload_codec=JSON_PAYLOAD_CODEC` to read them, or write a new MessagePack store with `convert(source, destination, definitions)`, which never writes its source. The MessagePack codec takes the keys, integers, timestamps and nesting the C# reference's object reader takes and refuses the rest on read and on write (`CultCachePayloadFormatError`, `PayloadCodecFault`; see the README, Payload format); the single-file store's reader takes the same map keys. A 0.3 JSON payload that is an object or list is refused by count as a payload with bytes after its first MessagePack value, a `ValueError`. `define_database_entry_type` inherits the checked codec too: main wrote `{b'k': 1}` in an untyped slot, which is now refused on write, and a bin map key in an entry payload is refused on read where main read it, so a main-era store with a bin-keyed entry fails to load. The checked codec walks each tree twice (the depth walk, then the carried-value check), which roughly doubles entry and document codec cost; the double walk is left in place. The JSON codec's `depth_faults=(RecursionError,)` gives a JSON payload nested past the interpreter's stack the typed `CultCachePayloadDepthError`, which resolves the deferred `cut-union-bounds-py.s2.depth-typed-refusal-lost` for the JSON codec only. This is the same minor bump as the rest of this section: 0.4.0 is not yet tagged. - `parse_stored_at` (was `_parse_stored_at`) is public: cultmesh-py judges a peer's `storedAt` by it. A peer's `document_put_raw` whose `storedAt` is missing, empty or not a stamp is refused `message_invalid` (field `document`) and nothing is minted or stored (variants:ruling:raw-put-without-stamp-refused). A subscribed server's stampless put now raises `ValueError` from `CultMeshClient.read_next_change` instead of being stored under a minted stamp. +### Fixed + +- MessagePack payloads decode under msgpack's pure-Python fallback (`MSGPACK_PUREPYTHON=1`, or a pure-Python wheel such as an embedded interpreter ships): the map hook took the pairs as a list, and the fallback passes a generator, so every map payload failed. + ### Added - `CultCacheError` is exported from the package root (`from cultcache_py import CultCacheError`); it was reachable only from the private `cultcache_py.cache` module. diff --git a/packages/cultcache-py/src/cultcache_py/documents.py b/packages/cultcache-py/src/cultcache_py/documents.py index ef376eff..7a171292 100644 --- a/packages/cultcache-py/src/cultcache_py/documents.py +++ b/packages/cultcache-py/src/cultcache_py/documents.py @@ -248,9 +248,11 @@ def _key_image(key: Any) -> Any: return _NAN_KEY if isinstance(key, float) and key != key else key -def _checked_map(pairs: list[tuple[Any, Any]]) -> dict[Any, Any]: +def _checked_map(pairs: Iterable[tuple[Any, Any]]) -> dict[Any, Any]: """The read hook of every MessagePack map: the keys the C# reference's object reader accepts (str, int, float, - bool, timestamp) and no duplicate.""" + bool, timestamp) and no duplicate. msgpack's C extension passes a list and its pure-Python fallback a generator, + so the pairs are taken once.""" + pairs = list(pairs) for key, _ in pairs: if not isinstance(key, _KEY_TYPES): raise PayloadCodecFault("map_key_kind", _node_kind(key)) diff --git a/packages/cultcache-py/tests/test_payload_codec.py b/packages/cultcache-py/tests/test_payload_codec.py index bd1720d9..45b35bd0 100644 --- a/packages/cultcache-py/tests/test_payload_codec.py +++ b/packages/cultcache-py/tests/test_payload_codec.py @@ -1061,5 +1061,32 @@ class ConvertTests(unittest.TestCase): self.assertTrue(destination.exists()) +PURE_PYTHON_PROBE = """ +import msgpack, msgpack.fallback +assert msgpack.Unpacker is msgpack.fallback.Unpacker, "msgpack is not on its pure-Python fallback" +from cultcache_py import MESSAGEPACK_PAYLOAD_CODEC, PayloadCodecFault +value = {"name": "hull", "parts": [{"id": 1, "mass": 2.5}, {"id": 2, "tags": {"a": True}}]} +assert MESSAGEPACK_PAYLOAD_CODEC.decode(msgpack.packb(value)) == value +try: + MESSAGEPACK_PAYLOAD_CODEC.decode(bytes.fromhex("82 a1 61 01 a1 61 02")) +except PayloadCodecFault as fault: + assert fault.code == "duplicate_map_key", fault.code +else: + raise AssertionError("a duplicate key was read") +""" + + +class PurePythonMsgpackTests(unittest.TestCase): + def test_maps_decode_and_refuse_duplicates_on_the_pure_python_fallback(self) -> None: + # msgpack's C extension hands object_pairs_hook a list, its fallback a generator; the map hook takes either. + import subprocess + import sys + + source = str(Path(__file__).resolve().parents[1] / "src") + env = dict(os.environ, MSGPACK_PUREPYTHON="1", PYTHONPATH=os.pathsep.join(filter(None, [source, os.environ.get("PYTHONPATH")]))) + run = subprocess.run([sys.executable, "-c", PURE_PYTHON_PROBE], env=env, capture_output=True, text=True) + self.assertEqual(run.returncode, 0, run.stderr) + + if __name__ == "__main__": unittest.main() From ba1f0a4cfdee813304f584fa20c9b55ae2dc0666 Mon Sep 17 00:00:00 2001 From: Eureka Date: Fri, 27 Nov 2026 20:14:13 +0000 Subject: [PATCH 2/2] cultcache-rs: redb stores hold one record per key (cut-rs-redb-one-record-per-key) (#181) --- packages/cultcache-rs/CHANGELOG.md | 4 + packages/cultcache-rs/src/lib.rs | 179 ++++++++++++++++++++++++++++- 2 files changed, 177 insertions(+), 6 deletions(-) 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..4a2f974c 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(table: &impl ReadableTable<&'static [u8], &'static [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); @@ -5564,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(); @@ -6157,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)?; @@ -6342,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)?; @@ -9226,6 +9279,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 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()?;