Skip to main content

genegraph_storage/
graph.rs

1//! First-class graph storage types (RFC #81-P3).
2//!
3//! The canonical on-disk layout is an edge-list Lance dataset:
4//! `src: UInt32|UInt64`, `dst: UInt32|UInt64` and an optional
5//! `weight: Float32|Float64` column (all non-null). Node-id and weight
6//! widths are schema-chosen — `u32` node-id and `f64` weight defaults,
7//! `u64`/`f32` opt-ins (#106) — and declare the storage limits
8//! explicitly rather than narrowing silently (consistent with #51).
9//! Weights are persisted faithfully — the storage layer makes no domain
10//! assumptions, so normalization transforms belong to the producer; the
11//! opt-in [`GraphWriteOptions::weight_range`] asserts compliance with a
12//! declared interval instead. `CsMat` CSR conversion stays at the API
13//! boundary ([`StoredGraph::to_csr`]); sprs never reaches the format
14//! layer.
15
16use std::collections::BTreeMap;
17
18use sprs::{CsMat, TriMat};
19
20use crate::{StorageError, StorageResult};
21
22/// Node-id storage width of a graph collection.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum NodeIdWidth {
25    /// `UInt32` ids (default); caps the graph at ~4.29 billion nodes.
26    U32,
27    /// `UInt64` ids (opt-in via schema).
28    U64,
29}
30
31impl NodeIdWidth {
32    pub const fn as_str(&self) -> &'static str {
33        match self {
34            NodeIdWidth::U32 => "u32",
35            NodeIdWidth::U64 => "u64",
36        }
37    }
38
39    pub fn parse(s: &str) -> StorageResult<Self> {
40        match s {
41            "u32" => Ok(NodeIdWidth::U32),
42            "u64" => Ok(NodeIdWidth::U64),
43            other => Err(StorageError::Invalid(format!(
44                "unknown node-id width '{other}' (expected u32 or u64)"
45            ))),
46        }
47    }
48
49    /// The `DataType` used for `src`/`dst` columns at this width.
50    pub(crate) const fn data_type(self) -> arrow::datatypes::DataType {
51        match self {
52            NodeIdWidth::U32 => arrow::datatypes::DataType::UInt32,
53            NodeIdWidth::U64 => arrow::datatypes::DataType::UInt64,
54        }
55    }
56}
57
58/// Edge-weight storage width of a graph collection, mirroring
59/// [`NodeIdWidth`] (#106): the width is schema-declared through
60/// [`GraphWriteOptions::weight_type`], resolving the RFC #81 open
61/// question ("Float64 only, or allow Float32?") with "both,
62/// schema-declared".
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum WeightType {
65    /// `Float64` weights (default): the same width and exactness as the
66    /// `value` column of the legacy sparse-matrix artifacts, so an f64
67    /// CSR (laplacian, adjacency) round-trips bit-identically through
68    /// the graph API just like through `save_sparse`.
69    F64,
70    /// `Float32` weights (opt-in): half the storage bytes for
71    /// memory-bound consumers. Weights that cannot be represented exactly
72    /// at this width are rejected on save instead of being silently
73    /// narrowed; finite values beyond the f32 range surface
74    /// [`StorageError::Overflow`] (#51). Infinities narrow bit-exactly;
75    /// NaN is preserved as NaN (classification semantics only — the
76    /// payload is not guaranteed bit-exact, unlike the
77    /// [`WeightType::F64`] width).
78    F32,
79}
80
81impl WeightType {
82    pub const fn as_str(&self) -> &'static str {
83        match self {
84            WeightType::F64 => "f64",
85            WeightType::F32 => "f32",
86        }
87    }
88
89    pub fn parse(s: &str) -> StorageResult<Self> {
90        match s {
91            "f64" => Ok(WeightType::F64),
92            "f32" => Ok(WeightType::F32),
93            other => Err(StorageError::Invalid(format!(
94                "unknown weight width '{other}' (expected f32 or f64)"
95            ))),
96        }
97    }
98
99    /// The `DataType` used for the `weight` column at this width.
100    pub(crate) const fn data_type(self) -> arrow::datatypes::DataType {
101        match self {
102            WeightType::F64 => arrow::datatypes::DataType::Float64,
103            WeightType::F32 => arrow::datatypes::DataType::Float32,
104        }
105    }
106}
107
108/// A directed edge with an optional weight (RFC #81-P3).
109///
110/// `weight` is `f64` at the API boundary (the widest width, like node ids
111/// are `u64`) and is persisted faithfully: the storage layer makes no
112/// domain assumptions, so normalization transforms belong to the producer
113/// (declare [`GraphWriteOptions::weight_range`] for an opt-in bounds
114/// assertion on already-normalized values). The storage width is
115/// schema-declared via [`GraphWriteOptions::weight_type`] — `Float64` by
116/// default, mirroring the `value` column of the legacy sparse-matrix
117/// artifacts — and weights that cannot be stored exactly at a declared
118/// `Float32` width are rejected, never silently narrowed. A collection is
119/// either fully weighted or topology-only; mixed edges are rejected.
120#[derive(Debug, Clone, Copy, PartialEq)]
121pub struct GraphEdge {
122    pub src: u64,
123    pub dst: u64,
124    pub weight: Option<f64>,
125}
126
127impl GraphEdge {
128    pub fn weighted(src: u64, dst: u64, weight: f64) -> Self {
129        Self {
130            src,
131            dst,
132            weight: Some(weight),
133        }
134    }
135
136    pub fn unweighted(src: u64, dst: u64) -> Self {
137        Self {
138            src,
139            dst,
140            weight: None,
141        }
142    }
143}
144
145/// Options for [`crate::traits::backend::StorageBackend::save_graph_with`].
146#[derive(Debug, Clone)]
147pub struct GraphWriteOptions {
148    /// Storage width for node ids (default `U32`); ids above the limit
149    /// surface [`StorageError::Overflow`] instead of being truncated.
150    pub node_id_width: NodeIdWidth,
151    /// Storage width for edge weights (default `F64`, mirroring
152    /// `node_id_width`, #106): weights are `f64` at the API boundary.
153    /// The default matches the sparse-matrix `value` column (bit-exact
154    /// f64 round trips); an explicit `F32` declaration halves the storage
155    /// bytes but rejects values that cannot be stored exactly instead of
156    /// silently narrowing them.
157    pub weight_type: WeightType,
158    /// Opt-in weight-range compliance check (#106): when `Some((low,
159    /// high))`, every weight must already lie in the closed interval — a
160    /// bounds assertion that catches a forgotten producer transform,
161    /// never a transform the storage layer performs (normalization
162    /// belongs upstream; values are persisted faithfully). NaN lies in
163    /// no interval and is rejected; an inverted interval is a rejected
164    /// configuration.
165    pub weight_range: Option<(f64, f64)>,
166    /// Explicit node count (e.g. to keep isolated vertices). Must be at
167    /// least `max(src, dst) + 1` over all edges; defaults to exactly that.
168    pub num_nodes: Option<u64>,
169    /// User properties stored on the collection (registry level) and
170    /// stamped into the dataset schema metadata (dataset level).
171    pub properties: BTreeMap<String, String>,
172}
173
174impl Default for GraphWriteOptions {
175    fn default() -> Self {
176        Self {
177            node_id_width: NodeIdWidth::U32,
178            weight_type: WeightType::F64,
179            weight_range: None,
180            num_nodes: None,
181            properties: BTreeMap::new(),
182        }
183    }
184}
185
186impl GraphWriteOptions {
187    pub fn with_width(node_id_width: NodeIdWidth) -> Self {
188        Self {
189            node_id_width,
190            ..Default::default()
191        }
192    }
193}
194
195/// Options for the graph read path (#108).
196///
197/// The tolerant default is the compat shim: an unstamped dataset loads with
198/// `num_nodes = max_id + 1` and columns are read positionally (name-agnostic),
199/// so pre-collections triplet artifacts still load. Strict mode makes the
200/// hazard detectable at the API instead of silently resizing.
201#[derive(Debug, Clone, Copy, Default)]
202pub struct GraphReadOptions {
203    /// When `true`, reject datasets without a `num_nodes` stamp with a typed
204    /// [`StorageError::Invalid`] instead of silently resizing to `max_id + 1`
205    /// (a graph whose trailing vertices are isolated would otherwise load
206    /// with a smaller node count than was written). Also validates the
207    /// `src`/`dst`/`weight` column names, positively identifying
208    /// pre-collections triplet artifacts (`row`/`col`/`value`) rather than
209    /// positionally coercing them.
210    pub strict: bool,
211}
212
213impl GraphReadOptions {
214    /// Strict read mode: reject unstamped `num_nodes` and validate column
215    /// names (#108).
216    pub fn strict() -> Self {
217        Self { strict: true }
218    }
219}
220
221/// A graph collection loaded back from storage (RFC #81-P3).
222#[derive(Debug, Clone, PartialEq)]
223pub struct StoredGraph {
224    /// Edges in stored order; `weight` is `None` for topology-only
225    /// collections. `f32`-stored weights are upcast to `f64` losslessly
226    /// at load time.
227    pub edges: Vec<GraphEdge>,
228    /// Storage width used for node ids.
229    pub node_id_width: NodeIdWidth,
230    /// Storage width used for the `weight` column (mirrors
231    /// `node_id_width`, #106); for topology-only collections it reports
232    /// the declared width from the dataset metadata (the `F64` default
233    /// when unstamped) and is meaningful only when `weighted`.
234    pub weight_type: WeightType,
235    /// Node count (from the dataset metadata; isolated vertices included).
236    pub num_nodes: u64,
237    /// Whether the edge list carries weights.
238    pub weighted: bool,
239}
240
241impl StoredGraph {
242    /// Converts the edge list to a CSR matrix at the API boundary.
243    ///
244    /// Topology-only graphs get weight `1.0` (unweighted convention); the
245    /// result is `CsMat<f64>` — weights are `f64` at the API boundary, so
246    /// `WeightType::F64` collections round-trip exactly.
247    pub fn to_csr(&self) -> StorageResult<CsMat<f64>> {
248        let n = self.num_nodes;
249        if n > usize::MAX as u64 {
250            return Err(StorageError::Overflow(format!(
251                "node count {n} exceeds the addressable size"
252            )));
253        }
254        let n = n as usize;
255        let mut trimat = TriMat::new((n, n));
256        trimat.reserve(self.edges.len());
257        for edge in &self.edges {
258            let (src, dst) = (edge.src as usize, edge.dst as usize);
259            if src >= n || dst >= n {
260                return Err(StorageError::Invalid(format!(
261                    "edge ({}, {}) out of bounds for {}-node graph",
262                    edge.src, edge.dst, n
263                )));
264            }
265            let weight = edge.weight.unwrap_or(1.0);
266            trimat.add_triplet(src, dst, weight);
267        }
268        let csr = trimat.to_csr();
269        if csr.rows() != n || csr.cols() != n {
270            return Err(StorageError::Invalid(format!(
271                "dimension mismatch after CSR conversion: expected {n}x{n}, got {}x{}",
272                csr.rows(),
273                csr.cols()
274            )));
275        }
276        Ok(csr)
277    }
278}
279
280/// Dataset-level schema-metadata keys stamped by the `save_graph` /
281/// `save_vectors` writers (RFC #81-P1: dataset-level kinds alongside
282/// registry-level kinds). User properties may not shadow these.
283pub(crate) const RESERVED_METADATA_KEYS: [&str; 5] = [
284    "kind",
285    "node_id_width",
286    "weighted",
287    "num_nodes",
288    "weight_type",
289];