Skip to main content

vortex_session/
session.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! The [`VortexSession`] container.
5//!
6//! A [`VortexSession`] is a type-map of [`VortexSessionVar`]s keyed by [`TypeId`]. It is backed by
7//! an [`ArcSwapMap`], giving lock-free reads and copy-on-write writes:
8//!
9//! * **Reads** ([`SessionExt::get`], [`SessionExt::get_opt`]) load the current snapshot
10//!   without taking any lock and hand back a [`SessionGuard`] that derefs to the variable. Because a
11//!   read never takes a lock, it can never deadlock, and because it never holds a lock across the
12//!   returned reference there is no reader/writer contention.
13//!
14//! * **Writes** ([`VortexSession::with_some`], and [`SessionExt::get`] or
15//!   [`SessionExt::get_or_insert_with`] on a missing variable) are copy-on-write: the map is cloned,
16//!   the change applied to the private copy, and the new map atomically published. The value is
17//!   constructed *before* the map is updated, so no user code (in particular, no `Default::default`
18//!   implementation or initializer closure) ever runs while a lock is held. This is the key
19//!   difference from the previous `DashMap`-backed session, where `entry().or_insert_with(f)` ran
20//!   `f` while holding the shard's write lock and could deadlock if `f` re-entered the session.
21//!
22//! A modified session is produced by mutating it **in place**: [`VortexSession::with_some`] — and
23//! the configuration `with_*` helpers built on it — apply their change copy-on-write to the shared
24//! backing cell. Clones of a session share that cell, so a variable registered through one clone
25//! (or one `with_*` call) is visible to all of them. This is what late plugin/encoding registration
26//! relies on.
27//!
28//! To build a session from scratch, start from [`VortexSession::empty`] and chain the `with_*`
29//! helpers. Each [`empty`](VortexSession::empty) creates its own backing cell, so a session built
30//! this way is independent of any other.
31
32use std::any::TypeId;
33use std::any::type_name;
34use std::fmt::Debug;
35use std::fmt::Formatter;
36use std::hash::BuildHasherDefault;
37use std::marker::PhantomData;
38use std::ops::Deref;
39use std::ops::DerefMut;
40use std::sync::Arc;
41
42use arc_swap::Guard;
43use vortex_error::VortexExpect;
44use vortex_error::vortex_panic;
45use vortex_utils::aliases::hash_map::HashMap;
46
47use crate::ArcSwapMap;
48use crate::IdHasher;
49use crate::SessionExt;
50use crate::SessionVar;
51use crate::UnknownPluginPolicy;
52
53/// A [`SessionVar`] that can be stored in a [`VortexSession`].
54///
55/// This trait is implemented automatically for every [`SessionVar`] that is also [`Clone`], so
56/// types opt in by implementing [`Clone`] rather than implementing this trait directly. The trait
57/// itself stays object-safe (so it can be stored as `Arc<dyn VortexSessionVar>`); the [`Clone`]
58/// bound lives on the blanket impl rather than the trait.
59///
60/// Requiring [`Clone`] lets the configuration `with_*` helpers read a variable, modify a copy, and
61/// re-insert the result.
62pub trait VortexSessionVar: SessionVar {}
63
64impl<V: SessionVar + Clone> VortexSessionVar for V {}
65
66/// The hasher for the session type-map; [`TypeId`]s are already hashes.
67type IdHashBuilder = BuildHasherDefault<IdHasher>;
68
69/// The immutable type-map backing a published [`VortexSession`] snapshot.
70type SessionVars = HashMap<TypeId, Arc<dyn VortexSessionVar>, IdHashBuilder>;
71
72/// The shared, copy-on-write store that publishes [`SessionVars`] snapshots.
73type SharedSessionVars = ArcSwapMap<TypeId, Arc<dyn VortexSessionVar>, IdHashBuilder>;
74
75/// A reference to a session variable of type `V`, returned by [`SessionExt::get`] and
76/// [`SessionExt::get_opt`].
77///
78/// It borrows the session's current snapshot through an [`arc_swap::Guard`], so reads never take a
79/// lock or a full [`Arc`] clone. The guard is tied to the session borrow it was read from, so it is
80/// meant to be used on the stack rather than stored in a long-lived data structure (holding it pins
81/// an internal arc-swap slot, which can contend with concurrent writers). `SessionGuard` derefs to
82/// `V`, so it can be used wherever a `&V` is expected.
83pub struct SessionGuard<'a, V> {
84    snapshot: Guard<Arc<SessionVars>>,
85    _session: PhantomData<&'a VortexSession>,
86    _marker: PhantomData<fn() -> V>,
87}
88
89impl<V: VortexSessionVar> Deref for SessionGuard<'_, V> {
90    type Target = V;
91
92    fn deref(&self) -> &V {
93        // The constructor of `SessionGuard` guarantees the variable is present in `snapshot`.
94        self.snapshot
95            .get(&TypeId::of::<V>())
96            .vortex_expect("SessionGuard invariant: variable present in snapshot")
97            .as_any()
98            .downcast_ref::<V>()
99            .vortex_expect("Type mismatch - this is a bug")
100    }
101}
102
103impl<V: VortexSessionVar> Debug for SessionGuard<'_, V> {
104    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
105        Debug::fmt(&**self, f)
106    }
107}
108
109/// A copy-on-write mutable handle to a session variable of type `V`, returned by
110/// [`SessionExt::get_mut`].
111///
112/// It holds a private clone of the variable and exposes it through [`DerefMut`]. When the handle is
113/// dropped, the (possibly mutated) value is re-inserted into the
114/// session, replacing the previous one. Because the session stores each variable behind a shared
115/// [`Arc`] observed by every clone, handing out a plain `&mut` to the stored value would be unsound;
116/// this guard provides mutable access by cloning on read and publishing on drop instead.
117pub struct SessionMut<'a, V: VortexSessionVar> {
118    session: &'a VortexSession,
119    // `Some` for the whole lifetime of the guard; taken in `drop` to move it back into the session.
120    value: Option<V>,
121}
122
123impl<V: VortexSessionVar> Deref for SessionMut<'_, V> {
124    type Target = V;
125
126    fn deref(&self) -> &V {
127        self.value
128            .as_ref()
129            .vortex_expect("SessionMut invariant: value present until drop")
130    }
131}
132
133impl<V: VortexSessionVar> DerefMut for SessionMut<'_, V> {
134    fn deref_mut(&mut self) -> &mut V {
135        self.value
136            .as_mut()
137            .vortex_expect("SessionMut invariant: value present until drop")
138    }
139}
140
141impl<V: VortexSessionVar> Drop for SessionMut<'_, V> {
142    fn drop(&mut self) {
143        if let Some(value) = self.value.take() {
144            self.session.register(value);
145        }
146    }
147}
148
149impl<V: VortexSessionVar> Debug for SessionMut<'_, V> {
150    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
151        Debug::fmt(&**self, f)
152    }
153}
154
155/// A Vortex session encapsulates the set of extensible arrays, layouts, compute functions,
156/// dtypes, etc. that are available for use in a given context.
157///
158/// It is also the entry-point passed to dynamic libraries to initialize Vortex plugins.
159///
160/// Cloning a session is cheap and shares the backing store: a variable registered through one
161/// clone (via [`VortexSession::with_some`] or one of the `with_*` helpers) is observed by all
162/// clones. To build an *independent* session, start from [`VortexSession::empty`].
163#[derive(Clone)]
164pub struct VortexSession(SharedSessionVars);
165
166impl Debug for VortexSession {
167    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
168        self.0
169            .read(|vars| f.debug_tuple("VortexSession").field(vars).finish())
170    }
171}
172
173impl VortexSession {
174    /// Create a new [`VortexSession`] with no session state.
175    pub fn empty() -> Self {
176        Self(SharedSessionVars::default())
177    }
178
179    /// Inserts a session variable of type `V`, unconditionally replacing any existing variable of
180    /// that type.
181    ///
182    /// [`SessionMut`] uses this copy-on-write primitive on drop, while
183    /// [`with_some`](Self::with_some) and [`get_or_insert_with`](SessionExt::get_or_insert_with)
184    /// use [`ArcSwapMap::insert_if_absent`](crate::arc_swap_map::ArcSwapMap::insert_if_absent) so
185    /// that a first registration cannot overwrite another. The mutation is applied in place to the
186    /// shared backing store, so it is visible through every clone.
187    pub fn register<V: VortexSessionVar>(&self, var: V) {
188        self.0.insert(TypeId::of::<V>(), Arc::new(var));
189    }
190
191    /// Inserts a new session variable of type `V` with its default value, mutating this session in
192    /// place and returning it for chaining.
193    ///
194    /// The change is applied copy-on-write to the shared backing store, so it is observed through
195    /// every clone of this session.
196    ///
197    /// # Panics
198    ///
199    /// If a variable of that type already exists.
200    pub fn with<V: VortexSessionVar + Default>(self) -> Self {
201        self.with_some(V::default())
202    }
203
204    /// Inserts a new session variable of type `V`, mutating this session in place and returning it
205    /// for chaining.
206    ///
207    /// The change is applied copy-on-write to the shared backing store, so it is observed through
208    /// every clone of this session.
209    ///
210    /// # Panics
211    ///
212    /// If a variable of that type already exists.
213    pub fn with_some<V: VortexSessionVar>(self, var: V) -> Self {
214        if !self.0.insert_if_absent(TypeId::of::<V>(), Arc::new(var)) {
215            vortex_panic!(
216                "Session variable of type {} already exists",
217                type_name::<V>()
218            );
219        }
220        self
221    }
222
223    /// Returns whether unknown plugins should deserialize as foreign placeholders.
224    pub fn allows_unknown(&self) -> bool {
225        self.get_opt::<UnknownPluginPolicy>()
226            .is_some_and(|p| p.allow_unknown)
227    }
228
229    /// Allow deserializing unknown plugin IDs as non-executable foreign placeholders.
230    ///
231    /// Mutates this session in place and returns it for chaining.
232    pub fn allow_unknown(&self) {
233        self.get_mut::<UnknownPluginPolicy>().allow_unknown = true;
234    }
235}
236
237impl SessionExt for VortexSession {
238    fn session(&self) -> VortexSession {
239        self.clone()
240    }
241
242    fn get<V: VortexSessionVar + Default>(&self) -> SessionGuard<'_, V> {
243        self.get_or_insert_with(V::default)
244    }
245
246    fn get_or_insert_with<V: VortexSessionVar>(
247        &self,
248        init: impl FnOnce() -> V,
249    ) -> SessionGuard<'_, V> {
250        if let Some(var) = self.get_opt::<V>() {
251            return var;
252        }
253
254        // NB: `init` runs before the map is updated, never inside it, because it may re-enter the
255        // session. If a concurrent writer published a value first, that value is kept.
256        let var: Arc<dyn VortexSessionVar> = Arc::new(init());
257        self.0.insert_if_absent(TypeId::of::<V>(), var);
258
259        self.get_opt::<V>()
260            .vortex_expect("a variable of type `V` is present after `insert_if_absent`")
261    }
262
263    fn get_opt<V: VortexSessionVar>(&self) -> Option<SessionGuard<'_, V>> {
264        let snapshot = self.0.load();
265        snapshot
266            .contains_key(&TypeId::of::<V>())
267            .then(|| SessionGuard {
268                snapshot,
269                _session: PhantomData,
270                _marker: PhantomData,
271            })
272    }
273
274    fn get_mut<V: VortexSessionVar + Default + Clone>(&self) -> SessionMut<'_, V> {
275        let value = (*self.get::<V>()).clone();
276        SessionMut {
277            session: self,
278            value: Some(value),
279        }
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use std::any::Any;
286    use std::panic::AssertUnwindSafe;
287    use std::panic::catch_unwind;
288    use std::sync::Barrier;
289    use std::thread;
290
291    use super::VortexSession;
292    use crate::SessionExt;
293    use crate::SessionVar;
294
295    #[derive(Clone, Debug, Default, PartialEq, Eq)]
296    struct Counter {
297        count: u32,
298    }
299
300    impl SessionVar for Counter {
301        fn as_any(&self) -> &dyn Any {
302            self
303        }
304
305        fn as_any_mut(&mut self) -> &mut dyn Any {
306            self
307        }
308    }
309
310    #[derive(Clone, Debug, Default)]
311    struct Other;
312
313    impl SessionVar for Other {
314        fn as_any(&self) -> &dyn Any {
315            self
316        }
317
318        fn as_any_mut(&mut self) -> &mut dyn Any {
319            self
320        }
321    }
322
323    thread_local! {
324        /// Lets `Reentrant::default` reach back into the session it is being inserted into.
325        static REENTRANT_SESSION: std::cell::RefCell<Option<VortexSession>> =
326            const { std::cell::RefCell::new(None) };
327    }
328
329    #[derive(Clone, Debug)]
330    struct Reentrant {
331        inner: u32,
332    }
333
334    impl Default for Reentrant {
335        fn default() -> Self {
336            // Re-enter the *same* session while this default is being constructed, itself
337            // triggering another default insertion. This is only sound because the default is
338            // built outside the `rcu` closure (no lock held); if it ran under the closure this
339            // would deadlock or recurse forever.
340            REENTRANT_SESSION.with(|s| {
341                if let Some(session) = s.borrow().as_ref() {
342                    drop(session.get::<Counter>());
343                }
344            });
345            Reentrant { inner: 7 }
346        }
347    }
348
349    impl SessionVar for Reentrant {
350        fn as_any(&self) -> &dyn Any {
351            self
352        }
353
354        fn as_any_mut(&mut self) -> &mut dyn Any {
355            self
356        }
357    }
358
359    #[test]
360    fn with_some_round_trip() {
361        let session = VortexSession::empty().with_some(Counter { count: 1 });
362
363        assert_eq!(*session.get::<Counter>(), Counter { count: 1 });
364        assert!(session.get_opt::<Other>().is_none());
365    }
366
367    #[test]
368    fn get_inserts_default() {
369        let session = VortexSession::empty();
370        assert!(session.get_opt::<Counter>().is_none());
371
372        assert_eq!(session.get::<Counter>().count, 0);
373        // The default was published, so it is now observable.
374        assert!(session.get_opt::<Counter>().is_some());
375    }
376
377    #[test]
378    fn get_or_insert_with_inserts_only_when_absent() {
379        let session = VortexSession::empty();
380
381        assert_eq!(session.get_or_insert_with(|| Counter { count: 3 }).count, 3);
382        assert_eq!(
383            session
384                .get_or_insert_with::<Counter>(|| panic!("the variable is already present"))
385                .count,
386            3
387        );
388    }
389
390    #[test]
391    fn register_is_visible_through_clones() {
392        let session = VortexSession::empty();
393        let clone = session.clone();
394
395        session.register(Counter { count: 7 });
396
397        // Registration mutates the shared backing store.
398        assert_eq!(clone.get::<Counter>().count, 7);
399    }
400
401    #[test]
402    fn with_some_mutates_shared_store() {
403        let session = VortexSession::empty();
404        let clone = session.clone();
405
406        let configured = session.with_some(Counter { count: 5 });
407        assert_eq!(configured.get::<Counter>().count, 5);
408
409        // `with_some` mutates the shared backing store in place, so the clone observes it too.
410        assert_eq!(clone.get::<Counter>().count, 5);
411    }
412
413    #[test]
414    fn allow_unknown_mutates_shared_store() {
415        let session = VortexSession::empty();
416        let clone = session.clone();
417        assert!(!clone.allows_unknown());
418
419        session.allow_unknown();
420
421        // The flag is flipped on the shared backing store.
422        assert!(clone.allows_unknown());
423    }
424
425    #[test]
426    fn empty_sessions_are_independent() {
427        // Each `empty()` creates its own backing cell, so separately built sessions do not share
428        // state.
429        let session = VortexSession::empty().with_some(Counter { count: 1 });
430        let other = VortexSession::empty().with_some(Counter { count: 2 });
431
432        session.register(Counter { count: 9 });
433        assert_eq!(session.get::<Counter>().count, 9);
434        assert_eq!(other.get::<Counter>().count, 2);
435    }
436
437    #[test]
438    #[should_panic(expected = "already exists")]
439    fn with_some_duplicate_panics() {
440        VortexSession::empty()
441            .with::<Counter>()
442            .with_some(Counter { count: 1 });
443    }
444
445    #[test]
446    fn get_opt_does_not_insert_a_default() {
447        let session = VortexSession::empty();
448
449        // Unlike `get`, `get_opt` is a pure read and never publishes a default.
450        assert!(session.get_opt::<Counter>().is_none());
451        assert!(session.get_opt::<Counter>().is_none());
452    }
453
454    #[test]
455    fn inserting_a_default_while_holding_a_guard_succeeds() {
456        let session = VortexSession::empty().with_some(Counter { count: 5 });
457
458        // Hold a read guard for one variable...
459        let counter = session.get::<Counter>();
460
461        // ...then read a *missing* variable, which inserts its default copy-on-write via `rcu`
462        // while `counter` is still alive. A `SessionGuard` is a lock-free snapshot, not a lock, so
463        // the write proceeds without waiting on the outstanding guard rather than deadlocking.
464        let other = session.get::<Other>();
465
466        // The held guard still observes the snapshot it was read from (which arc-swap keeps alive
467        // for the guard's lifetime), and the freshly read guard sees the just-inserted default.
468        assert_eq!(counter.count, 5);
469        let _: &Other = &other;
470
471        // The inserted default is also observable through a subsequent independent read.
472        assert!(session.get_opt::<Other>().is_some());
473    }
474
475    #[test]
476    fn a_held_guard_keeps_observing_its_own_snapshot_after_a_write() {
477        let session = VortexSession::empty().with_some(Counter { count: 1 });
478
479        let held = session.get::<Counter>();
480        session.register(Counter { count: 2 });
481
482        // The held guard pins the snapshot it was read from, so it still sees the old value, while
483        // a fresh read sees the newly published one.
484        assert_eq!(held.count, 1);
485        assert_eq!(session.get::<Counter>().count, 2);
486    }
487
488    #[test]
489    fn default_insertion_may_reenter_the_session_without_deadlocking() {
490        let session = VortexSession::empty();
491        REENTRANT_SESSION.with(|s| *s.borrow_mut() = Some(session.clone()));
492
493        // `get::<Reentrant>` inserts a default; building that default re-enters the same session
494        // via `get::<Counter>` (another default insertion). Because each default is constructed
495        // outside the `rcu` closure, both inserts complete instead of deadlocking.
496        assert_eq!(session.get::<Reentrant>().inner, 7);
497        assert!(session.get_opt::<Reentrant>().is_some());
498        assert!(session.get_opt::<Counter>().is_some());
499
500        REENTRANT_SESSION.with(|s| *s.borrow_mut() = None);
501    }
502
503    #[test]
504    fn get_mut_inserts_default_then_mutates() {
505        let session = VortexSession::empty();
506        assert!(session.get_opt::<Counter>().is_none());
507
508        session.get_mut::<Counter>().count += 5;
509
510        assert_eq!(session.get::<Counter>().count, 5);
511    }
512
513    #[test]
514    fn get_mut_mutation_is_visible_through_clones() {
515        let session = VortexSession::empty().with_some(Counter { count: 1 });
516        let clone = session.clone();
517
518        session.get_mut::<Counter>().count = 9;
519
520        // The mutated value is published copy-on-write to the shared backing store.
521        assert_eq!(clone.get::<Counter>().count, 9);
522    }
523
524    #[test]
525    fn concurrent_with_some_same_type_allows_only_one_winner() {
526        for _ in 0..200 {
527            let session = VortexSession::empty();
528            let clone_a = session.clone();
529            let clone_b = session.clone();
530            let barrier = Barrier::new(2);
531
532            let (res_a, res_b) = thread::scope(|s| {
533                let h_a = s.spawn(|| {
534                    barrier.wait();
535                    catch_unwind(AssertUnwindSafe(|| clone_a.with_some(Counter { count: 1 })))
536                });
537                let h_b = s.spawn(|| {
538                    barrier.wait();
539                    catch_unwind(AssertUnwindSafe(|| clone_b.with_some(Counter { count: 2 })))
540                });
541                (h_a.join().unwrap(), h_b.join().unwrap())
542            });
543
544            let (winner, loser, expected) = match (res_a, res_b) {
545                (Ok(winner), Err(panic)) => (winner, panic, 1),
546                (Err(panic), Ok(winner)) => (winner, panic, 2),
547                (Ok(_), Ok(_)) => {
548                    panic!("both concurrent with_some calls succeeded for same type")
549                }
550                (Err(_), Err(_)) => {
551                    panic!("both concurrent with_some calls panicked for same type")
552                }
553            };
554            let msg = loser
555                .downcast_ref::<String>()
556                .map(String::as_str)
557                .or_else(|| loser.downcast_ref::<&str>().copied())
558                .unwrap_or("");
559            assert!(msg.contains("already exists"), "unexpected panic: {msg}");
560            assert_eq!(winner.get::<Counter>().count, expected);
561            assert_eq!(session.get::<Counter>().count, expected);
562        }
563    }
564}