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 /// True when writing straight to `destination` (a non-regular file such as
599 /// `/dev/null`): there is no sibling temp and no rename on commit.
600 direct: bool,
601}
602
603impl AtomicOutput {
604 /// Stage a protected temp output beside `destination`.
605 pub fn create(destination: impl AsRef<Path>) -> io::Result<Self> {
606 let destination = destination.as_ref().to_path_buf();
607
608 // A non-regular destination (a character device like `/dev/null`, a
609 // FIFO, or a socket) can't be published by staging a sibling temp and
610 // renaming over it: its directory may be unwritable (e.g. `/dev`) and
611 // an atomic replace is meaningless for it. Write straight through.
612 if is_non_regular_file(&destination) {
613 let file = OpenOptions::new().write(true).open(&destination)?;
614 return Ok(Self {
615 temp_path: destination.clone(),
616 destination,
617 file: Some(file),
618 preserved_mode: None,
619 committed: false,
620 direct: true,
621 });
622 }
623
624 let dir = destination
625 .parent()
626 .filter(|parent| !parent.as_os_str().is_empty())
627 .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
628 let (file, temp_path) = create_protected_in(&dir, ".sqlspl-out-")?;
629 let preserved_mode = published_mode(&destination, &dir)?;
630 Ok(Self {
631 destination,
632 temp_path,
633 file: Some(file),
634 preserved_mode,
635 committed: false,
636 direct: false,
637 })
638 }
639
640 /// The protected temp file to write generated content into.
641 pub fn writer(&mut self) -> &mut File {
642 self.file
643 .as_mut()
644 .expect("AtomicOutput::writer after commit")
645 }
646
647 /// The protected temp path (owner-only while being written).
648 pub fn temp_path(&self) -> &Path {
649 &self.temp_path
650 }
651
652 /// The final destination path.
653 pub fn destination(&self) -> &Path {
654 &self.destination
655 }
656
657 /// Flush and fsync the temp file, apply the published mode, then atomically
658 /// rename it over the destination and fsync the destination's directory so
659 /// the rename itself is durable. Only after this returns `Ok` does the
660 /// destination change.
661 ///
662 /// Atomicity note: `rename(2)` is atomic on Unix (same filesystem, which is
663 /// guaranteed since the temp is a sibling of the destination). On Windows
664 /// `fs::rename` over an existing file is not atomic; this module is
665 /// Unix-first.
666 pub fn commit(mut self) -> io::Result<()> {
667 let mut file = self
668 .file
669 .take()
670 .ok_or_else(|| invalid_data("AtomicOutput already committed"))?;
671 file.flush()?;
672 if self.direct {
673 // Bytes already went to the destination; there is nothing to rename.
674 // `sync_all` may be unsupported on a special file, so tolerate it.
675 let _ = file.sync_all();
676 self.committed = true;
677 return Ok(());
678 }
679 // Durability of the file contents before the rename that publishes them.
680 file.sync_all()?;
681 drop(file);
682 apply_published_mode(&self.temp_path, self.preserved_mode)?;
683 fs::rename(&self.temp_path, &self.destination)?;
684 // Durability of the rename itself: without a directory fsync a commit
685 // that returned `Ok` could still lose the published directory entry on
686 // power loss right after the rename. A real I/O error here fails the
687 // commit; a filesystem that simply doesn't support directory fsync is
688 // tolerated.
689 sync_parent_dir(&self.destination)?;
690 self.committed = true;
691 Ok(())
692 }
693}
694
695impl Drop for AtomicOutput {
696 fn drop(&mut self) {
697 // In direct mode `temp_path` *is* the destination — never remove it.
698 if !self.committed && !self.direct {
699 let _ = fs::remove_file(&self.temp_path);
700 }
701 }
702}
703
704/// True if `path` exists and is not a regular file (a character/block device,
705/// FIFO, or socket, e.g. `/dev/null`). Such destinations can't be published via
706/// a sibling temp and rename, so they are written through directly.
707fn is_non_regular_file(path: &Path) -> bool {
708 fs::metadata(path)
709 .map(|m| !m.file_type().is_file())
710 .unwrap_or(false)
711}
712
713/// The mode the published file should carry: an existing destination's own mode
714/// (preserved), or — for a new destination — the umask-adjusted mode a normal
715/// output file would get. `None` off Unix, where no mode is applied.
716fn published_mode(destination: &Path, dir: &Path) -> io::Result<Option<u32>> {
717 #[cfg(unix)]
718 {
719 use std::os::unix::fs::MetadataExt;
720 if let Ok(metadata) = fs::metadata(destination) {
721 return Ok(Some(metadata.mode() & 0o777));
722 }
723 // New destination: probe the umask-adjusted default with a normal
724 // create, read its mode, then remove the probe. Read the mode into a
725 // Result first so the probe is removed even when `metadata` fails,
726 // rather than leaking the temp file on that error path.
727 let probe = dir.join(random_name(".sqlspl-probe-"));
728 let file = File::create(&probe)?;
729 let mode = file.metadata().map(|metadata| metadata.mode() & 0o777);
730 drop(file);
731 let _ = fs::remove_file(&probe);
732 Ok(Some(mode?))
733 }
734 #[cfg(not(unix))]
735 {
736 let _ = (destination, dir);
737 Ok(None)
738 }
739}
740
741/// Best-effort fsync of `path`'s parent directory, making a just-completed
742/// `rename` into it durable across power loss.
743///
744/// Opening a directory and calling `fsync` on it is the POSIX way to persist a
745/// directory entry. Some platforms/filesystems refuse a directory `fsync`
746/// (returning an "unsupported" error), which is ignored; a *genuine* I/O error
747/// (e.g. `EIO`) is propagated so `commit` never reports durability it did not
748/// achieve. A no-op off Unix.
749fn sync_parent_dir(path: &Path) -> io::Result<()> {
750 #[cfg(unix)]
751 {
752 let parent = match path.parent() {
753 Some(parent) if !parent.as_os_str().is_empty() => parent,
754 _ => Path::new("."),
755 };
756 let dir = File::open(parent)?;
757 if let Err(err) = dir.sync_all() {
758 if !is_ignorable_dir_sync_error(&err) {
759 return Err(err);
760 }
761 }
762 }
763 #[cfg(not(unix))]
764 {
765 let _ = path;
766 }
767 Ok(())
768}
769
770/// Whether a directory `fsync` error only means "this filesystem does not
771/// support fsync-ing a directory" (safe to ignore) rather than a real I/O
772/// failure. `ENOTSUP`/`EOPNOTSUPP` map to `Unsupported` and `EINVAL` to
773/// `InvalidInput`; anything else (notably `EIO`) is a genuine durability error.
774fn is_ignorable_dir_sync_error(err: &io::Error) -> bool {
775 matches!(
776 err.kind(),
777 io::ErrorKind::Unsupported | io::ErrorKind::InvalidInput
778 )
779}
780
781/// Apply the published mode to the finished temp file before rename.
782fn apply_published_mode(temp_path: &Path, mode: Option<u32>) -> io::Result<()> {
783 #[cfg(unix)]
784 {
785 use std::os::unix::fs::PermissionsExt;
786 if let Some(mode) = mode {
787 fs::set_permissions(temp_path, fs::Permissions::from_mode(mode))?;
788 }
789 }
790 #[cfg(not(unix))]
791 {
792 let _ = (temp_path, mode);
793 }
794 Ok(())
795}
796
797/// A group of [`AtomicOutput`]s published together.
798///
799/// Every staged output writes into its own protected temp file; nothing lands
800/// until [`publish`](Self::publish) renames each into place after all content
801/// is written. Dropping the set without publishing removes every temp file and
802/// leaves all destinations untouched. Publication is per-file atomic (each
803/// `rename` is atomic); it is not a single cross-file transaction, so a failure
804/// partway through can leave earlier renames applied — the individual
805/// no-truncation-before-success guarantee still holds for each destination.
806#[derive(Default)]
807pub struct PublicationSet {
808 outputs: Vec<AtomicOutput>,
809}
810
811impl PublicationSet {
812 /// An empty set.
813 pub fn new() -> Self {
814 Self::default()
815 }
816
817 /// Stage a protected output beside `destination` and return it for writing.
818 pub fn stage(&mut self, destination: impl AsRef<Path>) -> io::Result<&mut AtomicOutput> {
819 self.outputs.push(AtomicOutput::create(destination)?);
820 Ok(self
821 .outputs
822 .last_mut()
823 .expect("just pushed an output onto the set"))
824 }
825
826 /// Publish every staged output by renaming its temp file into place.
827 pub fn publish(self) -> io::Result<()> {
828 for output in self.outputs {
829 output.commit()?;
830 }
831 Ok(())
832 }
833}
834
835/// The outcome of publishing several destinations that are *not* one atomic
836/// cross-file transaction. Each destination's own no-truncation-before-success
837/// guarantee still holds, but a failure partway through can leave earlier
838/// destinations already published; [`PartialPublication`] reports exactly which
839/// destinations landed and which one failed, so a caller never has to pretend
840/// the set was pairwise atomic across filesystems.
841#[derive(Debug)]
842pub struct PartialPublication {
843 /// Destinations that were published before the failure, in publish order.
844 pub published: Vec<PathBuf>,
845 /// The destination whose rename failed.
846 pub failed: PathBuf,
847 /// The underlying I/O error.
848 pub source: io::Error,
849}
850
851impl std::fmt::Display for PartialPublication {
852 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
853 write!(
854 f,
855 "partial publication: failed to publish `{}` ({}); already published: [{}]",
856 self.failed.display(),
857 self.source,
858 self.published
859 .iter()
860 .map(|p| p.display().to_string())
861 .collect::<Vec<_>>()
862 .join(", ")
863 )
864 }
865}
866
867impl std::error::Error for PartialPublication {}
868
869/// Publish a sequence of already-written [`AtomicOutput`]s in order, renaming
870/// each finished temp file over its destination. Returns [`PartialPublication`]
871/// if a rename fails after one or more destinations were already published —
872/// honestly reporting that the set is not atomic across files/filesystems.
873pub fn publish_in_order(outputs: Vec<AtomicOutput>) -> Result<(), PartialPublication> {
874 let mut published = Vec::new();
875 for output in outputs {
876 let destination = output.destination().to_path_buf();
877 match output.commit() {
878 Ok(()) => published.push(destination),
879 Err(source) => {
880 return Err(PartialPublication {
881 published,
882 failed: destination,
883 source,
884 })
885 }
886 }
887 }
888 Ok(())
889}
890
891// --- Family state + budget ---------------------------------------------------
892
893/// An exact memory budget (in bytes) for a correlated table family's buffered
894/// rows. Once a family's buffered rows would exceed it, the buffer spills to a
895/// protected spool rather than growing without bound.
896#[derive(Debug, Clone, Copy, PartialEq, Eq)]
897pub struct FamilyBudget {
898 /// The maximum number of buffered bytes to hold in memory.
899 pub max_bytes: u64,
900}
901
902impl Default for FamilyBudget {
903 fn default() -> Self {
904 // A conservative default; a compiled plan supplies an exact budget.
905 Self {
906 max_bytes: 64 * 1024 * 1024,
907 }
908 }
909}
910
911/// Which kind of family rows a spool holds, for observability.
912#[derive(Debug, Clone, Copy, PartialEq, Eq)]
913pub enum SpillKind {
914 /// Buffered child rows of a family.
915 Child,
916 /// Buffered rows of a single table.
917 Table,
918}
919
920/// Where a [`FamilyBuffer`]'s rows currently live.
921pub enum FamilyState {
922 /// In memory, within budget: the family's parent/aggregate rows.
923 ParentState(Vec<SpooledRow>),
924 /// Spilled child rows in a protected spool.
925 ChildSpool(ProtectedSpool),
926 /// Spilled table rows in a protected spool.
927 TableSpool(ProtectedSpool),
928}
929
930/// Incremental replay of buffered family rows.
931///
932/// In-memory rows are moved into an owning iterator. Spilled rows are decoded
933/// one record at a time from the protected spool, so replay retains at most one
934/// decoded row instead of rebuilding the complete family in memory.
935pub enum FamilyRowReplay<'a> {
936 /// Rows that remained within the configured memory budget.
937 Memory(std::vec::IntoIter<SpooledRow>),
938 /// Rows decoded incrementally from a protected spool.
939 Spool(SpoolReader<&'a mut File>),
940}
941
942impl Iterator for FamilyRowReplay<'_> {
943 type Item = io::Result<SpooledRow>;
944
945 fn next(&mut self) -> Option<Self::Item> {
946 match self {
947 Self::Memory(rows) => rows.next().map(Ok),
948 Self::Spool(reader) => reader.read_row().transpose(),
949 }
950 }
951}
952
953/// Buffers a family's rows under an exact byte budget, spilling deterministically
954/// to a [`ProtectedSpool`] the moment a push would cross the budget.
955///
956/// The buffer never retains every child row in an unbounded `Vec`: once spilled,
957/// each further row is written straight to the protected spool. The spill
958/// decision is deterministic — it depends only on the (fixed) budget and the
959/// rows pushed, not on wall-clock or allocation timing — so a given plan spills
960/// identically on every run.
961pub struct FamilyBuffer {
962 budget: u64,
963 used: u64,
964 table_id: u32,
965 temp: TempConfig,
966 spill_kind: SpillKind,
967 state: FamilyState,
968 /// Whether the rows have already been replayed. Replay is single-shot: the
969 /// in-memory state is drained on first replay, so a second call would
970 /// silently yield nothing. Guard against that so a future second pass fails
971 /// loudly instead — the spilled and in-memory arms stay consistent.
972 replayed: bool,
973}
974
975impl FamilyBuffer {
976 /// A buffer that starts in memory and spills on demand.
977 pub fn new(
978 budget: FamilyBudget,
979 table_id: u32,
980 temp: TempConfig,
981 spill_kind: SpillKind,
982 ) -> Self {
983 Self {
984 budget: budget.max_bytes,
985 used: 0,
986 table_id,
987 temp,
988 spill_kind,
989 state: FamilyState::ParentState(Vec::new()),
990 replayed: false,
991 }
992 }
993
994 /// A buffer that chooses its storage up front from an estimate: if the
995 /// family is already known to exceed the budget it spills before the first
996 /// row, avoiding a transient in-memory spike.
997 pub fn with_estimate(
998 budget: FamilyBudget,
999 table_id: u32,
1000 temp: TempConfig,
1001 spill_kind: SpillKind,
1002 estimated_bytes: u64,
1003 ) -> io::Result<Self> {
1004 let mut buffer = Self::new(budget, table_id, temp, spill_kind);
1005 if estimated_bytes > buffer.budget {
1006 buffer.spill()?;
1007 }
1008 Ok(buffer)
1009 }
1010
1011 /// The table id every pushed row is expected to carry.
1012 pub fn table_id(&self) -> u32 {
1013 self.table_id
1014 }
1015
1016 /// Whether the buffer has spilled to disk.
1017 pub fn is_spilled(&self) -> bool {
1018 !matches!(self.state, FamilyState::ParentState(_))
1019 }
1020
1021 /// The current storage state.
1022 pub fn state(&self) -> &FamilyState {
1023 &self.state
1024 }
1025
1026 /// Buffer one row, spilling to a protected spool if it would cross the
1027 /// budget.
1028 pub fn push(&mut self, row: SpooledRow) -> io::Result<()> {
1029 if self.is_spilled() {
1030 return self.write_spilled(&row);
1031 }
1032 let size = row.estimated_bytes();
1033 if self.used + size <= self.budget {
1034 self.used += size;
1035 if let FamilyState::ParentState(rows) = &mut self.state {
1036 rows.push(row);
1037 }
1038 Ok(())
1039 } else {
1040 // Crossing the budget: move what we have to a spool, then append.
1041 self.spill()?;
1042 self.write_spilled(&row)
1043 }
1044 }
1045
1046 /// Replay buffered rows in push order without materializing a spilled
1047 /// family in memory.
1048 pub fn replay_rows(&mut self) -> io::Result<FamilyRowReplay<'_>> {
1049 if self.replayed {
1050 return Err(invalid_data(
1051 "FamilyBuffer::replay_rows is single-shot and was already replayed",
1052 ));
1053 }
1054 self.replayed = true;
1055 match &mut self.state {
1056 FamilyState::ParentState(rows) => {
1057 Ok(FamilyRowReplay::Memory(std::mem::take(rows).into_iter()))
1058 }
1059 FamilyState::ChildSpool(spool) | FamilyState::TableSpool(spool) => {
1060 Ok(FamilyRowReplay::Spool(spool.rewind()?))
1061 }
1062 }
1063 }
1064
1065 /// Collect every buffered row in push order.
1066 ///
1067 /// Prefer [`replay_rows`](Self::replay_rows) on generation paths: this
1068 /// compatibility helper intentionally materializes the result for callers
1069 /// that need an owned collection.
1070 pub fn drain_rows(&mut self) -> io::Result<Vec<SpooledRow>> {
1071 self.replay_rows()?.collect()
1072 }
1073
1074 /// Move any in-memory rows into a fresh protected spool and switch state.
1075 ///
1076 /// Rows go through the spool's persistent buffered writer; no per-row flush
1077 /// — buffered writes are flushed once when the spool is later drained.
1078 fn spill(&mut self) -> io::Result<()> {
1079 let mut spool = ProtectedSpool::create(&self.temp)?;
1080 if let FamilyState::ParentState(rows) = &self.state {
1081 for row in rows {
1082 spool.write_row(row)?;
1083 }
1084 }
1085 self.state = match self.spill_kind {
1086 SpillKind::Child => FamilyState::ChildSpool(spool),
1087 SpillKind::Table => FamilyState::TableSpool(spool),
1088 };
1089 Ok(())
1090 }
1091
1092 /// Append a row directly to the active spool's buffered writer (no per-row
1093 /// flush; the buffer is flushed once at drain).
1094 fn write_spilled(&mut self, row: &SpooledRow) -> io::Result<()> {
1095 match &mut self.state {
1096 FamilyState::ChildSpool(spool) | FamilyState::TableSpool(spool) => spool.write_row(row),
1097 // `push`/`with_estimate` only reach here after `spill`, so the state
1098 // is always a spool; treat an in-memory state as a no-op rather than
1099 // panicking.
1100 FamilyState::ParentState(_) => Ok(()),
1101 }
1102 }
1103}
1104
1105#[cfg(test)]
1106mod tests {
1107 use super::*;
1108
1109 #[cfg(unix)]
1110 #[test]
1111 fn atomic_output_writes_through_to_non_regular_file() {
1112 // /dev/null is a character device: staging a sibling temp in /dev and
1113 // renaming over it fails (the directory is unwritable), so the output
1114 // must be written straight through instead.
1115 let mut out = AtomicOutput::create("/dev/null").expect("open /dev/null");
1116 out.writer().write_all(b"hello, void").expect("write");
1117 out.commit().expect("commit to /dev/null");
1118 }
1119
1120 #[test]
1121 fn directory_fsync_errors_distinguish_unsupported_from_real_io() {
1122 // "Filesystem doesn't support a directory fsync" is ignorable; a genuine
1123 // I/O error must propagate so `commit` never reports false durability.
1124 assert!(is_ignorable_dir_sync_error(&io::Error::from(
1125 io::ErrorKind::Unsupported
1126 )));
1127 assert!(is_ignorable_dir_sync_error(&io::Error::from(
1128 io::ErrorKind::InvalidInput
1129 )));
1130 assert!(!is_ignorable_dir_sync_error(&io::Error::other(
1131 "input/output error"
1132 )));
1133 }
1134
1135 #[test]
1136 fn family_buffer_replay_is_single_shot() {
1137 // Replay drains the in-memory rows, so a second replay would silently
1138 // yield an empty family. It must fail loudly instead, keeping the
1139 // in-memory and spilled arms consistent.
1140 let mut buffer = FamilyBuffer::new(
1141 FamilyBudget::default(),
1142 0,
1143 TempConfig::default(),
1144 SpillKind::Child,
1145 );
1146 buffer
1147 .push(SpooledRow {
1148 table_id: 0,
1149 row_index: 0,
1150 values: vec![GeneratedValue::Integer(1)],
1151 })
1152 .unwrap();
1153 assert!(buffer.replay_rows().is_ok());
1154 assert!(
1155 buffer.replay_rows().is_err(),
1156 "a second replay must fail loudly, not silently return an empty family"
1157 );
1158 }
1159
1160 #[test]
1161 fn spool_round_trip_preserves_every_value_shape() {
1162 let temp = TempConfig::default();
1163 let mut spool = ProtectedSpool::create(&temp).unwrap();
1164 let row = SpooledRow {
1165 table_id: 9,
1166 row_index: 3,
1167 values: vec![
1168 GeneratedValue::Null,
1169 GeneratedValue::Integer(-1),
1170 GeneratedValue::Text("x".into()),
1171 GeneratedValue::Bytes(vec![1, 2, 3]),
1172 ],
1173 };
1174 spool.write_row(&row).unwrap();
1175 let mut reader = spool.rewind().unwrap();
1176 assert_eq!(reader.read_row().unwrap(), Some(row));
1177 assert_eq!(reader.read_row().unwrap(), None);
1178 }
1179
1180 #[test]
1181 fn cancellation_token_is_independent_per_instance() {
1182 let a = CancellationToken::new();
1183 let b = CancellationToken::new();
1184 a.cancel();
1185 assert!(a.is_cancelled());
1186 assert!(!b.is_cancelled());
1187 }
1188}