Skip to main content

rca_sharing/
cache.rs

1//! Caches weak typed references inside an explicitly owned namespace.
2//!
3//! Fresh ordinary construction evaluates its seed before initial loading, even
4//! when storage contains a value. A live compatible hit does no seed, load or
5//! subscription work. Require always loads first and rejects storage absence;
6//! its loaded value may then lose to an existing live reference.
7//!
8//! Constructors check, build outside the cache lock, then check again. Racing
9//! candidates may both seed, load and subscribe; one live publication wins and
10//! the losing subscription is dropped outside the lock. There is no exactly-once
11//! provider guarantee. Reset removes lookup entries, not storage, existing
12//! handles or in-flight constructors; a later publication can repopulate it.
13//!
14//! Initial load borrows the seed. Subscription context records initial versus
15//! user intent, without duplicating a move-only seed. Unlike Swift Sharing, a
16//! subscription does not automatically restore a captured original default.
17//! Producer absence, conflict handling, persistence ordering and Store action
18//! delivery are separate policies, not supplied by this cache.
19//!
20//! Loading and subscribing are separate provider calls. A non-replaying provider
21//! can miss an update between them; construction does not promise a continuous
22//! snapshot or an event history. Providers requiring continuity must supply
23//! replay, atomic snapshot/registration or revision reconciliation themselves.
24//! Synchronous subscription delivery may replace the initially loaded value or
25//! seed before construction returns.
26//!
27//! Only cache admission requires `Value: Send + 'static`; no `Sync`, `Clone` or
28//! `Debug` is required of values. General in-memory [`Shared`] remains usable
29//! with local values. Provider identities and callbacks run outside the cache
30//! lock. Looking up, inserting, or clearing entries can wait for that lock.
31//! Value access keeps the ordinary non-blocking shared-value access contract.
32//!
33//! Reloads arbitrate on their captured reference: the latest started request
34//! alone may commit, even when it completes absent, fails or is cancelled.
35//! Superseded callers still receive their own provider errors, but cannot
36//! replace the current value. Successful producer delivery also supersedes
37//! earlier reloads; failed delivery leaves their authority unchanged. Producer
38//! ordering, absence and conflict rules remain separate policies.
39
40use std::any::{Any, TypeId};
41use std::collections::HashMap;
42use std::convert::Infallible;
43use std::fmt;
44use std::sync::{Arc, Mutex, Weak};
45
46use super::{Shared, SharedAccessError, SharedReader, SharedReference, try_lock};
47
48/// Identifies a resource and its codec configuration within one cache namespace.
49#[derive(Clone, Eq, PartialEq)]
50pub struct SharedKeyIdentity {
51    /// Names the resource within a cache namespace, including backend identity.
52    address: String,
53    /// Distinguishes incompatible codec implementations at the same address.
54    codec: TypeId,
55    /// Distinguishes incompatible settings of the same codec implementation.
56    configuration: String,
57}
58
59impl SharedKeyIdentity {
60    /// Creates a stable address with explicit codec type and configuration.
61    ///
62    /// Equal addresses must designate the same resource. Include backend/store
63    /// identity in the address when one cache serves multiple stores. Codec
64    /// configuration must distinguish incompatible instances of the same type.
65    #[must_use]
66    pub fn new<Codec: 'static>(
67        address: impl Into<String>,
68        configuration: impl Into<String>,
69    ) -> Self {
70        Self {
71            address: address.into(),
72            codec: TypeId::of::<Codec>(),
73            configuration: configuration.into(),
74        }
75    }
76}
77
78impl fmt::Debug for SharedKeyIdentity {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        f.debug_struct("SharedKeyIdentity").finish_non_exhaustive()
81    }
82}
83
84/// Distinguishes a borrowed construction seed from an explicit storage load.
85pub enum SharedLoadContext<'a, Value> {
86    /// Initial construction borrows its already evaluated seed.
87    Initial(&'a Value),
88    /// Explicit require or reload supplies no default.
89    UserInitiated,
90}
91
92impl<Value> fmt::Debug for SharedLoadContext<'_, Value> {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.write_str(match self {
95            Self::Initial(_) => "SharedLoadContext::Initial(..)",
96            Self::UserInitiated => "SharedLoadContext::UserInitiated",
97        })
98    }
99}
100
101/// Identifies subscription intent without retaining a duplicate seed value.
102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub enum SharedSubscribeContext {
104    /// Ordinary seeded construction follows its initial load.
105    Initial,
106    /// Require or key replacement skips an implicit initial load.
107    UserInitiated,
108}
109
110/// Supplies typed loading and an owned subscription for a stable resource.
111///
112/// Implementations must keep identity stable and represent absence as outer
113/// `None`, independently of a stored optional value. Subscription guards must
114/// release their provider registration on drop. Retain the supplied weak
115/// subscriber, not an independently captured strong handle to its owner.
116/// Loading before subscribing does not itself prevent missed updates. Specify
117/// the provider's replay, registration and absence rules when stronger continuity
118/// is required; successful subscription setup is not necessarily delivery acknowledgement.
119pub trait SharedReaderKey: Send + Sync + 'static {
120    /// Value admitted to the heterogeneous cache.
121    type Value: Send + 'static;
122    /// Original provider failure, without a required formatting trait.
123    type Error;
124    /// Resource retained until the final captured reference is dropped.
125    type Subscription: Send + Sync + 'static;
126
127    /// Returns the stable resource and codec compatibility identity.
128    fn identity(&self) -> SharedKeyIdentity;
129
130    /// Loads storage, keeping a missing value distinct from a provider failure.
131    ///
132    /// # Errors
133    /// Returns the original provider failure.
134    fn load(
135        &self,
136        context: SharedLoadContext<'_, Self::Value>,
137    ) -> impl Future<Output = Result<Option<Self::Value>, Self::Error>> + Send;
138
139    /// Starts owned producer delivery without holding a cache or value lock.
140    ///
141    /// # Errors
142    /// Returns the original subscription failure; construction is not published.
143    fn subscribe(
144        &self,
145        context: SharedSubscribeContext,
146        subscriber: SharedSubscriber<Self::Value>,
147    ) -> Result<Self::Subscription, Self::Error>;
148}
149
150/// Adds explicit saving capability to a typed readable resource.
151///
152/// Cache-backed mutation uses ordinary [`Shared::try_update`] and its explicit
153/// publication callback. This trait does not install automatic saving, flush
154/// barriers, coalescing, rollback or a runtime.
155pub trait SharedKey: SharedReaderKey {
156    /// Saves a borrowed value using the provider's own completion guarantee.
157    ///
158    /// # Errors
159    /// Returns the original encoding or provider failure.
160    fn save(&self, value: &Self::Value) -> impl Future<Output = Result<(), Self::Error>> + Send;
161}
162
163/// Delivers owned values through a weak captured reference.
164pub struct SharedSubscriber<Value> {
165    /// Targets only the original captured value; never resolves a new cache hit.
166    reference: Weak<SharedReference<Value>>,
167    /// Shares reload ordering without keeping its resource alive.
168    loads: Weak<Mutex<Option<Weak<()>>>>,
169}
170
171impl<Value> SharedSubscriber<Value> {
172    /// Replaces a live value, returning false after its final owner has gone.
173    ///
174    /// This conveys data only, not Store scope or action-delivery authority.
175    /// Successful replacement supersedes already started reloads atomically.
176    /// Displaced values are dropped after releasing both internal locks.
177    ///
178    /// # Errors
179    /// Returns Busy or Poisoned without applying the value or superseding a reload.
180    ///
181    /// # Panics
182    /// A displaced value's destructor may panic after replacement. It runs
183    /// after releasing both internal locks.
184    pub fn yield_value(&self, mut value: Value) -> Result<bool, SharedAccessError> {
185        self.prepare_publication()
186            .map_or(Ok(false), |publication| publication.try_replace(&mut value))
187    }
188
189    /// Retains this captured reference for one externally fenced publication.
190    ///
191    /// Prepare before acquiring a caller-owned cancellation fence. Release that
192    /// fence before dropping this owner or the displaced value. Preparation does
193    /// not grant Store, session or subscription authority and never finds a new
194    /// reference by logical identity. Returns None after the captured resource ends.
195    #[must_use]
196    pub fn prepare_publication(&self) -> Option<SharedPublication<Value>> {
197        Some(SharedPublication {
198            reference: self.reference.upgrade()?,
199            loads: self.loads.upgrade()?,
200        })
201    }
202}
203
204/// Briefly retains one captured reference and its reload coordinator.
205///
206/// Drop this prepared owner outside external control fences: it may be the final
207/// reference owner, whose value/resource destructors can run arbitrary code.
208#[must_use]
209pub struct SharedPublication<Value> {
210    /// Retains the exact captured owner through an externally fenced swap.
211    reference: Arc<SharedReference<Value>>,
212    /// Lets successful producer delivery retire earlier reloads atomically.
213    loads: Arc<Mutex<Option<Weak<()>>>>,
214}
215
216impl<Value> SharedPublication<Value> {
217    /// Swaps the captured value with the caller's value without dropping either.
218    ///
219    /// On success the slot contains the displaced value; otherwise it is unchanged.
220    /// This lets an external cancellation owner hold its commit fence over the
221    /// swap, then release that fence before dropping the displaced value. No user
222    /// callback or value destructor runs here. Successful swaps supersede reloads.
223    ///
224    /// # Errors
225    /// Returns Busy or Poisoned without changing the slot or reload authority.
226    pub fn try_replace(&self, value: &mut Value) -> Result<bool, SharedAccessError> {
227        let retired = {
228            let mut latest = self.loads.lock().map_err(|_error| load_poisoned())?;
229            let mut current = try_lock(&self.reference.value)?;
230            std::mem::swap(&mut *current, value);
231            latest.take()
232        };
233        drop(retired);
234        Ok(true)
235    }
236}
237
238impl<Value> fmt::Debug for SharedPublication<Value> {
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        f.debug_struct("SharedPublication").finish_non_exhaustive()
241    }
242}
243
244impl<Value> Clone for SharedSubscriber<Value> {
245    fn clone(&self) -> Self {
246        Self {
247            reference: Weak::clone(&self.reference),
248            loads: Weak::clone(&self.loads),
249        }
250    }
251}
252
253impl<Value> fmt::Debug for SharedSubscriber<Value> {
254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        f.debug_struct("SharedSubscriber").finish_non_exhaustive()
256    }
257}
258
259/// Attaches a repeatable default without changing the base key's identity.
260pub struct SharedKeyDefault<Key, Seed> {
261    /// Supplies resource identity independently of the default value.
262    key: Key,
263    /// Evaluates a fresh default only when the requested operation needs one.
264    seed: Seed,
265}
266
267impl<Key, Seed> SharedKeyDefault<Key, Seed> {
268    /// Associates a base key with a seed closure without invoking it.
269    #[must_use]
270    pub const fn new(key: Key, seed: Seed) -> Self {
271        Self { key, seed }
272    }
273
274    /// Removes the default for require, key replacement or an overriding seed.
275    ///
276    /// # Panics
277    /// Propagates a destructor panic from the unused seed's captures. The key is
278    /// still owned locally and is dropped if that cleanup unwinds.
279    #[must_use]
280    pub fn into_key(self) -> Key {
281        let Self { key, seed } = self;
282        drop(seed);
283        key
284    }
285}
286
287impl<Key: SharedReaderKey, Seed: Fn() -> Key::Value> SharedKeyDefault<Key, Seed> {
288    /// Evaluates the default on every direct access, independently of cache hits.
289    pub fn initial_value(&self) -> Key::Value {
290        (self.seed)()
291    }
292}
293
294impl<Key, Seed> fmt::Debug for SharedKeyDefault<Key, Seed> {
295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296        f.debug_struct("SharedKeyDefault").finish_non_exhaustive()
297    }
298}
299
300/// Keeps cache admission failures distinct from value access and provider causes.
301enum Failure<Cause> {
302    /// A live address has an incompatible codec, value type or concrete key type.
303    Collision,
304    /// A require operation found no stored value, independently of cache state.
305    Absent,
306    /// The namespace's metadata lock was poisoned.
307    Poisoned,
308    /// Access to the binding, captured value, or reload coordinator failed.
309    Access(SharedAccessError),
310    /// The provider's original owned load or subscription failure.
311    Provider(Cause),
312}
313
314/// Preserves a cache, value-access or original typed provider failure.
315pub struct SharedKeyError<Cause> {
316    /// Retains the typed cause while public formatting hides provider details.
317    failure: Failure<Cause>,
318}
319
320impl<Cause> SharedKeyError<Cause> {
321    /// Returns whether a live address has incompatible value, key or codec identity.
322    #[must_use]
323    pub const fn is_collision(&self) -> bool {
324        matches!(self.failure, Failure::Collision)
325    }
326
327    /// Returns whether require found no stored value.
328    #[must_use]
329    pub const fn is_absent(&self) -> bool {
330        matches!(self.failure, Failure::Absent)
331    }
332
333    /// Returns whether the cache metadata lock was poisoned.
334    #[must_use]
335    pub const fn is_poisoned(&self) -> bool {
336        matches!(self.failure, Failure::Poisoned)
337    }
338
339    /// Returns the access error for a binding, captured value, or reload coordinator.
340    #[must_use]
341    pub const fn access_error(&self) -> Option<&SharedAccessError> {
342        match &self.failure {
343            Failure::Access(error) => Some(error),
344            _ => None,
345        }
346    }
347
348    /// Recovers the original provider cause without requiring domain traits.
349    #[must_use]
350    pub fn into_failure(self) -> Option<Cause> {
351        match self.failure {
352            Failure::Provider(cause) => Some(cause),
353            _ => None,
354        }
355    }
356
357    /// Supplies the same redacted text to Display and quoted Debug without allocating.
358    const fn message(&self) -> &'static str {
359        match &self.failure {
360            Failure::Collision => "shared key has an incompatible live reference",
361            Failure::Absent => "required shared value is absent from storage",
362            Failure::Poisoned => "shared cache metadata is poisoned",
363            Failure::Access(error) => error.message(),
364            Failure::Provider(_) => "shared key provider failed",
365        }
366    }
367}
368
369impl<Cause> fmt::Debug for SharedKeyError<Cause> {
370    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371        f.debug_struct("SharedKeyError")
372            .field("kind", &self.message())
373            .finish_non_exhaustive()
374    }
375}
376
377impl<Cause> fmt::Display for SharedKeyError<Cause> {
378    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
379        f.write_str(self.message())
380    }
381}
382
383impl<Cause: std::error::Error + 'static> std::error::Error for SharedKeyError<Cause> {
384    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
385        match &self.failure {
386            Failure::Access(error) => Some(error),
387            Failure::Provider(cause) => Some(cause),
388            _ => None,
389        }
390    }
391}
392
393impl<Cause> From<SharedAccessError> for SharedKeyError<Cause> {
394    fn from(error: SharedAccessError) -> Self {
395        Self {
396            failure: Failure::Access(error),
397        }
398    }
399}
400
401/// Stores a provider identity for admission and later full reload checks.
402#[derive(Clone, Eq, PartialEq)]
403struct Compatibility {
404    /// Immutable resource address, codec and configuration supplied outside locks.
405    identity: SharedKeyIdentity,
406}
407
408impl Compatibility {
409    /// Calls provider identity code before entering the namespace lock.
410    fn for_key<Key: SharedReaderKey>(key: &Key) -> Self {
411        Self {
412            identity: key.identity(),
413        }
414    }
415}
416
417/// Admits compatible lookups without keeping their values or subscriptions alive.
418struct Entry {
419    /// Detects incompatible codecs after the map key established address equality.
420    codec: TypeId,
421    /// Retains compact codec settings; the map key already owns the resource address.
422    configuration: Box<str>,
423    /// Erases the value type while retaining only weak allocation identity.
424    reference: Weak<dyn Any + Send + Sync>,
425}
426
427impl Entry {
428    /// Compares remaining identity fields after lookup matched the resource address.
429    fn matches_at_same_address(&self, other: &Compatibility) -> bool {
430        self.codec == other.identity.codec
431            && self.configuration.as_ref() == other.identity.configuration.as_str()
432    }
433}
434
435/// Owns provider state for exactly one cached reference, not its writable cohorts.
436struct KeyResource<Key: SharedReaderKey> {
437    /// Retains the provider used by explicit reload after key replacement.
438    key: Key,
439    /// Binds later reloads to the original complete provider identity.
440    compatibility: Compatibility,
441    /// Rejects reload through a different namespace without retaining this cache.
442    namespace: Weak<Mutex<HashMap<Box<str>, Entry>>>,
443    /// Unregisters delivery when the final captured reference drops.
444    _subscription: Key::Subscription,
445    /// Holds only the latest request's weak identity; attempts own their tokens.
446    loads: Arc<Mutex<Option<Weak<()>>>>,
447}
448
449/// Lets callers find the same live shared value by key.
450///
451/// Clones share the same cache. [`Self::new`] creates a separate cache.
452/// Cache entries do not keep values or subscriptions alive. A reader or writable handle keeps its value alive.
453/// The last reference to the value drops the subscription.
454///
455/// [`Self::reader`] and [`Self::shared`] reuse a live value without loading or subscribing again.
456/// On a miss, each call evaluates its seed, asks the provider to load, then subscribes.
457/// Concurrent misses for a compatible key can both run these steps.
458/// If one call finds the other's live value, it uses that value and drops its own subscription outside the cache lock.
459/// [`Self::require_reader`] and [`Self::require`] always check storage first, even on a cache hit.
460///
461/// The stored value can change between the load and the subscription. The cache does not replay missed updates.
462/// To close this gap, the provider must replay updates, register atomically with a snapshot, or reconcile revisions.
463/// A provider can also deliver a new value during subscription, before the caller receives the handle.
464#[derive(Clone, Default)]
465pub struct SharedKeyCache {
466    /// Shares weak lookup metadata between clones, never strong value ownership.
467    entries: Arc<Mutex<HashMap<Box<str>, Entry>>>,
468}
469
470impl fmt::Debug for SharedKeyCache {
471    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472        f.debug_struct("SharedKeyCache").finish_non_exhaustive()
473    }
474}
475
476impl SharedKeyCache {
477    /// Creates an empty independent namespace without provider work.
478    #[must_use]
479    pub fn new() -> Self {
480        Self::default()
481    }
482
483    /// Returns a writable handle with its own binding to the shared value.
484    ///
485    /// This method uses the same load and subscription rules as [`Self::reader`].
486    /// Rebinding this handle does not rebind a handle from another call for the same key.
487    /// Clones of this handle do follow the new binding. See [`Shared::rebind`].
488    ///
489    /// # Errors
490    /// Returns collision, metadata poison, or an original load/subscription failure.
491    ///
492    /// # Panics
493    /// Propagates the same callback and destructor panics as [`Self::reader`].
494    pub async fn shared<Key: SharedKey>(
495        &self,
496        key: Key,
497        seed: impl FnOnce() -> Key::Value,
498    ) -> Result<Shared<Key::Value>, SharedKeyError<Key::Error>> {
499        Ok(cohort(self.reader(key, seed).await?))
500    }
501
502    /// Returns a reader for a live value or asks the provider for one.
503    ///
504    /// On a cache miss, the seed runs even if storage contains a value.
505    /// If storage has no value, the cache uses the seed as the initial value before it subscribes.
506    /// See [`SharedKeyCache`] for simultaneous misses and updates between load and subscription.
507    ///
508    /// # Errors
509    /// Returns collision, metadata poison, or an original load/subscription failure.
510    ///
511    /// # Panics
512    /// Propagates seed, provider and discarded value/resource destructor panics.
513    /// These callbacks run without the cache lock; publication may already have
514    /// occurred before cleanup panics.
515    pub async fn reader<Key: SharedReaderKey>(
516        &self,
517        key: Key,
518        seed: impl FnOnce() -> Key::Value,
519    ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
520        let compatibility = Compatibility::for_key(&key);
521        if let Some(reference) = self.lookup::<Key>(&compatibility)? {
522            let reader = SharedReader { reference };
523            resource::<Key>(&reader)?;
524            drop(compatibility);
525            drop(seed);
526            drop(key);
527            return Ok(reader);
528        }
529        let seed = seed();
530        let loaded = match key.load(SharedLoadContext::Initial(&seed)).await {
531            Ok(loaded) => loaded,
532            Err(cause) => {
533                let error = provider(cause);
534                drop(seed);
535                drop(compatibility);
536                drop(key);
537                return Err(error);
538            }
539        };
540        let value = match loaded {
541            Some(value) => {
542                drop(seed);
543                value
544            }
545            None => seed,
546        };
547        let reference = build_reference(
548            key,
549            compatibility.clone(),
550            Arc::downgrade(&self.entries),
551            value,
552            SharedSubscribeContext::Initial,
553        )?;
554        self.publish::<Key>(compatibility, reference)
555    }
556
557    /// Constructs with a default closure while preserving the base key identity.
558    ///
559    /// # Errors
560    /// Returns the same failures as [`Self::shared`].
561    ///
562    /// # Panics
563    /// Propagates the same callback and destructor panics as [`Self::reader`].
564    pub async fn shared_default<Key: SharedKey, Seed: Fn() -> Key::Value>(
565        &self,
566        default: SharedKeyDefault<Key, Seed>,
567    ) -> Result<Shared<Key::Value>, SharedKeyError<Key::Error>> {
568        self.shared(default.key, default.seed).await
569    }
570
571    /// Constructs a reader without adding the default wrapper to cache identity.
572    ///
573    /// # Errors
574    /// Returns the same failures as [`Self::reader`].
575    ///
576    /// # Panics
577    /// Propagates the same callback and destructor panics as [`Self::reader`].
578    pub async fn reader_default<Key: SharedReaderKey, Seed: Fn() -> Key::Value>(
579        &self,
580        default: SharedKeyDefault<Key, Seed>,
581    ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
582        self.reader(default.key, default.seed).await
583    }
584
585    /// Requires stored data before creating or reusing a writable reference.
586    ///
587    /// Use [`SharedKeyDefault::into_key`] to require a default key without using
588    /// its seed. A live cached value may win over the newly loaded value.
589    ///
590    /// # Errors
591    /// Returns absence, collision, poison, or original load/subscription failure.
592    ///
593    /// # Panics
594    /// Propagates the same provider and destructor panics as [`Self::require_reader`].
595    pub async fn require<Key: SharedKey>(
596        &self,
597        key: Key,
598    ) -> Result<Shared<Key::Value>, SharedKeyError<Key::Error>> {
599        Ok(cohort(self.require_reader(key).await?))
600    }
601
602    /// Requires stored data before looking up a read-only reference.
603    ///
604    /// # Errors
605    /// Returns absence even with a live cache hit, or collision/poison/provider failure.
606    ///
607    /// # Panics
608    /// Propagates provider and discarded value/resource destructor panics. Cleanup
609    /// completes before a selected reader or original provider cause is returned.
610    pub async fn require_reader<Key: SharedReaderKey>(
611        &self,
612        key: Key,
613    ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
614        let loaded = match key.load(SharedLoadContext::UserInitiated).await {
615            Ok(loaded) => loaded,
616            Err(cause) => {
617                let error = provider(cause);
618                drop(key);
619                return Err(error);
620            }
621        }
622        .ok_or(SharedKeyError {
623            failure: Failure::Absent,
624        })?;
625        let compatibility = Compatibility::for_key(&key);
626        if let Some(reference) = self.lookup::<Key>(&compatibility)? {
627            let reader = SharedReader { reference };
628            resource::<Key>(&reader)?;
629            drop(compatibility);
630            drop(loaded);
631            drop(key);
632            return Ok(reader);
633        }
634        let reference = build_reference(
635            key,
636            compatibility.clone(),
637            Arc::downgrade(&self.entries),
638            loaded,
639            SharedSubscribeContext::UserInitiated,
640        )?;
641        self.publish::<Key>(compatibility, reference)
642    }
643
644    /// Reloads a captured writable reference, retaining its current value on absence.
645    ///
646    /// Concurrent rebinding does not retarget this operation after capture.
647    /// Only the latest started reload on that reference may replace its value;
648    /// completion, failure or cancellation never revives an older request.
649    ///
650    /// # Errors
651    /// Returns incompatible key, access failure, or original provider failure.
652    ///
653    /// # Panics
654    /// Propagates provider and displaced-value cleanup panics. Releasing the
655    /// captured reference can also run a panicking destructor before return.
656    pub async fn reload<Key: SharedReaderKey>(
657        &self,
658        shared: &Shared<Key::Value>,
659        key: &Key,
660    ) -> Result<(), SharedKeyError<Key::Error>> {
661        let reader = shared.reader()?;
662        let result = self.reload_reader(&reader, key).await;
663        drop(reader);
664        result
665    }
666
667    /// Reloads a read-only captured reference without granting mutation access.
668    ///
669    /// # Errors
670    /// Returns incompatible key, value-access failure, or original provider failure.
671    ///
672    /// # Panics
673    /// Propagates provider and displaced or rejected value destructor panics.
674    pub async fn reload_reader<Key: SharedReaderKey>(
675        &self,
676        reader: &SharedReader<Key::Value>,
677        key: &Key,
678    ) -> Result<(), SharedKeyError<Key::Error>> {
679        let resource = resource::<Key>(reader)?;
680        if !std::ptr::eq(resource.namespace.as_ptr(), Arc::as_ptr(&self.entries))
681            || resource.compatibility != Compatibility::for_key(key)
682        {
683            return Err(collision());
684        }
685        reload_reference(reader, key, &resource.loads).await
686    }
687
688    /// Rebinds to a key before reloading, seeding fresh owners from current data.
689    ///
690    /// `seed` runs synchronously only on a target-cache miss and supplies an
691    /// owned current-value snapshot without requiring `Clone`. The new owner
692    /// skips initial load and subscribes with user intent. Reload failure does
693    /// not roll the binding back. Unwrap default keys with `into_key`.
694    ///
695    /// # Errors
696    /// Returns collision, cache/value access, subscription or explicit-load failure.
697    ///
698    /// # Panics
699    /// A seed callback panic poisons the captured source value. Provider or
700    /// displaced value/resource destructor panics also propagate. The receiving
701    /// handle and its clones can already refer to the replacement value.
702    pub async fn load<Key: SharedKey>(
703        &self,
704        shared: &Shared<Key::Value>,
705        key: Key,
706        seed: impl FnOnce(&Key::Value) -> Key::Value,
707    ) -> Result<(), SharedKeyError<Key::Error>> {
708        let reader = self.replacement(&shared.reader()?, key, seed)?;
709        let resource = resource::<Key>(&reader)?;
710        shared.rebind(&cohort(reader.clone()))?;
711        let result = reload_reference(&reader, &resource.key, &resource.loads).await;
712        drop(reader);
713        result
714    }
715
716    /// Replaces this reader's reference before explicitly reloading the selected key.
717    ///
718    /// Other reader clones retain their previously captured reference.
719    ///
720    /// # Errors
721    /// Returns collision, cache/value access, subscription or explicit-load failure.
722    ///
723    /// # Panics
724    /// A seed callback panic poisons the captured source value. Provider or
725    /// displaced value/resource destructor panics also propagate. This reader
726    /// may already be replaced and is not rolled back.
727    pub async fn load_reader<Key: SharedReaderKey>(
728        &self,
729        reader: &mut SharedReader<Key::Value>,
730        key: Key,
731        seed: impl FnOnce(&Key::Value) -> Key::Value,
732    ) -> Result<(), SharedKeyError<Key::Error>> {
733        let replacement = self.replacement(reader, key, seed)?;
734        let previous = std::mem::replace(reader, replacement);
735        let resource = match resource::<Key>(reader) {
736            Ok(resource) => resource,
737            Err(error) => {
738                drop(std::mem::replace(reader, previous));
739                return Err(error);
740            }
741        };
742        drop(previous);
743        reload_reference(reader, &resource.key, &resource.loads).await
744    }
745
746    /// Clears weak lookup entries without revoking owners or touching storage.
747    ///
748    /// In-flight constructors may publish again after this reset.
749    ///
750    /// # Errors
751    /// Returns metadata poison if another operation panicked while holding its lock.
752    pub fn reset(&self) -> Result<(), SharedKeyError<Infallible>> {
753        let previous = {
754            let mut entries = self.entries.lock().map_err(|_error| poisoned())?;
755            std::mem::take(&mut *entries)
756        };
757        drop(previous);
758        Ok(())
759    }
760
761    /// Captures a replacement without rebinding the caller or performing a load.
762    ///
763    /// A miss snapshots the current value and subscribes with user intent. The
764    /// caller validates the concrete retained resource before changing its handle.
765    fn replacement<Key: SharedReaderKey>(
766        &self,
767        current: &SharedReader<Key::Value>,
768        key: Key,
769        seed: impl FnOnce(&Key::Value) -> Key::Value,
770    ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
771        let compatibility = Compatibility::for_key(&key);
772        if let Some(reference) = self.lookup::<Key>(&compatibility)? {
773            // The caller validates the concrete resource before committing its binding.
774            let reader = SharedReader { reference };
775            drop(compatibility);
776            drop(seed);
777            drop(key);
778            return Ok(reader);
779        }
780        let value = current.read(seed)?;
781        let reference = build_reference(
782            key,
783            compatibility.clone(),
784            Arc::downgrade(&self.entries),
785            value,
786            SharedSubscribeContext::UserInitiated,
787        )?;
788        self.publish::<Key>(compatibility, reference)
789    }
790
791    /// Upgrades a compatible live entry, releasing the metadata lock before drops.
792    #[expect(
793        clippy::type_complexity,
794        reason = "keeps the value type and provider failure coupled at this private boundary"
795    )]
796    fn lookup<Key: SharedReaderKey>(
797        &self,
798        compatibility: &Compatibility,
799    ) -> Result<Option<Arc<SharedReference<Key::Value>>>, SharedKeyError<Key::Error>> {
800        let found = {
801            let entries = self.entries.lock().map_err(|_error| poisoned())?;
802            entries
803                .get(compatibility.identity.address.as_str())
804                .map(|entry| {
805                    // Compatibility contains only owned strings and type IDs, so
806                    // comparing it runs no provider code. Carry the owner out
807                    // even on collision: its final drop may reenter this cache.
808                    (
809                        entry.matches_at_same_address(compatibility),
810                        entry.reference.upgrade(),
811                    )
812                })
813        };
814        match found {
815            Some((compatible, Some(reference))) => {
816                if !compatible {
817                    return Err(collision());
818                }
819                reference
820                    .downcast()
821                    .map(Some)
822                    .map_err(|_reference| collision())
823            }
824            _ => Ok(None),
825        }
826    }
827
828    /// Selects the live winner after provider construction outside the cache lock.
829    ///
830    /// Losing candidates and displaced weak entries are destroyed after unlocking.
831    fn publish<Key: SharedReaderKey>(
832        &self,
833        mut compatibility: Compatibility,
834        candidate: Arc<SharedReference<Key::Value>>,
835    ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
836        let erased: Arc<dyn Any + Send + Sync> = Arc::clone(&candidate) as Arc<_>;
837        let (winner, previous) = {
838            let mut entries = self.entries.lock().map_err(|_error| poisoned())?;
839            let winner = entries
840                .get(compatibility.identity.address.as_str())
841                .and_then(|entry| {
842                    entry
843                        .reference
844                        .upgrade()
845                        .map(|reference| (entry.matches_at_same_address(&compatibility), reference))
846                });
847            let previous = if winner.is_none() {
848                entries.insert(
849                    take_compact(&mut compatibility.identity.address),
850                    Entry {
851                        codec: compatibility.identity.codec,
852                        configuration: take_compact(&mut compatibility.identity.configuration),
853                        reference: Arc::downgrade(&erased),
854                    },
855                )
856            } else {
857                None
858            };
859            (winner, previous)
860        };
861        drop(previous);
862        drop(erased);
863        if let Some((compatible, winner)) = winner {
864            if !compatible {
865                return Err(collision());
866            }
867            let reader = SharedReader {
868                reference: winner.downcast().map_err(|_reference| collision())?,
869            };
870            resource::<Key>(&reader)?;
871            drop(candidate);
872            return Ok(reader);
873        }
874        Ok(SharedReader {
875            reference: candidate,
876        })
877    }
878}
879
880/// Moves compact text or copies it without releasing its excess capacity.
881fn take_compact(text: &mut String) -> Box<str> {
882    if text.len() == text.capacity() {
883        std::mem::take(text).into_boxed_str()
884    } else {
885        // The caller releases the original buffer after the cache lock.
886        Box::from(text.as_str())
887    }
888}
889
890/// Creates an independent rebinding slot over an already captured reference.
891fn cohort<Value>(reader: SharedReader<Value>) -> Shared<Value> {
892    Shared {
893        cohort: Arc::new(Mutex::new(reader)),
894    }
895}
896
897/// Establishes weak delivery before subscribing, then retains the provider guard.
898///
899/// Synchronous subscription delivery may replace the seed. The one-time slot
900/// keeps the provider's type recoverable without locking during later lookups.
901fn build_reference<Key: SharedReaderKey>(
902    key: Key,
903    compatibility: Compatibility,
904    namespace: Weak<Mutex<HashMap<Box<str>, Entry>>>,
905    value: Key::Value,
906    context: SharedSubscribeContext,
907) -> Result<Arc<SharedReference<Key::Value>>, SharedKeyError<Key::Error>> {
908    let reference = Arc::new(SharedReference::new(value));
909    // Establish delivery arbitration before subscribe can synchronously yield.
910    let loads = Arc::new(Mutex::new(None));
911    let subscription = match key.subscribe(
912        context,
913        SharedSubscriber {
914            reference: Arc::downgrade(&reference),
915            loads: Arc::downgrade(&loads),
916        },
917    ) {
918        Ok(subscription) => subscription,
919        Err(cause) => {
920            let error = provider(cause);
921            drop(loads);
922            drop(reference);
923            drop(namespace);
924            drop(compatibility);
925            drop(key);
926            return Err(error);
927        }
928    };
929    // Only construction can install the resource. The supplied subscriber holds weak references.
930    let installed = reference.retained.set(Box::new(KeyResource {
931        key,
932        compatibility,
933        namespace,
934        _subscription: subscription,
935        loads,
936    }));
937    assert!(
938        installed.is_ok(),
939        "a new shared reference has no retained resource"
940    );
941    Ok(reference)
942}
943
944/// Checks the concrete provider type as well as the reference's already typed value.
945fn resource<Key: SharedReaderKey>(
946    reader: &SharedReader<Key::Value>,
947) -> Result<&KeyResource<Key>, SharedKeyError<Key::Error>> {
948    reader
949        .reference
950        .retained
951        .get()
952        .and_then(|resource| resource.downcast_ref::<KeyResource<Key>>())
953        .ok_or_else(collision)
954}
955
956/// Starts one reload and commits only if no later load or delivery superseded it.
957async fn reload_reference<Key: SharedReaderKey>(
958    reader: &SharedReader<Key::Value>,
959    key: &Key,
960    loads: &Mutex<Option<Weak<()>>>,
961) -> Result<(), SharedKeyError<Key::Error>> {
962    let attempt = ReferenceLoadAttempt::begin(&reader.reference, loads)?;
963    let loaded = key
964        .load(SharedLoadContext::UserInitiated)
965        .await
966        .map_err(provider)?;
967    attempt.commit(loaded)?;
968    Ok(())
969}
970
971/// Owns one non-reusable request token and retires it on cancellation or failure.
972struct ReferenceLoadAttempt<'a, Value> {
973    /// Borrows the captured destination for the complete load attempt.
974    reference: &'a SharedReference<Value>,
975    /// Serialises token replacement with value commit and producer delivery.
976    loads: &'a Mutex<Option<Weak<()>>>,
977    /// Keeps this request's allocation identity unique while the attempt exists.
978    identity: Arc<()>,
979    /// Skips cancellation cleanup once commit has consumed this request's authority.
980    retired: bool,
981}
982
983impl<'a, Value> ReferenceLoadAttempt<'a, Value> {
984    /// Supersedes earlier attempts before starting provider work.
985    fn begin(
986        reference: &'a SharedReference<Value>,
987        loads: &'a Mutex<Option<Weak<()>>>,
988    ) -> Result<Self, SharedAccessError> {
989        let identity = Arc::new(());
990        let previous = {
991            let mut latest = loads.lock().map_err(|_error| load_poisoned())?;
992            latest.replace(Arc::downgrade(&identity))
993        };
994        drop(previous);
995        Ok(Self {
996            reference,
997            loads,
998            identity,
999            retired: false,
1000        })
1001    }
1002
1003    /// Compares request identity without reviving a completed or cancelled attempt.
1004    fn is_latest(&self, latest: Option<&Weak<()>>) -> bool {
1005        // Both owners keep their allocation identities unique; comparison needs
1006        // no temporary Weak increment/decrement or upgrade of a retired request.
1007        latest.is_some_and(|latest| std::ptr::eq(latest.as_ptr(), Arc::as_ptr(&self.identity)))
1008    }
1009
1010    /// Applies only the latest result, dropping displaced or rejected values unlocked.
1011    ///
1012    /// Absence retires the latest request without replacing its current value.
1013    fn commit(mut self, value: Option<Value>) -> Result<bool, SharedAccessError> {
1014        let mut value = value;
1015        let (committed, displaced, previous) = {
1016            let mut latest = self.loads.lock().map_err(|_error| load_poisoned())?;
1017            if self.is_latest(latest.as_ref()) {
1018                // Validate and replace under one coordinator guard. Never
1019                // block on value access or drop user values under either lock.
1020                let displaced = if value.is_some() {
1021                    let mut current = try_lock(&self.reference.value)?;
1022                    value
1023                        .take()
1024                        .map(|value| std::mem::replace(&mut *current, value))
1025                } else {
1026                    None
1027                };
1028                (true, displaced, latest.take())
1029            } else {
1030                (false, None, None)
1031            }
1032        };
1033        self.retired = true;
1034        drop(previous);
1035        drop(displaced);
1036        drop(value);
1037        Ok(committed)
1038    }
1039}
1040
1041impl<Value> Drop for ReferenceLoadAttempt<'_, Value> {
1042    fn drop(&mut self) {
1043        if self.retired {
1044            return;
1045        }
1046        // Drop cannot report poison and must not introduce a second panic.
1047        // A poisoned coordinator remains poisoned for subsequent operations.
1048        let previous = if let Ok(mut latest) = self.loads.lock() {
1049            if self.is_latest(latest.as_ref()) {
1050                latest.take()
1051            } else {
1052                None
1053            }
1054        } else {
1055            None
1056        };
1057        drop(previous);
1058    }
1059}
1060
1061/// Classifies reload-coordinator poison as captured-reference access failure.
1062fn load_poisoned() -> SharedAccessError {
1063    SharedAccessError {
1064        kind: super::AccessKind::Poisoned,
1065    }
1066}
1067
1068/// Preserves a provider cause without formatting or cloning it.
1069fn provider<Cause>(cause: Cause) -> SharedKeyError<Cause> {
1070    SharedKeyError {
1071        failure: Failure::Provider(cause),
1072    }
1073}
1074
1075/// Reports incompatible live identity without exposing resource details.
1076fn collision<Cause>() -> SharedKeyError<Cause> {
1077    SharedKeyError {
1078        failure: Failure::Collision,
1079    }
1080}
1081
1082/// Distinguishes namespace metadata poison from captured-reference access poison.
1083fn poisoned<Cause>() -> SharedKeyError<Cause> {
1084    SharedKeyError {
1085        failure: Failure::Poisoned,
1086    }
1087}
1088
1089#[cfg(test)]
1090mod tests {
1091    use super::*;
1092
1093    /// Checks that the result owns each non-empty, exact-sized buffer.
1094    #[test]
1095    fn take_compact_transfers_exact_capacity_buffers() {
1096        for expected in ["", "shared-profile"] {
1097            let mut text = Box::<str>::from(expected).into_string();
1098            let pointer = text.as_ptr();
1099            assert_eq!(text.capacity(), text.len());
1100
1101            let compact = take_compact(&mut text);
1102
1103            assert_eq!(compact.as_ref(), expected);
1104            if !expected.is_empty() {
1105                assert_eq!(compact.as_ptr(), pointer);
1106            }
1107            assert_eq!(text, "");
1108            assert_eq!(text.capacity(), 0);
1109        }
1110    }
1111
1112    /// Checks that copies leave oversized buffers with the caller.
1113    #[test]
1114    fn take_compact_preserves_buffers_with_spare_capacity() {
1115        for expected in ["", "shared-profile"] {
1116            let mut text = String::with_capacity(expected.len() + 16);
1117            text.push_str(expected);
1118            let pointer = text.as_ptr();
1119            let capacity = text.capacity();
1120            assert!(capacity > text.len());
1121
1122            let compact = take_compact(&mut text);
1123
1124            assert_eq!(compact.as_ref(), expected);
1125            assert_eq!(text, expected);
1126            assert_eq!(text.as_ptr(), pointer);
1127            assert_eq!(text.capacity(), capacity);
1128            if !expected.is_empty() {
1129                assert_ne!(compact.as_ptr(), pointer);
1130            }
1131        }
1132    }
1133
1134    // Diagnostic formatting must neither require Debug on values nor disclose them.
1135    #[test]
1136    fn diagnostics_redact_resource_identity_and_non_debug_values() {
1137        struct Secret(&'static str);
1138
1139        let identity = SharedKeyIdentity::new::<()>("private-address", "private-configuration");
1140        let reference = Arc::new(SharedReference::new(Secret("private-value")));
1141        let loads = Arc::new(Mutex::new(None));
1142        let subscriber = SharedSubscriber {
1143            reference: Arc::downgrade(&reference),
1144            loads: Arc::downgrade(&loads),
1145        };
1146        let publication = subscriber.prepare_publication().unwrap();
1147        let value = reference.value.lock().unwrap();
1148        let initial = format!("{:?}", SharedLoadContext::Initial(&*value));
1149        let explicit = format!("{:?}", SharedLoadContext::<Secret>::UserInitiated);
1150        assert_ne!(initial, explicit);
1151        for diagnostic in [
1152            format!("{identity:?}"),
1153            format!("{subscriber:?}"),
1154            format!("{publication:?}"),
1155            format!("{:?}", SharedKeyCache::new()),
1156            initial,
1157            explicit,
1158        ] {
1159            for secret in ["private-address", "private-configuration", value.0] {
1160                assert!(!diagnostic.contains(secret));
1161            }
1162        }
1163    }
1164
1165    // Public diagnostics redact provider details while the typed error chain preserves them.
1166    #[test]
1167    fn provider_error_source_preserves_the_cause_without_disclosing_it() {
1168        let error = provider(std::io::Error::new(
1169            std::io::ErrorKind::PermissionDenied,
1170            "private-provider-path",
1171        ));
1172        assert!(!error.is_absent());
1173        assert!(!error.is_collision());
1174        assert!(!error.is_poisoned());
1175        assert!(error.access_error().is_none());
1176        assert!(!format!("{error}: {error:?}").contains("private-provider-path"));
1177        let source = std::error::Error::source(&error)
1178            .unwrap()
1179            .downcast_ref::<std::io::Error>()
1180            .unwrap();
1181        assert_eq!(source.kind(), std::io::ErrorKind::PermissionDenied);
1182        assert_eq!(source.to_string(), "private-provider-path");
1183        let recovered = error.into_failure().unwrap();
1184        assert_eq!(recovered.kind(), std::io::ErrorKind::PermissionDenied);
1185        assert_eq!(recovered.to_string(), "private-provider-path");
1186    }
1187
1188    // Poison must reject all metadata operations without revoking captured owners.
1189    #[test]
1190    fn poisoned_metadata_rejects_lookup_publication_and_reset_without_revoking_owners() {
1191        let cache = SharedKeyCache::new();
1192        let seeds = std::cell::Cell::new(0);
1193        let seed = || {
1194            seeds.set(seeds.get() + 1);
1195            7
1196        };
1197        let owner = futures_executor::block_on(cache.reader(LayoutKey, seed)).unwrap();
1198        let compatibility = Compatibility::for_key(&LayoutKey);
1199        let candidate = build_reference(
1200            LayoutKey,
1201            compatibility.clone(),
1202            Arc::downgrade(&cache.entries),
1203            11,
1204            SharedSubscribeContext::UserInitiated,
1205        )
1206        .unwrap();
1207        let provisional = Arc::downgrade(&candidate);
1208        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1209            let _guard = cache.entries.lock().unwrap();
1210            panic!("metadata interrupted");
1211        }));
1212        assert!(panic.is_err());
1213        let errors = [
1214            futures_executor::block_on(cache.reader(LayoutKey, seed)).unwrap_err(),
1215            cache
1216                .publish::<LayoutKey>(compatibility, candidate)
1217                .unwrap_err(),
1218            cache.reset().unwrap_err(),
1219        ];
1220        for error in errors {
1221            assert!(error.is_poisoned());
1222            assert!(!error.is_collision());
1223            assert!(!error.is_absent());
1224            assert!(error.access_error().is_none());
1225            assert!(std::error::Error::source(&error).is_none());
1226            assert!(error.to_string().contains("metadata is poisoned"));
1227            assert!(error.into_failure().is_none());
1228        }
1229        assert_eq!(seeds.get(), 1);
1230        assert!(provisional.upgrade().is_none());
1231        assert_eq!(owner.read(|value| *value).unwrap(), 7);
1232    }
1233
1234    // Internal fault injection, not a publicly constructible cache state.
1235    #[test]
1236    fn mismatched_erased_entry_rejects_reader_without_seed_or_owner_leak() {
1237        let cache = SharedKeyCache::new();
1238        let compatibility = Compatibility::for_key(&LayoutKey);
1239        let owner = Arc::new(SharedReference::new("private-wrong-value"));
1240        let erased: Arc<dyn Any + Send + Sync> = Arc::clone(&owner) as Arc<_>;
1241        cache.entries.lock().unwrap().insert(
1242            compatibility.identity.address.clone().into_boxed_str(),
1243            Entry {
1244                codec: compatibility.identity.codec,
1245                configuration: compatibility
1246                    .identity
1247                    .configuration
1248                    .clone()
1249                    .into_boxed_str(),
1250                reference: Arc::downgrade(&erased),
1251            },
1252        );
1253        drop(erased);
1254
1255        let error = futures_executor::block_on(cache.reader(LayoutKey, || {
1256            panic!("a mismatched live reference must not fall back to its seed")
1257        }))
1258        .unwrap_err();
1259        assert!(error.is_collision());
1260        assert_eq!(
1261            error.to_string(),
1262            "shared key has an incompatible live reference"
1263        );
1264        assert!(!format!("{error:?}").contains("private-wrong-value"));
1265        assert!(!error.is_poisoned());
1266        assert_eq!(Arc::strong_count(&owner), 1);
1267        assert_eq!(*owner.value.lock().unwrap(), "private-wrong-value");
1268        drop(cache);
1269        assert_eq!(Arc::strong_count(&owner), 1);
1270    }
1271
1272    // A forged compatible identity must not turn a failed downcast into publication.
1273    #[test]
1274    fn mismatched_erased_winner_rejects_publication_and_drops_candidate_outside_lock() {
1275        use std::sync::atomic::{AtomicUsize, Ordering};
1276
1277        struct CandidateDrop(SharedKeyCache, Arc<AtomicUsize>);
1278        impl Drop for CandidateDrop {
1279            fn drop(&mut self) {
1280                assert!(
1281                    self.0.entries.try_lock().is_ok(),
1282                    "candidate drop holds metadata lock"
1283                );
1284                self.1.fetch_add(1, Ordering::SeqCst);
1285            }
1286        }
1287
1288        let cache = SharedKeyCache::new();
1289        let compatibility = Compatibility::for_key(&LayoutKey);
1290        let owner = Arc::new(SharedReference::new("private-wrong-value"));
1291        let erased: Arc<dyn Any + Send + Sync> = Arc::clone(&owner) as Arc<_>;
1292        let retained = Arc::downgrade(&erased);
1293        cache.entries.lock().unwrap().insert(
1294            compatibility.identity.address.clone().into_boxed_str(),
1295            Entry {
1296                codec: compatibility.identity.codec,
1297                configuration: compatibility
1298                    .identity
1299                    .configuration
1300                    .clone()
1301                    .into_boxed_str(),
1302                reference: Weak::clone(&retained),
1303            },
1304        );
1305        drop(erased);
1306        let drops = Arc::new(AtomicUsize::new(0));
1307        let candidate = Arc::new(SharedReference::new(11_usize));
1308        candidate
1309            .retained
1310            .set(Box::new(CandidateDrop(cache.clone(), Arc::clone(&drops))))
1311            .unwrap_or_else(|_| panic!("fresh candidate has no retained resource"));
1312        let provisional = Arc::downgrade(&candidate);
1313
1314        let error = cache
1315            .publish::<LayoutKey>(compatibility.clone(), candidate)
1316            .unwrap_err();
1317        assert!(error.is_collision());
1318        assert_eq!(
1319            error.to_string(),
1320            "shared key has an incompatible live reference"
1321        );
1322        assert!(!format!("{error:?}").contains("private-wrong-value"));
1323        assert_eq!(drops.load(Ordering::SeqCst), 1);
1324        assert!(provisional.upgrade().is_none());
1325        assert_eq!(Arc::strong_count(&owner), 1);
1326        let entries = cache.entries.lock().unwrap();
1327        assert_eq!(entries.len(), 1);
1328        assert!(Weak::ptr_eq(
1329            &entries[compatibility.identity.address.as_str()].reference,
1330            &retained
1331        ));
1332        drop(entries);
1333        assert_eq!(*owner.value.lock().unwrap(), "private-wrong-value");
1334        drop(cache);
1335        assert_eq!(drops.load(Ordering::SeqCst), 1);
1336        assert_eq!(Arc::strong_count(&drops), 1);
1337    }
1338
1339    // A poisoned coordinator cannot accept a new load, commit or producer value.
1340    #[test]
1341    fn poisoned_reload_coordinator_preserves_values_and_does_not_panic_during_retirement() {
1342        let reference = Arc::new(SharedReference::new(7));
1343        let loads = Arc::new(Mutex::new(None));
1344        let subscriber = SharedSubscriber {
1345            reference: Arc::downgrade(&reference),
1346            loads: Arc::downgrade(&loads),
1347        };
1348        let publication = subscriber.prepare_publication().unwrap();
1349        let attempt = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
1350        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1351            let _guard = loads.lock().unwrap();
1352            panic!("reload coordination interrupted");
1353        }));
1354        assert!(panic.is_err());
1355        assert!(attempt.commit(Some(11)).unwrap_err().is_poisoned());
1356        let error = ReferenceLoadAttempt::begin(&reference, &loads)
1357            .err()
1358            .unwrap();
1359        assert!(error.is_poisoned());
1360        let mut next = 13;
1361        assert!(
1362            publication
1363                .try_replace(&mut next)
1364                .unwrap_err()
1365                .is_poisoned()
1366        );
1367        assert_eq!(next, 13);
1368        assert_eq!(*reference.value.lock().unwrap(), 7);
1369        assert!(loads.is_poisoned());
1370    }
1371
1372    // Coordinator poison must reach callers before provider I/O, without leaking owners.
1373    #[test]
1374    fn reload_propagates_coordinator_poison_before_invoking_provider() {
1375        use std::sync::atomic::{AtomicUsize, Ordering};
1376
1377        #[derive(Clone)]
1378        struct Key {
1379            loads: Arc<AtomicUsize>,
1380            retirements: Arc<AtomicUsize>,
1381        }
1382        struct Subscription(Arc<AtomicUsize>);
1383
1384        impl Drop for Subscription {
1385            fn drop(&mut self) {
1386                self.0.fetch_add(1, Ordering::SeqCst);
1387            }
1388        }
1389
1390        impl SharedReaderKey for Key {
1391            type Value = usize;
1392            type Error = Infallible;
1393            type Subscription = Subscription;
1394
1395            fn identity(&self) -> SharedKeyIdentity {
1396                SharedKeyIdentity::new::<Self>("poisoned-reload", "")
1397            }
1398
1399            fn load(
1400                &self,
1401                _: SharedLoadContext<'_, usize>,
1402            ) -> impl Future<Output = Result<Option<usize>, Infallible>> + Send {
1403                self.loads.fetch_add(1, Ordering::SeqCst);
1404                std::future::ready(Ok(None))
1405            }
1406
1407            fn subscribe(
1408                &self,
1409                _: SharedSubscribeContext,
1410                _: SharedSubscriber<usize>,
1411            ) -> Result<Subscription, Infallible> {
1412                Ok(Subscription(Arc::clone(&self.retirements)))
1413            }
1414        }
1415
1416        let key = Key {
1417            loads: Arc::new(AtomicUsize::new(0)),
1418            retirements: Arc::new(AtomicUsize::new(0)),
1419        };
1420        let cache = SharedKeyCache::new();
1421        let reader = futures_executor::block_on(cache.reader(key.clone(), || 7)).unwrap();
1422        let owner = Arc::downgrade(&reader.reference);
1423        let loads = Arc::clone(&resource::<Key>(&reader).unwrap().loads);
1424        assert_eq!(key.loads.load(Ordering::SeqCst), 1);
1425        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1426            let _guard = loads.lock().unwrap();
1427            panic!("reload coordination interrupted");
1428        }));
1429        assert!(panic.is_err());
1430
1431        let error = futures_executor::block_on(cache.reload_reader(&reader, &key)).unwrap_err();
1432        assert!(error.access_error().unwrap().is_poisoned());
1433        assert!(!error.is_poisoned(), "not a metadata-lock failure");
1434        assert!(!error.is_collision());
1435        assert!(
1436            std::error::Error::source(&error)
1437                .unwrap()
1438                .downcast_ref::<SharedAccessError>()
1439                .unwrap()
1440                .is_poisoned()
1441        );
1442        assert_eq!(key.loads.load(Ordering::SeqCst), 1);
1443        assert_eq!(reader.read(|value| *value).unwrap(), 7);
1444        assert!(loads.is_poisoned());
1445        assert_eq!(key.retirements.load(Ordering::SeqCst), 0);
1446        drop(reader);
1447        assert!(owner.upgrade().is_none());
1448        assert_eq!(key.retirements.load(Ordering::SeqCst), 1);
1449    }
1450
1451    // Capture contention must fail before a reload reaches the provider.
1452    #[test]
1453    fn reload_rejects_a_busy_cohort_without_changing_its_capture() {
1454        use std::sync::atomic::{AtomicUsize, Ordering};
1455
1456        #[derive(Clone)]
1457        struct CountingKey(Arc<AtomicUsize>);
1458
1459        impl SharedReaderKey for CountingKey {
1460            type Value = usize;
1461            type Error = Infallible;
1462            type Subscription = ();
1463
1464            fn identity(&self) -> SharedKeyIdentity {
1465                SharedKeyIdentity::new::<Self>("busy-cohort", "")
1466            }
1467
1468            fn load(
1469                &self,
1470                _: SharedLoadContext<'_, usize>,
1471            ) -> impl Future<Output = Result<Option<usize>, Infallible>> + Send {
1472                self.0.fetch_add(1, Ordering::SeqCst);
1473                std::future::ready(Ok(None))
1474            }
1475
1476            fn subscribe(
1477                &self,
1478                _: SharedSubscribeContext,
1479                _: SharedSubscriber<usize>,
1480            ) -> Result<(), Infallible> {
1481                Ok(())
1482            }
1483        }
1484
1485        let key = CountingKey(Arc::new(AtomicUsize::new(0)));
1486        let cache = SharedKeyCache::new();
1487        let reader = futures_executor::block_on(cache.reader(key.clone(), || 7)).unwrap();
1488        assert_eq!(key.0.load(Ordering::SeqCst), 1);
1489        let shared = cohort(reader.clone());
1490        let guard = shared.cohort.lock().unwrap();
1491        let error = futures_executor::block_on(cache.reload(&shared, &key)).unwrap_err();
1492        assert!(error.access_error().unwrap().is_busy());
1493        assert_eq!(key.0.load(Ordering::SeqCst), 1);
1494        assert_eq!(reader.read(|value| *value).unwrap(), 7);
1495        drop(guard);
1496        futures_executor::block_on(cache.reload(&shared, &key)).unwrap();
1497        assert_eq!(key.0.load(Ordering::SeqCst), 2);
1498        assert_eq!(shared.read(|value| *value).unwrap(), 7);
1499    }
1500
1501    // Private cohort guards stop capture or rebind without fabricating cache state.
1502    #[test]
1503    fn load_contention_retires_provisional_subscription_before_retry() {
1504        #[derive(Clone)]
1505        struct Key(Arc<Mutex<Vec<&'static str>>>);
1506        struct Subscription(Arc<Mutex<Vec<&'static str>>>);
1507        impl Drop for Subscription {
1508            fn drop(&mut self) {
1509                self.0.lock().unwrap().push("retire");
1510            }
1511        }
1512        impl SharedReaderKey for Key {
1513            type Value = String;
1514            type Error = Infallible;
1515            type Subscription = Subscription;
1516
1517            fn identity(&self) -> SharedKeyIdentity {
1518                SharedKeyIdentity::new::<Self>("contended-load", "")
1519            }
1520            fn load(
1521                &self,
1522                context: SharedLoadContext<'_, String>,
1523            ) -> impl Future<Output = Result<Option<String>, Infallible>> + Send {
1524                assert!(matches!(context, SharedLoadContext::UserInitiated));
1525                self.0.lock().unwrap().push("reload");
1526                std::future::ready(Ok(None))
1527            }
1528            fn subscribe(
1529                &self,
1530                context: SharedSubscribeContext,
1531                _: SharedSubscriber<String>,
1532            ) -> Result<Subscription, Infallible> {
1533                assert_eq!(context, SharedSubscribeContext::UserInitiated);
1534                self.0.lock().unwrap().push("subscribe");
1535                Ok(Subscription(Arc::clone(&self.0)))
1536            }
1537        }
1538        impl SharedKey for Key {
1539            fn save(&self, _: &String) -> impl Future<Output = Result<(), Infallible>> + Send {
1540                self.0.lock().unwrap().push("save");
1541                std::future::ready(Ok(()))
1542            }
1543        }
1544
1545        let cache = SharedKeyCache::new();
1546        let key = Key(Arc::new(Mutex::new(Vec::new())));
1547        let shared = Shared::new(String::from("original"));
1548        let original = shared.reader().unwrap();
1549        let guard = shared.cohort.lock().unwrap();
1550        let error = futures_executor::block_on(cache.load(&shared, key.clone(), |_| {
1551            panic!("capture contention must not seed")
1552        }))
1553        .unwrap_err();
1554        assert!(error.access_error().unwrap().is_busy());
1555        assert!(error.into_failure().is_none());
1556        assert!(key.0.lock().unwrap().is_empty());
1557        drop(guard);
1558
1559        let mut retained_guard = None;
1560        let error = futures_executor::block_on(cache.load(&shared, key.clone(), |value| {
1561            assert_eq!(value, "original");
1562            retained_guard = Some(shared.cohort.lock().unwrap());
1563            String::from("provisional")
1564        }))
1565        .unwrap_err();
1566        assert!(error.access_error().unwrap().is_busy());
1567        assert!(error.into_failure().is_none());
1568        assert_eq!(*key.0.lock().unwrap(), ["subscribe", "retire"]);
1569        drop(retained_guard);
1570        assert!(shared.read(|value| value == "original").unwrap());
1571        assert!(original.read(|value| value == "original").unwrap());
1572
1573        futures_executor::block_on(cache.load(&shared, key.clone(), |value| {
1574            assert_eq!(value, "original");
1575            String::from("replacement")
1576        }))
1577        .unwrap();
1578        assert_eq!(
1579            *key.0.lock().unwrap(),
1580            ["subscribe", "retire", "subscribe", "reload"]
1581        );
1582        assert!(shared.read(|value| value == "replacement").unwrap());
1583        assert!(original.read(|value| value == "original").unwrap());
1584        drop(shared);
1585        assert_eq!(
1586            *key.0.lock().unwrap(),
1587            ["subscribe", "retire", "subscribe", "reload", "retire"]
1588        );
1589    }
1590
1591    #[test]
1592    fn failed_subscription_orphan_cannot_prepare_without_its_coordinator() {
1593        struct Value(u8, Arc<Mutex<Vec<u8>>>);
1594        impl Drop for Value {
1595            fn drop(&mut self) {
1596                self.1.lock().unwrap().push(self.0);
1597            }
1598        }
1599        struct Captured {
1600            subscriber: SharedSubscriber<Value>,
1601            publication: SharedPublication<Value>,
1602        }
1603        struct FailingSubscription(Arc<Mutex<Option<Captured>>>);
1604        impl SharedReaderKey for FailingSubscription {
1605            type Value = Value;
1606            type Error = &'static str;
1607            type Subscription = ();
1608
1609            fn identity(&self) -> SharedKeyIdentity {
1610                SharedKeyIdentity::new::<Self>("orphan", "")
1611            }
1612
1613            fn load(
1614                &self,
1615                _: SharedLoadContext<'_, Value>,
1616            ) -> impl Future<Output = Result<Option<Value>, &'static str>> + Send {
1617                std::future::ready(Ok(None))
1618            }
1619
1620            fn subscribe(
1621                &self,
1622                context: SharedSubscribeContext,
1623                subscriber: SharedSubscriber<Value>,
1624            ) -> Result<(), &'static str> {
1625                assert!(matches!(context, SharedSubscribeContext::Initial));
1626                let publication = subscriber.prepare_publication().unwrap();
1627                assert!(
1628                    self.0
1629                        .lock()
1630                        .unwrap()
1631                        .replace(Captured {
1632                            subscriber,
1633                            publication,
1634                        })
1635                        .is_none()
1636                );
1637                Err("subscription failed")
1638            }
1639        }
1640
1641        let cache = SharedKeyCache::new();
1642        let captured = Arc::new(Mutex::new(None));
1643        let drops = Arc::new(Mutex::new(Vec::new()));
1644        let error = futures_executor::block_on(
1645            cache.reader(FailingSubscription(Arc::clone(&captured)), || {
1646                Value(1, Arc::clone(&drops))
1647            }),
1648        )
1649        .unwrap_err();
1650        assert_eq!(error.into_failure(), Some("subscription failed"));
1651        assert!(cache.entries.lock().unwrap().is_empty());
1652        assert!(drops.lock().unwrap().is_empty());
1653        let Captured {
1654            subscriber,
1655            publication,
1656        } = captured.lock().unwrap().take().unwrap();
1657
1658        // Split a real provisional owner only at this private protocol boundary.
1659        // This is not a public scheduling proof or a fabricated weak identity.
1660        let SharedPublication { reference, loads } = publication;
1661        assert!(reference.retained.get().is_none());
1662        assert_eq!(Arc::strong_count(&reference), 1);
1663        assert_eq!(Arc::strong_count(&loads), 1);
1664        drop(loads);
1665        assert!(subscriber.loads.upgrade().is_none());
1666        assert_eq!(subscriber.reference.strong_count(), 1);
1667
1668        assert!(subscriber.prepare_publication().is_none());
1669        assert_eq!(Arc::strong_count(&reference), 1);
1670        assert_eq!(reference.value.lock().unwrap().0, 1);
1671        assert!(drops.lock().unwrap().is_empty());
1672        assert!(
1673            !subscriber
1674                .yield_value(Value(2, Arc::clone(&drops)))
1675                .unwrap()
1676        );
1677        assert_eq!(*drops.lock().unwrap(), [2]);
1678        assert_eq!(reference.value.lock().unwrap().0, 1);
1679        assert_eq!(Arc::strong_count(&reference), 1);
1680        drop(reference);
1681        assert_eq!(*drops.lock().unwrap(), [2, 1]);
1682        assert!(subscriber.reference.upgrade().is_none());
1683        assert!(subscriber.prepare_publication().is_none());
1684        drop(subscriber);
1685        drop(cache);
1686        assert_eq!(*drops.lock().unwrap(), [2, 1]);
1687        assert_eq!(Arc::strong_count(&drops), 1);
1688    }
1689
1690    #[test]
1691    fn subscriber_swap_retains_displaced_value_until_external_fence_is_released() {
1692        struct Reentrant(Arc<Mutex<bool>>, Arc<std::sync::atomic::AtomicUsize>);
1693        impl Drop for Reentrant {
1694            fn drop(&mut self) {
1695                *self
1696                    .0
1697                    .try_lock()
1698                    .expect("destructor can reenter cancellation") = false;
1699                self.1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1700            }
1701        }
1702        let control = Arc::new(Mutex::new(true));
1703        let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1704        let reference = Arc::new(SharedReference::new(Reentrant(
1705            Arc::clone(&control),
1706            Arc::clone(&drops),
1707        )));
1708        let loads = Arc::new(Mutex::new(None));
1709        let subscriber = SharedSubscriber {
1710            reference: Arc::downgrade(&reference),
1711            loads: Arc::downgrade(&loads),
1712        };
1713        let mut next = Reentrant(Arc::clone(&control), Arc::clone(&drops));
1714        let publication = subscriber.prepare_publication().unwrap();
1715        drop(reference);
1716        let guard = control.lock().unwrap();
1717        assert!(publication.try_replace(&mut next).unwrap());
1718        drop(guard);
1719        drop(next);
1720        assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 1);
1721        drop(publication);
1722        assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 2);
1723        assert!(!*control.lock().unwrap());
1724        assert!(subscriber.prepare_publication().is_none());
1725    }
1726
1727    #[test]
1728    fn prepared_publication_and_cancellation_have_one_final_commit_order() {
1729        let reference = Arc::new(SharedReference::new(7));
1730        let loads = Arc::new(Mutex::new(None));
1731        let subscriber = SharedSubscriber {
1732            reference: Arc::downgrade(&reference),
1733            loads: Arc::downgrade(&loads),
1734        };
1735        let publication = subscriber.prepare_publication().unwrap();
1736        let control = Arc::new(Mutex::new(true));
1737        let publishing = Arc::clone(&control);
1738        let cancelling = Arc::clone(&control);
1739        let (checked, checked_rx) = std::sync::mpsc::channel();
1740        let (resume, resume_rx) = std::sync::mpsc::channel();
1741        let (attempted, attempted_rx) = std::sync::mpsc::channel();
1742        let (cancelled, cancelled_rx) = std::sync::mpsc::channel();
1743        let worker = std::thread::spawn(move || {
1744            let mut next = 8;
1745            let fence = publishing.lock().unwrap();
1746            assert!(*fence);
1747            checked.send(()).unwrap();
1748            resume_rx.recv().unwrap(); // controlled pause immediately before swap
1749            assert!(publication.try_replace(&mut next).unwrap());
1750            drop(fence);
1751            assert_eq!(next, 7);
1752        });
1753        checked_rx.recv().unwrap();
1754        let cancellation_worker = std::thread::spawn(move || {
1755            attempted.send(()).unwrap();
1756            *cancelling.lock().unwrap() = false;
1757            cancelled.send(()).unwrap();
1758        });
1759        attempted_rx.recv().unwrap();
1760        assert_eq!(*reference.value.lock().unwrap(), 7);
1761        assert!(matches!(
1762            cancelled_rx.try_recv(),
1763            Err(std::sync::mpsc::TryRecvError::Empty)
1764        ));
1765        resume.send(()).unwrap();
1766        worker.join().unwrap();
1767        cancellation_worker.join().unwrap();
1768        cancelled_rx.recv().unwrap();
1769        assert_eq!(*reference.value.lock().unwrap(), 8);
1770        let publication = subscriber.prepare_publication().unwrap();
1771        let mut next = 99;
1772        {
1773            let fence = control.lock().unwrap();
1774            if *fence {
1775                publication.try_replace(&mut next).unwrap();
1776            }
1777        }
1778        assert_eq!(next, 99);
1779        assert_eq!(*reference.value.lock().unwrap(), 8);
1780    }
1781
1782    #[test]
1783    fn obsolete_attempts_cannot_clear_the_latest_loading_token() {
1784        let reference = SharedReference::new(1);
1785        let loads = Mutex::new(None);
1786        let old = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
1787        let latest = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
1788        assert!(!old.commit(Some(10)).unwrap());
1789        assert!(latest.is_latest(loads.lock().unwrap().as_ref()));
1790        assert!(latest.commit(Some(20)).unwrap());
1791        assert!(loads.lock().unwrap().is_none());
1792        assert_eq!(*reference.value.lock().unwrap(), 20);
1793
1794        let old = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
1795        let latest = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
1796        drop(old);
1797        assert!(latest.is_latest(loads.lock().unwrap().as_ref()));
1798        drop(latest);
1799        assert!(loads.lock().unwrap().is_none());
1800    }
1801
1802    #[test]
1803    fn latest_busy_commit_retires_without_replacing_or_poisoning() {
1804        let reference = SharedReference::new(1);
1805        let loads = Mutex::new(None);
1806        let attempt = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
1807        let current = reference.value.lock().unwrap();
1808        assert!(attempt.commit(Some(2)).unwrap_err().is_busy());
1809        assert!(loads.lock().unwrap().is_none());
1810        assert_eq!(*current, 1);
1811        drop(current);
1812        assert!(
1813            ReferenceLoadAttempt::begin(&reference, &loads)
1814                .unwrap()
1815                .commit(Some(3))
1816                .unwrap()
1817        );
1818    }
1819
1820    struct LayoutKey;
1821
1822    impl SharedReaderKey for LayoutKey {
1823        type Value = usize;
1824        type Error = Infallible;
1825        type Subscription = ();
1826
1827        fn identity(&self) -> SharedKeyIdentity {
1828            SharedKeyIdentity::new::<()>("layout", "")
1829        }
1830
1831        fn load(
1832            &self,
1833            _: SharedLoadContext<'_, usize>,
1834        ) -> impl Future<Output = Result<Option<usize>, Infallible>> + Send {
1835            std::future::ready(Ok(None))
1836        }
1837
1838        fn subscribe(
1839            &self,
1840            _: SharedSubscribeContext,
1841            _: SharedSubscriber<usize>,
1842        ) -> Result<(), Infallible> {
1843            Ok(())
1844        }
1845    }
1846
1847    #[test]
1848    fn reports_retained_reference_layout() {
1849        // Adding keyed metadata to public handles would increase every capture.
1850        assert_eq!(size_of::<Shared<usize>>(), size_of::<Arc<()>>());
1851        assert_eq!(size_of::<SharedReader<usize>>(), size_of::<Arc<()>>());
1852        eprintln!(
1853            "Shared<usize>={} SharedReader<usize>={} old-value-mutex={} retained-reference={} keyed-resource={} coordinator={} attempt={} strong-token={} weak-token={} subscriber={}",
1854            size_of::<Shared<usize>>(),
1855            size_of::<SharedReader<usize>>(),
1856            size_of::<Mutex<usize>>(),
1857            size_of::<SharedReference<usize>>(),
1858            size_of::<KeyResource<LayoutKey>>(),
1859            size_of::<Mutex<Option<Weak<()>>>>(),
1860            size_of::<ReferenceLoadAttempt<'_, usize>>(),
1861            size_of::<Arc<()>>(),
1862            size_of::<Weak<()>>(),
1863            size_of::<SharedSubscriber<usize>>(),
1864        );
1865    }
1866}