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