Skip to main content

vortex_edition/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Definitions of Vortex *editions*: named sets of serialized component IDs. Frozen editions
5//! carry a forever read-compatibility guarantee; draft editions do not, and their members can
6//! change or be removed.
7//!
8//! Editions live on the session, like encodings do: [`EditionSession`] holds the registered
9//! editions and [`EnabledEditions`] selects which of them a writer may emit. Declarations
10//! are plain constants — an [`EditionId`] plus an [`Edition`] record, and one
11//! [`EditionInclusion`] per member stating that it is a member of an edition *and every
12//! later edition of the same family*. Any crate can register declarations into a session,
13//! so inclusions can live next to the component they describe.
14//!
15//! Every membership is typed by a [`ComponentKind`], and members are resolved one kind at a
16//! time with [`EditionSessionExt::enabled_component_ids`]: the file writer restricts the
17//! arrays, layouts, extension dtypes, and aggregates it writes from separate id sets. Array
18//! memberships name wire IDs rather than in-memory array representations. An array plugin may
19//! serialize one current in-memory representation under several historical IDs. The serialization
20//! context validates the ID chosen by the plugin before writing it. Readers resolve the ID stored
21//! in the file and either deserialize it into the current representation or reject it as unknown.
22//!
23//! An edition is represented as a **draft** until its [`Edition::min_library_version`] is
24//! recorded. A stable edition may freeze in the release that cuts it; once that release version
25//! is known, the field is backfilled to document the freeze. The per-edition member sets are
26//! computed from the registered declarations by [`EditionSession::components_in`], and
27//! correctness is enforced by unit tests: [`EditionSession::validate`] checks a whole registry,
28//! and [`test_harness::validate_edition`] validates one edition's constraints — call it once in
29//! the `#[cfg(test)]` module of each edition definition.
30//!
31//! The first-party edition declarations live in this crate. The public `vortex` crate
32//! re-exports them and registers and enables them on the default session. See the published spec at
33//! <https://docs.vortex.dev/specs/versioning.html>.
34
35pub mod declarations;
36mod session;
37pub mod test_harness;
38#[cfg(test)]
39mod tests;
40
41use std::fmt;
42use std::fmt::Debug;
43use std::fmt::Display;
44use std::fmt::Formatter;
45
46pub use declarations::EDITION_DECLARATIONS;
47pub use declarations::EDITION_FAMILIES;
48pub use declarations::unstable::UNSTABLE;
49pub use session::EditionSession;
50pub use session::EditionSessionExt;
51pub use session::EnabledEditions;
52use vortex_error::VortexResult;
53use vortex_error::vortex_bail;
54use vortex_session::registry::Id;
55
56/// The identifier of an edition, e.g. `core2026.07.0`.
57///
58/// The `family` names an independently versioned, additive group of members (`core` is the set
59/// available to the default writer). For `core`, the date components record when the edition
60/// freezes; that date is prospective while the edition is still a draft. Dates order editions
61/// chronologically *within* a family; there is no ordering across families.
62#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
63pub struct EditionId {
64    /// The edition family, e.g. `core`.
65    pub family: &'static str,
66    /// Year in the edition date. For `core`, this is the freeze year.
67    pub year: u16,
68    /// Month in the edition date. For `core`, this is the freeze month.
69    pub month: u8,
70    /// Distinguishes editions with the same family, year, and month; normally `0`.
71    pub version: u8,
72}
73
74impl EditionId {
75    /// Create an edition identifier. Validated by [`EditionId::validate`], which
76    /// [`test_harness::validate_edition`] exercises
77    /// per edition in unit tests.
78    pub const fn new(family: &'static str, year: u16, month: u8, version: u8) -> Self {
79        Self {
80            family,
81            year,
82            month,
83            version,
84        }
85    }
86
87    /// Returns true if `self` is the same edition as `other` or an earlier edition of the
88    /// same family. Editions of different families are never ordered.
89    pub fn is_at_or_before(&self, other: &EditionId) -> bool {
90        self.family == other.family
91            && (self.year, self.month, self.version) <= (other.year, other.month, other.version)
92    }
93
94    /// Validate the identifier's form: a non-empty lowercase family, a four-digit year,
95    /// and a month in 01-12. Checked for every declared edition by
96    /// [`EditionSession::validate`] and per edition by
97    /// [`test_harness::validate_edition`].
98    pub fn validate(&self) -> VortexResult<()> {
99        if self.family.is_empty() || !self.family.chars().all(|c| c.is_ascii_lowercase()) {
100            vortex_bail!("edition {self} must have a non-empty lowercase family, e.g. `core`");
101        }
102        if !(1000..=9999).contains(&self.year) {
103            vortex_bail!("edition {self} must have a four-digit year");
104        }
105        if !(1..=12).contains(&self.month) {
106            vortex_bail!("edition {self} must have a month in 01-12");
107        }
108        Ok(())
109    }
110}
111
112impl Display for EditionId {
113    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
114        write!(
115            f,
116            "{}{}.{:02}.{}",
117            self.family, self.year, self.month, self.version
118        )
119    }
120}
121
122/// A family of editions: an independently versioned, additive group of members, registered
123/// with [`EditionSession::declare_family`].
124///
125/// Every [`EditionId`] names one. Declaring the family is what makes the name real:
126/// [`EditionSession::validate`] rejects an edition whose family was never declared, so a typo
127/// cannot quietly mint a family of one.
128#[derive(Clone, Copy, Debug)]
129pub struct EditionFamily {
130    /// The family name, matching the [`EditionId::family`] of its editions, e.g. `core`.
131    pub name: &'static str,
132    /// The library or project whose releases provide readers for this family's editions.
133    /// [`Edition::min_library_version`] refers to versions of this origin.
134    pub origin: &'static str,
135    /// What the family is for. Exported into the family's record, so a few sentences at
136    /// most: the long form belongs in the published spec.
137    pub doc: &'static str,
138}
139
140impl EditionFamily {
141    /// Validate the family's form: a non-empty lowercase name, origin, and doc. Checked for every
142    /// declared family by [`EditionSession::validate`].
143    pub fn validate(&self) -> VortexResult<()> {
144        if self.name.is_empty() || !self.name.chars().all(|c| c.is_ascii_lowercase()) {
145            vortex_bail!(
146                "edition family {:?} must have a non-empty lowercase name, e.g. `core`",
147                self.name
148            );
149        }
150        if self.origin.trim().is_empty() {
151            vortex_bail!(
152                "edition family {} must name its origin library or project",
153                self.name
154            );
155        }
156        if self.doc.trim().is_empty() {
157            vortex_bail!("edition family {} must document what it is for", self.name);
158        }
159        Ok(())
160    }
161}
162
163/// The kind of member an edition membership covers.
164///
165/// Ids are unique per kind, not globally: a layout named `vortex.flat` and an array named
166/// `vortex.flat` are different members. Every membership records its kind, and the writer
167/// resolves one kind at a time, so the set restricting written arrays never restricts
168/// written layouts. Further kinds (scalar functions, say) can be added the same way.
169#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
170pub enum ComponentKind {
171    /// A serialized array representation, e.g. `vortex.alp`, registered in the session's array
172    /// registry.
173    Array,
174    /// A layout encoding, e.g. `vortex.flat`, registered in the session's layout registry.
175    Layout,
176    /// An extension dtype, e.g. `vortex.timestamp`, registered in the session's dtype registry.
177    DType,
178    /// An aggregate function, e.g. `vortex.min`, written into zone maps and registered in
179    /// the session's aggregate function registry.
180    Aggregate,
181}
182
183impl Display for ComponentKind {
184    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
185        f.write_str(match self {
186            Self::Array => "array",
187            Self::Layout => "layout",
188            Self::DType => "dtype",
189            Self::Aggregate => "aggregate",
190        })
191    }
192}
193
194/// An edition: a named set of serialized components that can acquire a read-compatibility
195/// guarantee, registered with [`EditionSession::declare_edition`].
196/// The set itself is computed from the registered [`EditionInclusion`]s by
197/// [`EditionSession::components_in`].
198#[derive(Clone, Copy, Debug)]
199pub struct Edition {
200    /// The edition identifier. For a `core` edition, its date records when it freezes.
201    pub id: EditionId,
202    /// Whether this edition becomes immutable when it freezes. An edition that is not immutable,
203    /// such as [`UNSTABLE`], never freezes and stays a draft, so its members can always change or
204    /// be removed.
205    pub immutable: bool,
206    /// The minimum version of the edition family's [`EditionFamily::origin`] whose reader
207    /// supports every member of this edition. Always `None` for an edition that never freezes.
208    ///
209    /// A stable edition may freeze in the release that cuts it. Until that release is cut, its
210    /// version is not known and this remains `None`. The version is then backfilled to document
211    /// the already completed freeze and identify the first released reader supporting every
212    /// member. A draft has no recorded read-forever guarantee; that does not imply that its
213    /// behavior is expected to change.
214    /// Validated against the members' [`EditionInclusion::required_vortex_release`] values:
215    /// no member may require a version newer than the edition declares.
216    pub min_library_version: Option<&'static str>,
217}
218
219impl Edition {
220    /// A draft is an edition whose `min_library_version` has not been recorded yet. Members of a
221    /// draft can change or be removed.
222    ///
223    /// This describes the absence of a frozen compatibility guarantee, not necessarily the
224    /// implementation stability of its members.
225    pub fn is_draft(&self) -> bool {
226        self.min_library_version.is_none()
227    }
228}
229
230/// Declares that a serialized component is a member of an edition — and of every later edition of
231/// the same family. Registered with [`EditionSession::declare_inclusion`].
232#[derive(Clone, Copy, Debug)]
233pub struct EditionInclusion {
234    /// What the membership covers. Ids are unique per kind, so this is part of the
235    /// member's identity, not a label.
236    pub kind: ComponentKind,
237    /// The interned component id, e.g. `vortex.alp`.
238    pub component_id: Id,
239    /// The first edition this component is a member of.
240    pub since: EditionId,
241    /// The earliest Vortex release supporting this member, recorded from evidence (e.g.
242    /// compat-fixture history for serialized components). `None` until recorded.
243    pub required_vortex_release: Option<&'static str>,
244}
245
246/// A source of a component id for edition declarations.
247///
248/// Implemented for raw id strings (`"vortex.alp"`) and interned [`Id`]s here; encoding
249/// vtables implement it where they are defined, so a declaration can name the vtable
250/// (`&Primitive`) instead of spelling its id. The id alone does not say what kind of
251/// component it names — [`EditionMember`] pairs it with a [`ComponentKind`].
252pub trait AsComponentId: Debug + Send + Sync {
253    /// The interned component id.
254    fn component_id(&self) -> Id;
255}
256
257impl AsComponentId for str {
258    #[expect(
259        clippy::disallowed_methods,
260        reason = "interning a dynamic component id at declaration time"
261    )]
262    fn component_id(&self) -> Id {
263        Id::new(self)
264    }
265}
266
267impl AsComponentId for Id {
268    fn component_id(&self) -> Id {
269        *self
270    }
271}
272
273// `str` is unsized and cannot be a trait object, so declaration blocks name components as
274// `&"vortex.alp"` through this impl.
275impl AsComponentId for &'static str {
276    fn component_id(&self) -> Id {
277        (**self).component_id()
278    }
279}
280
281/// A member that joins an edition, named by id string or vtable and tagged with its kind.
282/// Built with the per-kind constructors, so a declaration reads
283/// as `EditionMember::array(&"vortex.alp")`.
284#[derive(Clone, Copy, Debug)]
285pub struct EditionMember {
286    /// What kind of member this is.
287    pub kind: ComponentKind,
288    /// The member, named by id string or by vtable.
289    pub component: &'static dyn AsComponentId,
290}
291
292impl EditionMember {
293    /// An array encoding member, e.g. `vortex.alp`.
294    pub const fn array(component: &'static dyn AsComponentId) -> Self {
295        Self {
296            kind: ComponentKind::Array,
297            component,
298        }
299    }
300
301    /// A layout member, e.g. `vortex.flat`.
302    pub const fn layout(component: &'static dyn AsComponentId) -> Self {
303        Self {
304            kind: ComponentKind::Layout,
305            component,
306        }
307    }
308
309    /// An extension dtype member, e.g. `vortex.timestamp`.
310    pub const fn dtype(component: &'static dyn AsComponentId) -> Self {
311        Self {
312            kind: ComponentKind::DType,
313            component,
314        }
315    }
316
317    /// An aggregate function member, e.g. `vortex.min`.
318    pub const fn aggregate(component: &'static dyn AsComponentId) -> Self {
319        Self {
320            kind: ComponentKind::Aggregate,
321            component,
322        }
323    }
324}
325
326/// Declares an edition together with its new members in one block. Registered with
327/// [`EditionSession::declare`], which derives each entry's membership (`since` = the declared
328/// edition) from the block structure.
329#[derive(Clone, Copy, Debug)]
330pub struct EditionDeclaration {
331    /// The edition being declared.
332    pub edition: Edition,
333    /// The members that join the family at this edition, each tagged with its [`ComponentKind`].
334    /// Earlier entries are inherited and never restated.
335    pub added: &'static [EditionMember],
336}
337
338impl EditionInclusion {
339    /// Declare that a component of `kind` is a member of `since` and every later edition of
340    /// the same family. The component can be named by id string or by vtable.
341    pub fn new<C: AsComponentId + ?Sized>(
342        kind: ComponentKind,
343        component: &C,
344        since: EditionId,
345    ) -> Self {
346        Self {
347            kind,
348            component_id: component.component_id(),
349            since,
350            required_vortex_release: None,
351        }
352    }
353
354    /// Declare that an array encoding is a member of `since` and every later edition of the
355    /// same family.
356    pub fn array<C: AsComponentId + ?Sized>(encoding: &C, since: EditionId) -> Self {
357        Self::new(ComponentKind::Array, encoding, since)
358    }
359
360    /// Declare that an extension dtype is a member of `since` and every later edition of the
361    /// same family.
362    pub fn dtype<C: AsComponentId + ?Sized>(dtype: &C, since: EditionId) -> Self {
363        Self::new(ComponentKind::DType, dtype, since)
364    }
365
366    /// Validate the declaration's form: a lowercase `namespace.name` component id and, if
367    /// recorded, a well-formed `major.minor.patch` release. Checked for every declared
368    /// inclusion by [`EditionSession::validate`].
369    pub fn validate(&self) -> VortexResult<()> {
370        let id = self.component_id.as_str();
371        let well_formed = !id.starts_with('.')
372            && !id.ends_with('.')
373            && id.contains('.')
374            && id
375                .chars()
376                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "._-".contains(c));
377        if !well_formed {
378            vortex_bail!(
379                "invalid {} id {id:?}: expected lowercase `namespace.name`, e.g. `vortex.alp`",
380                self.kind
381            );
382        }
383        if let Some(release) = self.required_vortex_release
384            && parse_release(release).is_none()
385        {
386            vortex_bail!(
387                "{} {id} declares malformed required_vortex_release {release:?}",
388                self.kind
389            );
390        }
391        Ok(())
392    }
393}
394
395/// Parse a `major.minor.patch` release string into a comparable key.
396pub(crate) fn parse_release(release: &str) -> Option<Vec<u64>> {
397    let parts: Vec<u64> = release
398        .split('.')
399        .map(|part| part.parse::<u64>().ok())
400        .collect::<Option<_>>()?;
401    (parts.len() == 3).then_some(parts)
402}