Skip to main content

waratah_storage/encode/
versioned.rs

1//! Versioned hexastore key/value layout (Phase 2b).
2//!
3//! ```text
4//! key   = encode_index_key(permutation, EncodedQuad) || commit_ts_desc(u64 BE)
5//! value = op(u8) || visibility(u32 BE)
6//! ```
7//!
8//! Pattern scan prefixes use encoded bound terms only and do **not** include
9//! `commit_ts`. See `project_plan.md` → Hexastore record layout.
10
11use super::binary::{IndexPermutation, decode_index_key, encode_index_key};
12use super::encoded_term::{EncodedQuad, RDF_TYPE};
13use crate::StorageError;
14use crate::types::{CommitTs, PartitionAxis, StorageOp, VisibilityLabel};
15
16/// Fixed length of a hexastore record value (`op` + `visibility`).
17pub const STORAGE_VALUE_LEN: usize = 5;
18
19/// Length of the descending `commit_ts` key suffix.
20pub const COMMIT_TS_LEN: usize = 8;
21
22/// Build a versioned hexastore key: term bytes ‖ descending `commit_ts`.
23pub fn encode_versioned_key(
24    permutation: IndexPermutation,
25    quad: &EncodedQuad,
26    commit_ts: CommitTs,
27) -> Vec<u8> {
28    let mut key = encode_index_key(permutation, quad);
29    key.extend_from_slice(&commit_ts.to_descending_be_bytes());
30    key
31}
32
33/// Decode a versioned hexastore key into the logical quad and commit timestamp.
34pub fn decode_versioned_key(
35    permutation: IndexPermutation,
36    key: &[u8],
37) -> Result<(EncodedQuad, CommitTs), StorageError> {
38    let (term_key, commit_ts) = versioned_parts(key)?;
39    let quad = decode_index_key(permutation, term_key)?;
40    Ok((quad, commit_ts))
41}
42
43/// Split a versioned key into its term prefix and commit timestamp
44/// **without decoding any terms**.
45///
46/// The commit timestamp is the trailing [`COMMIT_TS_LEN`]-byte descending
47/// big-endian suffix; the term prefix is everything before it, left as raw
48/// bytes. Callers that need decoded terms use [`decode_versioned_key`] (all
49/// slots) or decode specific slots themselves — this split exists so the
50/// per-key visibility checks can read the timestamp and compare logical-key
51/// bytes without paying a four-term parse per key.
52///
53/// A key shorter than [`COMMIT_TS_LEN`] is corruption and errors — it is
54/// never treated as "all timestamp, no terms".
55pub fn versioned_parts(key: &[u8]) -> Result<(&[u8], CommitTs), StorageError> {
56    if key.len() < COMMIT_TS_LEN {
57        return Err(StorageError::Corrupt(format!(
58            "versioned key too short: {} bytes",
59            key.len()
60        )));
61    }
62    let (term_key, ts_bytes) = key.split_at(key.len() - COMMIT_TS_LEN);
63    let commit_ts = CommitTs::from_descending_be_bytes(
64        ts_bytes
65            .try_into()
66            .map_err(|_| StorageError::Corrupt("commit_ts suffix must be 8 bytes".to_owned()))?,
67    );
68    Ok((term_key, commit_ts))
69}
70
71/// Term-prefix portion of a versioned key (excludes the `commit_ts` suffix).
72pub fn versioned_key_term_prefix(key: &[u8]) -> Result<&[u8], StorageError> {
73    Ok(versioned_parts(key)?.0)
74}
75
76/// One encoded version used to prepare axis-local index puts (no DB access).
77#[derive(Debug, Clone, Copy)]
78pub struct HexastoreVersion<'a> {
79    /// Already-encoded quad terms.
80    pub quad: &'a EncodedQuad,
81    /// Cluster commit timestamp of this version.
82    pub commit_ts: CommitTs,
83    /// `Put` or `Delete`.
84    pub op: StorageOp,
85    /// Cell-level visibility label.
86    pub visibility: VisibilityLabel,
87}
88
89/// One prepared hexastore `Put` targeting an axis-local column family.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct HexastorePut {
92    /// Index into [`IndexPermutation::for_axis`] (`0` or `1`).
93    pub cf_index: usize,
94    /// Versioned index key (`encoded terms || descending commit_ts`).
95    pub key: Vec<u8>,
96    /// Fixed 5-byte value (`op` ‖ `visibility`).
97    pub value: [u8; STORAGE_VALUE_LEN],
98}
99
100/// Encode every axis-local index put for `versions` without touching storage.
101///
102/// `TSG` puts are omitted when the predicate is not `rdf:type`, matching the
103/// single-quad insert path.
104pub fn prepare_hexastore_puts<'a>(
105    axis: PartitionAxis,
106    versions: impl IntoIterator<Item = HexastoreVersion<'a>>,
107) -> Vec<HexastorePut> {
108    let permutations = IndexPermutation::for_axis(axis);
109    let mut puts = Vec::new();
110    for version in versions {
111        let value = encode_storage_value(version.op, version.visibility);
112        for (cf_index, permutation) in permutations.into_iter().enumerate() {
113            if permutation == IndexPermutation::Tsg && version.quad.predicate != RDF_TYPE {
114                continue;
115            }
116            puts.push(HexastorePut {
117                cf_index,
118                key: encode_versioned_key(permutation, version.quad, version.commit_ts),
119                value,
120            });
121        }
122    }
123    puts
124}
125
126/// Encode `op` ‖ `visibility` as a fixed 5-byte value.
127pub fn encode_storage_value(op: StorageOp, visibility: VisibilityLabel) -> [u8; STORAGE_VALUE_LEN] {
128    let mut buf = [0u8; STORAGE_VALUE_LEN];
129    buf[0] = op.as_u8();
130    buf[1..5].copy_from_slice(&visibility.0.to_be_bytes());
131    buf
132}
133
134/// Decode a 5-byte hexastore value into `(op, visibility)`.
135pub fn decode_storage_value(bytes: &[u8]) -> Result<(StorageOp, VisibilityLabel), StorageError> {
136    if bytes.len() != STORAGE_VALUE_LEN {
137        return Err(StorageError::Corrupt(format!(
138            "storage value must be {STORAGE_VALUE_LEN} bytes, got {}",
139            bytes.len()
140        )));
141    }
142    let op = StorageOp::from_u8(bytes[0])?;
143    let visibility = VisibilityLabel(u32::from_be_bytes(
144        bytes[1..5].try_into().expect("slice length checked above"),
145    ));
146    Ok((op, visibility))
147}
148
149/// Decode one temporal-index posting value:
150/// `op(u8) ‖ visibility(u32 BE) ‖ begin(i128 BE) ‖ end(i128 BE)` — 37 bytes.
151///
152/// A value shorter than the fixed body cannot come from our writer (every
153/// write path stores complete postings), so truncation is corruption and
154/// returns [`StorageError::Corrupt`] instead of panicking on a slice.
155pub fn decode_temporal_posting_value(
156    value: &[u8],
157) -> Result<(StorageOp, VisibilityLabel, i128, i128), StorageError> {
158    let body_len = STORAGE_VALUE_LEN + 32;
159    let bytes = value.get(..body_len).ok_or_else(|| {
160        StorageError::Corrupt(format!(
161            "temporal posting value must be {body_len} bytes, got {}",
162            value.len()
163        ))
164    })?;
165    let (op, visibility) = decode_storage_value(&bytes[..STORAGE_VALUE_LEN])?;
166    let begin = i128::from_be_bytes(
167        bytes[STORAGE_VALUE_LEN..STORAGE_VALUE_LEN + 16]
168            .try_into()
169            .expect("slice length checked above"),
170    );
171    let end = i128::from_be_bytes(
172        bytes[STORAGE_VALUE_LEN + 16..body_len]
173            .try_into()
174            .expect("slice length checked above"),
175    );
176    Ok((op, visibility, begin, end))
177}
178
179/// State machine for descending-`commit_ts` prefix scans under a snapshot.
180///
181/// For each logical quad (shared term prefix), the first version with
182/// `commit_ts <= snapshot` is the visible candidate; later (older) versions
183/// of the same quad are skipped.
184#[derive(Debug, Default)]
185pub struct SnapshotScanState {
186    /// Term prefix of the last handled logical quad. Empty until the first
187    /// candidate is taken (logical keys are never empty — every versioned key
188    /// carries at least one encoded term).
189    last_handled_logical: Vec<u8>,
190}
191
192impl SnapshotScanState {
193    /// Returns `true` when `commit_ts` is the newest version visible at `snapshot`.
194    ///
195    /// The candidate's logical key is copied into the state's own reusable
196    /// buffer (`clear()` + `extend_from_slice`), so a scan pays no per-row
197    /// allocation after the first handled version.
198    pub fn consider_slice(
199        &mut self,
200        logical_key: &[u8],
201        commit_ts: CommitTs,
202        snapshot_ts: u64,
203    ) -> bool {
204        if self.last_handled_logical.as_slice() == logical_key {
205            return false;
206        }
207        if commit_ts.0 > snapshot_ts {
208            return false;
209        }
210        self.last_handled_logical.clear();
211        self.last_handled_logical.extend_from_slice(logical_key);
212        true
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219    use crate::types::SnapshotId;
220    use crate::{GraphName, Literal, NamedNode, Quad};
221    use pretty_assertions::assert_eq;
222
223    #[test]
224    fn temporal_posting_value_rejects_truncation_instead_of_panicking() {
225        let body: Vec<u8> = encode_storage_value(StorageOp::Put, VisibilityLabel(7))
226            .into_iter()
227            .chain(42_i128.to_be_bytes())
228            .chain((-9_i128).to_be_bytes())
229            .collect();
230        let (op, visibility, begin, end) = decode_temporal_posting_value(&body).unwrap();
231        assert_eq!(op, StorageOp::Put);
232        assert_eq!(visibility, VisibilityLabel(7));
233        assert_eq!((begin, end), (42, -9));
234
235        // Every truncation is corruption, not a panic — 0..=36 bytes all
236        // error cleanly.
237        for len in 0..body.len() {
238            assert!(
239                decode_temporal_posting_value(&body[..len]).is_err(),
240                "a {len}-byte value must read corrupt"
241            );
242        }
243    }
244
245    fn sample_encoded_quad() -> EncodedQuad {
246        EncodedQuad::from(&Quad::new(
247            NamedNode::new("http://ex/s").unwrap(),
248            NamedNode::new("http://ex/p").unwrap(),
249            Literal::from("obj"),
250            GraphName::DefaultGraph,
251        ))
252    }
253
254    #[test]
255    fn descending_commit_ts_newer_sorts_before_older() {
256        let quad = sample_encoded_quad();
257        let newer = encode_versioned_key(IndexPermutation::Spog, &quad, CommitTs(20));
258        let older = encode_versioned_key(IndexPermutation::Spog, &quad, CommitTs(10));
259        assert!(
260            newer < older,
261            "newer commit_ts must sort first under same term prefix"
262        );
263        assert!(newer.starts_with(&encode_index_key(IndexPermutation::Spog, &quad)));
264        assert!(older.starts_with(&encode_index_key(IndexPermutation::Spog, &quad)));
265        assert_eq!(
266            encode_versioned_key(IndexPermutation::Spog, &quad, CommitTs(0)),
267            {
268                let mut key = encode_index_key(IndexPermutation::Spog, &quad);
269                key.extend_from_slice(&[0xFF; COMMIT_TS_LEN]);
270                key
271            },
272            "commit_ts 0 is the last versioned key (term bytes || 0xFF x 8)"
273        );
274    }
275
276    #[test]
277    fn versioned_key_round_trip() {
278        let quad = sample_encoded_quad();
279        let key = encode_versioned_key(IndexPermutation::Posg, &quad, CommitTs(42));
280        let (decoded, ts) = decode_versioned_key(IndexPermutation::Posg, &key).unwrap();
281        assert_eq!(decoded, quad);
282        assert_eq!(ts, CommitTs(42));
283    }
284
285    #[test]
286    fn versioned_parts_splits_the_term_prefix_and_the_timestamp() {
287        let quad = sample_encoded_quad();
288        for permutation in [IndexPermutation::Spog, IndexPermutation::Posg] {
289            let key = encode_versioned_key(permutation, &quad, CommitTs(42));
290            let (term_key, commit_ts) = versioned_parts(&key).unwrap();
291            assert_eq!(term_key, encode_index_key(permutation, &quad));
292            assert_eq!(commit_ts, CommitTs(42));
293            // Agreement with the full decode: same split, same timestamp.
294            let (quad2, ts2) = decode_versioned_key(permutation, &key).unwrap();
295            assert_eq!(ts2, commit_ts);
296            assert_eq!(quad2, quad);
297        }
298    }
299
300    #[test]
301    fn versioned_parts_rejects_short_keys_instead_of_truncating() {
302        let quad = sample_encoded_quad();
303        let full = encode_versioned_key(IndexPermutation::Spog, &quad, CommitTs(42));
304        // Every prefix shorter than the timestamp suffix is corruption,
305        // never "the whole key is the timestamp".
306        for len in 0..COMMIT_TS_LEN {
307            assert!(
308                versioned_parts(&full[..len]).is_err(),
309                "a {len}-byte key must read corrupt"
310            );
311        }
312        // Exactly the suffix: empty term prefix, timestamp intact.
313        let (term_key, commit_ts) = versioned_parts(&full[full.len() - COMMIT_TS_LEN..]).unwrap();
314        assert!(term_key.is_empty());
315        assert_eq!(commit_ts, CommitTs(42));
316    }
317
318    #[test]
319    fn storage_value_round_trip() {
320        let bytes = encode_storage_value(StorageOp::Delete, VisibilityLabel(0x00ab_cdef));
321        assert_eq!(bytes.len(), STORAGE_VALUE_LEN);
322        let (op, vis) = decode_storage_value(&bytes).unwrap();
323        assert_eq!(op, StorageOp::Delete);
324        assert_eq!(vis, VisibilityLabel(0x00ab_cdef));
325    }
326
327    #[test]
328    fn storage_value_rejects_wrong_length() {
329        assert!(decode_storage_value(&[1, 0, 0, 0]).is_err());
330        assert!(decode_storage_value(&[1, 0, 0, 0, 0, 0]).is_err());
331        assert!(decode_storage_value(&[]).is_err());
332    }
333
334    #[test]
335    fn storage_value_rejects_reserved_op_zero() {
336        let mut bytes = encode_storage_value(StorageOp::Put, VisibilityLabel(0));
337        bytes[0] = 0;
338        assert!(decode_storage_value(&bytes).is_err());
339    }
340
341    #[test]
342    fn snapshot_scan_state_picks_newest_visible_version() {
343        let logical = b"quad-a";
344        let mut state = SnapshotScanState::default();
345        let snapshot = SnapshotId(15).0;
346
347        // Newer than snapshot — skip, do not mark handled.
348        assert!(!state.consider_slice(logical, CommitTs(20), snapshot));
349        // Visible version — take and mark.
350        assert!(state.consider_slice(logical, CommitTs(10), snapshot));
351        // Older version of same logical quad — skip.
352        assert!(!state.consider_slice(logical, CommitTs(5), snapshot));
353        // A second quad is an unrelated logical key.
354        assert!(state.consider_slice(b"quad-b", CommitTs(5), snapshot));
355    }
356
357    fn version_of(quad: &EncodedQuad) -> HexastoreVersion<'_> {
358        HexastoreVersion {
359            quad,
360            commit_ts: CommitTs(1),
361            op: StorageOp::Put,
362            visibility: VisibilityLabel::default(),
363        }
364    }
365
366    #[test]
367    fn prepare_puts_writes_both_s_axis_indexes() {
368        let quad = sample_encoded_quad();
369        let puts = prepare_hexastore_puts(PartitionAxis::S, [version_of(&quad)]);
370        assert_eq!(puts.len(), 2);
371        assert_eq!(puts[0].cf_index, 0);
372        assert_eq!(puts[1].cf_index, 1);
373        assert_eq!(
374            puts[0].key,
375            encode_versioned_key(IndexPermutation::Spog, &quad, CommitTs(1))
376        );
377        assert_eq!(
378            puts[1].key,
379            encode_versioned_key(IndexPermutation::Sopg, &quad, CommitTs(1))
380        );
381    }
382
383    #[test]
384    fn prepare_puts_skips_tsg_for_non_type_quads() {
385        let quad = sample_encoded_quad();
386        let puts = prepare_hexastore_puts(PartitionAxis::O, [version_of(&quad)]);
387        assert_eq!(puts.len(), 1);
388        assert_eq!(puts[0].cf_index, 0);
389        assert_eq!(
390            puts[0].key,
391            encode_versioned_key(IndexPermutation::Opsg, &quad, CommitTs(1))
392        );
393    }
394}