sql_splitter/generate/output.rs
1//! Protected family state, spooling, and atomic publication.
2//!
3//! Generation can produce more state than fits in memory (a family's buffered
4//! child rows) and more than one output that must land together (rendered SQL
5//! plus an emitted model). This module supplies the security-critical
6//! primitives for both:
7//!
8//! * [`ProtectedSpool`] — an owner-only (`0600`) temporary file with a
9//! cryptographically unpredictable name, used to spill buffered rows. Its
10//! name is never printed at normal verbosity because the name alone can leak
11//! workflow details, and the file is removed when the spool is dropped
12//! (success, ordinary failure, or a handled interruption all run `Drop`).
13//! * [`SpoolWriter`]/[`SpoolReader`]/[`SpooledRow`] — a length-prefixed, typed
14//! record format with a version byte. The reader rejects a version mismatch
15//! and an oversized length prefix *before* allocating, so a truncated or
16//! hostile spool cannot drive a huge allocation.
17//! * [`AtomicOutput`] and [`PublicationSet`] — write beside the destination
18//! into a protected temp file and `rename` into place only *after* success.
19//! An existing destination is never truncated before the new content is fully
20//! written and verified; on Unix the published file follows normal
21//! output-file permissions (an existing destination's mode is preserved; a new
22//! destination follows the umask-adjusted default) while the temp stayed
23//! owner-only throughout.
24//! * [`FamilyBuffer`]/[`FamilyState`]/[`FamilyBudget`] — an exact memory budget
25//! for a correlated table family. The buffer keeps rows in memory only while
26//! under budget and spills deterministically to a [`ProtectedSpool`] the
27//! moment a push would cross it, so it never retains every child row in an
28//! unbounded `Vec`.
29//! * [`CancellationToken`] and [`install_interrupt_handler`] — an atomic
30//! cancellation flag that generation/verification loops check and turn into a
31//! cancellation error, backed by a best-effort process-level Ctrl-C handler.
32//!
33//! # Durability caveat
34//!
35//! Cleanup is guard-based: it depends on `Drop` running. A normal return, a
36//! propagated `Err`, and a handled interruption all unwind and remove the
37//! protected files. `SIGKILL`, a power loss, a machine failure, or a
38//! `panic = "abort"` build can still leave a protected temp file behind — there
39//! is no crash-proof cleanup, only owner-only permissions limiting exposure.
40
41use std::fs::{self, File, OpenOptions};
42use std::io::{self, BufWriter, Read, Seek, Write};
43use std::path::{Path, PathBuf};
44use std::sync::atomic::{AtomicBool, Ordering};
45use std::sync::{Arc, Once};
46
47use rand::random;
48
49use super::value::{GenerateError, GeneratedValue};
50
51// --- Spool record framing constants -----------------------------------------
52
53/// The spool record format version. Bumping it invalidates old spools, which is
54/// safe: spools never outlive the run that wrote them.
55const SPOOL_VERSION: u8 = 1;
56
57/// The largest single spool record the reader will accept. A length prefix
58/// larger than this is refused before any allocation.
59///
60/// TODO(deferred, L5): this ceiling is only enforced on the spill path
61/// (`write_record`), so an identical oversized row succeeds when its family
62/// stays in memory. Whether a >64 MiB row is rejected therefore depends on the
63/// family budget rather than the row itself. Enforcing the same per-row ceiling
64/// on the in-memory path would remove the asymmetry; deferred because it only
65/// bites pathologically large single values.
66const MAX_RECORD_BYTES: usize = 64 * 1024 * 1024;
67
68/// The largest single text/bytes field the reader will accept, refused before
69/// allocation.
70const MAX_FIELD_BYTES: usize = 32 * 1024 * 1024;
71
72/// The largest number of fields a single record may declare, refused before
73/// allocation.
74const MAX_FIELDS: u32 = 65_536;
75
76// --- Cancellation ------------------------------------------------------------
77
78/// Set by the process-level interrupt handler; observed by every
79/// [`CancellationToken`]. A `static` (not an `Arc`) because a signal handler can
80/// only touch `'static` data.
81static PROCESS_INTERRUPTED: AtomicBool = AtomicBool::new(false);
82
83/// Guards a single install of the interrupt handler.
84static INSTALL_HANDLER: Once = Once::new();
85
86/// The C signal handler: an async-signal-safe atomic store and nothing else.
87#[cfg(unix)]
88extern "C" fn on_sigint(_signal: libc::c_int) {
89 PROCESS_INTERRUPTED.store(true, Ordering::SeqCst);
90}
91
92/// Install the process-level Ctrl-C (SIGINT) handler exactly once.
93///
94/// The handler only flips an atomic flag every generation/verification loop
95/// already polls through a [`CancellationToken`], so the actual signal wiring
96/// stays minimal. On non-Unix targets this is a no-op and cancellation must be
97/// driven explicitly (e.g. [`CancellationToken::cancel`]); the atomic-flag
98/// mechanism itself is fully portable and testable regardless.
99pub fn install_interrupt_handler() {
100 INSTALL_HANDLER.call_once(|| {
101 #[cfg(unix)]
102 // SAFETY: `on_sigint` performs only an async-signal-safe atomic store,
103 // so installing it as a SIGINT handler is sound. The previous handler
104 // returned by `signal` is intentionally discarded: install is
105 // best-effort and this process owns SIGINT for the run's duration.
106 unsafe {
107 libc::signal(libc::SIGINT, on_sigint as *const () as libc::sighandler_t);
108 }
109 });
110}
111
112/// An atomic cancellation flag that generation/verification loops poll.
113///
114/// Each token owns its own flag (so tests never perturb one another), and every
115/// token additionally observes the process-level interrupt flag set by the
116/// installed Ctrl-C handler. A loop calls [`check`](Self::check) each iteration
117/// and returns the resulting error so registered spool/output guards clean up
118/// as the stack unwinds.
119#[derive(Clone, Default)]
120pub struct CancellationToken(Arc<AtomicBool>);
121
122impl CancellationToken {
123 /// A fresh token, not yet cancelled.
124 pub fn new() -> Self {
125 Self::default()
126 }
127
128 /// Request cancellation. Used by tests and by any caller that decides to
129 /// abort; the installed signal handler flips the process-level flag every
130 /// token also observes.
131 pub fn cancel(&self) {
132 self.0.store(true, Ordering::SeqCst);
133 }
134
135 /// Whether this token (or the process) has been cancelled.
136 ///
137 /// The flag is a single-writer, single-bit latch (never un-set) used only to
138 /// decide whether to stop, so a `Relaxed` load on the polling path is
139 /// sufficient — no other memory is published through it. `cancel` stores with
140 /// `SeqCst` for an unambiguous happens-before with any later observer.
141 pub fn is_cancelled(&self) -> bool {
142 self.0.load(Ordering::Relaxed) || PROCESS_INTERRUPTED.load(Ordering::Relaxed)
143 }
144
145 /// `Ok(())` while running, or a `GEN-CANCELLED` error once cancelled — the
146 /// value a loop returns so its guards run.
147 pub fn check(&self) -> Result<(), GenerateError> {
148 if self.is_cancelled() {
149 Err(GenerateError::diagnostic(
150 &crate::diagnostic::codes::CANCELLED,
151 "runtime",
152 "generation was interrupted",
153 ))
154 } else {
155 Ok(())
156 }
157 }
158}
159
160// --- Temp directory + protected file creation --------------------------------
161
162/// Where protected spool files are created.
163///
164/// Spools are never renamed into a destination, so by default they live in the
165/// OS temp directory; a caller may pin a specific directory (e.g. a fast local
166/// scratch volume). [`AtomicOutput`], by contrast, always writes beside its
167/// destination because atomic `rename` requires the same filesystem.
168#[derive(Debug, Clone, Default)]
169pub struct TempConfig {
170 dir: Option<PathBuf>,
171}
172
173impl TempConfig {
174 /// Spool into `dir` instead of the OS temp directory.
175 pub fn in_dir(dir: impl Into<PathBuf>) -> Self {
176 Self {
177 dir: Some(dir.into()),
178 }
179 }
180
181 /// The directory protected spools are created in.
182 fn dir(&self) -> PathBuf {
183 self.dir.clone().unwrap_or_else(std::env::temp_dir)
184 }
185}
186
187/// A cryptographically unpredictable 256-bit file name with the given prefix.
188///
189/// The name is unguessable so a concurrent local attacker cannot pre-create or
190/// race the protected file, and it is deliberately opaque so nothing about the
191/// workflow leaks through it.
192fn random_name(prefix: &str) -> String {
193 let a: u64 = random();
194 let b: u64 = random();
195 let c: u64 = random();
196 let d: u64 = random();
197 format!("{prefix}{a:016x}{b:016x}{c:016x}{d:016x}.tmp")
198}
199
200/// Create a fresh, exclusively-owned file in `dir`, returning it with its path.
201///
202/// Uses `create_new(true)` (`O_EXCL`) so an existing name is never reused, and
203/// on Unix forces mode `0600` — both at `open` time and with an explicit
204/// `set_permissions` afterward, so the file is owner-only regardless of the
205/// ambient umask. Retries a handful of times if the random name collides.
206fn create_protected_in(dir: &Path, prefix: &str) -> io::Result<(File, PathBuf)> {
207 for _ in 0..16 {
208 let path = dir.join(random_name(prefix));
209 let mut options = OpenOptions::new();
210 options.read(true).write(true).create_new(true);
211 #[cfg(unix)]
212 {
213 use std::os::unix::fs::OpenOptionsExt;
214 options.mode(0o600);
215 }
216 match options.open(&path) {
217 Ok(file) => {
218 #[cfg(unix)]
219 {
220 // Force exactly 0600 even under a restrictive umask that
221 // would otherwise clear owner bits from the open() mode.
222 use std::os::unix::fs::PermissionsExt;
223 fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
224 }
225 return Ok((file, path));
226 }
227 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
228 Err(error) => return Err(error),
229 }
230 }
231 Err(io::Error::new(
232 io::ErrorKind::AlreadyExists,
233 "could not create a unique protected temporary file",
234 ))
235}
236
237// --- Protected spool ---------------------------------------------------------
238
239/// An owner-only temporary file used to spill buffered rows, removed on drop.
240///
241/// The backing file is created with [`create_protected_in`] (mode `0600`,
242/// unpredictable name). Append rows with [`write_row`](Self::write_row), then
243/// [`rewind`](Self::rewind) to read them back. Dropping the spool removes the
244/// file; see the module docs for the SIGKILL/power-loss caveat.
245///
246/// Writes go through one persistent [`BufWriter`] and reuse a single scratch
247/// buffer for the whole spool lifetime, so spilling a large family costs no
248/// per-row writer allocation and does not flush per row — the buffer is flushed
249/// once on [`rewind`](Self::rewind) (or explicitly via [`flush`](Self::flush)).
250pub struct ProtectedSpool {
251 file: BufWriter<File>,
252 path: PathBuf,
253 scratch: Vec<u8>,
254}
255
256impl ProtectedSpool {
257 /// Create a protected spool in `temp`'s directory.
258 pub fn create(temp: &TempConfig) -> io::Result<Self> {
259 let (file, path) = create_protected_in(&temp.dir(), ".sqlspl-spool-")?;
260 Ok(Self {
261 file: BufWriter::new(file),
262 path,
263 scratch: Vec::new(),
264 })
265 }
266
267 /// The spool's backing path. Callers must not print this at normal
268 /// verbosity — the name can leak workflow details.
269 pub fn path(&self) -> &Path {
270 &self.path
271 }
272
273 /// Append one length-prefixed record, reusing the spool's persistent
274 /// buffered writer and scratch buffer (no per-row allocation, no per-row
275 /// flush).
276 pub fn write_row(&mut self, row: &SpooledRow) -> io::Result<()> {
277 write_record(&mut self.file, &mut self.scratch, row)
278 }
279
280 /// Flush buffered writes to the backing file.
281 pub fn flush(&mut self) -> io::Result<()> {
282 self.file.flush()
283 }
284
285 /// Flush buffered writes, seek to the start, and return a reader over the
286 /// spooled records.
287 pub fn rewind(&mut self) -> io::Result<SpoolReader<&mut File>> {
288 self.file.flush()?;
289 let file = self.file.get_mut();
290 file.rewind()?;
291 Ok(SpoolReader::new(file))
292 }
293}
294
295impl Drop for ProtectedSpool {
296 fn drop(&mut self) {
297 let _ = fs::remove_file(&self.path);
298 }
299}
300
301// --- Spool records -----------------------------------------------------------
302
303/// One spooled row: its owning table id, its row index, and its column values.
304#[derive(Debug, Clone, PartialEq)]
305pub struct SpooledRow {
306 /// Index of the owning table within the plan's `tables`.
307 pub table_id: u32,
308 /// Zero-based index of this row within its table.
309 pub row_index: u64,
310 /// Column values, positionally aligned with the table's columns.
311 pub values: Vec<GeneratedValue>,
312}
313
314impl SpooledRow {
315 /// A conservative estimate of this row's in-memory footprint, used to keep a
316 /// [`FamilyBuffer`] inside its byte budget.
317 pub fn estimated_bytes(&self) -> u64 {
318 // table_id + row_index + field count, plus each field's payload.
319 let header = 16u64;
320 header + self.values.iter().map(value_bytes).sum::<u64>()
321 }
322
323 /// Encode the record body (everything after the version+length frame).
324 fn encode_body(&self, out: &mut Vec<u8>) {
325 out.extend_from_slice(&self.table_id.to_le_bytes());
326 out.extend_from_slice(&self.row_index.to_le_bytes());
327 let count = self.values.len() as u32;
328 out.extend_from_slice(&count.to_le_bytes());
329 for value in &self.values {
330 encode_value(value, out);
331 }
332 }
333
334 /// Decode a record body, rejecting oversized field counts and lengths
335 /// before allocating.
336 fn decode_body(body: &[u8]) -> io::Result<Self> {
337 let mut cursor = io::Cursor::new(body);
338 let table_id = read_u32(&mut cursor)?;
339 let row_index = read_u64(&mut cursor)?;
340 let count = read_u32(&mut cursor)?;
341 if count > MAX_FIELDS {
342 return Err(invalid_data("spool record declares too many fields"));
343 }
344 let mut values = Vec::with_capacity(count as usize);
345 for _ in 0..count {
346 values.push(decode_value(&mut cursor)?);
347 }
348 Ok(Self {
349 table_id,
350 row_index,
351 values,
352 })
353 }
354}
355
356/// The heap+inline footprint estimate for one value.
357fn value_bytes(value: &GeneratedValue) -> u64 {
358 match value {
359 GeneratedValue::Null | GeneratedValue::Default | GeneratedValue::Boolean(_) => 1,
360 GeneratedValue::Integer(_) => 16,
361 GeneratedValue::Decimal { .. } => 20,
362 GeneratedValue::Text(text)
363 | GeneratedValue::DateTime(text)
364 | GeneratedValue::Json(text) => text.len() as u64 + 8,
365 GeneratedValue::Bytes(bytes) => bytes.len() as u64 + 8,
366 }
367}
368
369/// Field tag bytes, one per [`GeneratedValue`] variant.
370mod tag {
371 pub const NULL: u8 = 0;
372 pub const DEFAULT: u8 = 1;
373 pub const BOOLEAN: u8 = 2;
374 pub const INTEGER: u8 = 3;
375 pub const DECIMAL: u8 = 4;
376 pub const TEXT: u8 = 5;
377 pub const BYTES: u8 = 6;
378 pub const DATETIME: u8 = 7;
379 pub const JSON: u8 = 8;
380}
381
382fn encode_value(value: &GeneratedValue, out: &mut Vec<u8>) {
383 match value {
384 GeneratedValue::Null => out.push(tag::NULL),
385 GeneratedValue::Default => out.push(tag::DEFAULT),
386 GeneratedValue::Boolean(flag) => {
387 out.push(tag::BOOLEAN);
388 out.push(u8::from(*flag));
389 }
390 GeneratedValue::Integer(value) => {
391 out.push(tag::INTEGER);
392 out.extend_from_slice(&value.to_le_bytes());
393 }
394 GeneratedValue::Decimal { minor, scale } => {
395 out.push(tag::DECIMAL);
396 out.extend_from_slice(&minor.to_le_bytes());
397 out.extend_from_slice(&scale.to_le_bytes());
398 }
399 GeneratedValue::Text(text) => encode_len_prefixed(tag::TEXT, text.as_bytes(), out),
400 GeneratedValue::Bytes(bytes) => encode_len_prefixed(tag::BYTES, bytes, out),
401 GeneratedValue::DateTime(text) => encode_len_prefixed(tag::DATETIME, text.as_bytes(), out),
402 GeneratedValue::Json(text) => encode_len_prefixed(tag::JSON, text.as_bytes(), out),
403 }
404}
405
406fn encode_len_prefixed(tag: u8, bytes: &[u8], out: &mut Vec<u8>) {
407 out.push(tag);
408 out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
409 out.extend_from_slice(bytes);
410}
411
412fn decode_value(cursor: &mut io::Cursor<&[u8]>) -> io::Result<GeneratedValue> {
413 let tag = read_u8(cursor)?;
414 let value = match tag {
415 tag::NULL => GeneratedValue::Null,
416 tag::DEFAULT => GeneratedValue::Default,
417 tag::BOOLEAN => GeneratedValue::Boolean(read_u8(cursor)? != 0),
418 tag::INTEGER => GeneratedValue::Integer(read_i128(cursor)?),
419 tag::DECIMAL => GeneratedValue::Decimal {
420 minor: read_i128(cursor)?,
421 scale: read_u32(cursor)?,
422 },
423 tag::TEXT => GeneratedValue::Text(read_string(cursor)?),
424 tag::BYTES => GeneratedValue::Bytes(read_bytes(cursor)?),
425 tag::DATETIME => GeneratedValue::DateTime(read_string(cursor)?),
426 tag::JSON => GeneratedValue::Json(read_string(cursor)?),
427 other => return Err(invalid_data(&format!("unknown spool field tag {other}"))),
428 };
429 Ok(value)
430}
431
432/// Read a length-prefixed byte field, rejecting an oversized length before
433/// allocating the buffer.
434fn read_bytes(cursor: &mut io::Cursor<&[u8]>) -> io::Result<Vec<u8>> {
435 let len = read_u32(cursor)? as usize;
436 if len > MAX_FIELD_BYTES {
437 return Err(invalid_data("spool field length exceeds the maximum"));
438 }
439 let mut buffer = vec![0u8; len];
440 cursor.read_exact(&mut buffer)?;
441 Ok(buffer)
442}
443
444fn read_string(cursor: &mut io::Cursor<&[u8]>) -> io::Result<String> {
445 let bytes = read_bytes(cursor)?;
446 String::from_utf8(bytes).map_err(|_| invalid_data("spool text field is not valid UTF-8"))
447}
448
449fn read_u8(cursor: &mut io::Cursor<&[u8]>) -> io::Result<u8> {
450 let mut buffer = [0u8; 1];
451 cursor.read_exact(&mut buffer)?;
452 Ok(buffer[0])
453}
454
455fn read_u32(cursor: &mut io::Cursor<&[u8]>) -> io::Result<u32> {
456 let mut buffer = [0u8; 4];
457 cursor.read_exact(&mut buffer)?;
458 Ok(u32::from_le_bytes(buffer))
459}
460
461fn read_u64(cursor: &mut io::Cursor<&[u8]>) -> io::Result<u64> {
462 let mut buffer = [0u8; 8];
463 cursor.read_exact(&mut buffer)?;
464 Ok(u64::from_le_bytes(buffer))
465}
466
467fn read_i128(cursor: &mut io::Cursor<&[u8]>) -> io::Result<i128> {
468 let mut buffer = [0u8; 16];
469 cursor.read_exact(&mut buffer)?;
470 Ok(i128::from_le_bytes(buffer))
471}
472
473fn invalid_data(message: &str) -> io::Error {
474 io::Error::new(io::ErrorKind::InvalidData, message.to_string())
475}
476
477/// Encode `row` into `scratch` and write one framed record — a version byte, a
478/// `u32` body length, then the body — to `writer`. `scratch` is reused across
479/// calls so a hot spooling loop never reallocates the encode buffer.
480fn write_record(
481 writer: &mut impl Write,
482 scratch: &mut Vec<u8>,
483 row: &SpooledRow,
484) -> io::Result<()> {
485 scratch.clear();
486 row.encode_body(scratch);
487 let len = u32::try_from(scratch.len())
488 .map_err(|_| invalid_data("spool record exceeds the maximum size"))?;
489 if scratch.len() > MAX_RECORD_BYTES {
490 return Err(invalid_data("spool record exceeds the maximum size"));
491 }
492 writer.write_all(&[SPOOL_VERSION])?;
493 writer.write_all(&len.to_le_bytes())?;
494 writer.write_all(scratch)?;
495 Ok(())
496}
497
498/// Writes [`SpooledRow`]s as version-tagged, length-prefixed records to any
499/// [`Write`]. [`ProtectedSpool`] has its own buffered [`write_row`] for hot
500/// spilling; this stand-alone writer is for one-off or caller-owned sinks.
501pub struct SpoolWriter<W> {
502 inner: W,
503 scratch: Vec<u8>,
504}
505
506impl<W: Write> SpoolWriter<W> {
507 /// Wrap a writer.
508 pub fn new(inner: W) -> Self {
509 Self {
510 inner,
511 scratch: Vec::new(),
512 }
513 }
514
515 /// Append one record: a version byte, a `u32` body length, then the body.
516 pub fn write_row(&mut self, row: &SpooledRow) -> io::Result<()> {
517 write_record(&mut self.inner, &mut self.scratch, row)
518 }
519
520 /// Flush the underlying writer.
521 pub fn flush(&mut self) -> io::Result<()> {
522 self.inner.flush()
523 }
524}
525
526/// Reads [`SpooledRow`]s written by a [`SpoolWriter`], rejecting a version
527/// mismatch and an oversized length prefix before allocating.
528pub struct SpoolReader<R> {
529 inner: R,
530}
531
532impl<R: Read> SpoolReader<R> {
533 /// Wrap a reader positioned at a record boundary.
534 pub fn new(inner: R) -> Self {
535 Self { inner }
536 }
537
538 /// The next record, or `None` at a clean end of stream.
539 pub fn read_row(&mut self) -> io::Result<Option<SpooledRow>> {
540 let mut version = [0u8; 1];
541 // A clean EOF at a record boundary ends the stream.
542 if !read_one(&mut self.inner, &mut version)? {
543 return Ok(None);
544 }
545 // Reject a version mismatch before reading or allocating the body.
546 if version[0] != SPOOL_VERSION {
547 return Err(invalid_data(&format!(
548 "spool version mismatch: expected {SPOOL_VERSION}, found {}",
549 version[0]
550 )));
551 }
552 let mut len_bytes = [0u8; 4];
553 self.inner.read_exact(&mut len_bytes)?;
554 let len = u32::from_le_bytes(len_bytes) as usize;
555 // Reject an oversized length before allocating the record buffer.
556 if len > MAX_RECORD_BYTES {
557 return Err(invalid_data("spool record length exceeds the maximum"));
558 }
559 let mut body = vec![0u8; len];
560 self.inner.read_exact(&mut body)?;
561 Ok(Some(SpooledRow::decode_body(&body)?))
562 }
563}
564
565/// Read exactly one byte, returning `Ok(false)` at an immediate EOF and
566/// retrying on an interrupted read.
567fn read_one(reader: &mut impl Read, buffer: &mut [u8; 1]) -> io::Result<bool> {
568 loop {
569 match reader.read(buffer) {
570 Ok(0) => return Ok(false),
571 Ok(_) => return Ok(true),
572 Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
573 Err(error) => return Err(error),
574 }
575 }
576}
577
578// --- Atomic output -----------------------------------------------------------
579
580/// Write beside a destination and `rename` into place only after success.
581///
582/// The content is written into a protected (`0600`, unpredictable name) temp
583/// file in the *destination's directory* — the same filesystem, so the final
584/// `rename` is atomic. The destination is never opened for truncation: it keeps
585/// its original bytes until [`commit`](Self::commit) renames the finished temp
586/// over it. On Unix the published file follows normal output-file permissions
587/// (an existing destination's mode is preserved; a new destination follows the
588/// umask-adjusted default), while the temp stayed owner-only throughout. If the
589/// output is dropped without committing, the temp file is removed and the
590/// destination is left untouched.
591pub struct AtomicOutput {
592 destination: PathBuf,
593 temp_path: PathBuf,
594 file: Option<File>,
595 /// The Unix mode to apply to the temp file immediately before rename.
596 preserved_mode: Option<u32>,
597 committed: bool,
598}
599
600impl AtomicOutput {
601 /// Stage a protected temp output beside `destination`.
602 pub fn create(destination: impl AsRef<Path>) -> io::Result<Self> {
603 let destination = destination.as_ref().to_path_buf();
604 let dir = destination
605 .parent()
606 .filter(|parent| !parent.as_os_str().is_empty())
607 .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
608 let (file, temp_path) = create_protected_in(&dir, ".sqlspl-out-")?;
609 let preserved_mode = published_mode(&destination, &dir)?;
610 Ok(Self {
611 destination,
612 temp_path,
613 file: Some(file),
614 preserved_mode,
615 committed: false,
616 })
617 }
618
619 /// The protected temp file to write generated content into.
620 pub fn writer(&mut self) -> &mut File {
621 self.file
622 .as_mut()
623 .expect("AtomicOutput::writer after commit")
624 }
625
626 /// The protected temp path (owner-only while being written).
627 pub fn temp_path(&self) -> &Path {
628 &self.temp_path
629 }
630
631 /// The final destination path.
632 pub fn destination(&self) -> &Path {
633 &self.destination
634 }
635
636 /// Flush and fsync the temp file, apply the published mode, then atomically
637 /// rename it over the destination and fsync the destination's directory so
638 /// the rename itself is durable. Only after this returns `Ok` does the
639 /// destination change.
640 ///
641 /// Atomicity note: `rename(2)` is atomic on Unix (same filesystem, which is
642 /// guaranteed since the temp is a sibling of the destination). On Windows
643 /// `fs::rename` over an existing file is not atomic; this module is
644 /// Unix-first.
645 pub fn commit(mut self) -> io::Result<()> {
646 let mut file = self
647 .file
648 .take()
649 .ok_or_else(|| invalid_data("AtomicOutput already committed"))?;
650 file.flush()?;
651 // Durability of the file contents before the rename that publishes them.
652 file.sync_all()?;
653 drop(file);
654 apply_published_mode(&self.temp_path, self.preserved_mode)?;
655 fs::rename(&self.temp_path, &self.destination)?;
656 // Durability of the rename itself: without a directory fsync a commit
657 // that returned `Ok` could still lose the published directory entry on
658 // power loss right after the rename. A real I/O error here fails the
659 // commit; a filesystem that simply doesn't support directory fsync is
660 // tolerated.
661 sync_parent_dir(&self.destination)?;
662 self.committed = true;
663 Ok(())
664 }
665}
666
667impl Drop for AtomicOutput {
668 fn drop(&mut self) {
669 if !self.committed {
670 let _ = fs::remove_file(&self.temp_path);
671 }
672 }
673}
674
675/// The mode the published file should carry: an existing destination's own mode
676/// (preserved), or — for a new destination — the umask-adjusted mode a normal
677/// output file would get. `None` off Unix, where no mode is applied.
678fn published_mode(destination: &Path, dir: &Path) -> io::Result<Option<u32>> {
679 #[cfg(unix)]
680 {
681 use std::os::unix::fs::MetadataExt;
682 if let Ok(metadata) = fs::metadata(destination) {
683 return Ok(Some(metadata.mode() & 0o777));
684 }
685 // New destination: probe the umask-adjusted default with a normal
686 // create, read its mode, then remove the probe. Read the mode into a
687 // Result first so the probe is removed even when `metadata` fails,
688 // rather than leaking the temp file on that error path.
689 let probe = dir.join(random_name(".sqlspl-probe-"));
690 let file = File::create(&probe)?;
691 let mode = file.metadata().map(|metadata| metadata.mode() & 0o777);
692 drop(file);
693 let _ = fs::remove_file(&probe);
694 Ok(Some(mode?))
695 }
696 #[cfg(not(unix))]
697 {
698 let _ = (destination, dir);
699 Ok(None)
700 }
701}
702
703/// Best-effort fsync of `path`'s parent directory, making a just-completed
704/// `rename` into it durable across power loss.
705///
706/// Opening a directory and calling `fsync` on it is the POSIX way to persist a
707/// directory entry. Some platforms/filesystems refuse a directory `fsync`
708/// (returning an "unsupported" error), which is ignored; a *genuine* I/O error
709/// (e.g. `EIO`) is propagated so `commit` never reports durability it did not
710/// achieve. A no-op off Unix.
711fn sync_parent_dir(path: &Path) -> io::Result<()> {
712 #[cfg(unix)]
713 {
714 let parent = match path.parent() {
715 Some(parent) if !parent.as_os_str().is_empty() => parent,
716 _ => Path::new("."),
717 };
718 let dir = File::open(parent)?;
719 if let Err(err) = dir.sync_all() {
720 if !is_ignorable_dir_sync_error(&err) {
721 return Err(err);
722 }
723 }
724 }
725 #[cfg(not(unix))]
726 {
727 let _ = path;
728 }
729 Ok(())
730}
731
732/// Whether a directory `fsync` error only means "this filesystem does not
733/// support fsync-ing a directory" (safe to ignore) rather than a real I/O
734/// failure. `ENOTSUP`/`EOPNOTSUPP` map to `Unsupported` and `EINVAL` to
735/// `InvalidInput`; anything else (notably `EIO`) is a genuine durability error.
736fn is_ignorable_dir_sync_error(err: &io::Error) -> bool {
737 matches!(
738 err.kind(),
739 io::ErrorKind::Unsupported | io::ErrorKind::InvalidInput
740 )
741}
742
743/// Apply the published mode to the finished temp file before rename.
744fn apply_published_mode(temp_path: &Path, mode: Option<u32>) -> io::Result<()> {
745 #[cfg(unix)]
746 {
747 use std::os::unix::fs::PermissionsExt;
748 if let Some(mode) = mode {
749 fs::set_permissions(temp_path, fs::Permissions::from_mode(mode))?;
750 }
751 }
752 #[cfg(not(unix))]
753 {
754 let _ = (temp_path, mode);
755 }
756 Ok(())
757}
758
759/// A group of [`AtomicOutput`]s published together.
760///
761/// Every staged output writes into its own protected temp file; nothing lands
762/// until [`publish`](Self::publish) renames each into place after all content
763/// is written. Dropping the set without publishing removes every temp file and
764/// leaves all destinations untouched. Publication is per-file atomic (each
765/// `rename` is atomic); it is not a single cross-file transaction, so a failure
766/// partway through can leave earlier renames applied — the individual
767/// no-truncation-before-success guarantee still holds for each destination.
768#[derive(Default)]
769pub struct PublicationSet {
770 outputs: Vec<AtomicOutput>,
771}
772
773impl PublicationSet {
774 /// An empty set.
775 pub fn new() -> Self {
776 Self::default()
777 }
778
779 /// Stage a protected output beside `destination` and return it for writing.
780 pub fn stage(&mut self, destination: impl AsRef<Path>) -> io::Result<&mut AtomicOutput> {
781 self.outputs.push(AtomicOutput::create(destination)?);
782 Ok(self
783 .outputs
784 .last_mut()
785 .expect("just pushed an output onto the set"))
786 }
787
788 /// Publish every staged output by renaming its temp file into place.
789 pub fn publish(self) -> io::Result<()> {
790 for output in self.outputs {
791 output.commit()?;
792 }
793 Ok(())
794 }
795}
796
797/// The outcome of publishing several destinations that are *not* one atomic
798/// cross-file transaction. Each destination's own no-truncation-before-success
799/// guarantee still holds, but a failure partway through can leave earlier
800/// destinations already published; [`PartialPublication`] reports exactly which
801/// destinations landed and which one failed, so a caller never has to pretend
802/// the set was pairwise atomic across filesystems.
803#[derive(Debug)]
804pub struct PartialPublication {
805 /// Destinations that were published before the failure, in publish order.
806 pub published: Vec<PathBuf>,
807 /// The destination whose rename failed.
808 pub failed: PathBuf,
809 /// The underlying I/O error.
810 pub source: io::Error,
811}
812
813impl std::fmt::Display for PartialPublication {
814 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
815 write!(
816 f,
817 "partial publication: failed to publish `{}` ({}); already published: [{}]",
818 self.failed.display(),
819 self.source,
820 self.published
821 .iter()
822 .map(|p| p.display().to_string())
823 .collect::<Vec<_>>()
824 .join(", ")
825 )
826 }
827}
828
829impl std::error::Error for PartialPublication {}
830
831/// Publish a sequence of already-written [`AtomicOutput`]s in order, renaming
832/// each finished temp file over its destination. Returns [`PartialPublication`]
833/// if a rename fails after one or more destinations were already published —
834/// honestly reporting that the set is not atomic across files/filesystems.
835pub fn publish_in_order(outputs: Vec<AtomicOutput>) -> Result<(), PartialPublication> {
836 let mut published = Vec::new();
837 for output in outputs {
838 let destination = output.destination().to_path_buf();
839 match output.commit() {
840 Ok(()) => published.push(destination),
841 Err(source) => {
842 return Err(PartialPublication {
843 published,
844 failed: destination,
845 source,
846 })
847 }
848 }
849 }
850 Ok(())
851}
852
853// --- Family state + budget ---------------------------------------------------
854
855/// An exact memory budget (in bytes) for a correlated table family's buffered
856/// rows. Once a family's buffered rows would exceed it, the buffer spills to a
857/// protected spool rather than growing without bound.
858#[derive(Debug, Clone, Copy, PartialEq, Eq)]
859pub struct FamilyBudget {
860 /// The maximum number of buffered bytes to hold in memory.
861 pub max_bytes: u64,
862}
863
864impl Default for FamilyBudget {
865 fn default() -> Self {
866 // A conservative default; a compiled plan supplies an exact budget.
867 Self {
868 max_bytes: 64 * 1024 * 1024,
869 }
870 }
871}
872
873/// Which kind of family rows a spool holds, for observability.
874#[derive(Debug, Clone, Copy, PartialEq, Eq)]
875pub enum SpillKind {
876 /// Buffered child rows of a family.
877 Child,
878 /// Buffered rows of a single table.
879 Table,
880}
881
882/// Where a [`FamilyBuffer`]'s rows currently live.
883pub enum FamilyState {
884 /// In memory, within budget: the family's parent/aggregate rows.
885 ParentState(Vec<SpooledRow>),
886 /// Spilled child rows in a protected spool.
887 ChildSpool(ProtectedSpool),
888 /// Spilled table rows in a protected spool.
889 TableSpool(ProtectedSpool),
890}
891
892/// Incremental replay of buffered family rows.
893///
894/// In-memory rows are moved into an owning iterator. Spilled rows are decoded
895/// one record at a time from the protected spool, so replay retains at most one
896/// decoded row instead of rebuilding the complete family in memory.
897pub enum FamilyRowReplay<'a> {
898 /// Rows that remained within the configured memory budget.
899 Memory(std::vec::IntoIter<SpooledRow>),
900 /// Rows decoded incrementally from a protected spool.
901 Spool(SpoolReader<&'a mut File>),
902}
903
904impl Iterator for FamilyRowReplay<'_> {
905 type Item = io::Result<SpooledRow>;
906
907 fn next(&mut self) -> Option<Self::Item> {
908 match self {
909 Self::Memory(rows) => rows.next().map(Ok),
910 Self::Spool(reader) => reader.read_row().transpose(),
911 }
912 }
913}
914
915/// Buffers a family's rows under an exact byte budget, spilling deterministically
916/// to a [`ProtectedSpool`] the moment a push would cross the budget.
917///
918/// The buffer never retains every child row in an unbounded `Vec`: once spilled,
919/// each further row is written straight to the protected spool. The spill
920/// decision is deterministic — it depends only on the (fixed) budget and the
921/// rows pushed, not on wall-clock or allocation timing — so a given plan spills
922/// identically on every run.
923pub struct FamilyBuffer {
924 budget: u64,
925 used: u64,
926 table_id: u32,
927 temp: TempConfig,
928 spill_kind: SpillKind,
929 state: FamilyState,
930 /// Whether the rows have already been replayed. Replay is single-shot: the
931 /// in-memory state is drained on first replay, so a second call would
932 /// silently yield nothing. Guard against that so a future second pass fails
933 /// loudly instead — the spilled and in-memory arms stay consistent.
934 replayed: bool,
935}
936
937impl FamilyBuffer {
938 /// A buffer that starts in memory and spills on demand.
939 pub fn new(
940 budget: FamilyBudget,
941 table_id: u32,
942 temp: TempConfig,
943 spill_kind: SpillKind,
944 ) -> Self {
945 Self {
946 budget: budget.max_bytes,
947 used: 0,
948 table_id,
949 temp,
950 spill_kind,
951 state: FamilyState::ParentState(Vec::new()),
952 replayed: false,
953 }
954 }
955
956 /// A buffer that chooses its storage up front from an estimate: if the
957 /// family is already known to exceed the budget it spills before the first
958 /// row, avoiding a transient in-memory spike.
959 pub fn with_estimate(
960 budget: FamilyBudget,
961 table_id: u32,
962 temp: TempConfig,
963 spill_kind: SpillKind,
964 estimated_bytes: u64,
965 ) -> io::Result<Self> {
966 let mut buffer = Self::new(budget, table_id, temp, spill_kind);
967 if estimated_bytes > buffer.budget {
968 buffer.spill()?;
969 }
970 Ok(buffer)
971 }
972
973 /// The table id every pushed row is expected to carry.
974 pub fn table_id(&self) -> u32 {
975 self.table_id
976 }
977
978 /// Whether the buffer has spilled to disk.
979 pub fn is_spilled(&self) -> bool {
980 !matches!(self.state, FamilyState::ParentState(_))
981 }
982
983 /// The current storage state.
984 pub fn state(&self) -> &FamilyState {
985 &self.state
986 }
987
988 /// Buffer one row, spilling to a protected spool if it would cross the
989 /// budget.
990 pub fn push(&mut self, row: SpooledRow) -> io::Result<()> {
991 if self.is_spilled() {
992 return self.write_spilled(&row);
993 }
994 let size = row.estimated_bytes();
995 if self.used + size <= self.budget {
996 self.used += size;
997 if let FamilyState::ParentState(rows) = &mut self.state {
998 rows.push(row);
999 }
1000 Ok(())
1001 } else {
1002 // Crossing the budget: move what we have to a spool, then append.
1003 self.spill()?;
1004 self.write_spilled(&row)
1005 }
1006 }
1007
1008 /// Replay buffered rows in push order without materializing a spilled
1009 /// family in memory.
1010 pub fn replay_rows(&mut self) -> io::Result<FamilyRowReplay<'_>> {
1011 if self.replayed {
1012 return Err(invalid_data(
1013 "FamilyBuffer::replay_rows is single-shot and was already replayed",
1014 ));
1015 }
1016 self.replayed = true;
1017 match &mut self.state {
1018 FamilyState::ParentState(rows) => {
1019 Ok(FamilyRowReplay::Memory(std::mem::take(rows).into_iter()))
1020 }
1021 FamilyState::ChildSpool(spool) | FamilyState::TableSpool(spool) => {
1022 Ok(FamilyRowReplay::Spool(spool.rewind()?))
1023 }
1024 }
1025 }
1026
1027 /// Collect every buffered row in push order.
1028 ///
1029 /// Prefer [`replay_rows`](Self::replay_rows) on generation paths: this
1030 /// compatibility helper intentionally materializes the result for callers
1031 /// that need an owned collection.
1032 pub fn drain_rows(&mut self) -> io::Result<Vec<SpooledRow>> {
1033 self.replay_rows()?.collect()
1034 }
1035
1036 /// Move any in-memory rows into a fresh protected spool and switch state.
1037 ///
1038 /// Rows go through the spool's persistent buffered writer; no per-row flush
1039 /// — buffered writes are flushed once when the spool is later drained.
1040 fn spill(&mut self) -> io::Result<()> {
1041 let mut spool = ProtectedSpool::create(&self.temp)?;
1042 if let FamilyState::ParentState(rows) = &self.state {
1043 for row in rows {
1044 spool.write_row(row)?;
1045 }
1046 }
1047 self.state = match self.spill_kind {
1048 SpillKind::Child => FamilyState::ChildSpool(spool),
1049 SpillKind::Table => FamilyState::TableSpool(spool),
1050 };
1051 Ok(())
1052 }
1053
1054 /// Append a row directly to the active spool's buffered writer (no per-row
1055 /// flush; the buffer is flushed once at drain).
1056 fn write_spilled(&mut self, row: &SpooledRow) -> io::Result<()> {
1057 match &mut self.state {
1058 FamilyState::ChildSpool(spool) | FamilyState::TableSpool(spool) => spool.write_row(row),
1059 // `push`/`with_estimate` only reach here after `spill`, so the state
1060 // is always a spool; treat an in-memory state as a no-op rather than
1061 // panicking.
1062 FamilyState::ParentState(_) => Ok(()),
1063 }
1064 }
1065}
1066
1067#[cfg(test)]
1068mod tests {
1069 use super::*;
1070
1071 #[test]
1072 fn directory_fsync_errors_distinguish_unsupported_from_real_io() {
1073 // "Filesystem doesn't support a directory fsync" is ignorable; a genuine
1074 // I/O error must propagate so `commit` never reports false durability.
1075 assert!(is_ignorable_dir_sync_error(&io::Error::from(
1076 io::ErrorKind::Unsupported
1077 )));
1078 assert!(is_ignorable_dir_sync_error(&io::Error::from(
1079 io::ErrorKind::InvalidInput
1080 )));
1081 assert!(!is_ignorable_dir_sync_error(&io::Error::other(
1082 "input/output error"
1083 )));
1084 }
1085
1086 #[test]
1087 fn family_buffer_replay_is_single_shot() {
1088 // Replay drains the in-memory rows, so a second replay would silently
1089 // yield an empty family. It must fail loudly instead, keeping the
1090 // in-memory and spilled arms consistent.
1091 let mut buffer = FamilyBuffer::new(
1092 FamilyBudget::default(),
1093 0,
1094 TempConfig::default(),
1095 SpillKind::Child,
1096 );
1097 buffer
1098 .push(SpooledRow {
1099 table_id: 0,
1100 row_index: 0,
1101 values: vec![GeneratedValue::Integer(1)],
1102 })
1103 .unwrap();
1104 assert!(buffer.replay_rows().is_ok());
1105 assert!(
1106 buffer.replay_rows().is_err(),
1107 "a second replay must fail loudly, not silently return an empty family"
1108 );
1109 }
1110
1111 #[test]
1112 fn spool_round_trip_preserves_every_value_shape() {
1113 let temp = TempConfig::default();
1114 let mut spool = ProtectedSpool::create(&temp).unwrap();
1115 let row = SpooledRow {
1116 table_id: 9,
1117 row_index: 3,
1118 values: vec![
1119 GeneratedValue::Null,
1120 GeneratedValue::Integer(-1),
1121 GeneratedValue::Text("x".into()),
1122 GeneratedValue::Bytes(vec![1, 2, 3]),
1123 ],
1124 };
1125 spool.write_row(&row).unwrap();
1126 let mut reader = spool.rewind().unwrap();
1127 assert_eq!(reader.read_row().unwrap(), Some(row));
1128 assert_eq!(reader.read_row().unwrap(), None);
1129 }
1130
1131 #[test]
1132 fn cancellation_token_is_independent_per_instance() {
1133 let a = CancellationToken::new();
1134 let b = CancellationToken::new();
1135 a.cancel();
1136 assert!(a.is_cancelled());
1137 assert!(!b.is_cancelled());
1138 }
1139}