Skip to main content

waratah_storage/
types.rs

1//! Waratah-specific storage types (not provided by `oxrdf`).
2
3use std::fmt;
4use std::str::FromStr;
5
6/// Hexastore partition axis managed by a consensus master node.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
8pub enum PartitionAxis {
9    /// Subject-partitioned indexes (`SPOG`, `SOPG`).
10    S,
11    /// Predicate-partitioned indexes (`PSOG`, `POSG`).
12    P,
13    /// Object-partitioned indexes (`OPSG`, `TSG`).
14    O,
15}
16
17impl PartitionAxis {
18    /// Every axis of the MVP three-way hexastore (`G` is deferred).
19    pub const ALL: [Self; 3] = [Self::S, Self::P, Self::O];
20
21    /// Single-letter axis name (`"s"`, `"p"`, `"o"`).
22    pub const fn as_str(self) -> &'static str {
23        match self {
24            Self::S => "s",
25            Self::P => "p",
26            Self::O => "o",
27        }
28    }
29}
30
31impl fmt::Display for PartitionAxis {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        f.write_str(self.as_str())
34    }
35}
36
37impl FromStr for PartitionAxis {
38    type Err = crate::StorageError;
39
40    fn from_str(value: &str) -> Result<Self, Self::Err> {
41        match value {
42            "s" | "S" => Ok(Self::S),
43            "p" | "P" => Ok(Self::P),
44            "o" | "O" => Ok(Self::O),
45            other => Err(crate::StorageError::UnknownAxis(other.to_owned())),
46        }
47    }
48}
49
50/// Cluster-wide write-time commit timestamp (`u64`).
51///
52/// Assigned at the compute/coordinator layer (TSO as the system matures).
53/// Stored as a descending big-endian suffix on hexastore keys (`!ts`).
54#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
55pub struct CommitTs(pub u64);
56
57impl CommitTs {
58    /// Encode as descending big-endian bytes so newer versions sort first.
59    pub fn to_descending_be_bytes(self) -> [u8; 8] {
60        (!self.0).to_be_bytes()
61    }
62
63    /// Decode from descending big-endian key suffix bytes.
64    pub fn from_descending_be_bytes(bytes: [u8; 8]) -> Self {
65        Self(!u64::from_be_bytes(bytes))
66    }
67}
68
69/// Cluster-wide MVCC snapshot identifier (same domain as [`CommitTs`]).
70///
71/// A scan returns the newest version of each logical quad with
72/// `commit_ts <= snapshot` whose operation is [`StorageOp::Put`].
73#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
74pub struct SnapshotId(pub u64);
75
76impl SnapshotId {
77    /// Read the newest committed version of every quad.
78    ///
79    /// A stand-in until Phase 8 hands compute a real timestamp from the cluster
80    /// TSO; reads taken this way are not repeatable across concurrent writes.
81    pub const fn latest() -> Self {
82        Self(u64::MAX)
83    }
84}
85
86impl From<CommitTs> for SnapshotId {
87    fn from(ts: CommitTs) -> Self {
88        Self(ts.0)
89    }
90}
91
92impl From<SnapshotId> for CommitTs {
93    fn from(id: SnapshotId) -> Self {
94        Self(id.0)
95    }
96}
97
98/// Semantic operation stored in a hexastore record value.
99///
100/// Logical RDF deletes append a [`StorageOp::Delete`] version; they do not
101/// issue a RocksDB tombstone for the RDF meaning of delete.
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
103#[repr(u8)]
104pub enum StorageOp {
105    /// Insert / upsert presence for this version.
106    Put = 1,
107    /// Hide the logical quad for snapshots at or after this version.
108    Delete = 2,
109}
110
111impl StorageOp {
112    /// Wire byte for this operation (`Put = 1`, `Delete = 2`).
113    pub const fn as_u8(self) -> u8 {
114        self as u8
115    }
116
117    /// Parse a wire byte; `0` is reserved unused.
118    pub fn from_u8(byte: u8) -> Result<Self, crate::StorageError> {
119        match byte {
120            1 => Ok(Self::Put),
121            2 => Ok(Self::Delete),
122            other => Err(crate::StorageError::Corrupt(format!(
123                "invalid storage op byte: {other}"
124            ))),
125        }
126    }
127}
128
129/// Cell-level visibility label id (`0` = unrestricted).
130///
131/// RBAC catalog interpretation is deferred; Phase 2b only stores and round-trips.
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
133pub struct VisibilityLabel(pub u32);
134
135/// The walk's own verdict on why one bounded scan page ended — the
136/// server-side fact that replaces the client's short-page inference
137/// (`rows.len() < limit` cannot distinguish "stopped at the limit" from
138/// "ran out, exactly at the limit", which costs a zero-row confirm
139/// request at every exact boundary).
140///
141/// The sinks are EDGE-triggered to keep the verdict honest at that
142/// boundary when purchased (`verdict_wanted`): a row arriving AT the
143/// page limit stops the walk without entering the page (`Limited` —
144/// that row proves more data exists), while a limit reached because the
145/// data ended lets the walk complete (terminal verdict). A
146/// LEVEL-triggered stop (halt the moment the count reaches the limit)
147/// cannot tell those two apart — which is why a consumer that declared
148/// it will not resume gets NO verdict at all rather than an unknowing
149/// one.
150///
151/// * `Limited` — the walk stopped at a demand boundary: the request's
152///   page limit. Under `verdict_wanted` this is constructive proof that
153///   more matching rows exist (the sink refused a row that arrived while
154///   the page was full); without it, the value is not surfaced — the
155///   response field is left unset instead.
156/// * `ExhaustedFilterTerms` — the walk completed every term of the
157///   request's allow-list (for a domain scan, every constraint); nothing
158///   more exists under THIS list. The scan's own key range outside the
159///   list was never consulted.
160/// * `ExhaustedScan` — the walk left the pattern's key range; nothing
161///   more exists for this scan at this snapshot, list or no list.
162///
163/// Terminal verdicts are genuine under every request shape: only a
164/// walk that ran out of keys can produce them. Each walk reports only
165/// what it can know: an allow-list walk never says `ExhaustedScan` (it
166/// never looks outside its terms), a contiguous prefix walk never says
167/// `ExhaustedFilterTerms` (it carries no wire filter terms).
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub enum ScanExhaustion {
170    /// Stopped at the page limit. Under `verdict_wanted`, a refused row
171    /// proved more rows exist under the same scope.
172    Limited,
173    /// The request's filter term list (or constraint list) is fully
174    /// served.
175    ExhaustedFilterTerms,
176    /// The scan's own key range is fully served at this snapshot.
177    ExhaustedScan,
178}
179
180impl ScanExhaustion {
181    /// Whether the value is one of the two terminal verdicts — a walk
182    /// that ran out of keys. `Limited` is never terminal. An ABSENT
183    /// verdict (the `Option` on [`ScanPage`] / the wire field) is not a
184    /// value and must be checked before this: absence means no verdict
185    /// was purchased, and a consumer holding absence resumes from its
186    /// cursor or infers from row counts.
187    pub fn is_terminal(self) -> bool {
188        matches!(self, Self::ExhaustedFilterTerms | Self::ExhaustedScan)
189    }
190}
191
192/// One bounded scan page plus the walk's verdict, when purchased.
193///
194/// `exhausted` is `None` exactly when the request declared
195/// `verdict_wanted = false` — no verdict was bought, nothing is claimed,
196/// and the consumer that opted out (an ASK / one-shot slice) infers from
197/// its row counts exactly as it did before the verdict existed. Server
198/// producers report `None` even for facts that were free to know (a
199/// short page's completed walk): the contract is "a verdict appears iff
200/// one was asked for". Compute-side synthesized answers (a skipped RPC,
201/// an empty graph window) report their genuine terminal verdict — they
202/// are local facts, not purchases.
203pub struct ScanPage {
204    /// The page's rows, at most `limit` of them.
205    pub rows: Vec<crate::encode::EncodedQuad>,
206    /// Why the walk ended — authoritative, not inferred from row count;
207    /// `None` when no verdict was purchased.
208    pub exhausted: Option<ScanExhaustion>,
209}
210
211/// One atomic object-term replacement: the versioned rows of
212/// `(subject, predicate, old_object, graph)` are deleted and rows of
213/// `(subject, predicate, new_object, graph)` are put in ONE WriteBatch at
214/// the shared commit timestamp, so no snapshot sees both rows or neither.
215/// The geo index upgrade's primitive — datatype-blind (see
216/// `Storage::apply_replace_pairs`).
217#[derive(Debug, Clone, PartialEq, Eq)]
218pub struct ReplacePair {
219    /// Shared subject of the old and new rows.
220    pub subject: crate::encode::EncodedTerm,
221    /// Shared predicate of the old and new rows.
222    pub predicate: crate::encode::EncodedTerm,
223    /// Shared graph of the old and new rows.
224    pub graph_name: crate::encode::EncodedTerm,
225    /// The object being replaced away.
226    pub old_object: crate::encode::EncodedTerm,
227    /// The object replacing it.
228    pub new_object: crate::encode::EncodedTerm,
229}
230
231impl ReplacePair {
232    /// The quad encoding away.
233    pub fn old_quad(&self) -> crate::encode::EncodedQuad {
234        crate::encode::EncodedQuad {
235            subject: self.subject.clone(),
236            predicate: self.predicate.clone(),
237            object: self.old_object.clone(),
238            graph_name: self.graph_name.clone(),
239        }
240    }
241
242    /// The quad replacing it.
243    pub fn new_quad(&self) -> crate::encode::EncodedQuad {
244        crate::encode::EncodedQuad {
245            subject: self.subject.clone(),
246            predicate: self.predicate.clone(),
247            object: self.new_object.clone(),
248            graph_name: self.graph_name.clone(),
249        }
250    }
251}