vortex-edition 0.94.0

Definitions of Vortex editions: named, frozen sets of serialized components with a read-compatibility guarantee
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

//! Session variables for registered and enabled editions.

use std::any::Any;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::sync::Arc;

use parking_lot::RwLock;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_session::ArcSwapMap;
use vortex_session::SessionExt;
use vortex_session::SessionGuard;
use vortex_session::SessionVar;
use vortex_session::registry::Id;

use crate::ComponentKind;
use crate::Edition;
use crate::EditionDeclaration;
use crate::EditionFamily;
use crate::EditionId;
use crate::EditionInclusion;
use crate::parse_release;

/// The session's registry of editions and edition inclusions.
///
/// Starts empty and is populated at initialization time: the `vortex` facade seeds the
/// first-party declarations (`vortex::editions`), and crates registering additional
/// encodings declare their inclusions (and, for new families, editions) alongside their
/// encoding registration. Clones share the same underlying registry, matching the other
/// session registries.
#[derive(Clone, Debug, Default)]
pub struct EditionSession {
    inner: Arc<RwLock<Inner>>,
}

#[derive(Debug, Default)]
struct Inner {
    /// Keyed by family name.
    families: BTreeMap<String, EditionFamily>,
    /// Keyed by the display form of the edition id.
    editions: BTreeMap<String, Edition>,
    /// One map per member kind, each keyed by interned member id, because ids are only unique
    /// within a kind. An id may have one inclusion per family. Ordered by kind, then by the id's
    /// string form.
    inclusions: BTreeMap<ComponentKind, BTreeMap<Id, Vec<EditionInclusion>>>,
}

impl Inner {
    fn check_edition(&self, edition: Edition) -> VortexResult<String> {
        let key = edition.id.to_string();
        if self.editions.contains_key(&key) {
            vortex_bail!("duplicate edition {key}");
        }
        Ok(key)
    }

    fn check_inclusion(&self, inclusion: &EditionInclusion) -> VortexResult<()> {
        let previous = self
            .inclusions
            .get(&inclusion.kind)
            .and_then(|by_id| by_id.get(&inclusion.component_id))
            .and_then(|history| {
                history
                    .iter()
                    .filter(|existing| existing.since.family == inclusion.since.family)
                    .max_by_key(|existing| {
                        (
                            existing.since.year,
                            existing.since.month,
                            existing.since.version,
                        )
                    })
            });

        if let Some(previous) = previous {
            vortex_bail!(
                "{} {} already joined family {} in edition {}",
                inclusion.kind,
                inclusion.component_id,
                inclusion.since.family,
                previous.since,
            );
        }
        Ok(())
    }

    fn insert_inclusion(&mut self, inclusion: EditionInclusion) {
        let history = self
            .inclusions
            .entry(inclusion.kind)
            .or_default()
            .entry(inclusion.component_id)
            .or_default();
        history.push(inclusion);
        history.sort_by_key(|entry| {
            (
                entry.since.family,
                entry.since.year,
                entry.since.month,
                entry.since.version,
            )
        });
    }
}

/// Registry of enabled editions, keyed by interned edition family.
type EditionsByFamily = ArcSwapMap<Id, EditionId>;

/// The editions enabled for writing in a session.
///
/// At most one edition is enabled per family. Enabling a newer or older edition from the
/// same family replaces the previous selection. This is separate from [`EditionSession`]:
/// registration describes what a session knows how to reason about, while enabling is the
/// explicit writer policy.
///
/// Backed by an [`ArcSwapMap`] keyed by edition family, so clones observe the same selection
/// and enabling an edition replaces the family's previous entry.
#[derive(Clone, Debug, Default)]
pub struct EnabledEditions {
    inner: EditionsByFamily,
}

impl EnabledEditions {
    /// Return the enabled editions.
    pub fn editions(&self) -> Vec<EditionId> {
        self.inner.read(|map| map.values().copied().collect())
    }

    fn enable(&self, edition: EditionId) {
        // The family is a `&'static str`; `Into<Id>` interns it once at enable time (a rare
        // config-time write, never on the read path).
        self.inner.insert(Id::from(edition.family), edition);
    }
}

impl EditionSession {
    /// Create a session variable with no declarations.
    pub fn empty() -> Self {
        Self {
            inner: Arc::new(RwLock::new(Inner::default())),
        }
    }

    /// Declare an edition together with the members added at it. Each entry's membership
    /// (`since`) is the declared edition; earlier entries are inherited and must not be restated.
    ///
    /// The declaration is validated in full before anything is registered: on error, neither the
    /// edition nor any of its members is published.
    pub fn declare(&self, declaration: &EditionDeclaration) -> VortexResult<()> {
        let mut inner = self.inner.write();
        let key = inner.check_edition(declaration.edition)?;

        let mut seen = BTreeSet::new();
        let mut inclusions = Vec::with_capacity(declaration.added.len());
        for member in declaration.added {
            let inclusion =
                EditionInclusion::new(member.kind, member.component, declaration.edition.id);
            inner.check_inclusion(&inclusion)?;
            if !seen.insert((inclusion.kind, inclusion.component_id)) {
                vortex_bail!(
                    "{} {} is listed more than once in edition {}",
                    inclusion.kind,
                    inclusion.component_id,
                    inclusion.since,
                );
            }
            inclusions.push(inclusion);
        }

        inner.editions.insert(key, declaration.edition);
        for inclusion in inclusions {
            inner.insert_inclusion(inclusion);
        }
        Ok(())
    }

    /// Declare an edition family. Errors if a family with the same name is already
    /// declared. Every family must be declared before [`EditionSession::validate`] will
    /// accept editions belonging to it.
    pub fn declare_family(&self, family: &EditionFamily) -> VortexResult<()> {
        let mut inner = self.inner.write();
        if inner.families.contains_key(family.name) {
            vortex_bail!("duplicate edition family {}", family.name);
        }
        inner.families.insert(family.name.to_string(), *family);
        Ok(())
    }

    /// All declared families, sorted by name.
    pub fn families(&self) -> Vec<EditionFamily> {
        self.inner.read().families.values().copied().collect()
    }

    /// Find a declared family by name.
    pub fn find_family(&self, name: &str) -> Option<EditionFamily> {
        self.inner.read().families.get(name).copied()
    }

    /// Declare an edition. Errors if an edition with the same id is already declared.
    pub fn declare_edition(&self, edition: Edition) -> VortexResult<()> {
        let mut inner = self.inner.write();
        let key = inner.check_edition(edition)?;
        inner.editions.insert(key, edition);
        Ok(())
    }

    /// Declare an edition inclusion. A component may belong to multiple families but joins each
    /// family only once. A newer wire representation uses a new component ID. Kind is part of the
    /// key, so an array encoding and a layout may share an id.
    pub fn declare_inclusion(&self, inclusion: EditionInclusion) -> VortexResult<()> {
        let mut inner = self.inner.write();
        inner.check_inclusion(&inclusion)?;
        inner.insert_inclusion(inclusion);
        Ok(())
    }

    /// All declared editions, sorted by family and then chronologically. The newest frozen
    /// edition of each family is that family's `current` edition; unversioned editions are
    /// drafts.
    pub fn editions(&self) -> Vec<Edition> {
        let mut editions: Vec<Edition> = self.inner.read().editions.values().copied().collect();
        editions.sort_by_key(|e| (e.id.family, e.id.year, e.id.month, e.id.version));
        editions
    }

    /// Find a declared edition by id.
    pub fn find(&self, id: &EditionId) -> Option<Edition> {
        self.inner.read().editions.get(&id.to_string()).copied()
    }

    /// Find a declared edition by its name, for example `core2025.10.0`.
    pub fn find_by_name(&self, name: &str) -> Option<Edition> {
        self.inner.read().editions.get(name).copied()
    }

    /// The newest frozen edition of a family, if any. Drafts are never current.
    pub fn current(&self, family: &str) -> Option<Edition> {
        self.editions()
            .into_iter()
            .rfind(|e| e.id.family == family && !e.is_draft())
    }

    /// Compute an edition's members of one kind, sorted by component id. For each id, this returns
    /// its inclusion in the edition's family when it joined at or before the requested edition.
    /// Only that kind's declarations are scanned.
    pub fn components_in(&self, edition: &EditionId, kind: ComponentKind) -> Vec<EditionInclusion> {
        let inner = self.inner.read();
        let Some(by_id) = inner.inclusions.get(&kind) else {
            return vec![];
        };
        by_id
            .values()
            .filter_map(|history| {
                history
                    .iter()
                    .filter(|inclusion| inclusion.since.is_at_or_before(edition))
                    .max_by_key(|inclusion| {
                        (
                            inclusion.since.year,
                            inclusion.since.month,
                            inclusion.since.version,
                        )
                    })
                    .copied()
            })
            .collect()
    }

    /// Validate all registered declarations. Errors on editions in undeclared families,
    /// inclusions referencing undeclared editions, editions out of chronological order within
    /// a family (unversioned drafts must be newest), malformed version strings, and members
    /// requiring a release newer than their edition declares.
    pub fn validate(&self) -> VortexResult<()> {
        let editions = self.editions();

        for family in self.families() {
            family.validate()?;
        }

        for edition in &editions {
            edition.id.validate()?;
            if self.find_family(edition.id.family).is_none() {
                vortex_bail!(
                    "edition {} belongs to undeclared family {}; declare the family before \
                     its editions",
                    edition.id,
                    edition.id.family,
                );
            }
            if !edition.immutable && !edition.is_draft() {
                vortex_bail!(
                    "edition {} never freezes, so it cannot record a min_library_version; \
                     promote members into a new edition",
                    edition.id
                );
            }
            if let Some(version) = edition.min_library_version
                && parse_release(version).is_none()
            {
                vortex_bail!(
                    "edition {} declares malformed min_library_version {version:?}",
                    edition.id
                );
            }
        }

        // Within each family, frozen editions must precede drafts: a frozen edition after
        // an unversioned one would imply the draft was skipped.
        for pair in editions.windows(2) {
            let (prev, next) = (&pair[0], &pair[1]);
            if prev.id.family == next.id.family && prev.is_draft() && !next.is_draft() {
                vortex_bail!(
                    "frozen edition {} follows draft {}; drafts must be newest in a family",
                    next.id,
                    prev.id,
                );
            }
        }

        let inner = self.inner.read();
        for inclusion in inner
            .inclusions
            .values()
            .flat_map(|by_id| by_id.values())
            .flatten()
        {
            inclusion.validate()?;

            let Some(edition) = inner.editions.get(&inclusion.since.to_string()) else {
                vortex_bail!(
                    "{} {} is included in undeclared edition {}",
                    inclusion.kind,
                    inclusion.component_id,
                    inclusion.since
                );
            };

            if let Some(required) = inclusion.required_vortex_release.and_then(parse_release)
                && let Some(declared) = edition.min_library_version.and_then(parse_release)
                && required > declared
            {
                vortex_bail!(
                    "{} {} requires release {}, newer than edition {}'s declared \
                     min_library_version",
                    inclusion.kind,
                    inclusion.component_id,
                    inclusion.required_vortex_release.unwrap_or_default(),
                    edition.id,
                );
            }
        }

        Ok(())
    }
}

impl SessionVar for EditionSession {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

impl SessionVar for EnabledEditions {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

/// Session data for Vortex editions.
pub trait EditionSessionExt: SessionExt {
    /// Returns the edition registry.
    fn editions(&self) -> SessionGuard<'_, EditionSession> {
        self.get::<EditionSession>()
    }

    /// Returns the editions enabled for writing.
    ///
    /// Accessing this method installs the enabled-editions session variable if it is absent, with
    /// an initially empty selection.
    fn enabled_editions(&self) -> SessionGuard<'_, EnabledEditions> {
        self.get::<EnabledEditions>()
    }

    /// Register an edition declaration with this session.
    fn register_edition(&self, declaration: &EditionDeclaration) -> VortexResult<()> {
        self.editions().declare(declaration)
    }

    /// Enable a registered edition for writing.
    ///
    /// Enabling an edition replaces the enabled edition from the same family. An edition
    /// must be registered first so a typo or unavailable third-party declaration cannot
    /// silently produce an empty writable set.
    fn enable_edition(&self, edition: EditionId) -> VortexResult<()> {
        if self.editions().find(&edition).is_none() {
            vortex_bail!("cannot enable unregistered edition {edition}");
        }
        self.enabled_editions().enable(edition);
        Ok(())
    }

    /// Resolve the ids of one [`ComponentKind`] across all enabled editions: what a writer may
    /// emit for that kind.
    ///
    /// Ids are only unique within a kind, so this never mixes kinds. An empty result means the
    /// enabled editions permit no components of this kind.
    fn enabled_component_ids(&self, kind: ComponentKind) -> Vec<Id> {
        let Some(enabled) = self.get_opt::<EnabledEditions>() else {
            return vec![];
        };
        let editions = self.editions();
        let mut ids: Vec<Id> = enabled
            .editions()
            .iter()
            .flat_map(|edition| editions.components_in(edition, kind))
            .map(|inclusion| inclusion.component_id)
            .collect();
        ids.sort_unstable();
        ids.dedup();
        ids
    }
}

impl<S: SessionExt> EditionSessionExt for S {}