Skip to main content

waratah_storage/encode/
catalog.rs

1//! MVCC named-graph catalog (`named_graphs_catalog` CF on the S axis).
2//!
3//! ```text
4//! key   = encode_term_bytes(NamedNode) || commit_ts_desc(u64 BE)
5//! value = state u8 (Present = 1, Dropped = 2)
6//! ```
7//!
8//! A future G axis may hold a **duplicate** of this CF for in-partition checks.
9//! That replica is not a second source of truth and is not implemented today.
10
11use super::binary::{TermReader, encode_term_bytes};
12use super::encoded_term::EncodedTerm;
13use super::versioned::{
14    COMMIT_TS_LEN, HexastoreVersion, SnapshotScanState, versioned_key_term_prefix,
15};
16use crate::StorageError;
17use crate::types::{CommitTs, SnapshotId, StorageOp};
18
19/// RocksDB column-family name. Opened only on [`crate::PartitionAxis::S`].
20pub const NAMED_GRAPHS_CATALOG_CF: &str = "named_graphs_catalog";
21
22/// Prefix extractor length: named-node type byte + 16-byte hash (same as SPOG).
23pub const CATALOG_MIN_PREFIX_SIZE: usize = 17;
24
25/// Presence / drop marker stored as a single byte.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27#[repr(u8)]
28pub enum GraphCatalogState {
29    /// Graph is in the dataset (empty or non-empty).
30    Present = 1,
31    /// Graph was dropped at this timestamp (MVCC; no Drop RPC yet).
32    Dropped = 2,
33}
34
35impl GraphCatalogState {
36    /// Wire byte.
37    pub const fn as_u8(self) -> u8 {
38        self as u8
39    }
40
41    /// Decode a catalog value byte.
42    pub fn from_u8(value: u8) -> Result<Self, StorageError> {
43        match value {
44            1 => Ok(Self::Present),
45            2 => Ok(Self::Dropped),
46            other => Err(StorageError::Corrupt(format!(
47                "unknown named-graph catalog state {other}"
48            ))),
49        }
50    }
51
52    /// Single-byte value for a RocksDB put.
53    pub const fn encode(self) -> [u8; 1] {
54        [self.as_u8()]
55    }
56}
57
58/// One catalog put staged into the S-axis `named_graphs_catalog` CF.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct CatalogPut {
61    /// `encode_term(graph) || descending commit_ts`.
62    pub key: Vec<u8>,
63    /// [`GraphCatalogState`] byte.
64    pub value: [u8; 1],
65}
66
67impl CatalogPut {
68    /// Encode a catalog version. `graph` must be a named node.
69    pub fn new(
70        graph: &EncodedTerm,
71        commit_ts: CommitTs,
72        state: GraphCatalogState,
73    ) -> Result<Self, StorageError> {
74        Ok(Self {
75            key: encode_catalog_key(graph, commit_ts)?,
76            value: state.encode(),
77        })
78    }
79}
80
81/// True when `term` is a SPARQL named-graph IRI (catalog member).
82pub fn is_catalog_graph(term: &EncodedTerm) -> bool {
83    matches!(term, EncodedTerm::NamedNode { .. })
84}
85
86/// Reject the RDF default graph and non-IRI graph names.
87pub fn require_catalog_graph(term: &EncodedTerm) -> Result<(), StorageError> {
88    match term {
89        EncodedTerm::NamedNode { .. } => Ok(()),
90        EncodedTerm::DefaultGraph => Err(StorageError::InvalidCatalogGraph(
91            "RDF default graph is not a named graph".into(),
92        )),
93        _ => Err(StorageError::InvalidCatalogGraph(
94            "named-graph catalog only accepts IRI graph names".into(),
95        )),
96    }
97}
98
99/// Term bytes used as the catalog key prefix (no timestamp).
100pub fn catalog_prefix(graph: &EncodedTerm) -> Result<Vec<u8>, StorageError> {
101    require_catalog_graph(graph)?;
102    Ok(encode_term_bytes(graph))
103}
104
105/// Versioned catalog key: encoded named node ‖ descending `commit_ts`.
106pub fn encode_catalog_key(
107    graph: &EncodedTerm,
108    commit_ts: CommitTs,
109) -> Result<Vec<u8>, StorageError> {
110    let mut key = catalog_prefix(graph)?;
111    key.extend_from_slice(&commit_ts.to_descending_be_bytes());
112    Ok(key)
113}
114
115/// Decode a catalog key into the graph IRI and commit timestamp.
116pub fn decode_catalog_key(key: &[u8]) -> Result<(EncodedTerm, CommitTs), StorageError> {
117    if key.len() < COMMIT_TS_LEN {
118        return Err(StorageError::Corrupt(format!(
119            "catalog key too short: {} bytes",
120            key.len()
121        )));
122    }
123    let (term_key, ts_bytes) = key.split_at(key.len() - COMMIT_TS_LEN);
124    let commit_ts = CommitTs::from_descending_be_bytes(
125        ts_bytes
126            .try_into()
127            .map_err(|_| StorageError::Corrupt("commit_ts suffix must be 8 bytes".to_owned()))?,
128    );
129    let mut cursor = term_key;
130    let graph = cursor.read_term()?;
131    if !cursor.is_empty() {
132        return Err(StorageError::Corrupt(format!(
133            "{} trailing byte(s) after catalog graph term",
134            cursor.len()
135        )));
136    }
137    require_catalog_graph(&graph)?;
138    Ok((graph, commit_ts))
139}
140
141/// Decode the 1-byte catalog value.
142pub fn decode_catalog_value(bytes: &[u8]) -> Result<GraphCatalogState, StorageError> {
143    if bytes.len() != 1 {
144        return Err(StorageError::Corrupt(format!(
145            "catalog value must be 1 byte, got {}",
146            bytes.len()
147        )));
148    }
149    GraphCatalogState::from_u8(bytes[0])
150}
151
152/// Distinct named-node graphs from `Put` versions, with the earliest commit_ts.
153///
154/// Deletes do not create catalog entries. DefaultGraph and blank graphs are skipped.
155pub fn catalog_graphs_from_versions<'a>(
156    versions: impl IntoIterator<Item = HexastoreVersion<'a>>,
157) -> Vec<(EncodedTerm, CommitTs)> {
158    let mut out: Vec<(EncodedTerm, CommitTs)> = Vec::new();
159    for version in versions {
160        if version.op != StorageOp::Put {
161            continue;
162        }
163        if !is_catalog_graph(&version.quad.graph_name) {
164            continue;
165        }
166        if let Some((_, ts)) = out
167            .iter_mut()
168            .find(|(graph, _)| graph == &version.quad.graph_name)
169        {
170            if version.commit_ts < *ts {
171                *ts = version.commit_ts;
172            }
173        } else {
174            out.push((version.quad.graph_name.clone(), version.commit_ts));
175        }
176    }
177    out
178}
179
180/// Deduplicate catalog graphs in the State by their IRI.
181/// If this catalog version is the newest visible at `snapshot`, return the graph IRI.
182/// If this catalog version is Dropped, return None.
183pub fn dedup_state_newest_catalog_graph(
184    state: &mut SnapshotScanState,
185    snapshot: SnapshotId,
186    key: &[u8],
187    value: &[u8],
188) -> Result<Option<EncodedTerm>, StorageError> {
189    let (graph, commit_ts) = decode_catalog_key(key)?;
190    let logical = versioned_key_term_prefix(key)?;
191    if !state.consider_slice(logical, commit_ts, snapshot.0) {
192        return Ok(None);
193    }
194    match decode_catalog_value(value)? {
195        GraphCatalogState::Present => Ok(Some(graph)),
196        GraphCatalogState::Dropped => Ok(None),
197    }
198}
199
200/// Fold a catalog CF (or memory map) into the named graphs visible at `snapshot`.
201pub fn collect_dedup_visible_catalog_graphs<'a>(
202    entries: impl IntoIterator<Item = (&'a [u8], &'a [u8])>,
203    snapshot: SnapshotId,
204) -> Result<Vec<EncodedTerm>, StorageError> {
205    let mut state = SnapshotScanState::default();
206    let mut out = Vec::new();
207    for (key, value) in entries {
208        if let Some(graph) = dedup_state_newest_catalog_graph(&mut state, snapshot, key, value)? {
209            out.push(graph);
210        }
211    }
212    Ok(out)
213}
214
215/// Stage `Present` versions for graphs whose newest catalog state is missing or Dropped.
216///
217/// Does not touch storage. The caller supplies each graph's newest version via
218/// `newest_state` (typically one prefix seek per graph).
219pub fn stage_catalog_puts(
220    graphs: &[(EncodedTerm, CommitTs)],
221    mut newest_state: impl FnMut(&EncodedTerm) -> Result<Option<GraphCatalogState>, StorageError>,
222) -> Result<Vec<CatalogPut>, StorageError> {
223    let mut puts = Vec::new();
224    for (graph, commit_ts) in graphs {
225        require_catalog_graph(graph)?;
226        match newest_state(graph)? {
227            None | Some(GraphCatalogState::Dropped) => {
228                puts.push(CatalogPut::new(
229                    graph,
230                    *commit_ts,
231                    GraphCatalogState::Present,
232                )?);
233            }
234            Some(GraphCatalogState::Present) => {}
235        }
236    }
237    Ok(puts)
238}
239
240/// Record the earliest Put `commit_ts` for each named graph in a SPOG version scan.
241pub fn record_first_put_graph(
242    first_puts: &mut Vec<(EncodedTerm, CommitTs)>,
243    graph: &EncodedTerm,
244    commit_ts: CommitTs,
245    op: StorageOp,
246) {
247    if op != StorageOp::Put || !is_catalog_graph(graph) {
248        return;
249    }
250    if let Some((_, ts)) = first_puts
251        .iter_mut()
252        .find(|(existing, _)| existing == graph)
253    {
254        if commit_ts < *ts {
255            *ts = commit_ts;
256        }
257    } else {
258        first_puts.push((graph.clone(), commit_ts));
259    }
260}
261
262/// Stats from [`crate::Storage::rebuild_named_graph_catalog`].
263#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
264pub struct CatalogRebuildStats {
265    /// Graphs that received a new `Present` version.
266    pub graphs_inserted: u64,
267    /// Graphs that already had a catalog version (Present or Dropped).
268    pub graphs_skipped: u64,
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use crate::encode::EncodedQuad;
275    use crate::{NamedNode, StorageOp, VisibilityLabel};
276
277    fn named(iri: &str) -> EncodedTerm {
278        EncodedTerm::from(&NamedNode::new(iri).unwrap())
279    }
280
281    #[test]
282    fn catalog_key_round_trip() {
283        let graph = named("http://ex/g");
284        let key = encode_catalog_key(&graph, CommitTs(42)).unwrap();
285        let (decoded, ts) = decode_catalog_key(&key).unwrap();
286        assert_eq!(decoded, graph);
287        assert_eq!(ts, CommitTs(42));
288    }
289
290    #[test]
291    fn newer_timestamp_sorts_first() {
292        let graph = named("http://ex/g");
293        let older = encode_catalog_key(&graph, CommitTs(10)).unwrap();
294        let newer = encode_catalog_key(&graph, CommitTs(20)).unwrap();
295        assert!(newer < older, "descending commit_ts must sort newest first");
296    }
297
298    #[test]
299    fn default_graph_is_rejected() {
300        let err = encode_catalog_key(&EncodedTerm::DefaultGraph, CommitTs(1)).unwrap_err();
301        assert!(matches!(err, StorageError::InvalidCatalogGraph(_)));
302    }
303
304    #[test]
305    fn collect_puts_skip_default_and_deletes() {
306        let named_quad = EncodedQuad {
307            subject: named("http://ex/s"),
308            predicate: named("http://ex/p"),
309            object: named("http://ex/o"),
310            graph_name: named("http://ex/g"),
311        };
312        let default_quad = EncodedQuad {
313            graph_name: EncodedTerm::DefaultGraph,
314            ..named_quad.clone()
315        };
316        let versions = [
317            HexastoreVersion {
318                quad: &named_quad,
319                commit_ts: CommitTs(20),
320                op: StorageOp::Put,
321                visibility: VisibilityLabel::default(),
322            },
323            HexastoreVersion {
324                quad: &named_quad,
325                commit_ts: CommitTs(10),
326                op: StorageOp::Put,
327                visibility: VisibilityLabel::default(),
328            },
329            HexastoreVersion {
330                quad: &default_quad,
331                commit_ts: CommitTs(10),
332                op: StorageOp::Put,
333                visibility: VisibilityLabel::default(),
334            },
335            HexastoreVersion {
336                quad: &named_quad,
337                commit_ts: CommitTs(30),
338                op: StorageOp::Delete,
339                visibility: VisibilityLabel::default(),
340            },
341        ];
342        let graphs = catalog_graphs_from_versions(versions);
343        assert_eq!(graphs.len(), 1);
344        assert_eq!(graphs[0].0, named("http://ex/g"));
345        assert_eq!(graphs[0].1, CommitTs(10));
346    }
347}