From 4f730119ee80a7869ef1fec4626825917d719049 Mon Sep 17 00:00:00 2001 From: Libby Date: Wed, 11 Nov 2026 07:27:36 +0000 Subject: [PATCH] cultcache-rs: re-registration re-derives holders over held records (or refuses); one index declaration (UNIQUE_INDEXES members) replaces cult_indexes; delete projects before the store delete; pins for re-pull and re-registration Co-Authored-By: Claude Sonnet 5.5 --- .../cultcache-rs-derive/src/lib.rs | 32 +++------ packages/cultcache-rs/src/lib.rs | 52 +++++++++----- packages/cultcache-rs/tests/unique_index.rs | 71 ++++++++++++++++++- 3 files changed, 113 insertions(+), 42 deletions(-) diff --git a/packages/cultcache-rs/cultcache-rs-derive/src/lib.rs b/packages/cultcache-rs/cultcache-rs-derive/src/lib.rs index a7a75266..c7f9a3a2 100644 --- a/packages/cultcache-rs/cultcache-rs-derive/src/lib.rs +++ b/packages/cultcache-rs/cultcache-rs-derive/src/lib.rs @@ -70,26 +70,15 @@ fn database_entry_codec(input: DeriveInput) -> syn::Result = slots.iter().filter_map(|slot| slot.index.as_ref().map(|alias| (alias, &slot.ident))).collect(); - let index_aliases: Vec<_> = index_members.iter().map(|(alias, _)| *alias).collect(); - let index_pushes = index_members.iter().map(|(alias, member)| { + let index_rows = index_members.iter().map(|(alias, member)| { quote! { - if let ::std::option::Option::Some(value) = ::cultcache_rs::CultLookupValue::lookup_value(&self.#member) { - held.push((#alias, value)); - } + (#alias, (|record: &Self| ::cultcache_rs::CultLookupValue::lookup_value(&record.#member)) + as fn(&Self) -> ::std::option::Option<::std::string::String>) } }); - let index_pushes: Vec<_> = index_pushes.collect(); - let unique_indexes = (!index_aliases.is_empty()).then(|| { - quote! { const UNIQUE_INDEXES: &'static [&'static str] = &[#(#index_aliases),*]; } - }); - let indexes_fn = (!index_pushes.is_empty()).then(|| { - quote! { - fn cult_indexes(&self) -> ::std::vec::Vec<(&'static str, ::std::string::String)> { - let mut held = ::std::vec::Vec::new(); - #(#index_pushes)* - held - } - } + let index_rows: Vec<_> = index_rows.collect(); + let unique_indexes = (!index_rows.is_empty()).then(|| { + quote! { const UNIQUE_INDEXES: &'static [::cultcache_rs::CultIndexMember] = &[#(#index_rows),*]; } }); Ok(quote! { @@ -99,7 +88,6 @@ fn database_entry_codec(input: DeriveInput) -> syn::Result Option { None } - /// The `#[cultcache(index)]` aliases. Each is unique: within one type no two records hold one non-blank value of it. - const UNIQUE_INDEXES: &'static [&'static str] = &[]; - /// Each `#[cultcache(index)]` member as (alias, value): a unique lookup, so a non-blank value names one record of - /// the type, which `get_by_index` finds it by. - fn cult_indexes(&self) -> Vec<(&'static str, String)> { - Vec::new() - } + /// The `#[cultcache(index)]` members, the one declaration: each is an alias with the reader of its value. Each is + /// unique: within one type no two records hold one non-blank value of it, and `get_by_index` finds the record by it. + const UNIQUE_INDEXES: &'static [CultIndexMember] = &[]; } +/// An index alias and how to read its value from a record; `None` is no value. +pub type CultIndexMember = (&'static str, fn(&T) -> Option); + /// What a `#[cultcache(name)]` or `#[cultcache(index)]` member says it is called: its text, or `None` for a member /// that holds no value (an `Option` that is `None`). The cache treats an empty name and a blank index value as none. pub trait CultLookupValue { @@ -2743,9 +2742,12 @@ type IndexSlot = (String, String, String); type IndexHolders = BTreeMap; fn project_indexes(payload: &[u8]) -> Result> { - let mut held = decode_payload::(payload)?.cult_indexes(); - held.retain(|(_, value)| !value.trim().is_empty()); - Ok(held) + let document = decode_payload::(payload)?; + Ok(T::UNIQUE_INDEXES + .iter() + .filter_map(|(alias, read)| read(&document).map(|value| (*alias, value))) + .filter(|(_, value)| !value.trim().is_empty()) + .collect()) } /// What an admission does to the holder map: slots it releases (still held by the key that held them) and slots it takes. @@ -2802,17 +2804,33 @@ impl CultCache { existing_type )); } + // The projector decides what the held records hold, so a changed declaration re-derives the holder table over + // them; a held violation (or a record the new type cannot decode) refuses the registration and changes nothing. + let previous = self.projectors.get(T::TYPE).copied(); + if T::UNIQUE_INDEXES.is_empty() { + self.projectors.remove(T::TYPE); + } else { + self.projectors.insert(T::TYPE.to_string(), project_indexes::); + } + let held_type = self.entries.range((T::TYPE.to_string(), String::new())..).next().is_some_and(|((held, _), _)| held == T::TYPE); + if held_type { + match self.judge_image(&self.entries) { + Ok(holders) => self.index_holders = holders, + Err(refusal) => { + match previous { + Some(project) => self.projectors.insert(T::TYPE.to_string(), project), + None => self.projectors.remove(T::TYPE), + }; + return Err(refusal); + } + } + } self.definitions.insert(T::TYPE.to_string(), T::SCHEMA_NAME); if T::GLOBAL { self.globals.insert(T::TYPE.to_string()); } else { self.globals.remove(T::TYPE); } - if T::UNIQUE_INDEXES.is_empty() { - self.projectors.remove(T::TYPE); - } else { - self.projectors.insert(T::TYPE.to_string(), project_indexes::); - } self.schema_name_definitions .insert(T::SCHEMA_NAME.to_string(), T::TYPE.to_string()); Ok(()) @@ -3030,7 +3048,7 @@ impl CultCache { /// blank value is not indexed, so it finds nothing; neither does an alias `T` does not declare. pub fn get_by_index(&self, alias: &str, value: &str) -> Result> { self.require_entry_type::()?; - if value.trim().is_empty() || !T::UNIQUE_INDEXES.contains(&alias) { + if value.trim().is_empty() || !T::UNIQUE_INDEXES.iter().any(|(declared, _)| *declared == alias) { return Ok(None); } let slot = (T::TYPE.to_string(), alias.to_string(), value.to_string()); @@ -3306,10 +3324,10 @@ impl CultCache { let Some(entry) = self.entries.get(&id).cloned() else { return Ok(false); }; + let released = self.projected_slots(&entry)?; if let Some(home) = self.home_index(T::TYPE)? { self.stores[home].store.delete(&entry)?; } - let released = self.projected_slots(&entry)?; self.entries.remove(&id); IndexChange { released, taken: Vec::new() }.apply(&mut self.index_holders); Ok(true) diff --git a/packages/cultcache-rs/tests/unique_index.rs b/packages/cultcache-rs/tests/unique_index.rs index 2416e0a0..73352375 100644 --- a/packages/cultcache-rs/tests/unique_index.rs +++ b/packages/cultcache-rs/tests/unique_index.rs @@ -129,9 +129,12 @@ fn skus(cache: &CultCache) -> Vec<(String, String)> { #[test] fn the_derive_emits_the_unique_aliases() { - assert_eq!(Unique::UNIQUE_INDEXES, &["Sku"]); - assert_eq!(Multi::UNIQUE_INDEXES, &["B", "A"]); - assert!(Plain::UNIQUE_INDEXES.is_empty()); + fn aliases() -> Vec<&'static str> { + T::UNIQUE_INDEXES.iter().map(|(alias, _)| *alias).collect() + } + assert_eq!(aliases::(), ["Sku"]); + assert_eq!(aliases::(), ["B", "A"]); + assert!(aliases::().is_empty()); } #[test] @@ -557,3 +560,65 @@ fn vectors_stores_hold_their_verdicts() { assert_eq!(std::fs::read(&path).unwrap(), before, "{file} is byte-identical"); } } + +// A pull replaces the holder table with the stored image's: a value another writer changed is released, not kept. +#[test] +fn a_second_pull_replaces_the_holders_with_the_stored_image() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("pull.cc"); + let mut cache = cache_at(&path); + cache.put("a", &unique("S")).unwrap(); + + cache_at(&path).put("a", &unique("T")).unwrap(); + cache.pull_all_backing_stores().unwrap(); + + assert_eq!(cache.get_by_index::("Sku", "S").unwrap(), None, "the replaced value is no longer held"); + assert_eq!(cache.get_by_index::("Sku", "T").unwrap(), cache.get::("a").unwrap()); + cache.put("b", &unique("S")).unwrap(); + assert!(cache.put("c", &unique("T")).is_err()); +} + +// The projector decides what held records hold: declaring an index for a type that already has records derives +// their holders, or refuses the registration when they collide. +#[test] +fn registering_an_index_over_held_records_derives_their_holders() { + let mut cache = CultCache::new(); + cache.register_entry_type::().unwrap(); + cache.put("a", &Twin { sku: "S".into(), category: "x".into() }).unwrap(); + cache.put("b", &Twin { sku: "T".into(), category: "x".into() }).unwrap(); + + cache.register_entry_type::().unwrap(); + + assert_eq!(cache.get_by_index::("Sku", "S").unwrap(), cache.get::("a").unwrap()); + assert!(cache.get_by_index::("Sku", "S").unwrap().is_some()); + assert!(cache.put("c", &unique("S")).is_err(), "a held value is refused"); + cache.put("c", &unique("U")).unwrap(); +} + +#[test] +fn registering_an_index_over_colliding_held_records_is_refused_and_changes_nothing() { + let mut cache = CultCache::new(); + cache.register_entry_type::().unwrap(); + cache.put("a", &Twin { sku: "S".into(), category: "x".into() }).unwrap(); + cache.put("b", &Twin { sku: "S".into(), category: "y".into() }).unwrap(); + + let text = error_text(cache.register_entry_type::()); + assert_eq!(text, refusal("a", "b", "tests.unique_item", "Sku")); + + // Still the unindexed declaration: duplicates keep landing, nothing is looked up. + cache.put("c", &Twin { sku: "S".into(), category: "z".into() }).unwrap(); + assert_eq!(cache.get_all_with_keys::().unwrap().len(), 3); + assert_eq!(cache.get_by_index::("Sku", "S").unwrap(), None); +} + +// Dropping the declaration releases the holders. +#[test] +fn registering_without_the_index_releases_the_holders() { + let mut cache = CultCache::new(); + cache.register_entry_type::().unwrap(); + cache.put("a", &unique("S")).unwrap(); + cache.register_entry_type::().unwrap(); + assert_eq!(cache.get_by_index::("Sku", "S").unwrap(), None, "no declaration, no 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"); +}