Skip to main content

nmbrs_runtime/
resource_pool.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Generic resource lifecycle and sharing pool — SRD-35 Push A.
5//!
6//! ## What this module provides
7//!
8//! Trait surface and runtime structure for sharing
9//! long-lived resources (CQL sessions, HTTP clients, …)
10//! across phases of one session, decoupled from per-phase
11//! adapter shells. The contract is intentionally generic —
12//! nothing here is CQL-specific.
13//!
14//! ### Core types
15//!
16//! - [`SharedResource`] — the trait every poolable resource
17//!   implements. Carries [`SharedResource::can_share`]
18//!   (capability declaration: thread-safe + designed for
19//!   sharing) and [`SharedResource::can_support_more_load`] (driver's
20//!   runtime judgement that another instance would relieve
21//!   knowable, substantial contention) — see the SRD-35
22//!   load-bearing rules.
23//! - [`ResourceKey`] — value-equality identity. Two keys
24//!   compare equal iff their adapter name and fields match
25//!   exactly. No derived hash function; the contract is
26//!   structural.
27//! - [`ShareCapability`] — strictest sharing the resource
28//!   *type* tolerates. Read by the pool at planning time
29//!   without an instance.
30//! - [`ResourceSharePolicy`] — user-elevatable isolation
31//!   policy. Must satisfy `policy >= capability_floor`.
32//! - [`ResourcePool`] — owns the `(ResourceKey, generation)
33//!   → Entry` map, tracks refcounts, emits lifecycle events.
34//!
35//! ## Push A scope
36//!
37//! Push A lays the trait foundation, the pool data
38//! structure, the lifecycle event emission, and a
39//! [`LegacyAdapterResource`] shim that wraps the existing
40//! `Arc<dyn DriverAdapter>` factories under `PerPhase`
41//! policy. Behaviour is byte-identical to today (a fresh
42//! resource per phase) but every phase boundary now emits
43//! the full `resource.{attach,init,detach,close}` event
44//! sequence.
45//!
46//! Push B will migrate the CQL adapter to `Shared` policy
47//! by splitting `CqlAdapter` into a per-phase shell + a
48//! `CassDriverInstance` that implements `SharedResource`
49//! directly with real async `close()`. The pool's
50//! multi-generation machinery is in place but exercised
51//! only by the synthetic mock resource in tests until then.
52
53use std::any::Any;
54use std::collections::{BTreeMap, HashMap};
55use std::future::Future;
56use std::pin::Pin;
57use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
58use std::sync::{Arc, Mutex, Weak};
59use std::time::Instant;
60
61use crate::adapter::DriverAdapter;
62use crate::observer::LogLevel;
63
64// =================================================================
65// Resource key — value-equality identity
66// =================================================================
67
68/// Structural value identity for a shared resource.
69///
70/// Two adapters that build equal `ResourceKey`s receive the
71/// same instance under `Shared` policy. The internal
72/// `BTreeMap` is sorted so equality is deterministic, and
73/// `Hash` is derived structurally for `HashMap` lookup. The
74/// pool never asks adapters to produce a "key digest"; the
75/// contract is value equality on the public type.
76///
77/// Adapters populate `fields` with **only** the params that
78/// distinguish one instance from another. Per-statement and
79/// per-phase shaping (timeouts, trace rates, dynamic
80/// controls) MUST NOT appear in the key — see SRD-35
81/// §"Instance-shaping vs shell-shaping params".
82#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
83pub struct ResourceKey {
84    /// Adapter name (`"cql"`, `"http"`, …) — the
85    /// adapter-name surface, not the engine-specific driver
86    /// identifier (which the adapter folds into the fields
87    /// when meaningful).
88    pub adapter: String,
89    /// Identity-bearing param values, sorted so equality is
90    /// independent of insertion order.
91    pub fields: BTreeMap<String, String>,
92}
93
94impl ResourceKey {
95    /// Construct a key for the given adapter with no fields
96    /// yet. Chain [`Self::with`] to populate.
97    pub fn new(adapter: impl Into<String>) -> Self {
98        Self {
99            adapter: adapter.into(),
100            fields: BTreeMap::new(),
101        }
102    }
103
104    /// Set or replace the value for one identity-bearing
105    /// field, returning `self` for chaining.
106    pub fn with(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
107        self.fields.insert(key.into(), value.into());
108        self
109    }
110
111    /// Render the key for a single line of log output
112    /// (`adapter{k1=v1,k2=v2}`). Stable shape — the
113    /// lifecycle-event surface relies on this format being
114    /// consistent across log consumers.
115    pub fn fmt_for_log(&self) -> String {
116        let mut s = String::with_capacity(64);
117        s.push_str(&self.adapter);
118        s.push('{');
119        let mut first = true;
120        for (k, v) in &self.fields {
121            if !first {
122                s.push(',');
123            }
124            first = false;
125            s.push_str(k);
126            s.push('=');
127            // Don't log secrets. Adapters can prefix
128            // sensitive fields with `_secret_` to redact.
129            if k.starts_with("_secret_") || k == "password" {
130                s.push_str("***");
131            } else {
132                s.push_str(v);
133            }
134        }
135        s.push('}');
136        s
137    }
138
139    /// SRD-104 — the **canonical fingerprint rendering** of this key to a
140    /// stable string, used as the accessor lookup key
141    /// ([`polydat::ResourceAccessor::lookup`]). Unlike [`Self::fmt_for_log`]
142    /// this rendering is **identity-preserving**: two keys that differ
143    /// only in an identity-bearing field (e.g. `password`) MUST render to
144    /// different strings or they would collide in the accessor. A secret
145    /// field (`password`, `_secret_*`) contributes a SHA-256 digest of its
146    /// value rather than the value itself, so the fingerprint keeps its
147    /// identity without ever carrying the cleartext into a kernel binding
148    /// or a diagnostic. The `BTreeMap` makes the field order
149    /// deterministic, so equal keys always render identically.
150    ///
151    /// This is the single rendering shared by both sides of the SRD-104
152    /// bridge: the resource pool renders each live entry's key with it when
153    /// resolving a lookup, and a consumer node builds the same string from
154    /// the fingerprint in scope. Shape: `adapter{k1=v1,k2=v2}`.
155    pub fn render_key(&self) -> String {
156        let mut s = String::with_capacity(64);
157        s.push_str(&self.adapter);
158        s.push('{');
159        let mut first = true;
160        for (k, v) in &self.fields {
161            if !first {
162                s.push(',');
163            }
164            first = false;
165            s.push_str(k);
166            s.push('=');
167            if k.starts_with("_secret_") || k == "password" {
168                use sha2::{Digest, Sha256};
169                let digest = Sha256::digest(v.as_bytes());
170                s.push_str("sha256:");
171                for byte in &digest[..8] {
172                    s.push_str(&format!("{byte:02x}"));
173                }
174            } else {
175                s.push_str(v);
176            }
177        }
178        s.push('}');
179        s
180    }
181}
182
183// =================================================================
184// Capability and policy
185// =================================================================
186
187/// Strongest sharing the resource *type* can tolerate.
188/// Declared by the factory at registration time so the pool
189/// can plan the entry layout without configuring or
190/// instantiating any resource. The live instance's
191/// [`SharedResource::can_share`] is a runtime safety net
192/// that aborts the session if it disagrees with this
193/// type-level declaration.
194///
195/// The variants order from most-shared to most-isolated;
196/// `PartialOrd` semantics let the pool check policy ≥
197/// capability with a single comparison.
198#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
199pub enum ShareCapability {
200    /// Safe to share one instance across every adapter
201    /// shell in the workload that produces an equal key.
202    /// CQL, HTTP-with-pool, OpenAPI typically.
203    Shared,
204    /// One instance per scenario subtree. Use when state
205    /// changes during the run that mustn't bleed across
206    /// scenarios (auth tokens, schema versions per
207    /// scenario).
208    PerScenario,
209    /// One instance per phase. Use when each phase
210    /// legitimately wants a fresh state object.
211    PerPhase,
212    /// One instance per fiber. Use only when the resource
213    /// type is `Send` but not `Sync`, or when the
214    /// underlying library mandates single-threaded use.
215    PerFiber,
216}
217
218/// User-selectable isolation. Must satisfy
219/// `policy >= capability_floor`.
220#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
221pub enum ResourceSharePolicy {
222    Shared,
223    PerScenario,
224    PerPhase,
225    PerFiber,
226}
227
228impl ResourceSharePolicy {
229    /// Map a user-string (CLI / workload param) to the
230    /// enum. Used by the SRD-04 umbrella surface
231    /// (`--resource-share <adapter>:<policy>`).
232    pub fn parse(s: &str) -> Result<Self, String> {
233        match s.trim().to_ascii_lowercase().as_str() {
234            "shared" => Ok(Self::Shared),
235            "per-scenario" | "per_scenario" => Ok(Self::PerScenario),
236            "per-phase" | "per_phase" => Ok(Self::PerPhase),
237            "per-fiber" | "per_fiber" => Ok(Self::PerFiber),
238            other => Err(format!(
239                "unknown resource-share policy '{other}' \
240                 (expected: shared, per-scenario, per-phase, per-fiber)"
241            )),
242        }
243    }
244}
245
246impl std::fmt::Display for ResourceSharePolicy {
247    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
248        let s = match self {
249            Self::Shared => "shared",
250            Self::PerScenario => "per-scenario",
251            Self::PerPhase => "per-phase",
252            Self::PerFiber => "per-fiber",
253        };
254        f.write_str(s)
255    }
256}
257
258/// Default sharing policy — the strongest sharing the
259/// capability allows. Used when the user gives no override.
260pub fn default_policy_for(cap: ShareCapability) -> ResourceSharePolicy {
261    match cap {
262        ShareCapability::Shared => ResourceSharePolicy::Shared,
263        ShareCapability::PerScenario => ResourceSharePolicy::PerScenario,
264        ShareCapability::PerPhase => ResourceSharePolicy::PerPhase,
265        ShareCapability::PerFiber => ResourceSharePolicy::PerFiber,
266    }
267}
268
269/// Minimum policy compatible with the given capability.
270/// Used by the pool to validate user-supplied policies at
271/// session start.
272pub fn capability_floor(cap: ShareCapability) -> ResourceSharePolicy {
273    match cap {
274        ShareCapability::Shared => ResourceSharePolicy::Shared,
275        ShareCapability::PerScenario => ResourceSharePolicy::PerScenario,
276        ShareCapability::PerPhase => ResourceSharePolicy::PerPhase,
277        ShareCapability::PerFiber => ResourceSharePolicy::PerFiber,
278    }
279}
280
281// =================================================================
282// SharedResource trait
283// =================================================================
284
285/// One async-init-and-close return type used by the
286/// trait. Returns a `Send` future so the pool can hold it
287/// across `.await` points without runtime fuss.
288pub type ResourceFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
289
290/// The trait every poolable resource implements.
291///
292/// `Send + Sync + 'static` is required so the pool can hold
293/// `Arc<dyn SharedResource>` and clone it across fibers.
294///
295/// Default implementations make the trivial case
296/// (always-shareable, never-saturated, no-op init/close)
297/// boilerplate-free — only `resource_key()` is required to
298/// override.
299pub trait SharedResource: Send + Sync + 'static {
300    /// The structural identity of this resource.
301    fn resource_key(&self) -> &ResourceKey;
302
303    /// **Capability** — does this instance support being
304    /// shared by multiple adapter shells concurrently?
305    /// Default `true`. See SRD-35 §"Two trait methods on
306    /// the live resource".
307    fn can_share(&self) -> bool {
308        true
309    }
310
311    /// **Live capacity** — can this instance accept *another*
312    /// concurrent caller right now without substantial
313    /// contention?
314    ///
315    /// `true` (default) → "yes, route the next attach to me;
316    /// I have capacity." `false` → "no, I'm saturated; the
317    /// pool should spawn a sibling for the new attach."
318    /// Parallel naming to `can_share()`: `can_share()` says
319    /// *whether* sharing is structurally possible at all;
320    /// `can_support_more_load()` says *whether one more
321    /// caller is OK at this moment*.
322    ///
323    /// Drivers that override MUST document their decision
324    /// criterion in the type docstring (the operator reading
325    /// a `reason=capacity-declined` lifecycle event needs to
326    /// be able to interpret what triggered it).
327    /// MUST be cheap (atomic read or short metric query);
328    /// MUST NOT block. SRD-35 §"Validity rules" requires
329    /// the body to reflect *current* in-flight load — never
330    /// historical/peak/lifetime metrics. The pool's guard in
331    /// `needs_sibling_spawn` catches the historical-state
332    /// failure mode (driver returns `false` at quiescence)
333    /// and emits a `Warn` event so operators can spot the
334    /// driver bug.
335    fn can_support_more_load(&self) -> bool {
336        true
337    }
338
339    /// Optional async init beyond what construction
340    /// already did. Called by the pool on first attach for
341    /// a key, exactly once per `(key, generation)`.
342    fn init(&self) -> ResourceFuture<'_, Result<(), String>> {
343        Box::pin(async { Ok(()) })
344    }
345
346    /// Symmetric teardown. Called when the entry's
347    /// refcount hits zero. MUST block until network /
348    /// kernel resources are *actually released* — no
349    /// async-Drop races, no sockets in TIME_WAIT being
350    /// counted as closed, no libuv worker thread races.
351    fn close(self: Arc<Self>) -> ResourceFuture<'static, Result<(), String>> {
352        Box::pin(async { Ok(()) })
353    }
354
355    /// Bridge for the Push A legacy-adapter shim. Default
356    /// returns `None`; only [`LegacyAdapterResource`]
357    /// overrides it to surface its wrapped `DriverAdapter`
358    /// handle. Push B retires this entirely once each
359    /// adapter has its own `SharedResource` impl with no
360    /// hidden `DriverAdapter` inside.
361    ///
362    /// Real `SharedResource` implementations should leave
363    /// this at the default — the pool layer is the right
364    /// place to surface domain-specific handles, not the
365    /// trait surface.
366    fn as_legacy_adapter(&self) -> Option<Arc<dyn DriverAdapter>> {
367        None
368    }
369
370    /// SRD-104 — the resource's **accessor payload**: a type-erased handle
371    /// (`Arc<dyn Any + Send + Sync>`) a kernel node can obtain by
372    /// fingerprint through its kernel tree's resource scope. The pool stores it on
373    /// the entry right after a successful init, and its
374    /// [`polydat::ResourceAccessor`] impl hands out clones. Default `None`
375    /// — a resource opts in only when it wants kernels to reach a live
376    /// handle (the first consumer is a CQL session handle, SRD-103); no
377    /// existing adapter is affected.
378    fn accessor_payload(&self) -> Option<Arc<dyn Any + Send + Sync>> {
379        None
380    }
381}
382
383// =================================================================
384// Internal entry — one per (key, generation)
385// =================================================================
386
387/// Pool entry tracking one resource instance and its
388/// refcount state.
389struct Entry {
390    key: ResourceKey,
391    policy: ResourceSharePolicy,
392    generation: usize,
393
394    /// The lazily-constructed resource. `tokio::sync::OnceCell`
395    /// would work too; we use a `Mutex<Option<…>>` because
396    /// Push A doesn't yet need cross-fiber concurrent first-
397    /// attach contention (the pool's outer mutex serialises),
398    /// and the simpler shape avoids pulling tokio into the
399    /// type signature.
400    resource: Mutex<Option<Arc<dyn SharedResource>>>,
401
402    /// Set when init failed. Subsequent attaches return the
403    /// cached error rather than retrying.
404    poisoned: AtomicBool,
405    /// Cached init error message, populated alongside
406    /// `poisoned`.
407    init_error: Mutex<Option<String>>,
408
409    /// Predicted future attaches that haven't yet landed
410    /// on this entry. SRD-35 Push D's pre-map walker
411    /// (`pre_map_pending_uses`) seeds this from the
412    /// scenario tree at session bootstrap; each `attach`
413    /// decrements eagerly. The pool's close trigger fires
414    /// the moment `pending_uses == 0 && live_attaches ==
415    /// 0`, releasing the resource the instant its last
416    /// predicted user is done.
417    pending_uses: AtomicUsize,
418    /// Currently in-use shells. Decremented on detach.
419    live_attaches: AtomicUsize,
420
421    /// Wall-clock instant at which `init()` started — used
422    /// to compute `elapsed_ms` on `init.completed` /
423    /// `init.failed` events.
424    init_started_at: Mutex<Option<Instant>>,
425
426    /// SRD-104 — the resource's type-erased **accessor payload**, populated
427    /// right after a successful init from [`SharedResource::accessor_payload`]
428    /// and returned by the pool's [`polydat::ResourceAccessor`] impl. `None`
429    /// until init succeeds, and `None` for resources that don't opt in (the
430    /// trait default). The payload lives and dies with the entry — no second
431    /// store.
432    accessor_payload: Mutex<Option<Arc<dyn Any + Send + Sync>>>,
433}
434
435impl Entry {
436    fn new(key: ResourceKey, policy: ResourceSharePolicy, generation: usize) -> Self {
437        Self {
438            key,
439            policy,
440            generation,
441            resource: Mutex::new(None),
442            poisoned: AtomicBool::new(false),
443            init_error: Mutex::new(None),
444            pending_uses: AtomicUsize::new(0),
445            live_attaches: AtomicUsize::new(0),
446            init_started_at: Mutex::new(None),
447            accessor_payload: Mutex::new(None),
448        }
449    }
450}
451
452// =================================================================
453// `can_support_more_load()` validity guard
454// =================================================================
455
456/// Decide whether the pool should spawn a sibling
457/// generation for this attach.
458///
459/// Returns `true` only when the active resource genuinely
460/// can't take another caller (`can_support_more_load() ==
461/// false`) AND there's actual concurrent load
462/// (`live_attaches > 0`). Both halves are required:
463///
464/// - `can_support_more_load() == true` → existing instance
465///   has capacity; route the attach there. No spawn.
466/// - `can_support_more_load() == false` AND `live > 0` →
467///   genuine saturation; spawn a sibling.
468/// - `can_support_more_load() == false` AND `live == 0` →
469///   **driver bug**: the resource refused a new caller
470///   while sitting completely idle. SRD-35 §"Validity
471///   rules" forbids this — `can_support_more_load()` must
472///   reflect *current* in-flight load, never historical /
473///   peak / lifetime state. The classic failure mode is a
474///   ring buffer or moving-average metric that filled
475///   during an earlier phase and hasn't decayed; reading
476///   it at quiescence falsely reports saturation. The
477///   guard logs a `Warn` so the operator sees the driver
478///   bug, and routes the attach to the existing idle
479///   instance instead of wasting a sibling.
480///
481/// Push A/B do not yet wire the sibling-spawn path, but
482/// this helper lands now so Push D's spawn logic uses it
483/// from day one. Tests exercise it directly.
484#[allow(dead_code)]
485fn needs_sibling_spawn(entry: &Entry, resource: &dyn SharedResource) -> bool {
486    if resource.can_support_more_load() {
487        // Existing generation has capacity — route there.
488        return false;
489    }
490    let live = entry.live_attaches.load(Ordering::Acquire);
491    if live == 0 {
492        // Driver bug: refused a new attach at quiescence.
493        // Log once per occurrence with the resource key so
494        // the operator can attribute it. Don't spawn — the
495        // existing idle generation is the right answer.
496        crate::diag!(
497            LogLevel::Warn,
498            "{EVENT_FAMILY}.share.suppressed key={} generation={} \
499             reason=quiescent-decline \
500             note=can_support_more_load() returned false with live_attaches=0; \
501             driver may be reading historical state (filled ring buffer, \
502             moving-average that hasn't decayed) instead of in-flight load \
503             (SRD-35 §\"Validity rules\")",
504            entry.key.fmt_for_log(),
505            entry.generation,
506        );
507        return false;
508    }
509    // Genuine saturation: refusing under live load.
510    true
511}
512
513// =================================================================
514// Lifecycle event emission
515// =================================================================
516
517/// Family prefix on every event line emitted by the pool.
518/// Enables log-side filtering with one substring.
519const EVENT_FAMILY: &str = "resource";
520
521/// Emit one lifecycle event line. All events carry `key`,
522/// `generation`, and `policy`; per-event extra fields are
523/// appended to the formatted suffix.
524fn emit_event(level: LogLevel, name: &str, entry: &Entry, extra: &str) {
525    let suffix = if extra.is_empty() {
526        String::new()
527    } else {
528        format!(" {extra}")
529    };
530    crate::diag!(
531        level,
532        "{EVENT_FAMILY}.{name} key={} generation={} policy={}{suffix}",
533        entry.key.fmt_for_log(),
534        entry.generation,
535        entry.policy,
536    );
537}
538
539// =================================================================
540// Resource pool
541// =================================================================
542
543/// One `(ResourceKey, generation)` map for the lifetime of
544/// one session. Owns lazy init, refcount transitions, and
545/// the close trigger.
546///
547/// The pool is `Send + Sync` and intended to be held in an
548/// `Arc` from the session root (executor's `ExecCtx` or
549/// equivalent). Each phase activation calls
550/// [`attach`] for the adapter names it needs;
551/// the returned [`AttachGuard`] holds a clone of the
552/// per-phase `DriverAdapter` shell and detaches on drop.
553pub struct ResourcePool {
554    inner: Mutex<PoolInner>,
555    /// Session-lived state adapters keep here, one value per type
556    /// ([`Self::extension`]). Closed at [`Self::shutdown`].
557    extensions: Mutex<HashMap<std::any::TypeId, Arc<dyn PoolExtension>>>,
558}
559
560/// Session-lived state an adapter keeps in the pool
561/// ([`ResourcePool::extension`]).
562pub trait PoolExtension: Any + Send + Sync {
563    /// The session is ending. Release what the extension holds: stop
564    /// threads, close files. Called once, off the async workers, so it
565    /// may block. Other holders of the extension may outlive this
566    /// call, which is why it is a call and not a drop.
567    fn close(&self);
568    /// The extension as `Any`, for the pool to hand it back typed.
569    fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
570}
571
572struct PoolInner {
573    /// Active entries keyed by `(ResourceKey, generation)`.
574    /// We use a `Vec<Arc<Entry>>` for ordered iteration;
575    /// the `HashMap` is the lookup index.
576    entries_by_key: HashMap<(ResourceKey, usize), Arc<Entry>>,
577
578    /// Cumulative attach count — used for diagnostic
579    /// post-mortems and the `nmbrs describe drivers` output
580    /// that's deferred to a later SRD.
581    total_attaches: usize,
582}
583
584impl ResourcePool {
585    pub fn new() -> Self {
586        Self {
587            inner: Mutex::new(PoolInner {
588                entries_by_key: HashMap::new(),
589                total_attaches: 0,
590            }),
591            extensions: Mutex::new(HashMap::new()),
592        }
593    }
594
595    /// The session's one value of type `T`, made by `init` on first
596    /// use.
597    ///
598    /// The pool's entries are adapters, keyed by adapter params and
599    /// closed when their last phase detaches. This is for what an
600    /// adapter must keep across phases under a key of its own: the
601    /// logfile adapter's tails, which are named by an op field and
602    /// must see the log through phases that do not use them
603    /// (SRD-117 §3.9). The value is closed at [`Self::shutdown`].
604    pub fn extension<T: PoolExtension>(&self, init: impl FnOnce() -> T) -> Arc<T> {
605        let mut extensions = self.extensions.lock().unwrap_or_else(|e| e.into_inner());
606        let entry = extensions
607            .entry(std::any::TypeId::of::<T>())
608            .or_insert_with(|| Arc::new(init()) as Arc<dyn PoolExtension>);
609        entry
610            .clone()
611            .as_any()
612            .downcast::<T>()
613            .unwrap_or_else(|_| unreachable!("an extension is stored under its own type"))
614    }
615
616    /// Total attach count since pool construction. Useful
617    /// for tests and post-mortem diagnostics.
618    pub fn total_attaches(&self) -> usize {
619        self.inner
620            .lock()
621            .unwrap_or_else(|e| e.into_inner())
622            .total_attaches
623    }
624
625    /// Number of distinct entries currently live in the
626    /// pool. One per `(key, generation)` that's been
627    /// attached at least once and not yet fully drained.
628    pub fn live_entries(&self) -> usize {
629        self.inner
630            .lock()
631            .unwrap_or_else(|e| e.into_inner())
632            .entries_by_key
633            .len()
634    }
635
636    /// Drain every live entry, awaiting each resource's
637    /// `close()` and removing the entry from the map. Call
638    /// at session end so `Shared`-policy entries — which
639    /// the per-attach detach intentionally keeps alive
640    /// across phases — release their network resources
641    /// before the process exits.
642    ///
643    /// Emits `resource.close.started reason=session-end`
644    /// per entry, then `resource.close.completed` /
645    /// `resource.close.failed` after each resource's
646    /// `close()` future resolves. Returns `Ok(())` even if
647    /// individual close calls fail — the failures are
648    /// logged and accounted, but the pool always finishes
649    /// the drain so the executor can move on.
650    pub async fn shutdown(self: &Arc<Self>) {
651        // Extensions first: closing one may stop a thread and wait
652        // for it, which must not happen on an async worker.
653        let extensions =
654            std::mem::take(&mut *self.extensions.lock().unwrap_or_else(|e| e.into_inner()));
655        if !extensions.is_empty() {
656            let _ = tokio::task::spawn_blocking(move || {
657                for extension in extensions.values() {
658                    extension.close();
659                }
660            })
661            .await;
662        }
663        // Snapshot the entries, then drop the lock so the
664        // close futures can run unblocked.
665        let entries: Vec<Arc<Entry>> = {
666            let inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
667            inner.entries_by_key.values().cloned().collect()
668        };
669        for entry in entries {
670            // Take the resource out of the slot. If it's
671            // already gone (concurrent close, or never
672            // realised after init failure), skip.
673            let resource = {
674                let mut slot = entry.resource.lock().unwrap_or_else(|e| e.into_inner());
675                slot.take()
676            };
677            let Some(resource) = resource else {
678                self.remove_entry(&entry.key, entry.generation);
679                continue;
680            };
681            let live = entry.live_attaches.load(Ordering::Acquire);
682            let pending = entry.pending_uses.load(Ordering::Acquire);
683            // Note residual counts on the started event so
684            // operators can spot bugs in the pre-map walker
685            // when it lands (Push D): if `pending > 0` at
686            // session end, the walker over-predicted; if
687            // `live > 0`, an attach guard wasn't dropped.
688            emit_event(
689                LogLevel::Debug,
690                "close.started",
691                &entry,
692                &format!("reason=session-end live={live} pending={pending}"),
693            );
694            let started_at = Instant::now();
695            let result = resource.close().await;
696            let elapsed_ms = started_at.elapsed().as_millis() as u64;
697            match result {
698                Ok(()) => emit_event(
699                    LogLevel::Debug,
700                    "close.completed",
701                    &entry,
702                    &format!("elapsed_ms={elapsed_ms}"),
703                ),
704                Err(ref e) => emit_event(
705                    LogLevel::Warn,
706                    "close.failed",
707                    &entry,
708                    &format!("elapsed_ms={elapsed_ms} error={e:?}"),
709                ),
710            }
711            self.remove_entry(&entry.key, entry.generation);
712        }
713    }
714
715    /// SRD-35 Push D: declare a predicted future attach for
716    /// `key` under `policy`. Called by the pre-map walker
717    /// once per phase that will eventually attach this key
718    /// — the per-key counter accumulates so a `Shared`
719    /// entry attached by 50 phases starts the run with
720    /// `pending_uses = 50`. Each `attach` decrements
721    /// eagerly; the entry's close trigger fires the moment
722    /// `pending == 0 && live == 0`, releasing the resource
723    /// the instant its last user is done rather than holding
724    /// it until session end.
725    ///
726    /// Idempotent for a given `(key, policy)` — the entry is
727    /// created on first call, then increments on subsequent
728    /// calls. The pre-map walker is the only declared caller;
729    /// adapters never invoke this directly.
730    pub fn declare_pending_use(&self, key: ResourceKey, policy: ResourceSharePolicy) {
731        let entry = self.get_or_create_entry(key, policy, 0);
732        entry.pending_uses.fetch_add(1, Ordering::AcqRel);
733    }
734
735    /// SRD-35 Push D: explicit per-key `pending_uses`
736    /// decrement, mirroring [`Self::declare_pending_use`].
737    /// Most callers don't need this — the [`AttachGuard`]
738    /// detach path already decrements via the `attach`-time
739    /// "slot consumed" semantic, and the close trigger
740    /// observes the resulting `pending == 0 && live == 0`
741    /// invariant. Provided so external callers (tests, future
742    /// pre-map invalidation paths) can adjust the counter
743    /// explicitly. Saturating at 0 — calling this on a key
744    /// with no pending uses left is a no-op, not an
745    /// underflow.
746    ///
747    /// Returns `true` when the call drove `pending` to 0
748    /// AND `live` was already 0 (so the entry was eligible
749    /// for close). Doesn't itself trigger close — the close
750    /// path runs on detach. Tests that exercise the
751    /// counter-only lifecycle use the return to assert the
752    /// "eligible for close" gate without setting up a real
753    /// attach.
754    pub fn complete_pending_use(&self, key: &ResourceKey) -> bool {
755        let inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
756        let Some(entry) = inner.entries_by_key.get(&(key.clone(), 0)).cloned() else {
757            return false;
758        };
759        drop(inner);
760        let cur = entry.pending_uses.load(Ordering::Acquire);
761        if cur == 0 {
762            return entry.live_attaches.load(Ordering::Acquire) == 0;
763        }
764        let new_pending = entry.pending_uses.fetch_sub(1, Ordering::AcqRel) - 1;
765        new_pending == 0 && entry.live_attaches.load(Ordering::Acquire) == 0
766    }
767
768    /// SRD-35 Push D introspection helper: how many predicted
769    /// future attaches remain on the entry for `key` (gen 0).
770    /// Returns `None` when no entry exists for the key.
771    /// Tests use this to assert pre-map walker correctness
772    /// without poking the pool internals.
773    pub fn pending_uses_for(&self, key: &ResourceKey) -> Option<usize> {
774        let inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
775        inner
776            .entries_by_key
777            .get(&(key.clone(), 0))
778            .map(|e| e.pending_uses.load(Ordering::Acquire))
779    }
780
781    /// Look up or create the entry for the given key under
782    /// the given policy. Generation 0 by default; siblings
783    /// (Push D) will create higher generations on
784    /// `can_support_more_load()` recommendation.
785    fn get_or_create_entry(
786        &self,
787        key: ResourceKey,
788        policy: ResourceSharePolicy,
789        generation: usize,
790    ) -> Arc<Entry> {
791        let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
792        let map_key = (key.clone(), generation);
793        if let Some(existing) = inner.entries_by_key.get(&map_key) {
794            return existing.clone();
795        }
796        let entry = Arc::new(Entry::new(key, policy, generation));
797        inner.entries_by_key.insert(map_key, entry.clone());
798        entry
799    }
800
801    /// Remove an entry from the active map. Called when its
802    /// refcount has fully drained.
803    fn remove_entry(&self, key: &ResourceKey, generation: usize) {
804        let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
805        inner.entries_by_key.remove(&(key.clone(), generation));
806    }
807
808    /// SRD-104 — resolve the accessor payload for the live entry whose
809    /// [`ResourceKey`] renders (via [`ResourceKey::render_key`]) to `key`.
810    /// Returns a clone of the stored `Arc<dyn Any>`, or `None` when no live
811    /// entry matches the fingerprint or the matched entry has no payload
812    /// (not opted in, or not yet initialised). This is the pool's half of
813    /// the [`polydat::ResourceAccessor`] bridge; see [`install_accessor`].
814    fn lookup_accessor_payload(&self, key: &str) -> Option<Arc<dyn Any + Send + Sync>> {
815        let inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
816        for entry in inner.entries_by_key.values() {
817            if entry.key.render_key() == key {
818                return entry
819                    .accessor_payload
820                    .lock()
821                    .unwrap_or_else(|e| e.into_inner())
822                    .clone();
823            }
824        }
825        None
826    }
827
828    /// Lazily realise the resource for an entry, emitting
829    /// `resource.init.{started,completed,failed}` events
830    /// around the call. Subsequent calls observe the
831    /// already-populated slot and return the existing
832    /// resource (or the cached error if init was poisoned).
833    async fn ensure_initialized(
834        &self,
835        entry: &Arc<Entry>,
836        first_attach: bool,
837        factory: ResourceFactory<'_>,
838    ) -> Result<Arc<dyn SharedResource>, String> {
839        // Fast path — already realised.
840        if let Some(existing) = entry
841            .resource
842            .lock()
843            .unwrap_or_else(|e| e.into_inner())
844            .clone()
845        {
846            return Ok(existing);
847        }
848        if entry.poisoned.load(Ordering::Acquire) {
849            let err = entry
850                .init_error
851                .lock()
852                .unwrap_or_else(|e| e.into_inner())
853                .clone()
854                .unwrap_or_else(|| "init poisoned".into());
855            return Err(err);
856        }
857
858        let reason = if first_attach {
859            "first-attach"
860        } else {
861            "capacity-declined"
862        };
863        emit_event(
864            LogLevel::Debug,
865            "init.started",
866            entry,
867            &format!("reason={reason}"),
868        );
869        *entry
870            .init_started_at
871            .lock()
872            .unwrap_or_else(|e| e.into_inner()) = Some(Instant::now());
873
874        // Run the factory + the resource's own `init()`.
875        // Errors poison the entry so subsequent attaches
876        // surface the same error rather than retrying.
877        let outcome: Result<Arc<dyn SharedResource>, String> = async {
878            let resource = factory.build().await?;
879            resource.init().await?;
880            Ok(resource)
881        }
882        .await;
883
884        let elapsed_ms = entry
885            .init_started_at
886            .lock()
887            .unwrap_or_else(|e| e.into_inner())
888            .map(|t| t.elapsed().as_millis() as u64)
889            .unwrap_or(0);
890
891        match outcome {
892            Ok(resource) => {
893                *entry.resource.lock().unwrap_or_else(|e| e.into_inner()) = Some(resource.clone());
894                // SRD-104: capture the resource's accessor payload (if any)
895                // onto the entry so the pool's ResourceAccessor impl can hand
896                // it to kernel nodes by fingerprint. `None` for resources that
897                // don't opt in (the trait default) — no-op then.
898                *entry
899                    .accessor_payload
900                    .lock()
901                    .unwrap_or_else(|e| e.into_inner()) = resource.accessor_payload();
902                emit_event(
903                    LogLevel::Debug,
904                    "init.completed",
905                    entry,
906                    &format!("elapsed_ms={elapsed_ms}"),
907                );
908                Ok(resource)
909            }
910            Err(e) => {
911                entry.poisoned.store(true, Ordering::Release);
912                *entry.init_error.lock().unwrap_or_else(|e| e.into_inner()) = Some(e.clone());
913                emit_event(
914                    LogLevel::Error,
915                    "init.failed",
916                    entry,
917                    &format!("elapsed_ms={elapsed_ms} error={e:?}"),
918                );
919                Err(e)
920            }
921        }
922    }
923}
924
925impl Default for ResourcePool {
926    fn default() -> Self {
927        Self::new()
928    }
929}
930
931/// Boxed, `Send` one-shot closure that builds a shared resource,
932/// returning a [`ResourceFuture`] yielding the resource (or an
933/// error message).
934type ResourceFactoryFn<'a> =
935    Box<dyn FnOnce() -> ResourceFuture<'a, Result<Arc<dyn SharedResource>, String>> + Send + 'a>;
936
937/// Closure-shaped factory for building a resource the first
938/// time its key is attached. Boxed so the pool can hold it
939/// across `.await` points and so callers don't have to type
940/// the future signature inline.
941pub struct ResourceFactory<'a> {
942    inner: ResourceFactoryFn<'a>,
943}
944
945impl<'a> ResourceFactory<'a> {
946    pub fn new<F, Fut>(f: F) -> Self
947    where
948        F: FnOnce() -> Fut + Send + 'a,
949        Fut: Future<Output = Result<Arc<dyn SharedResource>, String>> + Send + 'a,
950    {
951        Self {
952            inner: Box::new(move || Box::pin(f()) as ResourceFuture<'a, _>),
953        }
954    }
955
956    fn build(self) -> ResourceFuture<'a, Result<Arc<dyn SharedResource>, String>> {
957        (self.inner)()
958    }
959}
960
961// =================================================================
962// Public attach / detach surface
963// =================================================================
964
965/// Public attach call. Builds (or reuses) the entry for
966/// `key` under `policy`, lazily realises the resource via
967/// `factory` if this is the first attach, emits
968/// `resource.attach`, and returns a guard that detaches on
969/// drop.
970///
971/// `phase` is a free-form label that lands on the
972/// `resource.attach` / `resource.detach` event lines so
973/// operators can correlate lifecycle events with the
974/// per-phase activation that drove them.
975pub async fn attach(
976    pool: &Arc<ResourcePool>,
977    key: ResourceKey,
978    policy: ResourceSharePolicy,
979    phase: impl Into<String>,
980    factory: ResourceFactory<'_>,
981) -> Result<AttachGuard, String> {
982    let phase = phase.into();
983    let entry = pool.get_or_create_entry(key.clone(), policy, 0);
984    let first_attach = entry
985        .resource
986        .lock()
987        .unwrap_or_else(|e| e.into_inner())
988        .is_none()
989        && !entry.poisoned.load(Ordering::Acquire);
990
991    let resource = pool
992        .ensure_initialized(&entry, first_attach, factory)
993        .await?;
994
995    // Capability check: the live resource's can_share()
996    // must agree with the policy. PerPhase / PerFiber
997    // policies don't require can_share()=true; only
998    // Shared / PerScenario do.
999    let needs_share = matches!(
1000        policy,
1001        ResourceSharePolicy::Shared | ResourceSharePolicy::PerScenario
1002    );
1003    if needs_share && !resource.can_share() {
1004        return Err(format!(
1005            "resource for {} declared can_share()=false but policy is {policy}; \
1006             elevate isolation to per-phase or per-fiber, or fix the resource impl",
1007            entry.key.fmt_for_log(),
1008        ));
1009    }
1010
1011    // Bookkeeping: increment live attach, emit attach event
1012    let live = entry.live_attaches.fetch_add(1, Ordering::AcqRel) + 1;
1013    let pending_dec = entry.pending_uses.load(Ordering::Acquire);
1014    let pending = if pending_dec > 0 {
1015        entry.pending_uses.fetch_sub(1, Ordering::AcqRel) - 1
1016    } else {
1017        0
1018    };
1019    {
1020        let mut inner = pool.inner.lock().unwrap_or_else(|e| e.into_inner());
1021        inner.total_attaches += 1;
1022    }
1023    emit_event(
1024        LogLevel::Debug,
1025        "attach",
1026        &entry,
1027        &format!("phase={phase:?} pending={pending} live={live}"),
1028    );
1029
1030    Ok(AttachGuard {
1031        pool: Arc::clone(pool),
1032        entry,
1033        resource,
1034        phase,
1035        detached: false,
1036    })
1037}
1038
1039/// Owns an attached resource for the duration of one phase
1040/// activation. Drop emits `resource.detach` and, when the
1041/// entry's refcount has fully drained, schedules an async
1042/// `close()` (and emits `resource.close.*` events around it).
1043///
1044/// Holding the guard keeps the resource alive; releasing
1045/// it lets the pool tear down the resource if no other
1046/// shells reference it.
1047///
1048/// Implements `Debug` so test helpers like
1049/// `Result::expect_err` accept it as the success type when
1050/// the error path is the one under test.
1051pub struct AttachGuard {
1052    pool: Arc<ResourcePool>,
1053    entry: Arc<Entry>,
1054    resource: Arc<dyn SharedResource>,
1055    phase: String,
1056    detached: bool,
1057}
1058
1059impl std::fmt::Debug for AttachGuard {
1060    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1061        f.debug_struct("AttachGuard")
1062            .field("key", &self.entry.key)
1063            .field("generation", &self.entry.generation)
1064            .field("policy", &self.entry.policy)
1065            .field("phase", &self.phase)
1066            .field("detached", &self.detached)
1067            .finish()
1068    }
1069}
1070
1071impl AttachGuard {
1072    /// Borrow the underlying shared resource. The guard
1073    /// retains ownership; the `Arc` clone is cheap.
1074    pub fn resource(&self) -> Arc<dyn SharedResource> {
1075        Arc::clone(&self.resource)
1076    }
1077
1078    /// Resource key for the attached entry. Useful for log
1079    /// correlation in adapter shells.
1080    pub fn key(&self) -> &ResourceKey {
1081        &self.entry.key
1082    }
1083
1084    /// Explicit detach. Calling this drains the refcount
1085    /// and (if it hits zero) awaits the resource's
1086    /// `close()` synchronously, so the caller observes
1087    /// teardown completion at this point. The guard's
1088    /// `Drop` falls back to a best-effort spawn when
1089    /// `detach()` wasn't called explicitly.
1090    pub async fn detach(mut self) -> Result<(), String> {
1091        self.detach_inner(true).await
1092    }
1093
1094    async fn detach_inner(&mut self, await_close: bool) -> Result<(), String> {
1095        if self.detached {
1096            return Ok(());
1097        }
1098        self.detached = true;
1099
1100        let live = self.entry.live_attaches.fetch_sub(1, Ordering::AcqRel) - 1;
1101        let pending = self.entry.pending_uses.load(Ordering::Acquire);
1102        emit_event(
1103            LogLevel::Debug,
1104            "detach",
1105            &self.entry,
1106            &format!("phase={:?} pending={pending} live={live}", self.phase),
1107        );
1108
1109        // SRD-35 Push D: close trigger is unified across
1110        // every policy. The pool closes an entry the moment
1111        // its `(pending == 0, live == 0)` invariant is
1112        // satisfied — meaning "no more attaches predicted by
1113        // the pre-map AND nothing currently using it."
1114        //
1115        //   - `Shared` / `PerScenario`: pre-map seeds
1116        //     `pending_uses` to the predicted attach count
1117        //     (sum across all phases that produce this key).
1118        //     Each `attach` decrements pending eagerly; the
1119        //     last phase's detach drives both counters to
1120        //     zero and the entry closes immediately —
1121        //     releasing network resources before session end
1122        //     for keys whose users are all done. If the
1123        //     pre-map walker missed a phase (under-predict),
1124        //     the entry would close prematurely and be
1125        //     re-initialised on the next attach; if it
1126        //     over-predicts, `pending` stays > 0 and
1127        //     `pool.shutdown()` does the close at session
1128        //     end (the conservative default).
1129        //
1130        //   - `PerPhase` / `PerFiber`: pre-map intentionally
1131        //     skips these — each phase is its own key, so
1132        //     `pending` stays 0 throughout. Close fires on
1133        //     the first detach when `live` returns to 0.
1134        if live == 0 && pending == 0 {
1135            self.trigger_close(await_close, "refcount-zero").await?;
1136        }
1137        Ok(())
1138    }
1139
1140    async fn trigger_close(&self, await_close: bool, reason: &str) -> Result<(), String> {
1141        // Pull the resource out of the entry slot — only
1142        // the close path holds it after this point, and a
1143        // late attach would observe an empty slot and
1144        // re-init under a fresh generation.
1145        let resource_opt = {
1146            let mut slot = self
1147                .entry
1148                .resource
1149                .lock()
1150                .unwrap_or_else(|e| e.into_inner());
1151            slot.take()
1152        };
1153        let Some(resource) = resource_opt else {
1154            // Entry never realised (factory failed before
1155            // resource was set, or already closed).
1156            self.pool
1157                .remove_entry(&self.entry.key, self.entry.generation);
1158            return Ok(());
1159        };
1160
1161        emit_event(
1162            LogLevel::Debug,
1163            "close.started",
1164            &self.entry,
1165            &format!("reason={reason}"),
1166        );
1167        let started_at = Instant::now();
1168
1169        let entry_for_async = Arc::clone(&self.entry);
1170        let pool_for_async = Arc::clone(&self.pool);
1171        let close_future = resource.close();
1172
1173        if await_close {
1174            let result = close_future.await;
1175            let elapsed_ms = started_at.elapsed().as_millis() as u64;
1176            match result {
1177                Ok(()) => emit_event(
1178                    LogLevel::Debug,
1179                    "close.completed",
1180                    &self.entry,
1181                    &format!("elapsed_ms={elapsed_ms}"),
1182                ),
1183                Err(ref e) => emit_event(
1184                    LogLevel::Warn,
1185                    "close.failed",
1186                    &self.entry,
1187                    &format!("elapsed_ms={elapsed_ms} error={e:?}"),
1188                ),
1189            }
1190            self.pool
1191                .remove_entry(&self.entry.key, self.entry.generation);
1192            result
1193        } else {
1194            // Drop-path: spawn the close so we don't block
1195            // the dropping thread, but still emit the
1196            // events when it finishes. Errors get logged
1197            // via the events themselves.
1198            tokio::spawn(async move {
1199                let result = close_future.await;
1200                let elapsed_ms = started_at.elapsed().as_millis() as u64;
1201                match result {
1202                    Ok(()) => emit_event(
1203                        LogLevel::Debug,
1204                        "close.completed",
1205                        &entry_for_async,
1206                        &format!("elapsed_ms={elapsed_ms}"),
1207                    ),
1208                    Err(ref e) => emit_event(
1209                        LogLevel::Warn,
1210                        "close.failed",
1211                        &entry_for_async,
1212                        &format!("elapsed_ms={elapsed_ms} error={e:?}"),
1213                    ),
1214                }
1215                pool_for_async.remove_entry(&entry_for_async.key, entry_for_async.generation);
1216            });
1217            Ok(())
1218        }
1219    }
1220}
1221
1222impl Drop for AttachGuard {
1223    fn drop(&mut self) {
1224        if self.detached {
1225            return;
1226        }
1227        // Drop is sync; schedule the detach work onto the
1228        // current tokio runtime if there is one. If no
1229        // runtime is active (test fallback), do the
1230        // synchronous bookkeeping inline and skip the
1231        // close await.
1232        let live = self.entry.live_attaches.fetch_sub(1, Ordering::AcqRel) - 1;
1233        let pending = self.entry.pending_uses.load(Ordering::Acquire);
1234        self.detached = true;
1235        let phase = &self.phase;
1236        emit_event(
1237            LogLevel::Debug,
1238            "detach",
1239            &self.entry,
1240            &format!("phase={phase:?} pending={pending} live={live}"),
1241        );
1242
1243        // SRD-35 Push D unified close gate (mirrors
1244        // `detach_inner`): close as soon as both counters
1245        // hit zero, regardless of policy. Pre-map seeds
1246        // `pending_uses` so Shared/PerScenario entries close
1247        // when their last user drains — not at session end.
1248        if live == 0 && pending == 0 {
1249            // Take the resource out so the close path owns
1250            // it — even if no runtime is active to await
1251            // the close, the synchronous bookkeeping is
1252            // correct.
1253            let resource_opt = {
1254                let mut slot = self
1255                    .entry
1256                    .resource
1257                    .lock()
1258                    .unwrap_or_else(|e| e.into_inner());
1259                slot.take()
1260            };
1261            let Some(resource) = resource_opt else {
1262                self.pool
1263                    .remove_entry(&self.entry.key, self.entry.generation);
1264                return;
1265            };
1266
1267            // Try to spawn the close on the current
1268            // runtime. If we're outside a runtime
1269            // (tests, dryrun), the resource simply drops
1270            // synchronously here.
1271            let entry = Arc::clone(&self.entry);
1272            let pool = Arc::clone(&self.pool);
1273            emit_event(
1274                LogLevel::Debug,
1275                "close.started",
1276                &self.entry,
1277                "reason=refcount-zero",
1278            );
1279            let started_at = Instant::now();
1280
1281            if let Ok(handle) = tokio::runtime::Handle::try_current() {
1282                let close_future = resource.close();
1283                handle.spawn(async move {
1284                    let result = close_future.await;
1285                    let elapsed_ms = started_at.elapsed().as_millis() as u64;
1286                    match result {
1287                        Ok(()) => emit_event(
1288                            LogLevel::Debug,
1289                            "close.completed",
1290                            &entry,
1291                            &format!("elapsed_ms={elapsed_ms}"),
1292                        ),
1293                        Err(ref e) => emit_event(
1294                            LogLevel::Warn,
1295                            "close.failed",
1296                            &entry,
1297                            &format!("elapsed_ms={elapsed_ms} error={e:?}"),
1298                        ),
1299                    }
1300                    pool.remove_entry(&entry.key, entry.generation);
1301                });
1302            } else {
1303                // No runtime: drop synchronously, emit
1304                // a synthetic close.completed with
1305                // elapsed_ms=0 so log consumers still see
1306                // a paired close event.
1307                drop(resource);
1308                emit_event(
1309                    LogLevel::Debug,
1310                    "close.completed",
1311                    &self.entry,
1312                    "elapsed_ms=0",
1313                );
1314                self.pool
1315                    .remove_entry(&self.entry.key, self.entry.generation);
1316            }
1317        }
1318    }
1319}
1320
1321// =================================================================
1322// Legacy adapter wrapper — Push A bridge
1323// =================================================================
1324
1325/// Wraps an `Arc<dyn DriverAdapter>` from the existing
1326/// per-phase factory under `PerPhase` policy. Used until
1327/// each adapter migrates to a real `SharedResource` impl
1328/// (Push B for CQL, Push C for HTTP / OpenAPI / stdout).
1329///
1330/// `can_share()` returns `false` so the pool refuses to
1331/// give a `LegacyAdapterResource` to a second shell — it's
1332/// effectively single-use, matching today's behaviour.
1333///
1334/// Most callers shouldn't construct this directly — use
1335/// [`attach_legacy_adapter`] which handles the wrapping,
1336/// pool registration, and adapter unwrapping in one call.
1337pub struct LegacyAdapterResource {
1338    key: ResourceKey,
1339    adapter: Mutex<Option<Arc<dyn DriverAdapter>>>,
1340}
1341
1342impl LegacyAdapterResource {
1343    pub fn new(key: ResourceKey, adapter: Arc<dyn DriverAdapter>) -> Self {
1344        Self {
1345            key,
1346            adapter: Mutex::new(Some(adapter)),
1347        }
1348    }
1349
1350    /// Borrow the wrapped legacy adapter. Returns `None`
1351    /// after `close()` has consumed it.
1352    pub fn adapter(&self) -> Option<Arc<dyn DriverAdapter>> {
1353        self.adapter
1354            .lock()
1355            .unwrap_or_else(|e| e.into_inner())
1356            .clone()
1357    }
1358}
1359
1360impl SharedResource for LegacyAdapterResource {
1361    fn resource_key(&self) -> &ResourceKey {
1362        &self.key
1363    }
1364
1365    /// Legacy adapters are NOT yet declared shareable —
1366    /// each phase gets its own. Push B / C migrate
1367    /// adapters out of this shim and into real
1368    /// `can_share() = true` impls.
1369    fn can_share(&self) -> bool {
1370        false
1371    }
1372
1373    fn close(self: Arc<Self>) -> ResourceFuture<'static, Result<(), String>> {
1374        Box::pin(async move {
1375            // Drop the adapter Arc — the legacy factory
1376            // doesn't expose an async-close surface, so
1377            // this is best-effort sync teardown.
1378            let _ = self
1379                .adapter
1380                .lock()
1381                .unwrap_or_else(|e| e.into_inner())
1382                .take();
1383            Ok(())
1384        })
1385    }
1386
1387    fn as_legacy_adapter(&self) -> Option<Arc<dyn DriverAdapter>> {
1388        self.adapter()
1389    }
1390}
1391
1392/// Push B sibling of [`LegacyAdapterResource`] — wraps an
1393/// `Arc<dyn DriverAdapter>` but declares `can_share()=true`.
1394/// Used when an adapter has registered a
1395/// [`crate::adapter::SharedDriverRegistration`] opting it
1396/// into pool-shared semantics. The pool caches the
1397/// underlying `Arc<dyn DriverAdapter>` and hands the same
1398/// clone to every phase whose params produce the same
1399/// `ResourceKey`.
1400///
1401/// `close()` drops the wrapped adapter Arc — the actual
1402/// teardown timing is governed by the underlying
1403/// `DriverAdapter`'s `Drop`. Push D will add real async
1404/// `close()` to specific driver instances (e.g. awaiting
1405/// `cass_session_close()`'s `CassFuture` for the
1406/// cassandra-cpp engine).
1407pub struct SharedAdapterResource {
1408    key: ResourceKey,
1409    adapter: Mutex<Option<Arc<dyn DriverAdapter>>>,
1410}
1411
1412impl SharedAdapterResource {
1413    pub fn new(key: ResourceKey, adapter: Arc<dyn DriverAdapter>) -> Self {
1414        Self {
1415            key,
1416            adapter: Mutex::new(Some(adapter)),
1417        }
1418    }
1419
1420    pub fn adapter(&self) -> Option<Arc<dyn DriverAdapter>> {
1421        self.adapter
1422            .lock()
1423            .unwrap_or_else(|e| e.into_inner())
1424            .clone()
1425    }
1426}
1427
1428impl SharedResource for SharedAdapterResource {
1429    fn resource_key(&self) -> &ResourceKey {
1430        &self.key
1431    }
1432
1433    /// Push B: this wrapper declares the adapter shareable.
1434    /// The pool keeps one instance per `ResourceKey` and
1435    /// returns the same `Arc` to every matching attach.
1436    fn can_share(&self) -> bool {
1437        true
1438    }
1439
1440    fn close(self: Arc<Self>) -> ResourceFuture<'static, Result<(), String>> {
1441        Box::pin(async move {
1442            // Take the adapter Arc out of the slot so the
1443            // shutdown handshake runs on a stable owner.
1444            // Drop happens at the end of this scope; the
1445            // engine's Drop runs after `shutdown().await`
1446            // resolves.
1447            let adapter = self
1448                .adapter
1449                .lock()
1450                .unwrap_or_else(|e| e.into_inner())
1451                .take();
1452            if let Some(adapter) = adapter {
1453                adapter.shutdown().await;
1454            }
1455            Ok(())
1456        })
1457    }
1458
1459    fn as_legacy_adapter(&self) -> Option<Arc<dyn DriverAdapter>> {
1460        self.adapter()
1461    }
1462
1463    /// SRD-104 — surface the wrapped adapter's accessor payload (SRD-103's
1464    /// CQL session handle for the `cql` adapter). The pool captures this
1465    /// right after init and hands clones to kernel nodes by fingerprint. The
1466    /// pool-shared wrapper owns no payload itself; it delegates to the
1467    /// adapter, which builds one over its connected session. `None` for
1468    /// adapters that don't opt in (the trait default).
1469    fn accessor_payload(&self) -> Option<Arc<dyn Any + Send + Sync>> {
1470        self.adapter().and_then(|a| a.accessor_payload())
1471    }
1472}
1473
1474/// Push B high-level helper: attach a shareable adapter
1475/// through the pool under `Shared` policy. The first phase
1476/// whose params produce `key` triggers `factory`; every
1477/// subsequent matching phase reuses the same
1478/// `Arc<dyn DriverAdapter>`. Each call returns a fresh
1479/// guard; the pool's refcount drops the entry only when
1480/// every guard is released.
1481pub async fn attach_shared_adapter<F, Fut>(
1482    pool: &Arc<ResourcePool>,
1483    adapter_name: &str,
1484    phase: &str,
1485    key: ResourceKey,
1486    factory: F,
1487) -> Result<(Arc<dyn DriverAdapter>, AttachGuard), String>
1488where
1489    F: FnOnce() -> Fut + Send + 'static,
1490    Fut: Future<Output = Result<Arc<dyn DriverAdapter>, String>> + Send + 'static,
1491{
1492    let key_for_resource = key.clone();
1493    let factory = ResourceFactory::new(move || async move {
1494        let adapter = factory().await?;
1495        let res = SharedAdapterResource::new(key_for_resource, adapter);
1496        Ok(Arc::new(res) as Arc<dyn SharedResource>)
1497    });
1498    let guard = attach(pool, key, ResourceSharePolicy::Shared, phase, factory).await?;
1499    let adapter = guard.resource().as_legacy_adapter().ok_or_else(|| {
1500        format!(
1501            "internal: shared pool resource for adapter '{adapter_name}' did not surface \
1502         a DriverAdapter handle — should be unreachable"
1503        )
1504    })?;
1505    Ok((adapter, guard))
1506}
1507
1508/// Push A high-level helper for the executor: attach a
1509/// legacy adapter through the pool under `PerPhase` policy
1510/// and return both the unwrapped `Arc<dyn DriverAdapter>`
1511/// and the corresponding [`AttachGuard`].
1512///
1513/// The guard MUST outlive any use of the returned adapter
1514/// reference — typically the caller stores it alongside
1515/// the activity and drops it at phase teardown so the
1516/// pool sees the matching `resource.detach`.
1517///
1518/// `factory` builds the adapter the first time the entry
1519/// is realised. The pool only calls it once per
1520/// `(key, generation)` even though `PerPhase` policy
1521/// makes each phase its own key.
1522pub async fn attach_legacy_adapter<F, Fut>(
1523    pool: &Arc<ResourcePool>,
1524    adapter_name: &str,
1525    phase: &str,
1526    key_extras: &[(&str, &str)],
1527    factory: F,
1528) -> Result<(Arc<dyn DriverAdapter>, AttachGuard), String>
1529where
1530    F: FnOnce() -> Fut + Send + 'static,
1531    Fut: Future<Output = Result<Arc<dyn DriverAdapter>, String>> + Send + 'static,
1532{
1533    let mut key = ResourceKey::new(adapter_name);
1534    for (k, v) in key_extras {
1535        key = key.with(*k, *v);
1536    }
1537    let key_for_resource = key.clone();
1538    let factory = ResourceFactory::new(move || async move {
1539        let adapter = factory().await?;
1540        let res = LegacyAdapterResource::new(key_for_resource, adapter);
1541        Ok(Arc::new(res) as Arc<dyn SharedResource>)
1542    });
1543
1544    let guard = attach(pool, key, ResourceSharePolicy::PerPhase, phase, factory).await?;
1545    let resource = guard.resource();
1546    let adapter = resource.as_legacy_adapter().ok_or_else(|| {
1547        format!(
1548            "internal: pool resource for adapter '{adapter_name}' did not surface \
1549         a legacy DriverAdapter handle — Push A path should be unreachable"
1550        )
1551    })?;
1552    Ok((adapter, guard))
1553}
1554
1555// =================================================================
1556// Pre-map pending_uses walker — SRD-35 Push D
1557// =================================================================
1558
1559/// Walk the freshly-pre-mapped scenario tree and seed the
1560/// pool's `pending_uses` counter for every phase that will
1561/// attach a pool-shareable adapter. Called once at session
1562/// bootstrap, after the pre-map pass of
1563/// `crate::executor::execute_tree` (run with `pre_map_only` set)
1564/// returns and before the executor begins running any phase.
1565///
1566/// For each phase node:
1567///   1. Determine the adapter name — `phase.adapter` override
1568///      (when the phase declares one) wins over the
1569///      session-level `default_driver`.
1570///   2. Resolve the driver name without instantiating
1571///      anything (`resolve_driver_name`).
1572///   3. Look up the matching `SharedDriverRegistration`. If
1573///      none registered, the phase rides the legacy
1574///      `PerPhase` path — its key is per-phase-unique, so
1575///      pre-map contributes zero to any shared `pending_uses`
1576///      and the legacy close-on-detach path handles teardown.
1577///   4. Compute the resource key from the session's
1578///      `merged_params` via the registration's pure
1579///      `resource_key` function. `resource_key` failures are
1580///      hard errors at session bootstrap — surfacing the same
1581///      misconfiguration that `attach_shared_adapter` would
1582///      have hit at runtime, just earlier and in one place.
1583///   5. Increment the per-key `pending_uses` counter via
1584///      [`ResourcePool::declare_pending_use`].
1585///
1586/// This is a pure read of the scenario tree + phase params;
1587/// no adapters are instantiated. The walker can run before
1588/// `pool.shutdown()` would otherwise be a no-op — and must
1589/// run before the first phase, since pending counts are
1590/// the close trigger that releases shared resources promptly
1591/// when their last user finishes.
1592pub fn pre_map_pending_uses(
1593    pool: &Arc<ResourcePool>,
1594    tree: &crate::scene_tree::SceneTree,
1595    phases: &std::collections::HashMap<String, nmbrs_workload::model::WorkloadPhase>,
1596    default_driver: &str,
1597    merged_params: &std::collections::HashMap<String, String>,
1598) -> Result<(), String> {
1599    for node in tree.dfs_phases() {
1600        // Phase-level adapter override wins over session
1601        // default. Mirrors `executor::run_phase` (line 1903)
1602        // so the predicted key matches the runtime key
1603        // exactly.
1604        let adapter = phases
1605            .get(&node.name)
1606            .and_then(|p| p.adapter.clone())
1607            .unwrap_or_else(|| default_driver.to_string());
1608
1609        // Drive the same resolution the executor uses
1610        // (`<adapter>driver` selector param + DriverImpl
1611        // ranking). `None` here means the adapter has no
1612        // `DriverImpl` registered AND no fallback; skip.
1613        let selector = format!("{adapter}driver");
1614        let Some(driver_name) =
1615            crate::adapter::resolve_driver_name(&adapter, &selector, merged_params)
1616        else {
1617            continue;
1618        };
1619
1620        // Only adapters that opted into pool sharing have a
1621        // `SharedDriverRegistration`. Legacy adapters fall
1622        // through; their `PerPhase` close-on-detach path is
1623        // unaffected.
1624        let Some(reg) = crate::adapter::find_shared_driver(&adapter, driver_name) else {
1625            continue;
1626        };
1627
1628        let key = (reg.resource_key)(merged_params).map_err(|e| {
1629            format!(
1630                "resource pool pre-map: phase '{}' adapter '{}' driver '{}': {}",
1631                node.name, adapter, driver_name, e,
1632            )
1633        })?;
1634        pool.declare_pending_use(key, default_policy_for(reg.share_capability));
1635    }
1636    Ok(())
1637}
1638
1639/// SRD-117 §9.1 — show every op the scenario will reach to the
1640/// [`crate::adapter::PreMapHook`] of the adapter it resolves to, then
1641/// tell each hook the walk has ended.
1642///
1643/// An op's adapter is its own `adapter:` when it has one, else its
1644/// phase's, else the session default: the resolution
1645/// `executor::run_phase` makes.
1646pub fn pre_map_adapter_ops(
1647    tree: &crate::scene_tree::SceneTree,
1648    phases: &std::collections::HashMap<String, nmbrs_workload::model::WorkloadPhase>,
1649    default_driver: &str,
1650    ctx: &crate::adapter::PreMapContext<'_>,
1651) -> Result<(), String> {
1652    for node in tree.dfs_phases() {
1653        let Some(phase) = phases.get(&node.name) else {
1654            continue;
1655        };
1656        let phase_adapter = phase.adapter.as_deref().unwrap_or(default_driver);
1657        for op in &phase.ops {
1658            let adapter = op
1659                .params
1660                .get("adapter")
1661                .and_then(|v| v.as_str())
1662                .unwrap_or(phase_adapter);
1663            for hook in inventory::iter::<crate::adapter::PreMapHook> {
1664                if hook.adapter == adapter {
1665                    (hook.op)(ctx, &node.name, op)?;
1666                }
1667            }
1668        }
1669    }
1670    for hook in inventory::iter::<crate::adapter::PreMapHook> {
1671        (hook.finish)(ctx)?;
1672    }
1673    Ok(())
1674}
1675
1676/// The pool of the session now running, when there is one. An adapter
1677/// reaches its [`ResourcePool::extension`] through this at `map_op`.
1678pub fn active_pool() -> Option<Arc<ResourcePool>> {
1679    ACTIVE_POOL
1680        .lock()
1681        .unwrap_or_else(|e| e.into_inner())
1682        .upgrade()
1683}
1684
1685// =================================================================
1686// SRD-104 — resource-accessor bridge (pool ⇄ polydat)
1687// =================================================================
1688
1689/// The pool the process-global [`polydat::ResourceAccessor`] currently
1690/// resolves against, held as a `Weak` so the process-lifetime bridge never
1691/// keeps a finished session's pool (and its live network resources) alive.
1692/// Re-pointed each session by [`install_accessor`]; empty until the first
1693/// install.
1694static ACTIVE_POOL: Mutex<Weak<ResourcePool>> = Mutex::new(Weak::new());
1695
1696/// The bridge every nmbrs kernel tree resolves resources through
1697/// ([`pool_resources`]). It carries no state itself — it resolves against
1698/// the swappable [`ACTIVE_POOL`] — so a host process that runs several
1699/// sessions (TUI, `metrics watch`) re-points the pool without touching the
1700/// trees built before.
1701struct PoolAccessorView;
1702
1703impl polydat::ResourceAccessor for PoolAccessorView {
1704    fn lookup(&self, key: &str) -> Option<Arc<dyn Any + Send + Sync>> {
1705        let pool = ACTIVE_POOL
1706            .lock()
1707            .unwrap_or_else(|e| e.into_inner())
1708            .upgrade()?;
1709        pool.lookup_accessor_payload(key)
1710    }
1711}
1712
1713/// SRD-104 — point the resource bridge at `pool`. Called once at session
1714/// start where the [`ResourcePool`] is created.
1715///
1716/// Every kernel tree resolves through the same bridge ([`pool_resources`]),
1717/// and the pool it resolves against is swappable (`ACTIVE_POOL`), so a
1718/// second session in the same host process re-points the bridge at its own
1719/// pool rather than stranding on the first session's (now-closed) one.
1720/// Idempotent per session.
1721pub fn install_accessor(pool: &Arc<ResourcePool>) {
1722    *ACTIVE_POOL.lock().unwrap_or_else(|e| e.into_inner()) = Arc::downgrade(pool);
1723}
1724
1725/// A resource scope with the pool bridge installed: what every nmbrs
1726/// kernel tree is compiled with at its root
1727/// ([`crate::bindings::compile_scope_kernel`]). A kernel bound under the
1728/// tree joins its scope, so a node anywhere in it that captured
1729/// `ctx.resources()` resolves pool resources by key.
1730pub fn pool_resources() -> polydat::ResourceScope {
1731    polydat::ResourceScope::with_accessor(Arc::new(PoolAccessorView))
1732}
1733
1734// =================================================================
1735// Tests
1736// =================================================================
1737
1738#[cfg(test)]
1739mod tests {
1740    use super::*;
1741    use std::sync::atomic::AtomicU32;
1742
1743    /// Synthetic resource for unit tests — records every
1744    /// lifecycle call so assertions can verify the pool's
1745    /// invariants without touching real network resources.
1746    struct MockResource {
1747        key: ResourceKey,
1748        can_share: bool,
1749        saturated_after_attaches: u32,
1750        attach_count: AtomicU32,
1751        init_calls: AtomicU32,
1752        close_calls: AtomicU32,
1753        init_should_fail: bool,
1754    }
1755
1756    impl MockResource {
1757        fn new(key: ResourceKey) -> Arc<Self> {
1758            Arc::new(Self {
1759                key,
1760                can_share: true,
1761                saturated_after_attaches: u32::MAX,
1762                attach_count: AtomicU32::new(0),
1763                init_calls: AtomicU32::new(0),
1764                close_calls: AtomicU32::new(0),
1765                init_should_fail: false,
1766            })
1767        }
1768
1769        fn with_can_share(key: ResourceKey, can_share: bool) -> Arc<Self> {
1770            Arc::new(Self {
1771                key,
1772                can_share,
1773                saturated_after_attaches: u32::MAX,
1774                attach_count: AtomicU32::new(0),
1775                init_calls: AtomicU32::new(0),
1776                close_calls: AtomicU32::new(0),
1777                init_should_fail: false,
1778            })
1779        }
1780
1781        fn with_init_failure(key: ResourceKey) -> Arc<Self> {
1782            Arc::new(Self {
1783                key,
1784                can_share: true,
1785                saturated_after_attaches: u32::MAX,
1786                attach_count: AtomicU32::new(0),
1787                init_calls: AtomicU32::new(0),
1788                close_calls: AtomicU32::new(0),
1789                init_should_fail: true,
1790            })
1791        }
1792    }
1793
1794    impl SharedResource for MockResource {
1795        fn resource_key(&self) -> &ResourceKey {
1796            &self.key
1797        }
1798        fn can_share(&self) -> bool {
1799            self.can_share
1800        }
1801        fn can_support_more_load(&self) -> bool {
1802            // True (has capacity) until `attach_count`
1803            // crosses the saturation threshold; then
1804            // false (saturated). `u32::MAX` as the
1805            // threshold ⇒ always has capacity, matching
1806            // the trait default.
1807            self.attach_count.load(Ordering::Acquire) < self.saturated_after_attaches
1808        }
1809
1810        fn init(&self) -> ResourceFuture<'_, Result<(), String>> {
1811            self.init_calls.fetch_add(1, Ordering::AcqRel);
1812            let fail = self.init_should_fail;
1813            Box::pin(async move {
1814                if fail {
1815                    Err("simulated init failure".into())
1816                } else {
1817                    Ok(())
1818                }
1819            })
1820        }
1821
1822        fn close(self: Arc<Self>) -> ResourceFuture<'static, Result<(), String>> {
1823            self.close_calls.fetch_add(1, Ordering::AcqRel);
1824            Box::pin(async { Ok(()) })
1825        }
1826    }
1827
1828    fn key(adapter: &str, vendor: &str) -> ResourceKey {
1829        ResourceKey::new(adapter).with("vendor", vendor)
1830    }
1831
1832    #[test]
1833    fn key_value_equality_is_field_order_independent() {
1834        let a = ResourceKey::new("cql")
1835            .with("hosts", "h1")
1836            .with("port", "9042");
1837        let b = ResourceKey::new("cql")
1838            .with("port", "9042")
1839            .with("hosts", "h1");
1840        assert_eq!(a, b);
1841        assert_eq!(a.fmt_for_log(), b.fmt_for_log());
1842    }
1843
1844    #[test]
1845    fn key_log_format_redacts_password() {
1846        let k = ResourceKey::new("cql")
1847            .with("hosts", "h1")
1848            .with("password", "hunter2");
1849        let s = k.fmt_for_log();
1850        assert!(s.contains("hosts=h1"));
1851        assert!(s.contains("password=***"), "got: {s}");
1852        assert!(!s.contains("hunter2"));
1853    }
1854
1855    #[test]
1856    fn policy_parse_accepts_canonical_and_underscore_forms() {
1857        assert_eq!(
1858            ResourceSharePolicy::parse("shared").unwrap(),
1859            ResourceSharePolicy::Shared
1860        );
1861        assert_eq!(
1862            ResourceSharePolicy::parse("per-phase").unwrap(),
1863            ResourceSharePolicy::PerPhase
1864        );
1865        assert_eq!(
1866            ResourceSharePolicy::parse("per_phase").unwrap(),
1867            ResourceSharePolicy::PerPhase
1868        );
1869        assert_eq!(
1870            ResourceSharePolicy::parse("PER-FIBER").unwrap(),
1871            ResourceSharePolicy::PerFiber
1872        );
1873        ResourceSharePolicy::parse("nope").unwrap_err();
1874    }
1875
1876    #[test]
1877    fn capability_floor_orders_isolation_correctly() {
1878        // Shared is the lowest (most-shared); PerFiber is
1879        // the highest (most-isolated). User-policy must be
1880        // ≥ floor for capability.
1881        assert!(capability_floor(ShareCapability::Shared) <= ResourceSharePolicy::Shared);
1882        assert!(capability_floor(ShareCapability::PerPhase) > ResourceSharePolicy::Shared);
1883    }
1884
1885    #[tokio::test]
1886    async fn shared_resource_survives_detach_until_more_phases_predicted() {
1887        // SRD-35 Push D: the pre-map walker seeds
1888        // `pending_uses` with the predicted total attach
1889        // count. While `pending > 0`, detach MUST NOT close
1890        // — there's still a future phase that will use the
1891        // resource. The 55-phase open/close storm in the
1892        // operator's session.log was a Push A regression
1893        // where pending wasn't seeded; the resource closed
1894        // on the first detach and re-initialised every time.
1895        let pool = Arc::new(ResourcePool::new());
1896        let mock = MockResource::new(key("cql", "cassandra-cpp"));
1897        let mock_for_factory = Arc::clone(&mock);
1898
1899        // Pre-map says: 2 phases will attach this key.
1900        pool.declare_pending_use(mock.resource_key().clone(), ResourceSharePolicy::Shared);
1901        pool.declare_pending_use(mock.resource_key().clone(), ResourceSharePolicy::Shared);
1902        assert_eq!(pool.pending_uses_for(mock.resource_key()), Some(2));
1903
1904        // Phase A: attach + detach. pending drops to 1, so
1905        // close must NOT fire — phase B is still expected.
1906        let guard = attach(
1907            &pool,
1908            mock.resource_key().clone(),
1909            ResourceSharePolicy::Shared,
1910            "phase_A",
1911            ResourceFactory::new(
1912                move || async move { Ok(mock_for_factory as Arc<dyn SharedResource>) },
1913            ),
1914        )
1915        .await
1916        .unwrap();
1917
1918        assert_eq!(mock.init_calls.load(Ordering::Acquire), 1);
1919        guard.detach().await.unwrap();
1920        assert_eq!(
1921            mock.close_calls.load(Ordering::Acquire),
1922            0,
1923            "Shared-policy detach MUST NOT close while another \
1924             phase is still predicted to attach"
1925        );
1926        assert_eq!(pool.pending_uses_for(mock.resource_key()), Some(1));
1927        assert_eq!(pool.live_entries(), 1);
1928
1929        // Phase B: attach + detach. pending drops to 0,
1930        // live drops to 0 — close fires NOW, not at session
1931        // shutdown. Promptly releases the resource the
1932        // moment its last user is done.
1933        let mock_for_factory2 = Arc::clone(&mock);
1934        let guard2 = attach(
1935            &pool,
1936            mock.resource_key().clone(),
1937            ResourceSharePolicy::Shared,
1938            "phase_B",
1939            ResourceFactory::new(move || async move {
1940                Ok(mock_for_factory2 as Arc<dyn SharedResource>)
1941            }),
1942        )
1943        .await
1944        .unwrap();
1945        guard2.detach().await.unwrap();
1946        assert_eq!(
1947            mock.close_calls.load(Ordering::Acquire),
1948            1,
1949            "close MUST fire when pending hits 0 AND live hits 0 — \
1950             that's the SRD-35 Push D close-on-zero contract"
1951        );
1952        assert_eq!(pool.live_entries(), 0, "entry removed once closed");
1953
1954        // Pool shutdown is now a no-op for this key.
1955        pool.shutdown().await;
1956        assert_eq!(
1957            mock.close_calls.load(Ordering::Acquire),
1958            1,
1959            "shutdown() must NOT double-close an entry"
1960        );
1961    }
1962
1963    #[tokio::test]
1964    async fn shared_resource_overpredicted_pending_holds_until_shutdown() {
1965        // Conservative fallback: if the pre-map walker
1966        // over-predicts (predicts N phases but only N-1
1967        // actually attach), the entry stays alive until
1968        // shutdown — better than closing prematurely. The
1969        // residual `pending > 0` at session end is also
1970        // visible on the `close.started reason=session-end`
1971        // line so an operator can spot pre-map bugs.
1972        let pool = Arc::new(ResourcePool::new());
1973        let mock = MockResource::new(key("cql", "cassandra-cpp"));
1974        let mock_for_factory = Arc::clone(&mock);
1975
1976        // Pre-map says 3 phases, only 1 actually runs.
1977        for _ in 0..3 {
1978            pool.declare_pending_use(mock.resource_key().clone(), ResourceSharePolicy::Shared);
1979        }
1980        let guard = attach(
1981            &pool,
1982            mock.resource_key().clone(),
1983            ResourceSharePolicy::Shared,
1984            "phase_A",
1985            ResourceFactory::new(
1986                move || async move { Ok(mock_for_factory as Arc<dyn SharedResource>) },
1987            ),
1988        )
1989        .await
1990        .unwrap();
1991        guard.detach().await.unwrap();
1992
1993        // pending = 2 after one attach — close MUST NOT
1994        // fire mid-run.
1995        assert_eq!(pool.pending_uses_for(mock.resource_key()), Some(2));
1996        assert_eq!(mock.close_calls.load(Ordering::Acquire), 0);
1997        assert_eq!(pool.live_entries(), 1);
1998
1999        pool.shutdown().await;
2000        assert_eq!(
2001            mock.close_calls.load(Ordering::Acquire),
2002            1,
2003            "shutdown() drains residual entries with pending > 0"
2004        );
2005    }
2006
2007    #[tokio::test]
2008    async fn per_phase_resource_closes_on_detach() {
2009        // Counter-test: under `PerPhase` policy, the
2010        // legacy-shim semantics still apply — close fires
2011        // on the detach that drains refcount, no waiting
2012        // for shutdown. The synthetic mock has
2013        // `can_share=true`, so we explicitly use PerPhase
2014        // to exercise this branch.
2015        let pool = Arc::new(ResourcePool::new());
2016        let mock = MockResource::new(key("legacy", "synthetic"));
2017        let mock_for_factory = Arc::clone(&mock);
2018
2019        let guard = attach(
2020            &pool,
2021            mock.resource_key().clone(),
2022            ResourceSharePolicy::PerPhase,
2023            "phase_A",
2024            ResourceFactory::new(
2025                move || async move { Ok(mock_for_factory as Arc<dyn SharedResource>) },
2026            ),
2027        )
2028        .await
2029        .unwrap();
2030
2031        guard.detach().await.unwrap();
2032        assert_eq!(
2033            mock.close_calls.load(Ordering::Acquire),
2034            1,
2035            "PerPhase detach MUST close immediately"
2036        );
2037        assert_eq!(pool.live_entries(), 0);
2038    }
2039
2040    #[tokio::test]
2041    async fn init_failure_poisons_the_entry() {
2042        let pool = Arc::new(ResourcePool::new());
2043        let mock = MockResource::with_init_failure(key("cql", "cassandra-cpp"));
2044        let mock_for_factory = Arc::clone(&mock);
2045
2046        let result = attach(
2047            &pool,
2048            mock.resource_key().clone(),
2049            ResourceSharePolicy::Shared,
2050            "phase_A",
2051            ResourceFactory::new(
2052                move || async move { Ok(mock_for_factory as Arc<dyn SharedResource>) },
2053            ),
2054        )
2055        .await;
2056
2057        let err = result.expect_err("init failure must propagate");
2058        assert!(err.contains("simulated init failure"), "got: {err}");
2059    }
2060
2061    #[tokio::test]
2062    async fn shared_policy_against_can_share_false_resource_errors() {
2063        let pool = Arc::new(ResourcePool::new());
2064        let mock = MockResource::with_can_share(key("legacy", "x"), false);
2065        let mock_for_factory = Arc::clone(&mock);
2066
2067        let result = attach(
2068            &pool,
2069            mock.resource_key().clone(),
2070            ResourceSharePolicy::Shared,
2071            "phase_A",
2072            ResourceFactory::new(
2073                move || async move { Ok(mock_for_factory as Arc<dyn SharedResource>) },
2074            ),
2075        )
2076        .await;
2077
2078        let err = result.expect_err("shared policy on can_share()=false resource must be rejected");
2079        assert!(err.contains("can_share()=false"), "got: {err}");
2080        assert!(
2081            err.contains("per-phase") || err.contains("per-fiber"),
2082            "error must point at the available policies, got: {err}"
2083        );
2084    }
2085
2086    #[tokio::test]
2087    async fn per_phase_policy_with_can_share_false_works() {
2088        let pool = Arc::new(ResourcePool::new());
2089        let mock = MockResource::with_can_share(key("legacy", "x"), false);
2090        let mock_for_factory = Arc::clone(&mock);
2091
2092        let guard = attach(
2093            &pool,
2094            mock.resource_key().clone(),
2095            ResourceSharePolicy::PerPhase,
2096            "phase_A",
2097            ResourceFactory::new(
2098                move || async move { Ok(mock_for_factory as Arc<dyn SharedResource>) },
2099            ),
2100        )
2101        .await
2102        .expect("PerPhase must accept can_share()=false");
2103
2104        // PerPhase + can_share=false is exactly the
2105        // legacy-adapter shape; works without elevation.
2106        guard.detach().await.unwrap();
2107    }
2108
2109    #[tokio::test]
2110    async fn shared_policy_reuses_one_instance_across_attaches() {
2111        let pool = Arc::new(ResourcePool::new());
2112        let mock = MockResource::new(key("cql", "cassandra-cpp"));
2113        let mock_for_factory = Arc::clone(&mock);
2114        let factory_called = Arc::new(AtomicU32::new(0));
2115        let factory_called_clone = Arc::clone(&factory_called);
2116
2117        // SRD-35 Push D: pre-map predicts 3 phases will
2118        // attach this key, but the test only exercises 2.
2119        // The residual pending = 1 keeps the entry alive
2120        // until shutdown — this lets the test assert "Shared
2121        // policy holds across phases" without timing-coupling
2122        // the close trigger to detach order.
2123        for _ in 0..3 {
2124            pool.declare_pending_use(mock.resource_key().clone(), ResourceSharePolicy::Shared);
2125        }
2126
2127        let g1 = attach(
2128            &pool,
2129            mock.resource_key().clone(),
2130            ResourceSharePolicy::Shared,
2131            "phase_A",
2132            ResourceFactory::new(move || {
2133                factory_called_clone.fetch_add(1, Ordering::AcqRel);
2134                let m = Arc::clone(&mock_for_factory);
2135                async move { Ok(m as Arc<dyn SharedResource>) }
2136            }),
2137        )
2138        .await
2139        .unwrap();
2140
2141        // Second attach for the SAME key MUST reuse the
2142        // existing instance — factory MUST NOT be called
2143        // again. Push A's pool reuses by key+generation
2144        // even though the legacy adapter shim doesn't
2145        // typically exercise this; the synthetic test
2146        // proves the contract end-to-end.
2147        let mock_for_factory2 = Arc::clone(&mock);
2148        let factory_called_clone2 = Arc::clone(&factory_called);
2149        let g2 = attach(
2150            &pool,
2151            mock.resource_key().clone(),
2152            ResourceSharePolicy::Shared,
2153            "phase_B",
2154            ResourceFactory::new(move || {
2155                factory_called_clone2.fetch_add(1, Ordering::AcqRel);
2156                let m = Arc::clone(&mock_for_factory2);
2157                async move { Ok(m as Arc<dyn SharedResource>) }
2158            }),
2159        )
2160        .await
2161        .unwrap();
2162
2163        assert_eq!(
2164            factory_called.load(Ordering::Acquire),
2165            1,
2166            "factory must not be called twice for the same key under Shared policy"
2167        );
2168        assert_eq!(
2169            mock.init_calls.load(Ordering::Acquire),
2170            1,
2171            "init() must fire exactly once"
2172        );
2173        assert_eq!(pool.total_attaches(), 2);
2174        assert_eq!(pool.live_entries(), 1);
2175
2176        // Detach both guards. Pre-map predicted 3 phases;
2177        // only 2 attached, so pending stays > 0 and the
2178        // entry survives until session shutdown. The
2179        // session.log bug this contract locks down was the
2180        // resource closing on first detach, defeating
2181        // sharing across the next phase's attach.
2182        g1.detach().await.unwrap();
2183        assert_eq!(
2184            mock.close_calls.load(Ordering::Acquire),
2185            0,
2186            "close MUST NOT fire while another guard is live"
2187        );
2188        g2.detach().await.unwrap();
2189        assert_eq!(
2190            mock.close_calls.load(Ordering::Acquire),
2191            0,
2192            "close MUST NOT fire while pending uses remain — \
2193             the resource stays alive for predicted future phases"
2194        );
2195        assert_eq!(pool.live_entries(), 1, "entry stays cached across phases");
2196
2197        // The session-end shutdown drains the residual.
2198        pool.shutdown().await;
2199        assert_eq!(
2200            mock.close_calls.load(Ordering::Acquire),
2201            1,
2202            "shutdown() drains the entry"
2203        );
2204        assert_eq!(pool.live_entries(), 0);
2205    }
2206
2207    /// Minimal `DriverAdapter` stub used by the legacy-
2208    /// wrapper test below. `map_op` returns an error
2209    /// because the test never exercises the dispenser
2210    /// path — we only need a `DriverAdapter` value to
2211    /// hand to `LegacyAdapterResource::new`.
2212    struct LegacyDummy;
2213    impl crate::adapter::DriverAdapter for LegacyDummy {
2214        fn name(&self) -> &str {
2215            "legacy_dummy"
2216        }
2217        fn map_op<'a>(
2218            &'a self,
2219            _template: &'a nmbrs_workload::model::ParsedOp,
2220            _parent: std::sync::Arc<dyn polydat::Kernel>,
2221        ) -> std::pin::Pin<
2222            Box<
2223                dyn std::future::Future<
2224                        Output = Result<Box<dyn crate::adapter::OpDispenser>, String>,
2225                    > + Send
2226                    + 'a,
2227            >,
2228        > {
2229            Box::pin(async move { Err("dummy".into()) })
2230        }
2231    }
2232
2233    #[test]
2234    fn capacity_decline_at_quiescence_is_caught_as_driver_bug() {
2235        // SRD-35 validity rule: a `can_support_more_load()`
2236        // body that returns FALSE while `live_attaches ==
2237        // 0` is reading historical state, not active load
2238        // (e.g., a ring buffer that filled during a
2239        // previous phase). The pool's guard MUST treat
2240        // this as a driver bug — log a Warn and route the
2241        // attach to the existing idle generation instead
2242        // of wasting a spawn. Real saturation (decline +
2243        // live > 0) MUST trigger the spawn unchanged.
2244        struct Reports {
2245            key: ResourceKey,
2246            has_capacity: bool,
2247        }
2248        impl SharedResource for Reports {
2249            fn resource_key(&self) -> &ResourceKey {
2250                &self.key
2251            }
2252            fn can_support_more_load(&self) -> bool {
2253                self.has_capacity
2254            }
2255        }
2256
2257        let entry = Entry::new(ResourceKey::new("buggy"), ResourceSharePolicy::Shared, 0);
2258
2259        // Has capacity → never spawn, regardless of load.
2260        let calm = Reports {
2261            key: ResourceKey::new("buggy"),
2262            has_capacity: true,
2263        };
2264        assert!(
2265            !needs_sibling_spawn(&entry, &calm),
2266            "no spawn when the resource has capacity"
2267        );
2268
2269        // No capacity at quiescence → driver bug, suppressed.
2270        let buggy = Reports {
2271            key: ResourceKey::new("buggy"),
2272            has_capacity: false,
2273        };
2274        assert_eq!(entry.live_attaches.load(Ordering::Acquire), 0);
2275        assert!(
2276            !needs_sibling_spawn(&entry, &buggy),
2277            "quiescent decline must be suppressed (driver bug)"
2278        );
2279
2280        // No capacity + actual load → genuine saturation, spawn.
2281        entry.live_attaches.fetch_add(3, Ordering::AcqRel);
2282        assert!(
2283            needs_sibling_spawn(&entry, &buggy),
2284            "decline under live load is genuine saturation; spawn sibling"
2285        );
2286
2287        // Has capacity + load → still no spawn.
2288        assert!(
2289            !needs_sibling_spawn(&entry, &calm),
2290            "no spawn when there is capacity, even under load"
2291        );
2292    }
2293
2294    #[tokio::test]
2295    async fn shared_adapter_resource_returns_one_instance_for_one_key() {
2296        // Push B contract: under `Shared` policy, two
2297        // attaches against the same `ResourceKey` must
2298        // produce two guards backed by the SAME wrapped
2299        // `Arc<dyn DriverAdapter>` — the pool's caching is
2300        // what stops 50 phases from opening 50 cluster
2301        // sessions.
2302        let pool = Arc::new(ResourcePool::new());
2303        let adapter: Arc<dyn DriverAdapter> = Arc::new(LegacyDummy);
2304        let key = ResourceKey::new("cql").with("driver", "synthetic");
2305        let factory_call_count = Arc::new(AtomicU32::new(0));
2306
2307        // SRD-35 Push D: simulate the pre-map walker
2308        // declaring 3 future phases. The two attaches below
2309        // consume 2 of those 3, leaving pending = 1 so the
2310        // entry survives until shutdown — the assertion
2311        // shape this test was designed to verify.
2312        for _ in 0..3 {
2313            pool.declare_pending_use(key.clone(), ResourceSharePolicy::Shared);
2314        }
2315
2316        let factory_count_a = Arc::clone(&factory_call_count);
2317        let adapter_a = Arc::clone(&adapter);
2318        let (got_a, guard_a) =
2319            attach_shared_adapter(&pool, "cql", "phase_A", key.clone(), move || {
2320                factory_count_a.fetch_add(1, Ordering::AcqRel);
2321                let a = Arc::clone(&adapter_a);
2322                async move { Ok(a) }
2323            })
2324            .await
2325            .unwrap();
2326
2327        let factory_count_b = Arc::clone(&factory_call_count);
2328        let adapter_b = Arc::clone(&adapter);
2329        let (got_b, guard_b) =
2330            attach_shared_adapter(&pool, "cql", "phase_B", key.clone(), move || {
2331                factory_count_b.fetch_add(1, Ordering::AcqRel);
2332                let a = Arc::clone(&adapter_b);
2333                async move { Ok(a) }
2334            })
2335            .await
2336            .unwrap();
2337
2338        // The factory MUST be called exactly once even
2339        // though two phases attached.
2340        assert_eq!(
2341            factory_call_count.load(Ordering::Acquire),
2342            1,
2343            "Shared policy MUST cache the factory output"
2344        );
2345        assert!(
2346            Arc::ptr_eq(&got_a, &got_b),
2347            "both attaches MUST surface the SAME Arc<dyn DriverAdapter>"
2348        );
2349        assert_eq!(pool.live_entries(), 1);
2350        assert_eq!(pool.total_attaches(), 2);
2351
2352        guard_a.detach().await.unwrap();
2353        assert_eq!(
2354            pool.live_entries(),
2355            1,
2356            "entry stays live while any guard holds it"
2357        );
2358        guard_b.detach().await.unwrap();
2359        assert_eq!(
2360            pool.live_entries(),
2361            1,
2362            "Shared-policy entry stays cached across phases — \
2363             session shutdown is the close trigger, not last detach"
2364        );
2365        pool.shutdown().await;
2366        assert_eq!(pool.live_entries(), 0, "shutdown drains the cached entry");
2367    }
2368
2369    #[test]
2370    fn declare_then_complete_pending_use_drains_to_zero() {
2371        // SRD-35 Push D counter lifecycle: each
2372        // `declare_pending_use` call increments per-key;
2373        // each `complete_pending_use` decrements (saturating
2374        // at 0) and reports whether the entry is now
2375        // eligible for close (`pending == 0 && live == 0`).
2376        // The pool's close trigger sits on `(pending, live)`
2377        // both being zero — this test exercises the
2378        // counter-only side without a real attach to keep
2379        // the assertion shape tight.
2380        let pool = Arc::new(ResourcePool::new());
2381        let k = ResourceKey::new("cql").with("hosts", "h1");
2382        assert_eq!(
2383            pool.pending_uses_for(&k),
2384            None,
2385            "no entry exists before declare"
2386        );
2387
2388        // Pre-map walker declares: 3 phases will use this key.
2389        pool.declare_pending_use(k.clone(), ResourceSharePolicy::Shared);
2390        pool.declare_pending_use(k.clone(), ResourceSharePolicy::Shared);
2391        pool.declare_pending_use(k.clone(), ResourceSharePolicy::Shared);
2392        assert_eq!(pool.pending_uses_for(&k), Some(3));
2393        assert_eq!(
2394            pool.live_entries(),
2395            1,
2396            "declare_pending_use creates the entry on first call"
2397        );
2398
2399        // Drain phases 1 and 2: not yet eligible for close.
2400        let eligible = pool.complete_pending_use(&k);
2401        assert!(!eligible, "pending == 2; not eligible yet");
2402        assert_eq!(pool.pending_uses_for(&k), Some(2));
2403
2404        let eligible = pool.complete_pending_use(&k);
2405        assert!(!eligible, "pending == 1; not eligible yet");
2406        assert_eq!(pool.pending_uses_for(&k), Some(1));
2407
2408        // Phase 3 drains: pending hits 0, live is 0 (no
2409        // real attach in this test) — eligible for close.
2410        let eligible = pool.complete_pending_use(&k);
2411        assert!(
2412            eligible,
2413            "pending == 0 && live == 0 — entry is eligible for close"
2414        );
2415        assert_eq!(pool.pending_uses_for(&k), Some(0));
2416
2417        // Saturation: extra completes are no-ops, not
2418        // underflow. Stays "eligible for close" because the
2419        // invariant still holds.
2420        let eligible = pool.complete_pending_use(&k);
2421        assert!(
2422            eligible,
2423            "saturating decrement: extra completes don't underflow"
2424        );
2425        assert_eq!(pool.pending_uses_for(&k), Some(0));
2426    }
2427
2428    #[tokio::test]
2429    async fn declare_pending_use_paired_with_attach_closes_promptly() {
2430        // SRD-35 Push D end-to-end: pre-map seeds pending,
2431        // attach decrements eagerly, detach observes the
2432        // (pending == 0, live == 0) invariant and closes.
2433        // Verifies the close trigger fires the moment the
2434        // last predicted phase finishes, not at session end.
2435        let pool = Arc::new(ResourcePool::new());
2436        let mock = MockResource::new(key("cql", "cassandra-cpp"));
2437
2438        // Pre-map: exactly 1 phase will use this key.
2439        pool.declare_pending_use(mock.resource_key().clone(), ResourceSharePolicy::Shared);
2440
2441        let mock_for_factory = Arc::clone(&mock);
2442        let guard = attach(
2443            &pool,
2444            mock.resource_key().clone(),
2445            ResourceSharePolicy::Shared,
2446            "phase_A",
2447            ResourceFactory::new(
2448                move || async move { Ok(mock_for_factory as Arc<dyn SharedResource>) },
2449            ),
2450        )
2451        .await
2452        .unwrap();
2453        // After attach, pending dropped from 1 to 0.
2454        assert_eq!(pool.pending_uses_for(mock.resource_key()), Some(0));
2455
2456        guard.detach().await.unwrap();
2457        // Detach drove live to 0; pending was already 0;
2458        // close fired without waiting for shutdown.
2459        assert_eq!(
2460            mock.close_calls.load(Ordering::Acquire),
2461            1,
2462            "Push D: close fires the moment the last predicted \
2463             phase detaches — not at session shutdown"
2464        );
2465        assert_eq!(pool.live_entries(), 0);
2466    }
2467
2468    #[test]
2469    fn render_key_is_identity_preserving_unlike_log_format() {
2470        // SRD-104: `render_key()` is the accessor fingerprint — it must be
2471        // identity-preserving (NOT redact secrets), because two keys that
2472        // differ only in an identity-bearing field would otherwise collide
2473        // in the accessor. `fmt_for_log()` redacts (safe for logs) and so
2474        // deliberately collides; `render_key()` must not.
2475        let a = ResourceKey::new("cql")
2476            .with("hosts", "h1")
2477            .with("password", "p1");
2478        let b = ResourceKey::new("cql")
2479            .with("hosts", "h1")
2480            .with("password", "p2");
2481        assert_eq!(
2482            a.fmt_for_log(),
2483            b.fmt_for_log(),
2484            "log format redacts password → collides (expected)"
2485        );
2486        assert_ne!(
2487            a.render_key(),
2488            b.render_key(),
2489            "render_key must distinguish identity-bearing password"
2490        );
2491        assert!(
2492            !a.render_key().contains("p1") && a.render_key().contains("password=sha256:"),
2493            "the fingerprint must carry a digest of the secret, never the cleartext; got: {}",
2494            a.render_key()
2495        );
2496        // BTreeMap makes field order irrelevant to the rendering.
2497        let c = ResourceKey::new("cql")
2498            .with("password", "p1")
2499            .with("hosts", "h1");
2500        assert_eq!(
2501            a.render_key(),
2502            c.render_key(),
2503            "render_key is field-order independent"
2504        );
2505    }
2506
2507    #[tokio::test]
2508    async fn accessor_payload_populates_and_looks_up_by_render_key() {
2509        // SRD-104 pool-side round-trip: a resource that opts into an
2510        // accessor payload has it captured onto its entry at init, and the
2511        // pool resolves it by the key's canonical `render_key()` rendering
2512        // — the same string a consumer node builds from the fingerprint in
2513        // scope. Exercises the pool half of the bridge directly, without the
2514        // process-global (which would race across parallel tests).
2515        struct WithPayload {
2516            key: ResourceKey,
2517        }
2518        impl SharedResource for WithPayload {
2519            fn resource_key(&self) -> &ResourceKey {
2520                &self.key
2521            }
2522            fn accessor_payload(&self) -> Option<Arc<dyn Any + Send + Sync>> {
2523                Some(Arc::new(4242u64) as Arc<dyn Any + Send + Sync>)
2524            }
2525        }
2526
2527        let pool = Arc::new(ResourcePool::new());
2528        let key = ResourceKey::new("cql")
2529            .with("hosts", "h1")
2530            .with("keyspace", "ks");
2531        let rendered = key.render_key();
2532
2533        // No entry yet → miss.
2534        assert!(
2535            pool.lookup_accessor_payload(&rendered).is_none(),
2536            "no live entry ⇒ None"
2537        );
2538
2539        let key_for_factory = key.clone();
2540        let guard = attach(
2541            &pool,
2542            key.clone(),
2543            ResourceSharePolicy::Shared,
2544            "phase_A",
2545            ResourceFactory::new(move || async move {
2546                Ok(Arc::new(WithPayload {
2547                    key: key_for_factory,
2548                }) as Arc<dyn SharedResource>)
2549            }),
2550        )
2551        .await
2552        .unwrap();
2553
2554        // Hit by the canonical rendering; downcast to the concrete payload.
2555        let payload = pool
2556            .lookup_accessor_payload(&rendered)
2557            .expect("payload present after successful init");
2558        let n = payload
2559            .downcast_ref::<u64>()
2560            .expect("payload downcasts to u64");
2561        assert_eq!(*n, 4242);
2562
2563        // Detach with no pending uses drains the entry → miss again.
2564        guard.detach().await.unwrap();
2565        assert!(
2566            pool.lookup_accessor_payload(&rendered).is_none(),
2567            "closed entry ⇒ None"
2568        );
2569    }
2570
2571    #[tokio::test]
2572    async fn default_resource_has_no_accessor_payload() {
2573        // A resource that doesn't override `accessor_payload` (the trait
2574        // default) contributes no payload — the miss policy of the bridge.
2575        let pool = Arc::new(ResourcePool::new());
2576        let mock = MockResource::new(key("cql", "cassandra-cpp"));
2577        let rendered = mock.resource_key().render_key();
2578        let mock_for_factory = Arc::clone(&mock);
2579        let guard = attach(
2580            &pool,
2581            mock.resource_key().clone(),
2582            ResourceSharePolicy::Shared,
2583            "phase_A",
2584            ResourceFactory::new(
2585                move || async move { Ok(mock_for_factory as Arc<dyn SharedResource>) },
2586            ),
2587        )
2588        .await
2589        .unwrap();
2590        assert!(
2591            pool.lookup_accessor_payload(&rendered).is_none(),
2592            "default accessor_payload() ⇒ None even for a live entry"
2593        );
2594        guard.detach().await.unwrap();
2595    }
2596
2597    #[tokio::test]
2598    async fn legacy_adapter_resource_declares_non_shareable() {
2599        // Sanity: the bridge type used by Push A's
2600        // executor wiring declares itself non-shareable,
2601        // forcing PerPhase semantics for any adapter that
2602        // hasn't migrated yet.
2603        let key = ResourceKey::new("legacy");
2604        let adapter: Arc<dyn DriverAdapter> = Arc::new(LegacyDummy);
2605        let wrapped = Arc::new(LegacyAdapterResource::new(key, adapter));
2606        assert!(
2607            !wrapped.can_share(),
2608            "LegacyAdapterResource MUST declare can_share()=false"
2609        );
2610    }
2611}