genegraph_storage/generations.rs
1//! # Transactional generations (genegraph-storage #93, RFC #81 phase P5).
2//!
3//! Artifact generations are **immutable**: every publish (build, append,
4//! recompute) mints a fresh generation `{logical}__g{N}` — its artifacts are
5//! written once and never overwritten — and commits by atomically publishing
6//! the generation's metadata JSON (the single commit pointer, mirroring the
7//! snapshot/consensus-index pattern of segmented logs).
8//!
9//! Invariants:
10//! - A generation without a metadata file **was never committed**: readers
11//! and discovery ignore it; the sweep API sees it for garbage collection.
12//! - The commit itself is a single atomic filesystem operation
13//! ([`write_json_atomic`]): readers observe either the previous file or
14//! the complete new one, never a partial write.
15//! - Reader isolation (#97): pin acquisition (validation + registration) and
16//! the sweep's check-to-retirement transition are serialized by a
17//! per-generation state lock — a sweep never removes artifacts under a
18//! registered reader, and a pin never registers for a retired generation.
19//! - `__g{digits}` at the end of an instance name is reserved.
20
21use std::collections::HashMap;
22use std::path::{Path, PathBuf};
23use std::sync::{Arc, Mutex as StdMutex, OnceLock, Weak};
24
25use crate::{StorageError, StorageResult};
26
27/// Separator between a logical dataset name and its generation number.
28pub const GENERATION_SEP: &str = "__g";
29
30/// Logical dataset name: strips a trailing `__g{digits}` generation suffix.
31pub fn logical_name(name: &str) -> &str {
32 if let Some(pos) = name.rfind(GENERATION_SEP) {
33 let suffix = &name[pos + GENERATION_SEP.len()..];
34 if !suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_digit()) {
35 return &name[..pos];
36 }
37 }
38 name
39}
40
41/// Generation-qualified instance name: `{logical}__g{gen}`.
42pub fn generation_name(logical: &str, generation: u64) -> String {
43 format!("{logical}{GENERATION_SEP}{generation}")
44}
45
46/// Parse the generation number out of a gen-qualified instance name.
47/// Returns `None` for plain logical names or malformed suffixes.
48///
49/// Note (#95): digit suffixes above `u64::MAX` parse to `None` here; the
50/// scanners combine this with a `unwrap_or(u64::MAX)` fallback so such names
51/// sort last consistently instead of crashing discovery.
52pub fn parse_generation(name: &str) -> Option<u64> {
53 let pos = name.rfind(GENERATION_SEP)?;
54 let suffix = &name[pos + GENERATION_SEP.len()..];
55 if suffix.is_empty() || !suffix.bytes().all(|b| b.is_ascii_digit()) {
56 return None;
57 }
58 suffix.parse().ok()
59}
60
61/// Reject instance names carrying the reserved generation suffix
62/// (`__g{digits}`). Only [`generation_name`] may mint such names; a
63/// user-created logical instance with a reserved suffix would collide with
64/// the generation discovery and sweep machinery (#117-3).
65pub fn validate_logical_name(name: &str) -> StorageResult<()> {
66 if parse_generation(name).is_some() {
67 return Err(StorageError::Invalid(format!(
68 "instance name `{name}` carries the reserved generation suffix \
69 `{GENERATION_SEP}<n>`; generation handles are minted only via \
70 scoped_generation"
71 )));
72 }
73 Ok(())
74}
75
76/// File name of a per-instance artifact dataset: `{instance}_{key}.lance`.
77///
78/// Single source of the on-disk naming convention (#117-3): every producer
79/// (paths, registered `FileInfo` names) builds it here so the two roles
80/// cannot drift apart.
81pub fn artifact_file_name(instance: &str, key: &str) -> String {
82 artifact_file_name_ext(instance, key, "lance")
83}
84
85/// File name of a per-instance artifact with an explicit extension:
86/// `{instance}_{key}.{ext}` (the extension-general form of
87/// [`artifact_file_name`], used by the Arrow-IPC interop path, #142).
88pub fn artifact_file_name_ext(instance: &str, key: &str, ext: &str) -> String {
89 format!("{instance}_{key}.{ext}")
90}
91
92/// File name of the per-instance metadata registry: `{instance}_metadata.json`.
93pub fn metadata_file_name(instance: &str) -> String {
94 format!("{instance}_metadata.json")
95}
96
97/// Full artifact dataset path: `{base}/{instance}_{key}.lance`.
98pub fn artifact_file_path(base: &Path, instance: &str, key: &str) -> PathBuf {
99 base.join(artifact_file_name(instance, key))
100}
101
102/// Full artifact path with an explicit extension:
103/// `{base}/{instance}_{key}.{ext}` (#142).
104pub fn artifact_file_path_ext(base: &Path, instance: &str, key: &str, ext: &str) -> PathBuf {
105 base.join(artifact_file_name_ext(instance, key, ext))
106}
107
108/// Full metadata registry path: `{base}/{instance}_metadata.json`.
109pub fn metadata_file_path(base: &Path, instance: &str) -> PathBuf {
110 base.join(metadata_file_name(instance))
111}
112
113/// A committed generation: its number and the metadata file that pins it.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct GenerationInfo {
116 pub generation: u64,
117 pub metadata_path: PathBuf,
118}
119
120/// Committed generations of `logical` under `base`, ascending by generation
121/// number. A generation is committed iff its `{logical}__g{N}_metadata.json`
122/// exists; pre-commit crash residue is invisible here.
123pub async fn list_generations(base: &Path, logical: &str) -> StorageResult<Vec<GenerationInfo>> {
124 let mut out = Vec::new();
125 for (generation, metadata_path) in scan_generation_paths(base, logical).await? {
126 if metadata_path.is_file() {
127 out.push(GenerationInfo {
128 generation,
129 metadata_path,
130 });
131 }
132 }
133 out.sort_by_key(|g| g.generation);
134 Ok(out)
135}
136
137/// Generation numbers with **any** artifact present under `base`, committed
138/// or not (orphans from a pre-commit crash included), ascending.
139pub async fn list_artifact_generations(base: &Path, logical: &str) -> StorageResult<Vec<u64>> {
140 let mut gens = std::collections::BTreeSet::new();
141 let mut rd = tokio::fs::read_dir(base)
142 .await
143 .map_err(|e| StorageError::Io(e.to_string()))?;
144 let artifact_prefix = format!("{logical}{GENERATION_SEP}");
145 while let Some(entry) = rd
146 .next_entry()
147 .await
148 .map_err(|e| StorageError::Io(e.to_string()))?
149 {
150 let name = entry.file_name();
151 let name = name.to_string_lossy();
152 let Some(rest) = name.strip_prefix(&artifact_prefix) else {
153 continue;
154 };
155 let Some(num) = rest.split('_').next() else {
156 continue;
157 };
158 if !num.is_empty() && num.bytes().all(|b| b.is_ascii_digit()) {
159 gens.insert(num.parse::<u64>().unwrap_or(u64::MAX));
160 }
161 }
162 Ok(gens.into_iter().collect())
163}
164
165/// Delete every file of a generation — artifacts and, if present, the
166/// metadata commit pointer. Prefix matching is exact on
167/// `{logical}__g{gen}_`, so sibling datasets (`ds` vs `ds2`) are untouched.
168/// Safe to call on orphaned generations (no metadata) and on missing ones.
169///
170/// Reader isolation (#97): the pin check through the *complete removal* runs
171/// inside one per-generation state lock — the retirement transition is
172/// atomic with respect to [`pin_generation`], which validates and registers
173/// under that same lock. A pin attempt that races a sweep either precedes
174/// the sweep's lock acquisition (the sweep then sees the pin and is refused
175/// with [`StorageError::InvalidState`]) or waits for retirement to finish
176/// (and then fails validation, because the commit pointer is gone). A sweep
177/// can therefore never delete underneath a registered reader. Callers retry
178/// a refused sweep once their readers have released.
179pub async fn delete_generation(base: &Path, logical: &str, generation: u64) -> StorageResult<()> {
180 let prefix = format!("{logical}{GENERATION_SEP}{generation}_");
181 let metadata_path = base.join(format!("{prefix}metadata.json"));
182 // Resolve (or mint) the generation's state lock up front, then run the
183 // whole check-to-retirement critical section synchronously under it on
184 // the blocking pool: std locks must not be held across awaits.
185 let state = crate::commit::weak_lookup(
186 &GENERATION_STATES,
187 metadata_path.to_string_lossy().to_string(),
188 Arc::new(StdMutex::new(GenerationState::default())),
189 );
190 sweep_gate(SWEEP_GATE_PRE_LOCK);
191 let base = base.to_path_buf();
192 let logical = logical.to_string();
193 tokio::task::spawn_blocking(move || -> StorageResult<()> {
194 let state = state
195 .lock()
196 .unwrap_or_else(|poisoned| poisoned.into_inner());
197 if state.pins > 0 {
198 return Err(StorageError::InvalidState(format!(
199 "generation {generation} of '{logical}' is pinned by an in-flight reader; \
200 sweep refused until all readers release"
201 )));
202 }
203 // Past the check and still under the lock: no pin can register for
204 // this generation until the removals complete (test hook forces a
205 // pin attempt exactly in this window).
206 sweep_gate(SWEEP_GATE_POST_CHECK);
207 let rd = std::fs::read_dir(&base)
208 .map_err(|e| StorageError::Io(format!("read {base:?}: {e}")))?;
209 let mut removed = Vec::new();
210 for entry in rd {
211 let entry = entry.map_err(|e| StorageError::Io(e.to_string()))?;
212 if !entry.file_name().to_string_lossy().starts_with(&prefix) {
213 continue;
214 }
215 removed.push(entry.path());
216 }
217 for path in removed {
218 if path.is_dir() {
219 std::fs::remove_dir_all(&path)
220 .map_err(|e| StorageError::Io(format!("remove {path:?}: {e}")))?;
221 } else {
222 std::fs::remove_file(&path)
223 .map_err(|e| StorageError::Io(format!("remove {path:?}: {e}")))?;
224 }
225 }
226 Ok(())
227 })
228 .await
229 .map_err(|e| StorageError::Io(format!("generation sweep task failed: {e}")))?
230}
231
232// ---------------------------------------------------------------------------
233// Reader pins (#97)
234// ---------------------------------------------------------------------------
235
236/// Per-generation pin state; the lock guarding the state serializes pin
237/// registration/validation against the sweep's retirement transition.
238#[derive(Debug, Default)]
239struct GenerationState {
240 pins: usize,
241}
242
243/// Weak-valued registry of per-generation state locks (the #98 discipline):
244/// entries live only while a pin or an in-flight sweep holds the `Arc`.
245static GENERATION_STATES: OnceLock<StdMutex<HashMap<String, Weak<StdMutex<GenerationState>>>>> =
246 OnceLock::new();
247
248/// RAII pin on a committed generation (#97).
249///
250/// Acquired through [`pin_generation`]; while alive, it keeps one reference
251/// on the generation's state so a concurrent [`delete_generation`] refuses
252/// to touch it. Dropping the guard releases the reference.
253#[derive(Debug)]
254pub struct GenerationGuard {
255 state: Arc<StdMutex<GenerationState>>,
256}
257
258impl Drop for GenerationGuard {
259 fn drop(&mut self) {
260 let mut state = self
261 .state
262 .lock()
263 .unwrap_or_else(|poisoned| poisoned.into_inner());
264 state.pins -= 1;
265 }
266}
267
268/// Pins a committed generation for the duration of a read (#97).
269///
270/// Registration is refcounted per generation: several readers may pin the
271/// same generation concurrently and all succeed; a sweep is refused while
272/// any pin is alive. Validation (commit pointer exists) and registration
273/// happen atomically with respect to [`delete_generation`]'s retirement
274/// transition — both hold the generation's state lock, so a racing sweep
275/// either observes this pin (and is refused) or has already retired the
276/// generation (and this call fails validation).
277///
278/// Fails with [`StorageError::Invalid`] if the generation's metadata file
279/// (the commit pointer) does not exist — orphaned generations cannot be
280/// pinned. Pin and sweep must address the generation through the same
281/// `base` path: state is keyed by the metadata file path.
282pub fn pin_generation(info: &GenerationInfo) -> StorageResult<GenerationGuard> {
283 let state = crate::commit::weak_lookup(
284 &GENERATION_STATES,
285 info.metadata_path.to_string_lossy().to_string(),
286 Arc::new(StdMutex::new(GenerationState::default())),
287 );
288 {
289 let mut guard = state
290 .lock()
291 .unwrap_or_else(|poisoned| poisoned.into_inner());
292 // Validation under the state lock: a concurrent sweep either
293 // finished its retirement (metadata gone -> rejected here) or waits
294 // for this pin to register (and is then refused).
295 if !info.metadata_path.is_file() {
296 return Err(StorageError::Invalid(format!(
297 "generation {} is not committed (no metadata at {:?}); \
298 only committed generations can be pinned",
299 info.generation, info.metadata_path
300 )));
301 }
302 guard.pins += 1;
303 }
304 Ok(GenerationGuard { state })
305}
306
307/// Atomic JSON publish: write to a unique `{path}.tmp`, fsync, rename over
308/// `path`, then fsync the parent directory (#101).
309///
310/// The rename is the single commit point (POSIX-atomic within a directory):
311/// concurrent readers observe either the previous file or the complete new
312/// one, never a truncated write. The post-rename directory fsync makes the
313/// rename itself durable — without it, a crash can revert the metadata
314/// commit pointer (the single atomic commit of a generation, #93) to the
315/// previous generation, or lose it entirely on a first commit.
316///
317/// This is the ONLY sanctioned way to publish a metadata file. The tmp name
318/// is uuid-unique (#95) so concurrent publishers of the same path cannot
319/// corrupt each other's staging file; the last rename wins, which makes
320/// last-writer-wins explicit instead of interleaved.
321pub fn write_json_atomic(path: &Path, contents: &str) -> StorageResult<()> {
322 use std::io::Write;
323
324 let tmp = path.with_extension(format!("json.tmp.{}", uuid::Uuid::new_v4().simple()));
325 let parent = path.parent().unwrap_or_else(|| Path::new("."));
326 // `parent()` yields "" for bare filenames; resolve it to the working
327 // directory so the fsync discipline below has a real handle to sync.
328 let parent = if parent.as_os_str().is_empty() {
329 Path::new(".")
330 } else {
331 parent
332 };
333 if !parent.exists() {
334 std::fs::create_dir_all(parent).map_err(|e| StorageError::Io(e.to_string()))?;
335 // The fresh directory itself must be durable before anything is
336 // published inside it: fsync it and its parent so both directory
337 // entries survive a crash (#101).
338 if let Some(grandparent) = parent.parent()
339 && !grandparent.as_os_str().is_empty()
340 {
341 fsync_dir(grandparent)?;
342 }
343 fsync_dir(parent)?;
344 }
345 {
346 let mut f = std::fs::File::create(&tmp).map_err(|e| StorageError::Io(e.to_string()))?;
347 f.write_all(contents.as_bytes())
348 .map_err(|e| StorageError::Io(e.to_string()))?;
349 f.sync_all().map_err(|e| StorageError::Io(e.to_string()))?;
350 }
351 std::fs::rename(&tmp, path).map_err(|e| StorageError::Io(e.to_string()))?;
352 fsync_dir(parent)
353}
354
355/// fsyncs a directory so a completed rename is itself durable
356/// (directory-entry durability, #101 / lancefmt #95-3). No-op off unix.
357pub(crate) fn fsync_dir(dir: &Path) -> StorageResult<()> {
358 #[cfg(unix)]
359 {
360 let f = std::fs::File::open(dir)
361 .map_err(|e| StorageError::Io(format!("open dir {dir:?} for fsync: {e}")))?;
362 f.sync_all()
363 .map_err(|e| StorageError::Io(format!("fsync dir {dir:?}: {e}")))?;
364 }
365 #[cfg(not(unix))]
366 let _ = dir;
367 Ok(())
368}
369
370/// `(generation, metadata_path)` pairs implied by `{logical}__g{N}_metadata.json`
371/// names under `base` (the file itself may or may not exist).
372async fn scan_generation_paths(base: &Path, logical: &str) -> StorageResult<Vec<(u64, PathBuf)>> {
373 let mut out = Vec::new();
374 let mut rd = tokio::fs::read_dir(base)
375 .await
376 .map_err(|e| StorageError::Io(e.to_string()))?;
377 let prefix = format!("{logical}{GENERATION_SEP}");
378 while let Some(entry) = rd
379 .next_entry()
380 .await
381 .map_err(|e| StorageError::Io(e.to_string()))?
382 {
383 let name = entry.file_name();
384 let name = name.to_string_lossy().into_owned();
385 let Some(rest) = name.strip_prefix(&prefix) else {
386 continue;
387 };
388 let Some(meta) = rest.strip_suffix("_metadata.json") else {
389 continue;
390 };
391 if !meta.is_empty() && meta.bytes().all(|b| b.is_ascii_digit()) {
392 out.push((meta.parse().unwrap_or(u64::MAX), entry.path()));
393 }
394 }
395 Ok(out)
396}
397
398// ---------------------------------------------------------------------------
399// Test-only sweep gates (PR #99 review): force deterministic interleavings
400// of pin attempts against the sweep's critical section.
401// ---------------------------------------------------------------------------
402
403pub(crate) const SWEEP_GATE_PRE_LOCK: usize = 0;
404pub(crate) const SWEEP_GATE_POST_CHECK: usize = 1;
405
406// Non-test builds compile the gate calls away entirely.
407#[cfg(not(test))]
408fn sweep_gate(_stage: usize) {}
409
410#[cfg(test)]
411fn sweep_gates() -> &'static StdMutex<[Option<SweepGate>; 2]> {
412 static GATES: OnceLock<StdMutex<[Option<SweepGate>; 2]>> = OnceLock::new();
413 GATES.get_or_init(|| StdMutex::new([None, None]))
414}
415
416/// A gate the sweep must pass through: it signals `arrived` (so tests know
417/// the sweep is parked exactly at the stage) and blocks until `release`.
418#[cfg(test)]
419struct SweepGate {
420 arrived: std::sync::mpsc::Sender<()>,
421 release: std::sync::mpsc::Receiver<()>,
422}
423
424/// Arms a gate: the next sweep to reach `stage` signals the returned
425/// receiver and parks until the returned sender fires. Fires once.
426#[cfg(test)]
427pub(crate) fn arm_sweep_gate(
428 stage: usize,
429) -> (std::sync::mpsc::Receiver<()>, std::sync::mpsc::Sender<()>) {
430 let (arrived_tx, arrived_rx) = std::sync::mpsc::channel();
431 let (release_tx, release_rx) = std::sync::mpsc::channel();
432 let mut gates = sweep_gates()
433 .lock()
434 .unwrap_or_else(|poisoned| poisoned.into_inner());
435 gates[stage] = Some(SweepGate {
436 arrived: arrived_tx,
437 release: release_rx,
438 });
439 (arrived_rx, release_tx)
440}
441
442/// Blocks the sweep at `stage` if a gate is armed there (consumes it).
443#[cfg(test)]
444fn sweep_gate(stage: usize) {
445 let gate = sweep_gates()
446 .lock()
447 .unwrap_or_else(|poisoned| poisoned.into_inner())
448 .get_mut(stage)
449 .unwrap()
450 .take();
451 if let Some(gate) = gate {
452 // park: the test now knows exactly where the sweep is
453 let _ = gate.arrived.send(());
454 let _ = gate.release.recv();
455 }
456}