Skip to main content

waratah_storage/encode/
temporal.rs

1//! Temporal tick-axis projection, dyadic node arithmetic, and the O-axis
2//! `temporal_index` CF layout.
3//!
4//! This module is the **shared encoding-level mechanics** of the temporal
5//! plugin (see `ARCH.md`): both compute (the `waratah_temporal`
6//! plugin derives postings at ingest and covers query windows at plan time)
7//! and the O partition (the `temporal rebuild-index` walk) call the SAME
8//! projection and decomposition routines, so the two sides can never drift.
9//! Everything here is dependency-free integer code — no temporal semantics
10//! beyond ordered ticks, no I/O.
11//!
12//! # The tick axis
13//!
14//! One tick = one attosecond (10⁻¹⁸ s) on the proleptic Gregorian timeline,
15//! which is exactly the value space of `oxsdatatypes::Decimal` seconds: the
16//! stored `xsd:dateTime` term already carries its tick (`DateTime` encodes
17//! seconds-since-era as a `Decimal`, and `Decimal`'s wire bytes ARE a scaled
18//! `i128`). The full representable axis spans roughly ±5.4 trillion years —
19//! comfortably covering geological (billions of years) and electronic
20//! (sub-millisecond) domains on ONE linear axis.
21//!
22//! # Key ordering
23//!
24//! Posting keys prefix with the node's start tick encoded as **sign-flipped
25//! big-endian** bytes (`tick_to_key_u128` / `key_u128_to_tick`): XOR the top
26//! bit of the two's-complement `i128` (biased/offset binary). Big-endian
27//! alone is monotone within each sign half, but every negative tick has its
28//! top bit set, so raw two's-complement BE sorts ALL negatives ABOVE all
29//! positives — the axis would be cut in half with the halves swapped and
30//! every window crossing year zero would be non-contiguous. The flip maps
31//! signed order onto unsigned order exactly, making RocksDB byte order ==
32//! tick order over the whole axis. All dyadic arithmetic below operates in
33//! this flipped `u128` "key space"; signed `i128` ticks appear only in the
34//! exact interval values.
35//!
36//! # Dyadic nodes
37//!
38//! A dyadic node is an interval `[k·2^w, (k+1)·2^w)` of the key space: level
39//! `level` (0 = whole axis, 127 = width 2), width `2^(128-level)` keys. Nodes
40//! are laminar (any two nest or are disjoint), which is what makes the scan
41//! protocol complete: a stored posting under query node `m` is found either
42//! by `m`'s inclusive key range `[min_key, max_key]` (posting nested in `m`)
43//! or by one exact ancestor key (posting containing `m`). An **instant** is
44//! the degenerate node at level 128 (width 1): its posting key is simply the
45//! tick's key bytes.
46//!
47//! # CF layout (`temporal_index`, O axis only)
48//!
49//! ```text
50//! key   = node_start_key_u128_be(16) ‖ encode_term_bytes(term) ‖ commit_ts_desc(8)
51//! value = op u8 ‖ visibility u32 ‖ begin i128_be(16) ‖ end i128_be(16)
52//! ```
53//!
54//! The value's `begin`/`end` are the term's EXACT closed tick interval (the
55//! covering node only addresses; the pair decides). The partition applies
56//! postings verbatim, MVCC-collapses, dedups on full term bytes
57//! ([`TemporalCandidateState`]), and rejects on the exact interval predicate
58//! — it never derives keys or interprets datatypes. This CF is
59//! range-partitioned by node key, never by term hash (same invariant as the
60//! geo index for later O hash-subsharding).
61
62use super::binary::TermReader;
63use super::binary::encode_term_bytes;
64use super::encoded_term::EncodedTerm;
65use super::versioned::{COMMIT_TS_LEN, STORAGE_VALUE_LEN, encode_storage_value};
66use crate::StorageError;
67use crate::types::{CommitTs, SnapshotId, StorageOp, VisibilityLabel};
68
69/// RocksDB column-family name. Opened only on [`crate::PartitionAxis::O`].
70pub const TEMPORAL_INDEX_CF: &str = "temporal_index";
71
72/// RocksDB column-family name for temporal-index metadata (two reserved
73/// keys: the rebuild epoch and its tick-axis origin version). Opened only on
74/// [`crate::PartitionAxis::O`].
75pub const TEMPORAL_INDEX_META_CF: &str = "temporal_index_meta";
76
77/// The one reserved key in [`TEMPORAL_INDEX_META_CF`]: the rebuild epoch as
78/// 8-byte big-endian (`u64` commit_ts).
79pub const TEMPORAL_INDEX_EPOCH_KEY: &[u8] = b"temporal_index_epoch";
80
81/// The other reserved key in [`TEMPORAL_INDEX_META_CF`]: the version of the
82/// tick-axis ORIGIN an epoch was stamped under.
83///
84/// Same shape and reason as geo's liveness marker ([`GEO_INDEX_LIVENESS_KEY`]):
85/// moving the origin (B56 moved it 306 days) invalidates every posting key and
86/// every stored `begin`/`end` pair, but the epoch itself still reads stamped —
87/// a trusted index whose postings sit where no query looks. So the version
88/// rides beside the epoch, is written by `set_temporal_index_epoch`, and
89/// `temporal_index_epoch` reports `None` (untrusted) on mismatch, which makes
90/// startup's auto-rebuild re-cover the store instead of trusting it.
91pub const TEMPORAL_INDEX_ORIGIN_KEY: &[u8] = b"temporal_index_origin";
92
93/// Current tick-axis origin version. Bump ONLY when [`AXIS_ORIGIN_DAYS`]
94/// changes — i.e. when the calendar-to-stored alignment moves.
95pub const TEMPORAL_ORIGIN_VERSION: u64 = 1;
96
97/// Byte length of a persisted epoch value (big-endian `u64`).
98pub const TEMPORAL_EPOCH_VALUE_LEN: usize = 8;
99
100/// Byte length of a persisted origin-version value (big-endian `u64`).
101pub const TEMPORAL_ORIGIN_VALUE_LEN: usize = 8;
102
103/// Encode a persisted temporal-index epoch as 8-byte big-endian.
104pub fn encode_temporal_epoch(epoch: u64) -> Vec<u8> {
105    epoch.to_be_bytes().to_vec()
106}
107
108/// Decode a persisted temporal-index epoch.
109///
110/// An absent or malformed value decodes to `None`. Unlike the geo index, a
111/// missing epoch means **untrusted until the (auto-)rebuild stamps it**:
112/// temporal literals predate the plugin, so a legacy store has an empty
113/// index and no epoch, and a trusted-empty index would answer rewritten
114/// comparisons with zero rows (answer-affecting, forbidden). The compute
115/// startup auto-rebuild closes the window before any query is served.
116pub fn decode_temporal_epoch(bytes: Option<&[u8]>) -> Option<u64> {
117    let bytes = bytes?;
118    if bytes.len() != TEMPORAL_EPOCH_VALUE_LEN {
119        return None;
120    }
121    Some(u64::from_be_bytes(bytes.try_into().expect("len checked")))
122}
123
124/// Encode the tick-axis origin version.
125pub fn encode_temporal_origin(version: u64) -> Vec<u8> {
126    version.to_be_bytes().to_vec()
127}
128
129/// Decode the tick-axis origin version (`None` when absent or malformed).
130pub fn decode_temporal_origin(bytes: Option<&[u8]>) -> Option<u64> {
131    let bytes = bytes?;
132    if bytes.len() != TEMPORAL_ORIGIN_VALUE_LEN {
133        return None;
134    }
135    Some(u64::from_be_bytes(bytes.try_into().expect("len checked")))
136}
137
138/// Byte length of a node start key in every temporal-index key.
139pub const TEMPORAL_KEY_LEN: usize = 16;
140
141/// Value length: `op` + `visibility` + exact `begin` + exact `end`.
142pub const TEMPORAL_VALUE_LEN: usize = STORAGE_VALUE_LEN + 32;
143
144/// Attoseconds in one second.
145pub const ATTO_PER_SECOND: i128 = 1_000_000_000_000_000_000;
146/// Attoseconds in one minute.
147pub const ATTO_PER_MINUTE: i128 = 60 * ATTO_PER_SECOND;
148/// Attoseconds in one hour.
149pub const ATTO_PER_HOUR: i128 = 60 * ATTO_PER_MINUTE;
150/// Attoseconds in one day.
151pub const ATTO_PER_DAY: i128 = 24 * ATTO_PER_HOUR;
152/// The XSD 14-hour rule: a timezone-absent `xsd:dateTime` / `xsd:date` is
153/// order-indeterminate against a timezone-present value by at most ±14 h
154/// (`oxsdatatypes` implements the same bound in its `PartialOrd`). A
155/// timezone-absent term posts the uncertainty interval
156/// `[t − ATTO_TZ_INDETERMINATE, t + ATTO_TZ_INDETERMINATE]` — widened by the
157/// full day length for `xsd:date`, whose value is a day of unknown
158/// anchoring, not an instant — so every timezone-qualified window
159/// overlapping any possible reading finds it; the exact per-row predicate
160/// (the engine's own comparison) decides.
161pub const ATTO_TZ_INDETERMINATE: i128 = 14 * ATTO_PER_HOUR;
162
163/// Map a signed tick to its order-preserving key-space `u128`
164/// (biased / offset binary: XOR the sign bit).
165#[inline]
166pub fn tick_to_key_u128(tick: i128) -> u128 {
167    (tick as u128) ^ (1_u128 << 127)
168}
169
170/// Inverse of [`tick_to_key_u128`].
171#[inline]
172pub fn key_u128_to_tick(key: u128) -> i128 {
173    (key ^ (1_u128 << 127)) as i128
174}
175
176/// Days since the proleptic-Gregorian era for a calendar date
177/// (Howard Hinnant's `days_from_civil`), valid for the full `i64` year
178/// range.
179///
180/// The March-based year shift and `mp = (m + 9) % 12` counting are what make
181/// the algorithm branch-free over the whole range; the OUTPUT's zero is
182/// merely a consequence of the era/doe arithmetic and lands on **0000-03-01**
183/// (`days_from_civil(0, 3, 1) == 0`).
184///
185/// That zero is NOT the tick axis's zero. Every family must share ONE origin,
186/// and the origin is fixed by the stored representation: an `xsd:dateTime`'s
187/// tick is read straight from its persisted `Decimal` seconds, which are XSD
188/// `timeOnTimeline` — zero at **0001-01-01**. Calendar families are derived,
189/// so they must shift; see [`AXIS_ORIGIN_DAYS`] and [`tick_from_date`].
190pub fn days_from_civil(y: i64, m: u8, d: u8) -> i64 {
191    let y = y - i64::from(m <= 2); // shift to the March-based year
192    let era = y.div_euclid(400);
193    let yoe = y - era * 400; // [0, 399]
194    let mp = (i64::from(m) + 9) % 12; // March = 0
195    let doy = (153 * mp + 2) / 5 + i64::from(d) - 1; // [0, 365]
196    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
197    era * 146_097 + doe
198}
199
200/// Days from [`days_from_civil`]'s zero (0000-03-01) to the tick axis's zero
201/// (0001-01-01, the XSD `timeOnTimeline` epoch every stored `xsd:dateTime`
202/// already uses) — the offset calendar families subtract to land on ONE axis.
203///
204/// The value is `days_from_civil(1, 1, 1)`; it is written as a literal because
205/// `days_from_civil` cannot be `const fn` (`From<bool>` / `From<u8>` are not
206/// const-stable, so the algorithm would have to be contorted with `as` casts
207/// to derive it at compile time — a bad trade for a recognisable routine).
208/// The test `axis_origin_days_equals_the_calendar_distance_to_the_axis_zero`
209/// pins the relationship instead, so swapping the calendar routine fails
210/// loudly rather than silently re-splitting the axis by a new unknown offset.
211///
212/// Why this matters: within one family the offset cancels, so order and
213/// duration stay correct and only CROSS-family comparisons lie. The bug B56
214/// fixed was that `xsd:date` read 306 days later than the same instant as an
215/// `xsd:dateTime`, so `tf:isBefore(date, dateTime)` answered from numbers
216/// 306 days apart.
217const AXIS_ORIGIN_DAYS: i64 = 306;
218
219/// Midnight tick of a calendar date on the SHARED tick axis, `None` on
220/// representable-range overflow (the tick must fit the `i128` attosecond
221/// axis; values that fail here can never exist as parsed temporal terms
222/// anyway — the parser bounds are the representable bounds).
223///
224/// Subtracts [`AXIS_ORIGIN_DAYS`] so `date` / `gYear` / `gYearMonth` project
225/// onto the same origin an `xsd:dateTime`'s persisted tick already uses.
226/// Every calendar helper funnels through here, so the alignment holds for
227/// month starts, next-month starts, next-year starts, and both `gYear`
228/// interval edges.
229pub fn tick_from_date(y: i64, m: u8, d: u8) -> Option<i128> {
230    let day = days_from_civil(y, m, d) - AXIS_ORIGIN_DAYS;
231    i128::from(day).checked_mul(ATTO_PER_DAY)
232}
233
234/// First tick of one calendar month (`y`, `m`).
235pub fn month_start_tick(y: i64, m: u8) -> Option<i128> {
236    tick_from_date(y, m, 1)
237}
238
239/// First tick of the month AFTER (`y`, `m`) (December rolls the year).
240pub fn next_month_start_tick(y: i64, m: u8) -> Option<i128> {
241    if m >= 12 {
242        tick_from_date(y.checked_add(1)?, 1, 1)
243    } else {
244        tick_from_date(y, m + 1, 1)
245    }
246}
247
248/// First tick of the year AFTER `y`.
249pub fn next_year_start_tick(y: i64) -> Option<i128> {
250    tick_from_date(y.checked_add(1)?, 1, 1)
251}
252
253/// A dyadic node of the key space: level `0..=128`, width `2^(128-level)`
254/// keys starting at the multiple `index · 2^(128-level)`. Level 128 is the
255/// single-key leaf (an instant's exact tick). Nodes order by `(level, index)`
256/// — coarse first — which is the deterministic serialization order.
257#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
258pub struct DyadicNode {
259    /// Depth in the tree (0 = whole axis, 128 = single key).
260    pub level: u8,
261    /// Node index among the `2^level` nodes of this level
262    /// (`index == start_key >> (128 - level)`; 0 at level 0).
263    pub index: u128,
264}
265
266impl DyadicNode {
267    /// The single-key leaf holding `key` (an instant's node).
268    #[inline]
269    pub const fn leaf(key: u128) -> Self {
270        Self {
271            level: 128,
272            index: key,
273        }
274    }
275
276    /// Inclusive first key of this node.
277    #[inline]
278    pub fn min_key(&self) -> u128 {
279        match self.level {
280            0 => 0,
281            // Shifts < 128 only: level 0 returned above, level 128 has no
282            // shift (width 1).
283            128 => self.index,
284            level => self.index << (128 - u32::from(level)),
285        }
286    }
287
288    /// Inclusive last key of this node (`min_key | (MAX >> level)` — the
289    /// level-0 root maps to `u128::MAX`, never overflowing).
290    #[inline]
291    pub fn max_key(&self) -> u128 {
292        match self.level {
293            128 => self.index,
294            level => self.min_key() | (u128::MAX >> u32::from(level)),
295        }
296    }
297
298    /// The node's parent (level − 1); `None` at the root.
299    #[inline]
300    pub fn parent(&self) -> Option<Self> {
301        if self.level == 0 {
302            return None;
303        }
304        Some(Self {
305            level: self.level - 1,
306            index: self.index >> 1,
307        })
308    }
309}
310
311/// Snap a key DOWN to its containing level-`level` node's start key.
312#[inline]
313pub fn align_down_key(key: u128, level: u8) -> u128 {
314    match level {
315        0 => 0,
316        128 => key,
317        level => key & (u128::MAX << (128 - u32::from(level))),
318    }
319}
320
321/// Coverer configuration (temporal twin of the S2 coverer params): the node
322/// budget is **per interval**, the level window bounds grid coarseness.
323/// Process configuration on compute; the rebuild receives it over the RPC so
324/// policy stays compute-owned even though the partition executes the walk.
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326pub struct DyadicCovererConfig {
327    /// Coarsest allowed node level (nodes never coarser than this).
328    pub min_level: u8,
329    /// Finest allowed node level for covering (leaf instants bypass the
330    /// covering entirely — they post at their exact tick).
331    pub max_level: u8,
332    /// Maximum nodes one interval may post.
333    pub max_nodes: usize,
334}
335
336impl Default for DyadicCovererConfig {
337    fn default() -> Self {
338        Self {
339            min_level: 0,
340            max_level: 110,
341            max_nodes: 32,
342        }
343    }
344}
345
346/// Cover the inclusive key range `[begin_key, end_key]` with dyadic nodes.
347///
348/// First computes the **exact canonical decomposition** (greedy largest-node
349/// walk with single-key boundary leaves; tiles the range precisely, at most
350/// two nodes per level). When it exceeds `max_nodes`, falls back to the
351/// FINEST single grid level within `[min_level, max_level]` whose aligned
352/// node count fits the budget, snapping the range **outward** (`begin` down;
353/// the inclusive end is covered by its own aligned node) — a valid superset
354/// whose stick-out is bounded by one grid width per side. The exact
355/// `begin`/`end` pair rides every posting value, so stick-out costs candidate
356/// volume only, never correctness. Output nodes are sorted by start key.
357pub fn cover_axis_range(
358    begin_key: u128,
359    end_key: u128,
360    config: &DyadicCovererConfig,
361) -> Vec<DyadicNode> {
362    debug_assert!(begin_key <= end_key, "caller normalizes the range");
363    let max_nodes = config.max_nodes.max(1);
364    // Exact canonical decomposition (bounded by 2 nodes per level).
365    let mut exact: Vec<DyadicNode> = Vec::new();
366    // Stack of (level, index) candidates overlapping the range to test.
367    let mut stack: Vec<(u8, u128)> = vec![(0, 0)];
368    while let Some((level, index)) = stack.pop() {
369        let node = DyadicNode { level, index };
370        if node.max_key() < begin_key || node.min_key() > end_key {
371            continue; // disjoint
372        }
373        if node.min_key() >= begin_key && node.max_key() <= end_key {
374            exact.push(node);
375            continue;
376        }
377        // Straddles a boundary: recurse into both children (down to the
378        // single-key leaves — exact means exact).
379        if level < 128 {
380            let child_level = level + 1;
381            stack.push((child_level, index << 1));
382            stack.push((child_level, index << 1 | 1));
383        }
384    }
385    // Laminar nodes cannot share a start key, so ordering by min_key is a
386    // total order (and the deterministic output order).
387    exact.sort_unstable_by_key(|node| node.min_key());
388    if exact.len() <= max_nodes {
389        return exact;
390    }
391    // Budgeted: finest single grid level in the level window whose aligned
392    // node count fits (coarser grids fit fewer nodes; min_level floors the
393    // search and is used even when it exceeds the budget — a degenerate
394    // configuration, not an error).
395    let mut level = config.max_level.min(127);
396    let chosen = loop {
397        // Level 0 is the whole axis: definitionally one node, and the
398        // grid-width shift below would be 128 — illegal. Break before it;
399        // a level-0 cover fits any budget of at least one node. (Reaching
400        // level 0 requires min_level 0, max_nodes 1, and a window
401        // straddling a level-1 boundary.)
402        if level == 0 {
403            return vec![DyadicNode { level: 0, index: 0 }];
404        }
405        let start = align_down_key(begin_key, level);
406        let end = align_down_key(end_key, level);
407        let count = ((end - start) >> (128 - u32::from(level))) + 1;
408        if count <= max_nodes as u128 || level <= config.min_level {
409            break level;
410        }
411        level -= 1;
412    };
413    let start = align_down_key(begin_key, chosen);
414    let steps = (align_down_key(end_key, chosen) - start) >> (128 - u32::from(chosen));
415    (0..=steps)
416        .map(|step| DyadicNode {
417            level: chosen,
418            index: (start >> (128 - u32::from(chosen))) + step,
419        })
420        .collect()
421}
422
423/// One merged, sorted key interval to probe (compute-built from a covering:
424/// per-node descendant ranges ∪ exact ancestor keys as single-value ranges).
425#[derive(Debug, Clone, Copy, PartialEq, Eq)]
426pub struct TemporalCellInterval {
427    /// Inclusive lower key bound.
428    pub min_key: u128,
429    /// Inclusive upper key bound.
430    pub max_key: u128,
431}
432
433impl TemporalCellInterval {
434    /// Single-key interval (an exact ancestor posting).
435    pub const fn exact(key: u128) -> Self {
436        Self {
437            min_key: key,
438            max_key: key,
439        }
440    }
441
442    /// Encode as 32 big-endian bytes.
443    pub fn encode(self) -> [u8; 32] {
444        let mut out = [0_u8; 32];
445        out[0..16].copy_from_slice(&self.min_key.to_be_bytes());
446        out[16..32].copy_from_slice(&self.max_key.to_be_bytes());
447        out
448    }
449
450    /// Decode 32 big-endian bytes.
451    pub fn decode(bytes: &[u8]) -> Result<Self, StorageError> {
452        if bytes.len() != 32 {
453            return Err(StorageError::Corrupt(format!(
454                "temporal interval must be 32 bytes, got {}",
455                bytes.len()
456            )));
457        }
458        Ok(Self {
459            min_key: u128::from_be_bytes(bytes[0..16].try_into().expect("16-byte slice")),
460            max_key: u128::from_be_bytes(bytes[16..32].try_into().expect("16-byte slice")),
461        })
462    }
463}
464
465/// Merge a covering into the interval list (the temporal twin of geo's
466/// `intervals_for_covering`): each node contributes its inclusive descendant
467/// range **plus** the exact start key of every proper ancestor (which catch
468/// postings coarser than the query node — outward-snapped interval postings
469/// and coarse-level instants' containing beacons). Deduped, sorted by key.
470pub fn intervals_for_nodes(nodes: &[DyadicNode]) -> Vec<TemporalCellInterval> {
471    let mut intervals: Vec<TemporalCellInterval> = Vec::with_capacity(nodes.len() * 2);
472    for node in nodes {
473        intervals.push(TemporalCellInterval {
474            min_key: node.min_key(),
475            max_key: node.max_key(),
476        });
477        let mut parent = *node;
478        while let Some(up) = parent.parent() {
479            intervals.push(TemporalCellInterval::exact(up.min_key()));
480            parent = up;
481        }
482    }
483    intervals.sort_unstable_by_key(|interval| interval.min_key);
484    intervals.dedup();
485    intervals
486}
487
488/// The exact tick interval one stored temporal term covers. Projected once
489/// at ingest and carried verbatim in every posting value; the partition
490/// rejects against it without interpreting datatypes.
491#[derive(Debug, Clone, Copy, PartialEq, Eq)]
492pub struct TemporalShape {
493    /// Inclusive first tick of the interval.
494    pub begin: i128,
495    /// Inclusive last tick of the interval.
496    pub end: i128,
497}
498
499impl TemporalShape {
500    /// A single-tick instant.
501    pub const fn instant(tick: i128) -> Self {
502        Self {
503            begin: tick,
504            end: tick,
505        }
506    }
507
508    /// Whether this shape is a single tick (an instant posting).
509    pub fn is_instant(self) -> bool {
510        self.begin == self.end
511    }
512}
513
514/// Project a native temporal term onto the tick axis.
515///
516/// Returns `None` for every non-temporal term (including `xsd:time`, which
517/// is cyclic and has no anchoring on a linear timeline, and durations, which
518/// are lengths — not positions). This is the ONE definition of the projection
519/// shared by ingest, query covering, and the partition-side rebuild.
520///
521/// | Term | Interval |
522/// |---|---|
523/// | `xsd:dateTime` with timezone | instant at its timeline tick |
524/// | `xsd:dateTime` without timezone | `[t − 14 h, t + 14 h]` uncertainty |
525/// | `xsd:date` with timezone | its local day: `[UTC midnight − offset, +24 h)` as a closed tick interval |
526/// | `xsd:date` without timezone | the 24 h day widened by the ±14 h indeterminacy (unknown zone) |
527/// | `xsd:gYear` | `[Jan 1 00:00, next Jan 1 00:00]` (closed) |
528/// | `xsd:gYearMonth` | `[month start, next month start]` (closed) |
529///
530/// The gYear family is ALWAYS reckoned in UTC: a timezone offset, though
531/// legal in its lexical form, is ignored and the reference interval is the
532/// UTC boundary. SPARQL 1.0/1.1 define no ordering for these types (the
533/// operator table covers `xsd:dateTime` only — anything else is a type
534/// error), so the UTC rule is part of Waratah's documented ordering
535/// extension (`--strict-sparql` turns the extension into type errors),
536/// not a conformance surface. `xsd:gMonth` / `xsd:gDay` have no native
537/// term and do not project.
538pub fn temporal_term_interval(term: &EncodedTerm) -> Option<TemporalShape> {
539    match term {
540        EncodedTerm::DateTimeLiteral(value) => {
541            // `Decimal`'s wire bytes ARE the scaled i128 (attoseconds on the
542            // timeline); `to_be_bytes` is [seconds_decimal(16) ‖ tz(2)].
543            let raw = value.to_be_bytes();
544            let tick = i128::from_be_bytes(raw[0..16].try_into().expect("16-byte slice"));
545            Some(if value.timezone_offset().is_some() {
546                TemporalShape::instant(tick)
547            } else {
548                TemporalShape {
549                    begin: tick.saturating_sub(ATTO_TZ_INDETERMINATE),
550                    end: tick.saturating_add(ATTO_TZ_INDETERMINATE),
551                }
552            })
553        }
554        EncodedTerm::DateLiteral(value) => {
555            // XSD: a timezone-qualified date is THE DAY in that zone — the
556            // 24-hour interval starting at local midnight (UTC midnight
557            // shifted by the offset), not a single tick. A timezone-absent
558            // date is a day of unknown anchoring: order-indeterminate
559            // against qualified values by ±14 h, so its occupancy is the
560            // full day widened by the skew on both sides.
561            // `2025-03-15+05:00` occupies [2025-03-14T19:00Z, 2025-03-15T19:00Z).
562            let midnight = tick_from_date(value.year(), value.month(), value.day())?;
563            match value.timezone_offset() {
564                Some(offset) => {
565                    let zone = oxsdatatypes::DayTimeDuration::from(offset);
566                    let shift = i128::from(zone.hours() * 60 + zone.minutes()) * ATTO_PER_MINUTE;
567                    let begin = midnight.saturating_sub(shift);
568                    Some(TemporalShape {
569                        begin,
570                        end: begin.saturating_add(ATTO_PER_DAY - 1),
571                    })
572                }
573                None => Some(TemporalShape {
574                    begin: midnight.saturating_sub(ATTO_TZ_INDETERMINATE),
575                    end: midnight.saturating_add(ATTO_TZ_INDETERMINATE + ATTO_PER_DAY - 1),
576                }),
577            }
578        }
579        EncodedTerm::GYearLiteral(value) => {
580            let begin = tick_from_date(value.year(), 1, 1)?;
581            let end = next_year_start_tick(value.year())?;
582            Some(TemporalShape {
583                begin,
584                end: end.saturating_sub(1),
585            })
586        }
587        EncodedTerm::GYearMonthLiteral(value) => {
588            let begin = month_start_tick(value.year(), value.month())?;
589            let end = next_month_start_tick(value.year(), value.month())?;
590            Some(TemporalShape {
591                begin,
592                end: end.saturating_sub(1),
593            })
594        }
595        _ => None,
596    }
597}
598
599/// Compute the postings for one temporal term: the instant's exact leaf, or
600/// the budgeted covering of its interval (each node files the term under the
601/// node's start key). Returns an empty vec for unprojectable terms (they
602/// ingest unindexed; the residual path answers).
603pub fn postings_for_term(
604    term: &EncodedTerm,
605    commit_ts: CommitTs,
606    config: &DyadicCovererConfig,
607) -> Vec<TemporalIndexPut> {
608    let Some(shape) = temporal_term_interval(term) else {
609        return Vec::new();
610    };
611    let term_bytes = encode_term_bytes(term);
612    let nodes = if shape.is_instant() {
613        vec![DyadicNode::leaf(tick_to_key_u128(shape.begin))]
614    } else {
615        let begin_key = tick_to_key_u128(shape.begin);
616        let end_key = tick_to_key_u128(shape.end);
617        cover_axis_range(begin_key, end_key, config)
618    };
619    nodes
620        .into_iter()
621        .map(|node| TemporalIndexPut {
622            node_key: node.min_key(),
623            term: term_bytes.clone(),
624            commit_ts,
625            op: StorageOp::Put,
626            visibility: VisibilityLabel::default(),
627            begin: shape.begin,
628            end: shape.end,
629        })
630        .collect()
631}
632
633/// One staged temporal-index posting (compute-built or rebuild-derived; the
634/// O partition applies it verbatim).
635#[derive(Debug, Clone, PartialEq)]
636pub struct TemporalIndexPut {
637    /// Node start key this posting files the term under (the instant's exact
638    /// tick key for instants; a covering node's start key for intervals).
639    pub node_key: u128,
640    /// Encoded term bytes (a native temporal `EncodedTerm`).
641    pub term: Vec<u8>,
642    /// Cluster commit timestamp (same domain as the hexastore version).
643    pub commit_ts: CommitTs,
644    /// `Put` or `Delete`.
645    pub op: StorageOp,
646    /// Cell-level visibility label.
647    pub visibility: VisibilityLabel,
648    /// Exact interval start of the term (the truth, not the covering).
649    pub begin: i128,
650    /// Exact interval end of the term (inclusive).
651    pub end: i128,
652}
653
654impl TemporalIndexPut {
655    /// Encode the versioned key: `node_key ‖ term ‖ descending commit_ts`.
656    pub fn encode_key(&self) -> Vec<u8> {
657        let mut key = Vec::with_capacity(TEMPORAL_KEY_LEN + self.term.len() + COMMIT_TS_LEN);
658        key.extend_from_slice(&self.node_key.to_be_bytes());
659        key.extend_from_slice(&self.term);
660        key.extend_from_slice(&self.commit_ts.to_descending_be_bytes());
661        key
662    }
663
664    /// Encode the value: `op ‖ visibility ‖ begin ‖ end`.
665    pub fn encode_value(&self) -> Vec<u8> {
666        let mut value = Vec::with_capacity(TEMPORAL_VALUE_LEN);
667        value.extend_from_slice(&encode_storage_value(self.op, self.visibility));
668        value.extend_from_slice(&self.begin.to_be_bytes());
669        value.extend_from_slice(&self.end.to_be_bytes());
670        value
671    }
672
673    /// Build a posting from raw key/value bytes.
674    pub fn decode(key: &[u8], value: &[u8]) -> Result<Self, StorageError> {
675        if key.len() < TEMPORAL_KEY_LEN + COMMIT_TS_LEN {
676            return Err(StorageError::Corrupt(format!(
677                "temporal index key too short: {} bytes",
678                key.len()
679            )));
680        }
681        let node_key =
682            u128::from_be_bytes(key[0..TEMPORAL_KEY_LEN].try_into().expect("16-byte slice"));
683        let (term_bytes, ts_bytes) =
684            key[TEMPORAL_KEY_LEN..].split_at(key.len() - TEMPORAL_KEY_LEN - COMMIT_TS_LEN);
685        let commit_ts =
686            CommitTs::from_descending_be_bytes(ts_bytes.try_into().expect("8-byte slice"));
687        let mut cursor = term_bytes;
688        let _ = cursor.read_term()?;
689        if !cursor.is_empty() {
690            return Err(StorageError::Corrupt(format!(
691                "{} trailing byte(s) after temporal term",
692                cursor.len()
693            )));
694        }
695        if value.len() != TEMPORAL_VALUE_LEN {
696            return Err(StorageError::Corrupt(format!(
697                "temporal index value must be {} bytes, got {}",
698                TEMPORAL_VALUE_LEN,
699                value.len()
700            )));
701        }
702        let (op, visibility) = super::versioned::decode_storage_value(&value[..STORAGE_VALUE_LEN])?;
703        let begin = i128::from_be_bytes(
704            value[STORAGE_VALUE_LEN..STORAGE_VALUE_LEN + 16]
705                .try_into()
706                .expect("16-byte slice"),
707        );
708        let end = i128::from_be_bytes(
709            value[STORAGE_VALUE_LEN + 16..STORAGE_VALUE_LEN + 32]
710                .try_into()
711                .expect("16-byte slice"),
712        );
713        Ok(Self {
714            node_key,
715            term: term_bytes.to_vec(),
716            commit_ts,
717            op,
718            visibility,
719            begin,
720            end,
721        })
722    }
723
724    /// Exact interval check against a query predicate (the partition-side
725    /// reject: a pure integer comparison over the value pair).
726    pub fn matches(&self, query: &TemporalQueryPredicate) -> bool {
727        match *query {
728            TemporalQueryPredicate::Instant { tick } => self.begin <= tick && tick <= self.end,
729            TemporalQueryPredicate::Overlaps { begin, end } => {
730                self.begin <= end && begin <= self.end
731            }
732            TemporalQueryPredicate::WithinRange { begin, end } => {
733                begin <= self.begin && self.end <= end
734            }
735            TemporalQueryPredicate::InstantsInRange => self.begin == self.end,
736        }
737    }
738}
739
740/// Exact interval predicate a `TemporalCandidateScan` applies per candidate
741/// (partition-side, integer-only). The scan's key intervals already produce
742/// a superset; this drops postings whose exact pair misses, before the wire.
743#[derive(Debug, Clone, Copy, PartialEq, Eq)]
744pub enum TemporalQueryPredicate {
745    /// Keep postings whose exact interval covers the tick (which spans
746    /// contain instant X — the ancestor-chain scan shape).
747    Instant {
748        /// The query tick.
749        tick: i128,
750    },
751    /// Keep postings whose exact interval intersects `[begin, end]`
752    /// (span overlap queries).
753    Overlaps {
754        /// Query window start (inclusive).
755        begin: i128,
756        /// Query window end (inclusive).
757        end: i128,
758    },
759    /// Keep postings whose exact interval lies inside `[begin, end]`
760    /// (spans contained in span Y).
761    WithinRange {
762        /// Query window start (inclusive).
763        begin: i128,
764        /// Query window end (inclusive).
765        end: i128,
766    },
767    /// Keep only instant postings (begin == end); the key-range scans
768    /// enforce the window (which instants does span Y contain).
769    InstantsInRange,
770}
771
772impl TemporalQueryPredicate {
773    /// Wire encoding: one tag byte + up to 32 argument bytes.
774    pub fn encode(self) -> [u8; 33] {
775        let mut out = [0_u8; 33];
776        match self {
777            Self::Instant { tick } => {
778                out[0] = 0;
779                out[1..17].copy_from_slice(&tick.to_be_bytes());
780            }
781            Self::Overlaps { begin, end } => {
782                out[0] = 1;
783                out[1..17].copy_from_slice(&begin.to_be_bytes());
784                out[17..33].copy_from_slice(&end.to_be_bytes());
785            }
786            Self::WithinRange { begin, end } => {
787                out[0] = 2;
788                out[1..17].copy_from_slice(&begin.to_be_bytes());
789                out[17..33].copy_from_slice(&end.to_be_bytes());
790            }
791            Self::InstantsInRange => out[0] = 3,
792        }
793        out
794    }
795
796    /// Decode a wire-encoded predicate (must be exactly 33 bytes).
797    pub fn decode(bytes: &[u8]) -> Result<Self, StorageError> {
798        if bytes.len() != 33 {
799            return Err(StorageError::Corrupt(format!(
800                "temporal predicate must be 33 bytes, got {}",
801                bytes.len()
802            )));
803        }
804        let begin = || i128::from_be_bytes(bytes[1..17].try_into().expect("16-byte slice"));
805        let end = || i128::from_be_bytes(bytes[17..33].try_into().expect("16-byte slice"));
806        Ok(match bytes[0] {
807            0 => Self::Instant { tick: begin() },
808            1 => Self::Overlaps {
809                begin: begin(),
810                end: end(),
811            },
812            2 => Self::WithinRange {
813                begin: begin(),
814                end: end(),
815            },
816            3 => Self::InstantsInRange,
817            other => {
818                return Err(StorageError::Corrupt(format!(
819                    "unknown temporal predicate tag {other}"
820                )));
821            }
822        })
823    }
824}
825
826/// Outcome of one temporal-index candidate decision.
827#[derive(Debug, Clone, Copy, PartialEq, Eq)]
828pub enum TemporalCandidateDecision {
829    /// Emit this term as a candidate (first visible Put under the snapshot).
830    Emit,
831    /// Skip (older version, Delete at the snapshot, exact-rejectable, or
832    /// already emitted on this stream).
833    Skip,
834}
835
836/// State machine for one `TemporalCandidateScan` stream: MVCC collapse per
837/// logical `(node_key, term)` key, a DISTINCT seen-set over full term bytes
838/// (one interval posts under up to `max_nodes` non-adjacent node keys), and
839/// the exact-interval reject.
840#[derive(Debug, Default)]
841pub struct TemporalCandidateState {
842    /// Logical-key prefix of the last handled posting (`node_key ‖ term`).
843    last_handled_logical: Vec<u8>,
844    /// Full term bytes already emitted on this stream.
845    seen: rustc_hash::FxHashSet<Box<[u8]>>,
846}
847
848impl TemporalCandidateState {
849    /// Decide one visible posting row for a stream at `snapshot`.
850    #[allow(clippy::too_many_arguments)]
851    pub fn consider_posting(
852        &mut self,
853        key: &[u8],
854        commit_ts: CommitTs,
855        op: StorageOp,
856        snapshot: SnapshotId,
857        begin: i128,
858        end: i128,
859        query: &TemporalQueryPredicate,
860    ) -> Result<TemporalCandidateDecision, StorageError> {
861        // MVCC: the first version of each logical key with
862        // commit_ts <= snapshot wins; anything after it is older.
863        let logical_len = key.len().saturating_sub(COMMIT_TS_LEN);
864        let logical = &key[..logical_len];
865        if self.last_handled_logical.as_slice() == logical {
866            return Ok(TemporalCandidateDecision::Skip);
867        }
868        if commit_ts.0 > snapshot.0 {
869            return Ok(TemporalCandidateDecision::Skip);
870        }
871        self.last_handled_logical.clear();
872        self.last_handled_logical.extend_from_slice(logical);
873        if op != StorageOp::Put {
874            return Ok(TemporalCandidateDecision::Skip);
875        }
876        // Exact-interval reject over the value pair.
877        let shape = TemporalShape { begin, end };
878        if !shape_is_candidate(shape, query) {
879            return Ok(TemporalCandidateDecision::Skip);
880        }
881        if self.seen.contains(logical[TEMPORAL_KEY_LEN..].as_ref()) {
882            return Ok(TemporalCandidateDecision::Skip);
883        }
884        self.seen
885            .insert(logical[TEMPORAL_KEY_LEN..].to_vec().into_boxed_slice());
886        Ok(TemporalCandidateDecision::Emit)
887    }
888}
889
890/// Exact-interval reject shared by the streaming state machine and the
891/// direct value walk ([`TemporalIndexPut::matches`] callers that already
892/// decoded the posting).
893fn shape_is_candidate(shape: TemporalShape, query: &TemporalQueryPredicate) -> bool {
894    match *query {
895        TemporalQueryPredicate::Instant { tick } => shape.begin <= tick && tick <= shape.end,
896        TemporalQueryPredicate::Overlaps { begin, end } => shape.begin <= end && begin <= shape.end,
897        TemporalQueryPredicate::WithinRange { begin, end } => {
898            begin <= shape.begin && shape.end <= end
899        }
900        TemporalQueryPredicate::InstantsInRange => shape.begin == shape.end,
901    }
902}
903
904#[cfg(test)]
905mod tests {
906    use super::*;
907    use pretty_assertions::assert_eq;
908
909    // ---- tick / key mapping -------------------------------------------
910
911    #[test]
912    fn key_mapping_is_order_preserving_across_the_sign_boundary() {
913        // -2 < -1 < 0 < 1 < 2 in BOTH tick order and key order, and each
914        // tick round-trips.
915        let ticks = [-2_i128, -1, 0, 1, 2];
916        let keys: Vec<u128> = ticks.iter().map(|&t| tick_to_key_u128(t)).collect();
917        assert!(keys.windows(2).all(|w| w[0] < w[1]));
918        for &t in &ticks {
919            assert_eq!(key_u128_to_tick(tick_to_key_u128(t)), t);
920        }
921        // Geological era deep in the negative half sorts before the year
922        // 2026, and the axis minimum/maximum map to 0 / u128::MAX.
923        let permian = tick_to_key_u128(-252_000_000_i128 * 365 * ATTO_PER_DAY);
924        let now = tick_to_key_u128(2026 * 365 * ATTO_PER_DAY);
925        assert!(permian < now);
926        assert_eq!(tick_to_key_u128(i128::MIN), 0);
927        assert_eq!(tick_to_key_u128(i128::MAX), u128::MAX);
928    }
929
930    // ---- calendar projection -----------------------------------------
931
932    #[test]
933    fn days_from_civil_matches_known_dates() {
934        // Era-relative origin (no unix shift): 1970-01-01 is Hinnant's
935        // 719468; only differences and order carry meaning downstream.
936        assert_eq!(days_from_civil(1970, 1, 1), 719_468);
937        // 2000-03-01 is 11017 days after 1970-01-01 (post-century leap,
938        // March-based year start).
939        assert_eq!(days_from_civil(2000, 3, 1), 719_468 + 11_017);
940        // 1900-03-01 is 25508 days BEFORE 1970-01-01 (century non-leap).
941        assert_eq!(
942            days_from_civil(1970, 1, 1) - days_from_civil(1900, 3, 1),
943            25_508
944        );
945        // 2026-10-08 is 20734 days after 1970-01-01.
946        assert_eq!(days_from_civil(2026, 10, 8), 719_468 + 20_734);
947        // Leap-year day counting: 2024-02-29 exists, 2023-02-29 does not
948        // (the projection passes month/day through from parsed terms).
949        assert_eq!(
950            days_from_civil(2024, 3, 1) - days_from_civil(2024, 2, 1),
951            29
952        );
953        // BCE years produce earlier days.
954        assert!(days_from_civil(-252_000_000, 1, 1) < days_from_civil(-251_000_000, 1, 1));
955    }
956
957    #[test]
958    fn datetime_tick_reads_the_decimal_seconds() {
959        // Ticks are era-relative: assert CONSISTENCY, not an absolute origin.
960        // 1970-01-01T00:00:00Z and 01:00:00+01:00 are the same instant.
961        let utc: oxsdatatypes::DateTime = "1970-01-01T00:00:00Z".parse().unwrap();
962        let tz: oxsdatatypes::DateTime = "1970-01-01T01:00:00+01:00".parse().unwrap();
963        let utc_tick = i128::from_be_bytes(utc.to_be_bytes()[0..16].try_into().unwrap());
964        assert_eq!(
965            temporal_term_interval(&EncodedTerm::DateTimeLiteral(tz)),
966            Some(TemporalShape::instant(utc_tick))
967        );
968        // Timezone-absent posts the ±14 h uncertainty window around the same
969        // reading.
970        let naive: oxsdatatypes::DateTime = "1970-01-01T00:00:00".parse().unwrap();
971        assert_eq!(
972            temporal_term_interval(&EncodedTerm::DateTimeLiteral(naive)),
973            Some(TemporalShape {
974                begin: utc_tick - ATTO_TZ_INDETERMINATE,
975                end: utc_tick + ATTO_TZ_INDETERMINATE,
976            })
977        );
978        // Order: 2026 sorts after 1970.
979        let later: oxsdatatypes::DateTime = "2026-10-08T00:00:00Z".parse().unwrap();
980        let later_tick = i128::from_be_bytes(later.to_be_bytes()[0..16].try_into().unwrap());
981        assert!(later_tick > utc_tick);
982    }
983
984    #[test]
985    fn axis_origin_days_equals_the_calendar_distance_to_the_axis_zero() {
986        // B56's safety net. The offset written as a literal in the source
987        // (306) is `days_from_civil(1, 1, 1)`: the distance from Hinnant's
988        // era zero (0000-03-01) to the tick axis's zero (0001-01-01). If the
989        // calendar routine is ever swapped out, this fails loudly instead of
990        // the two origins silently re-splitting by some new unknown number of
991        // days — which is exactly how B56 hid: within one family the offset
992        // cancels, so only cross-family comparisons lie.
993        assert_eq!(AXIS_ORIGIN_DAYS, days_from_civil(1, 1, 1));
994        assert_eq!(AXIS_ORIGIN_DAYS, 306);
995        // ...and the axis zero really is where a stored dateTime says it is.
996        let epoch: EncodedTerm =
997            EncodedTerm::DateTimeLiteral("0001-01-01T00:00:00Z".parse().unwrap());
998        assert_eq!(temporal_term_interval(&epoch).unwrap().begin, 0);
999    }
1000
1001    #[test]
1002    fn every_family_projects_onto_one_shared_axis() {
1003        // THE test whose absence let B56 land. Every existing test was
1004        // within one family, so it passed under either origin.
1005        let date_time = |text: &str| EncodedTerm::DateTimeLiteral(text.parse().unwrap());
1006        let date = |text: &str| EncodedTerm::DateLiteral(text.parse().unwrap());
1007        let gyear = |text: &str| EncodedTerm::GYearLiteral(text.parse().unwrap());
1008        let gyear_month = |text: &str| EncodedTerm::GYearMonthLiteral(text.parse().unwrap());
1009        let begin = |term: &EncodedTerm| temporal_term_interval(term).unwrap().begin;
1010
1011        // A tz-present instant and the same calendar day must share a tick.
1012        for day in ["0001-01-01", "1970-01-01", "2025-01-01", "2024-02-29"] {
1013            let stamp = format!("{day}T00:00:00Z");
1014            assert_eq!(
1015                begin(&date(&format!("{day}Z"))),
1016                begin(&date_time(&stamp)),
1017                "date {day} must align with its midnight instant"
1018            );
1019        }
1020        // gYear / gYearMonth start ticks are the same calendar instants.
1021        assert_eq!(
1022            begin(&gyear("2025")),
1023            begin(&date_time("2025-01-01T00:00:00Z"))
1024        );
1025        assert_eq!(
1026            begin(&gyear_month("2025-03")),
1027            begin(&date_time("2025-03-01T00:00:00Z"))
1028        );
1029        // Deep time keeps the alignment too — the geological use case.
1030        assert_eq!(
1031            begin(&gyear("-252000000")),
1032            begin(&date_time("-252000000-01-01T00:00:00Z"))
1033        );
1034        // The 306-day split is gone: a date is no longer 306 days "later"
1035        // than the same instant as a dateTime.
1036        assert_eq!(
1037            begin(&date("2025-01-01Z")) - begin(&date_time("2025-01-01T00:00:00Z")),
1038            0
1039        );
1040    }
1041
1042    #[test]
1043    fn calendar_terms_project_to_their_spans() {
1044        let year: oxsdatatypes::GYear = "2025".parse().unwrap();
1045        let shape = temporal_term_interval(&EncodedTerm::GYearLiteral(year)).unwrap();
1046        assert_eq!(shape.begin, tick_from_date(2025, 1, 1).unwrap());
1047        // Closed end: last attosecond before 2026-01-01.
1048        assert_eq!(shape.end, tick_from_date(2026, 1, 1).unwrap() - 1);
1049        assert!(!shape.is_instant());
1050
1051        let month: oxsdatatypes::GYearMonth = "2025-03".parse().unwrap();
1052        let shape = temporal_term_interval(&EncodedTerm::GYearMonthLiteral(month)).unwrap();
1053        assert_eq!(shape.begin, tick_from_date(2025, 3, 1).unwrap());
1054        assert_eq!(shape.end, tick_from_date(2025, 4, 1).unwrap() - 1);
1055
1056        let date: oxsdatatypes::Date = "2025-03-15Z".parse().unwrap();
1057        let shape = temporal_term_interval(&EncodedTerm::DateLiteral(date)).unwrap();
1058        // UTC-qualified: the day interval anchored at its own midnight.
1059        assert_eq!(shape.begin, tick_from_date(2025, 3, 15).unwrap());
1060        assert_eq!(shape.end, shape.begin + ATTO_PER_DAY - 1);
1061        assert!(!shape.is_instant());
1062
1063        // Karachi: local midnight is 5 h before UTC midnight, so the day
1064        // spans [2025-03-14T19:00Z, 2025-03-15T19:00Z).
1065        let karachi: oxsdatatypes::Date = "2025-03-15+05:00".parse().unwrap();
1066        let shape = temporal_term_interval(&EncodedTerm::DateLiteral(karachi)).unwrap();
1067        assert_eq!(
1068            shape.begin,
1069            tick_from_date(2025, 3, 15).unwrap() - 5 * ATTO_PER_HOUR
1070        );
1071        assert_eq!(shape.end, shape.begin + ATTO_PER_DAY - 1);
1072
1073        // Los Angeles: local midnight is 8 h after UTC midnight.
1074        let la: oxsdatatypes::Date = "2025-03-15-08:00".parse().unwrap();
1075        let shape = temporal_term_interval(&EncodedTerm::DateLiteral(la)).unwrap();
1076        assert_eq!(
1077            shape.begin,
1078            tick_from_date(2025, 3, 15).unwrap() + 8 * ATTO_PER_HOUR
1079        );
1080
1081        let naive_date: oxsdatatypes::Date = "2025-03-15".parse().unwrap();
1082        let shape = temporal_term_interval(&EncodedTerm::DateLiteral(naive_date)).unwrap();
1083        // Unknown anchoring: the full 24 h day, widened by the ±14 h skew.
1084        assert_eq!(
1085            shape.begin,
1086            tick_from_date(2025, 3, 15).unwrap() - ATTO_TZ_INDETERMINATE
1087        );
1088        assert_eq!(
1089            shape.end,
1090            tick_from_date(2025, 3, 15).unwrap() + ATTO_TZ_INDETERMINATE + ATTO_PER_DAY - 1
1091        );
1092
1093        // Deep time survives: -252000000 (Permian-Triassic boundary era).
1094        let permian: oxsdatatypes::GYear = "-252000000".parse().unwrap();
1095        let shape = temporal_term_interval(&EncodedTerm::GYearLiteral(permian)).unwrap();
1096        assert!(shape.begin < 0);
1097        assert!(shape.end < 0);
1098        let recent: oxsdatatypes::GYear = "2025".parse().unwrap();
1099        let recent_shape = temporal_term_interval(&EncodedTerm::GYearLiteral(recent)).unwrap();
1100        assert!(recent_shape.begin > shape.end, "later years sort later");
1101    }
1102
1103    #[test]
1104    fn non_temporal_terms_do_not_project() {
1105        let integer: oxsdatatypes::Integer = "42".parse().unwrap();
1106        assert_eq!(
1107            temporal_term_interval(&EncodedTerm::IntegerLiteral(integer)),
1108            None
1109        );
1110        let time: oxsdatatypes::Time = "12:00:00".parse().unwrap();
1111        assert_eq!(
1112            temporal_term_interval(&EncodedTerm::TimeLiteral(time)),
1113            None
1114        );
1115        let duration: oxsdatatypes::DayTimeDuration = "PT1S".parse().unwrap();
1116        assert_eq!(
1117            temporal_term_interval(&EncodedTerm::DayTimeDurationLiteral(duration)),
1118            None
1119        );
1120    }
1121
1122    // ---- dyadic nodes + covering --------------------------------------
1123
1124    #[test]
1125    fn node_keys_bracket_their_range() {
1126        let root = DyadicNode { level: 0, index: 0 };
1127        assert_eq!(root.min_key(), 0);
1128        assert_eq!(root.max_key(), u128::MAX);
1129        let half = DyadicNode { level: 1, index: 1 };
1130        assert_eq!(half.min_key(), 1_u128 << 127);
1131        assert_eq!(half.max_key(), u128::MAX);
1132        let leaf = DyadicNode::leaf(7);
1133        assert_eq!(leaf.min_key(), 7);
1134        assert_eq!(leaf.max_key(), 7);
1135    }
1136
1137    #[test]
1138    fn exact_covering_tiles_the_range_exactly() {
1139        // [3, 12) on a toy 4-bit axis generalizes to: an exact decomposition
1140        // covers every key of the range exactly once.
1141        let (begin, end) = (tick_to_key_u128(3), tick_to_key_u128(11));
1142        let nodes = cover_axis_range(
1143            begin,
1144            end,
1145            &DyadicCovererConfig {
1146                max_nodes: usize::MAX,
1147                ..DyadicCovererConfig::default()
1148            },
1149        );
1150        assert!(!nodes.is_empty());
1151        // Laminar tiling: sorted nodes are disjoint and adjacent, and the
1152        // union is exactly [begin, end].
1153        let mut cursor = begin;
1154        for node in &nodes {
1155            assert_eq!(node.min_key(), cursor, "tiling gap/overlap at {node:?}");
1156            cursor = node.max_key().saturating_add(1);
1157        }
1158        assert_eq!(cursor, end.saturating_add(1));
1159        // Budget 1 degrades to the single containing node (a superset).
1160        let coarse = cover_axis_range(
1161            begin,
1162            end,
1163            &DyadicCovererConfig {
1164                max_nodes: 1,
1165                ..DyadicCovererConfig::default()
1166            },
1167        );
1168        assert_eq!(coarse.len(), 1);
1169        assert!(coarse[0].min_key() <= begin && coarse[0].max_key() >= end);
1170    }
1171
1172    #[test]
1173    fn budgeted_covering_is_a_superset_within_the_budget() {
1174        // A wide arbitrary range (a calendar month is not dyadically
1175        // aligned): the budgeted covering is a superset within the node
1176        // budget, and the exact covering of a month exceeds the budget.
1177        let begin = tick_to_key_u128(tick_from_date(2025, 3, 1).unwrap());
1178        let end = tick_to_key_u128(tick_from_date(2025, 4, 1).unwrap() - 1);
1179        let config = DyadicCovererConfig::default();
1180        let exact = cover_axis_range(
1181            begin,
1182            end,
1183            &DyadicCovererConfig {
1184                max_nodes: usize::MAX,
1185                ..config
1186            },
1187        );
1188        assert!(
1189            exact.len() > config.max_nodes,
1190            "a calendar month should need more than {} exact nodes, got {}",
1191            config.max_nodes,
1192            exact.len()
1193        );
1194        let budgeted = cover_axis_range(begin, end, &config);
1195        assert!(budgeted.len() <= config.max_nodes);
1196        assert_eq!(
1197            budgeted[0].min_key(),
1198            align_down_key(begin, budgeted[0].level)
1199        );
1200        assert!(budgeted[0].min_key() <= begin);
1201        assert!(budgeted.last().unwrap().max_key() >= end);
1202        // Deep time fits in a handful of nodes: 56 million years, oriented
1203        // earliest-first (the debug assert enforces begin ≤ end).
1204        let deep = cover_axis_range(
1205            tick_to_key_u128(tick_from_date(-252_000_000, 1, 1).unwrap()),
1206            tick_to_key_u128(tick_from_date(-56_000_000, 1, 1).unwrap()),
1207            &config,
1208        );
1209        assert!(!deep.is_empty() && deep.len() <= config.max_nodes);
1210    }
1211
1212    #[test]
1213    fn level_zero_and_min_level_do_not_panic() {
1214        // The whole-axis range: the exact walk emits the root; the
1215        // shift-by-128 corners never trigger.
1216        let whole = cover_axis_range(
1217            0,
1218            u128::MAX,
1219            &DyadicCovererConfig {
1220                max_nodes: 8,
1221                ..DyadicCovererConfig::default()
1222            },
1223        );
1224        assert_eq!(whole.len(), 1);
1225        assert_eq!(whole[0], DyadicNode { level: 0, index: 0 });
1226        // A near-whole range whose exact decomposition exceeds the budget
1227        // takes the budgeted grid, floored at min_level (2 half-axis nodes
1228        // even against a budget of 1 — the documented degenerate config).
1229        let spread = cover_axis_range(
1230            1,
1231            u128::MAX - 1,
1232            &DyadicCovererConfig {
1233                min_level: 1,
1234                max_level: 127,
1235                max_nodes: 1,
1236            },
1237        );
1238        assert_eq!(spread.len(), 2);
1239        assert!(spread.iter().all(|node| node.level == 1));
1240        assert_eq!(spread[0], DyadicNode { level: 1, index: 0 });
1241        assert_eq!(spread[1], DyadicNode { level: 1, index: 1 });
1242        // The reviewer's corner: the SAME near-whole window with min_level 0
1243        // used to descend past level 1 and shift by 128 — a guaranteed debug
1244        // panic (silently wrong in release). Level 0 is the whole axis: one
1245        // node, and the floor accepts it.
1246        let straddling = cover_axis_range(
1247            1,
1248            u128::MAX - 1,
1249            &DyadicCovererConfig {
1250                min_level: 0,
1251                max_level: 127,
1252                max_nodes: 1,
1253            },
1254        );
1255        assert_eq!(straddling, vec![DyadicNode { level: 0, index: 0 }]);
1256    }
1257
1258    #[test]
1259    fn intervals_include_descendant_ranges_and_ancestors() {
1260        // A leaf at a nonzero key: its own single-key range plus 128
1261        // DISTINCT ancestor start keys (levels 127..=0; high bits preserved,
1262        // low bits cleared per level).
1263        let intervals = intervals_for_nodes(&[DyadicNode::leaf(u128::MAX)]);
1264        assert_eq!(intervals.len(), 129);
1265        assert!(
1266            intervals.windows(2).all(|w| w[0].min_key < w[1].min_key),
1267            "sorted and deduped"
1268        );
1269        // The leaf's own range and the root ancestor are single keys.
1270        assert!(intervals.contains(&TemporalCellInterval::exact(u128::MAX)));
1271        assert!(intervals.contains(&TemporalCellInterval::exact(0)));
1272        // A coarse node contributes its real descendant RANGE plus exact
1273        // ancestor singles.
1274        let node = DyadicNode { level: 1, index: 1 };
1275        let intervals = intervals_for_nodes(&[node]);
1276        assert_eq!(intervals.len(), 2);
1277        assert!(intervals.contains(&TemporalCellInterval::exact(0)));
1278        assert!(intervals.contains(&TemporalCellInterval {
1279            min_key: node.min_key(),
1280            max_key: node.max_key()
1281        }));
1282    }
1283
1284    // ---- postings + candidate stream ----------------------------------
1285
1286    fn sample_term() -> EncodedTerm {
1287        let year: oxsdatatypes::GYear = "2025".parse().unwrap();
1288        EncodedTerm::GYearLiteral(year)
1289    }
1290
1291    #[test]
1292    fn postings_carry_the_exact_pair_and_round_trip() {
1293        let term = sample_term();
1294        let puts = postings_for_term(&term, CommitTs(9), &DyadicCovererConfig::default());
1295        assert!(!puts.is_empty());
1296        assert!(puts.len() <= 32);
1297        for put in &puts {
1298            let shape = TemporalShape {
1299                begin: put.begin,
1300                end: put.end,
1301            };
1302            assert_eq!(shape.begin, tick_from_date(2025, 1, 1).unwrap());
1303            assert_eq!(shape.end, tick_from_date(2026, 1, 1).unwrap() - 1);
1304            let decoded = TemporalIndexPut::decode(&put.encode_key(), &put.encode_value())
1305                .expect("round trip");
1306            assert_eq!(&decoded, put);
1307        }
1308    }
1309
1310    #[test]
1311    fn instant_terms_post_exactly_one_leaf() {
1312        let dt: oxsdatatypes::DateTime = "2025-03-15T12:00:00+00:00".parse().unwrap();
1313        let puts = postings_for_term(
1314            &EncodedTerm::DateTimeLiteral(dt),
1315            CommitTs(1),
1316            &DyadicCovererConfig::default(),
1317        );
1318        assert_eq!(puts.len(), 1);
1319        assert_eq!(puts[0].node_key, tick_to_key_u128(puts[0].begin));
1320        assert_eq!(puts[0].begin, puts[0].end);
1321    }
1322
1323    #[test]
1324    fn candidate_stream_mvcc_collapses_dedups_and_rejects() {
1325        let term = sample_term();
1326        let puts = postings_for_term(&term, CommitTs(5), &DyadicCovererConfig::default());
1327        let delete = TemporalIndexPut {
1328            commit_ts: CommitTs(7),
1329            op: StorageOp::Delete,
1330            ..puts[0].clone()
1331        };
1332        let query = TemporalQueryPredicate::Overlaps {
1333            begin: tick_from_date(2025, 6, 1).unwrap(),
1334            end: tick_from_date(2025, 7, 1).unwrap(),
1335        };
1336        let mut state = TemporalCandidateState::default();
1337        // All postings of the term emit exactly once (dedup across nodes).
1338        let mut emissions = 0;
1339        for put in &puts {
1340            if let TemporalCandidateDecision::Emit = state
1341                .consider_posting(
1342                    &put.encode_key(),
1343                    put.commit_ts,
1344                    put.op,
1345                    SnapshotId(10),
1346                    put.begin,
1347                    put.end,
1348                    &query,
1349                )
1350                .unwrap()
1351            {
1352                emissions += 1;
1353            }
1354        }
1355        assert_eq!(emissions, 1);
1356        // A second pass at a later ts re-emits nothing (seen-set)…
1357        for put in &puts {
1358            assert_eq!(
1359                state
1360                    .consider_posting(
1361                        &put.encode_key(),
1362                        put.commit_ts,
1363                        put.op,
1364                        SnapshotId(10),
1365                        put.begin,
1366                        put.end,
1367                        &query
1368                    )
1369                    .unwrap(),
1370                TemporalCandidateDecision::Skip
1371            );
1372        }
1373        // …but a Delete at ts 7 under a ts-10 snapshot skips; and under a
1374        // ts-6 snapshot (before the delete) the term is NOT re-emitted
1375        // because the stream already saw the logical keys above.
1376        assert_eq!(
1377            state
1378                .consider_posting(
1379                    &delete.encode_key(),
1380                    delete.commit_ts,
1381                    delete.op,
1382                    SnapshotId(10),
1383                    delete.begin,
1384                    delete.end,
1385                    &query
1386                )
1387                .unwrap(),
1388            TemporalCandidateDecision::Skip
1389        );
1390        // A fresh stream at snapshot 6 sees only the Put versions.
1391        let mut early = TemporalCandidateState::default();
1392        let mut emissions = 0;
1393        for put in &puts {
1394            if let TemporalCandidateDecision::Emit = early
1395                .consider_posting(
1396                    &put.encode_key(),
1397                    put.commit_ts,
1398                    put.op,
1399                    SnapshotId(6),
1400                    put.begin,
1401                    put.end,
1402                    &query,
1403                )
1404                .unwrap()
1405            {
1406                emissions += 1;
1407            }
1408        }
1409        assert_eq!(emissions, 1);
1410        // Future versions (commit_ts > snapshot) never emit.
1411        let future = TemporalIndexPut {
1412            commit_ts: CommitTs(11),
1413            ..puts[0].clone()
1414        };
1415        let mut fresh = TemporalCandidateState::default();
1416        assert_eq!(
1417            fresh
1418                .consider_posting(
1419                    &future.encode_key(),
1420                    future.commit_ts,
1421                    future.op,
1422                    SnapshotId(10),
1423                    future.begin,
1424                    future.end,
1425                    &query
1426                )
1427                .unwrap(),
1428            TemporalCandidateDecision::Skip
1429        );
1430    }
1431
1432    #[test]
1433    fn exact_reject_drops_misses_before_the_wire() {
1434        let mut state = TemporalCandidateState::default();
1435        let key_tick = tick_to_key_u128(tick_from_date(2025, 1, 1).unwrap());
1436        let key = {
1437            let mut k = key_tick.to_be_bytes().to_vec();
1438            k.extend_from_slice(&[1, 2, 3]);
1439            k.extend_from_slice(&CommitTs(1).to_descending_be_bytes());
1440            k
1441        };
1442        let _value = {
1443            let mut v = encode_storage_value(StorageOp::Put, VisibilityLabel::default()).to_vec();
1444            v.extend_from_slice(&tick_from_date(2025, 1, 1).unwrap().to_be_bytes());
1445            v.extend_from_slice(&(tick_from_date(2025, 12, 31).unwrap()).to_be_bytes());
1446            v
1447        };
1448        // The posting's exact interval: all of 2025.
1449        let begin = tick_from_date(2025, 1, 1).unwrap();
1450        let end = tick_from_date(2025, 12, 31).unwrap();
1451        // Point inside → emit; point in 2026 → reject; disjoint overlap →
1452        // reject; containing range → emit; instant filter on a span → reject.
1453        let at = |t: i128| TemporalQueryPredicate::Instant { tick: t };
1454        assert_eq!(
1455            state
1456                .consider_posting(
1457                    &key,
1458                    CommitTs(1),
1459                    StorageOp::Put,
1460                    SnapshotId(5),
1461                    begin,
1462                    end,
1463                    &at(tick_from_date(2025, 6, 1).unwrap())
1464                )
1465                .unwrap(),
1466            TemporalCandidateDecision::Emit
1467        );
1468        let mut state = TemporalCandidateState::default();
1469        assert_eq!(
1470            state
1471                .consider_posting(
1472                    &key,
1473                    CommitTs(1),
1474                    StorageOp::Put,
1475                    SnapshotId(5),
1476                    begin,
1477                    end,
1478                    &at(tick_from_date(2026, 6, 1).unwrap())
1479                )
1480                .unwrap(),
1481            TemporalCandidateDecision::Skip
1482        );
1483        let mut state = TemporalCandidateState::default();
1484        assert_eq!(
1485            state
1486                .consider_posting(
1487                    &key,
1488                    CommitTs(1),
1489                    StorageOp::Put,
1490                    SnapshotId(5),
1491                    begin,
1492                    end,
1493                    &TemporalQueryPredicate::Overlaps {
1494                        begin: tick_from_date(2026, 1, 1).unwrap(),
1495                        end: tick_from_date(2026, 2, 1).unwrap(),
1496                    }
1497                )
1498                .unwrap(),
1499            TemporalCandidateDecision::Skip
1500        );
1501        let mut state = TemporalCandidateState::default();
1502        assert_eq!(
1503            state
1504                .consider_posting(
1505                    &key,
1506                    CommitTs(1),
1507                    StorageOp::Put,
1508                    SnapshotId(5),
1509                    begin,
1510                    end,
1511                    &TemporalQueryPredicate::WithinRange {
1512                        begin: tick_from_date(2024, 1, 1).unwrap(),
1513                        end: tick_from_date(2026, 1, 1).unwrap(),
1514                    }
1515                )
1516                .unwrap(),
1517            TemporalCandidateDecision::Emit
1518        );
1519        let mut state = TemporalCandidateState::default();
1520        assert_eq!(
1521            state
1522                .consider_posting(
1523                    &key,
1524                    CommitTs(1),
1525                    StorageOp::Put,
1526                    SnapshotId(5),
1527                    begin,
1528                    end,
1529                    &TemporalQueryPredicate::InstantsInRange
1530                )
1531                .unwrap(),
1532            TemporalCandidateDecision::Skip
1533        );
1534    }
1535
1536    #[test]
1537    fn predicate_wire_round_trips() {
1538        for predicate in [
1539            TemporalQueryPredicate::Instant { tick: -123_456_789 },
1540            TemporalQueryPredicate::Overlaps {
1541                begin: 0,
1542                end: ATTO_PER_DAY,
1543            },
1544            TemporalQueryPredicate::WithinRange {
1545                begin: i128::MIN,
1546                end: i128::MAX,
1547            },
1548            TemporalQueryPredicate::InstantsInRange,
1549        ] {
1550            assert_eq!(
1551                TemporalQueryPredicate::decode(&predicate.encode()).unwrap(),
1552                predicate
1553            );
1554        }
1555        assert!(TemporalQueryPredicate::decode(&[0_u8; 32]).is_err());
1556        assert!(TemporalQueryPredicate::decode(&[9_u8; 33]).is_err());
1557    }
1558
1559    #[test]
1560    fn epoch_wire_round_trips() {
1561        assert_eq!(decode_temporal_epoch(None), None);
1562        assert_eq!(decode_temporal_epoch(Some(&[1, 2, 3])), None);
1563        assert_eq!(
1564            decode_temporal_epoch(Some(&encode_temporal_epoch(42))),
1565            Some(42)
1566        );
1567    }
1568
1569    /// The origin version rides the epoch and gates the trust decision: a
1570    /// stamp under a different axis origin (B56 moved the calendar families
1571    /// 306 days) must read UNTRUSTED, or a rebuilt-under-old-origin index is
1572    /// a trusted index whose postings sit where no query looks.
1573    #[test]
1574    fn origin_version_gates_the_epoch_trust_decision() {
1575        assert_eq!(decode_temporal_origin(None), None);
1576        assert_eq!(decode_temporal_origin(Some(&[1, 2, 3])), None);
1577        assert_eq!(
1578            decode_temporal_origin(Some(&encode_temporal_origin(7))),
1579            Some(7)
1580        );
1581        // Anything but the current version is not a trust signal.
1582        assert_ne!(
1583            encode_temporal_origin(TEMPORAL_ORIGIN_VERSION),
1584            encode_temporal_origin(0)
1585        );
1586        assert_eq!(TEMPORAL_ORIGIN_VERSION, 1);
1587        // The version the getters compare against is the one the setters
1588        // write, so a fresh stamp is always read back as trusted.
1589        let stamped = encode_temporal_origin(TEMPORAL_ORIGIN_VERSION);
1590        assert_eq!(
1591            decode_temporal_origin(Some(&stamped)),
1592            Some(TEMPORAL_ORIGIN_VERSION)
1593        );
1594    }
1595
1596    // Silence the unused-import lint when the term decode helper is only
1597    // used by TemporalIndexPut::decode above.
1598
1599    /// The term bytes of a posting decode back to the term (the
1600    /// `TermReader` walk in `decode` validated them).
1601    #[test]
1602    fn posting_term_bytes_decode_back() {
1603        let term = sample_term();
1604        let puts = postings_for_term(&term, CommitTs(2), &DyadicCovererConfig::default());
1605        let bytes = &puts[0].term;
1606        let mut reader: &[u8] = bytes.as_slice();
1607        let decoded = reader.read_term().expect("valid term bytes");
1608        assert!(reader.is_empty());
1609        assert_eq!(decoded, term);
1610    }
1611
1612    #[test]
1613    fn interval_wire_round_trips() {
1614        let interval = TemporalCellInterval {
1615            min_key: 1,
1616            max_key: u128::MAX,
1617        };
1618        assert_eq!(
1619            TemporalCellInterval::decode(&interval.encode()).unwrap(),
1620            interval
1621        );
1622        assert!(TemporalCellInterval::decode(&[0_u8; 31]).is_err());
1623    }
1624}