genegraph_storage/catalog.rs
1//! M-C1: catalog contract for table discovery and registration (#75).
2//!
3//! The [`TableDescriptor`] shape and the [`Catalog`] operations mirror the
4//! **Lance Namespace** client spec whose Apache Polaris implementation maps
5//! onto Polaris' **Generic Table API** (`name`, `format`, `base-location`,
6//! `properties`); see the Polaris + Lance integration announcement
7//! (2026-01-06). Per decision D1 in #75 this is a standards-hygiene
8//! contract only: no catalog server client is provided here.
9//!
10//! [`LocalRegistry`] implements the contract over the existing JSON metadata
11//! registry (a `GeneMetadata` instance), mirroring Lance Namespace's
12//! *Directory* semantics: every `*.lance` dataset registered in the
13//! metadata's files map is a table.
14
15use std::collections::BTreeMap;
16use std::path::PathBuf;
17
18use crate::StorageError;
19use crate::StorageResult;
20use crate::graph::GraphSource;
21pub use crate::metadata::CollectionKind;
22use crate::metadata::{FileInfo, GeneMetadata};
23
24/// Computed descriptor properties that mirror `FileInfo` fields; user
25/// properties cannot shadow them (enforced both in `register_table` and on
26/// the direct `save_*_with` write paths).
27pub(crate) const RESERVED_PROPERTIES: [&str; 6] = [
28 "filetype",
29 "storage_format",
30 "rows",
31 "cols",
32 "nnz",
33 "size_bytes",
34];
35
36/// Generic Table API-compatible table descriptor.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct TableDescriptor {
39 /// Unique table name within the registry (the metadata files-map key).
40 pub name: String,
41 /// Table format; always `lance` for this crate.
42 pub format: String,
43 /// Location of the table root (a `*.lance` dataset directory).
44 pub base_location: PathBuf,
45 /// First-class collection kind (RFC #81-P1): `vector-space`, `graph` or
46 /// `table`.
47 pub kind: CollectionKind,
48 /// Free-form key/value properties (filetype, shape, ...), merged with
49 /// the collection's user properties (RFC #81-P1).
50 pub properties: BTreeMap<String, String>,
51}
52
53/// Staleness of the graph linked to a vector space (#140), computed at
54/// describe time from current registry facts. Never persisted: there is
55/// no latch to clear, the signal follows the data on every call.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum GraphStaleness {
58 /// The vector space has no `graph` property: nothing to assess.
59 Unlinked,
60 /// Lineage (`source`/`source_rows`) is present and matches this
61 /// vector space: the graph was rebuilt against the current rows.
62 Fresh,
63 /// Detectable divergence: the lineage names another collection, the
64 /// lineage row count differs from the current row count, or (without
65 /// lineage) the stamped `num_nodes` differs from the row count.
66 Stale,
67 /// No lineage and `num_nodes` equals the row count. The counts agree;
68 /// the content may still differ. The library does not guess.
69 Unknown,
70}
71
72/// Vector-space descriptor plus its linked graph collection (RFC #81-P4).
73///
74/// A vector space references a graph collection by name through its `graph`
75/// user property; [`Catalog::describe_vector_space`] resolves both in one
76/// call.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct VectorSpaceDescriptor {
79 /// The vector-space collection itself.
80 pub vectors: TableDescriptor,
81 /// The linked graph collection, if the `graph` property is set.
82 pub graph: Option<TableDescriptor>,
83 /// Whether the linked graph still describes the current vectors
84 /// (#140). `Unlinked` when no graph is linked.
85 pub graph_staleness: GraphStaleness,
86}
87
88/// Registry of Lance tables backing a storage instance.
89pub trait Catalog {
90 /// All tables known to this registry.
91 fn list_tables(&self) -> StorageResult<Vec<TableDescriptor>>;
92 /// Whether a table with `name` is registered.
93 fn table_exists(&self, name: &str) -> StorageResult<bool>;
94 /// Descriptor for `name`, or `StorageError::Invalid` if absent.
95 fn describe_table(&self, name: &str) -> StorageResult<TableDescriptor>;
96 /// Adds `table` to the registry (replaces an existing entry of the same
97 /// name, mirroring Generic Table create-or-replace semantics).
98 fn register_table(&mut self, table: TableDescriptor) -> StorageResult<()>;
99 /// Removes `name` from the registry without deleting the dataset.
100 fn deregister_table(&mut self, name: &str) -> StorageResult<()>;
101
102 /// Describes a vector-space collection together with the graph
103 /// collection it references through the `graph` user property
104 /// (RFC #81-P4). Fails with [`StorageError::Invalid`] if `name` is not a
105 /// vector-space collection or the linked graph is not registered.
106 ///
107 /// The descriptor reports whether the linked graph still describes the
108 /// current vectors ([`GraphStaleness`], #140), computed from current
109 /// registry facts only.
110 fn describe_vector_space(&self, name: &str) -> StorageResult<VectorSpaceDescriptor> {
111 let vectors = self.describe_table(name)?;
112 if vectors.kind != CollectionKind::VectorSpace {
113 return Err(StorageError::Invalid(format!(
114 "collection '{name}' has kind '{}', not a vector space",
115 vectors.kind.as_str()
116 )));
117 }
118 let graph = match vectors.properties.get("graph") {
119 Some(graph_name) => Some(self.describe_table(graph_name)?),
120 None => None,
121 };
122 let graph_staleness = match &graph {
123 None => GraphStaleness::Unlinked,
124 Some(g) => {
125 let rows = vectors
126 .properties
127 .get("rows")
128 .and_then(|v| v.parse::<usize>().ok());
129 match (g.properties.get("source"), g.properties.get("source_rows")) {
130 // Declared lineage is authoritative when present.
131 (Some(source), Some(source_rows)) => {
132 if source == &vectors.name && source_rows.parse::<usize>().ok() == rows {
133 GraphStaleness::Fresh
134 } else {
135 GraphStaleness::Stale
136 }
137 }
138 // Without lineage only a num_nodes/rows divergence is
139 // detectable; an agreement proves nothing about content.
140 _ => {
141 match (
142 g.properties
143 .get("num_nodes")
144 .and_then(|v| v.parse::<usize>().ok()),
145 rows,
146 ) {
147 (Some(num_nodes), Some(rows)) if num_nodes != rows => {
148 GraphStaleness::Stale
149 }
150 _ => GraphStaleness::Unknown,
151 }
152 }
153 }
154 }
155 };
156 Ok(VectorSpaceDescriptor {
157 vectors,
158 graph,
159 graph_staleness,
160 })
161 }
162
163 /// Resolves a graph source against the registry (#140): the source
164 /// must be a registered vector-space collection. Feed the result to
165 /// [`crate::graph::GraphWriteOptions::source`]; the write paths stamp
166 /// it as the reserved `source`/`source_rows` metadata, and
167 /// [`Self::describe_vector_space`] turns the stamp into the
168 /// staleness signal. Lineage reasoning lives here, in the catalog —
169 /// storage write paths only persist declared facts.
170 fn graph_source(&self, name: &str) -> StorageResult<GraphSource> {
171 let table = self.describe_table(name)?;
172 if table.kind != CollectionKind::VectorSpace {
173 return Err(StorageError::Invalid(format!(
174 "graph source '{name}' has kind '{}', not a vector space",
175 table.kind.as_str()
176 )));
177 }
178 let rows = table
179 .properties
180 .get("rows")
181 .and_then(|v| v.parse::<usize>().ok())
182 .ok_or_else(|| {
183 StorageError::Invalid(format!(
184 "graph source '{name}' carries no usable 'rows' fact"
185 ))
186 })?;
187 Ok(GraphSource {
188 name: table.name,
189 rows,
190 })
191 }
192}
193
194/// [`Catalog`] implementation over the existing JSON metadata registry.
195///
196/// The registry wraps an owned [`GeneMetadata`]; mutate through the
197/// [`Catalog`] methods, then persist the instance with
198/// `StorageBackend::save_metadata` (or take it back with
199/// [`LocalRegistry::into_metadata`]).
200#[derive(Debug, Clone)]
201pub struct LocalRegistry {
202 metadata: GeneMetadata,
203 base: PathBuf,
204}
205
206impl LocalRegistry {
207 /// Wraps `metadata`, resolving table locations under `base`.
208 pub fn new(metadata: GeneMetadata, base: PathBuf) -> Self {
209 Self { metadata, base }
210 }
211
212 /// The wrapped metadata (for persistence).
213 pub fn metadata(&self) -> &GeneMetadata {
214 &self.metadata
215 }
216
217 /// Consumes the registry, returning the mutated metadata.
218 pub fn into_metadata(self) -> GeneMetadata {
219 self.metadata
220 }
221
222 fn descriptor(&self, key: &str, info: &FileInfo) -> TableDescriptor {
223 let kind = info
224 .kind
225 .or_else(|| CollectionKind::for_filetype(&info.filetype))
226 .unwrap_or(CollectionKind::Table);
227 let mut properties = BTreeMap::new();
228 properties.insert("filetype".to_string(), info.filetype.clone());
229 properties.insert("storage_format".to_string(), info.storage_format.clone());
230 properties.insert("rows".to_string(), info.rows.to_string());
231 properties.insert("cols".to_string(), info.cols.to_string());
232 if let Some(nnz) = info.nnz {
233 properties.insert("nnz".to_string(), nnz.to_string());
234 }
235 if let Some(size) = info.size_bytes {
236 properties.insert("size_bytes".to_string(), size.to_string());
237 }
238 // User properties overlay the computed ones; `kind` is always the
239 // authoritative typed value.
240 for (k, v) in &info.properties {
241 properties.insert(k.clone(), v.clone());
242 }
243 properties.insert("kind".to_string(), kind.as_str().to_string());
244 // The table format is the leading token of the storage format:
245 // `lance fixed-row` -> `lance`, `arrow-ipc` -> `arrow-ipc`,
246 // `arrow-ipc-stream` -> `arrow-ipc-stream`, `zzarr` -> `zzarr`
247 // (#142). The semantic kind stays `CollectionKind`.
248 let format = info
249 .storage_format
250 .split(' ')
251 .next()
252 .unwrap_or_default()
253 .to_string();
254 TableDescriptor {
255 name: key.to_string(),
256 format,
257 base_location: self.base.join(&info.filename),
258 kind,
259 properties,
260 }
261 }
262}
263
264/// Table formats the registry can describe: the Lance datasets this crate
265/// writes, and the Arrow-IPC interop artifacts (#142). Anything else keeps
266/// its typed rejection.
267const SUPPORTED_TABLE_FORMATS: [&str; 3] = ["lance", "arrow-ipc", "arrow-ipc-stream"];
268
269impl Catalog for LocalRegistry {
270 fn list_tables(&self) -> StorageResult<Vec<TableDescriptor>> {
271 let mut tables: Vec<TableDescriptor> = self
272 .metadata
273 .files
274 .iter()
275 .map(|(key, info)| self.descriptor(key, info))
276 .collect();
277 tables.sort_by(|a, b| a.name.cmp(&b.name));
278 Ok(tables)
279 }
280
281 fn table_exists(&self, name: &str) -> StorageResult<bool> {
282 Ok(self.metadata.files.contains_key(name))
283 }
284
285 fn describe_table(&self, name: &str) -> StorageResult<TableDescriptor> {
286 let info =
287 self.metadata.files.get(name).ok_or_else(|| {
288 StorageError::Invalid(format!("table '{name}' is not registered"))
289 })?;
290 Ok(self.descriptor(name, info))
291 }
292
293 fn register_table(&mut self, table: TableDescriptor) -> StorageResult<()> {
294 if !SUPPORTED_TABLE_FORMATS.contains(&table.format.as_str()) {
295 return Err(StorageError::UnsupportedFormat(format!(
296 "unsupported table format '{}'",
297 table.format
298 )));
299 }
300 let prop = |key: &str| table.properties.get(key).cloned();
301 let parse = |key: &str| -> StorageResult<Option<usize>> {
302 prop(key)
303 .map(|v| {
304 v.parse::<usize>().map_err(|_| {
305 StorageError::Invalid(format!(
306 "property '{key}' = '{v}' is not a valid integer"
307 ))
308 })
309 })
310 .transpose()
311 };
312 // RFC #81-P1: an explicit `kind` property wins; otherwise the typed
313 // `kind` field is authoritative. Unknown kinds and disagreements
314 // between the two are rejected (review PR #96) — silently picking
315 // one side would let a property contradict the descriptor.
316 let kind = match prop("kind") {
317 Some(k) => {
318 let prop_kind = CollectionKind::parse(&k)?;
319 if prop_kind != table.kind {
320 return Err(StorageError::Invalid(format!(
321 "kind mismatch for table '{}': typed field is '{}', \
322 'kind' property is '{}'",
323 table.name,
324 table.kind.as_str(),
325 prop_kind.as_str()
326 )));
327 }
328 Some(prop_kind)
329 }
330 None => Some(table.kind),
331 };
332 // User properties (everything not computed above) are persisted on
333 // the FileInfo so they survive the descriptor -> registry -> describe
334 // round-trip.
335 let user_properties: BTreeMap<String, String> = table
336 .properties
337 .iter()
338 .filter(|(k, _)| !RESERVED_PROPERTIES.contains(&k.as_str()) && k.as_str() != "kind")
339 .map(|(k, v)| (k.clone(), v.clone()))
340 .collect();
341 let mut info = FileInfo::new(
342 table
343 .base_location
344 .file_name()
345 .map(|n| n.to_string_lossy().to_string())
346 .unwrap_or_else(|| {
347 crate::generations::artifact_file_name(&self.metadata.name_id, &table.name)
348 }),
349 prop("filetype").as_deref().unwrap_or("vector"),
350 (parse("rows")?.unwrap_or(0), parse("cols")?.unwrap_or(0)),
351 parse("nnz")?,
352 None,
353 )?;
354 info.kind = kind;
355 if table.format != "lance" {
356 // Preserve a declared non-Lance table format (the IPC interop
357 // formats, #142) as the entry's storage format; Lance entries
358 // keep the filetype-derived format.
359 info.storage_format = table.format.clone();
360 }
361 info.properties = user_properties;
362 self.metadata.files.insert(table.name, info);
363 Ok(())
364 }
365
366 fn deregister_table(&mut self, name: &str) -> StorageResult<()> {
367 if self.metadata.files.remove(name).is_none() {
368 return Err(StorageError::Invalid(format!(
369 "table '{name}' is not registered"
370 )));
371 }
372 Ok(())
373 }
374}