Skip to main content

sql_splitter/writer/
mod.rs

1//! Buffered file writers for splitting SQL statements into per-table files.
2
3pub mod controller;
4pub mod profile;
5
6// `MockClock` is the deterministic-test seam for `Splitter::with_io_clock`
7// (see docs/features/ADAPTIVE_IO_PROFILES.md): only integration tests name
8// it, so the `sql-splitter` bin target sees it as unused.
9#[allow(unused_imports)]
10pub use controller::{Clock, Controller, EpochMeasurement, MockClock, RealClock};
11pub use profile::{
12    env_writer_count, probe_output_dir, IoStrategy, ProfileKind, ProfileValues, WriterProfile,
13};
14
15use crate::splitter::Compression;
16use ahash::AHashMap;
17use std::collections::hash_map::Entry;
18use std::fs::{self, File};
19use std::io::Write;
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
22use std::sync::mpsc::{sync_channel, Receiver, SyncSender, TrySendError};
23use std::sync::{Arc, Mutex};
24use std::thread::JoinHandle;
25use std::time::{Duration, Instant};
26
27/// A batched write job: pre-assembled bytes for one table.
28struct Chunk {
29    table: Arc<str>,
30    data: Vec<u8>,
31}
32
33/// Point-in-time snapshot of the writer pipeline's instrumentation counters.
34///
35/// These are the two signals the adaptive I/O controller samples per epoch
36/// (see `docs/features/ADAPTIVE_IO_PROFILES.md`): how fast the writer threads
37/// actually drain (`bytes_acked`) and how long the producer sat blocked
38/// shipping chunks (`send_stall`). Near-zero stall combined with low
39/// throughput means the *input* side is the bottleneck, so the write profile
40/// must not react to it.
41#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
42pub struct WriterStats {
43    /// Bytes actually written to output files: counted after each `write(2)`
44    /// returns (pre-fsync), *not* when chunks are enqueued or land in a
45    /// sink's coalescing buffer — buffered bytes would measure RAM speed,
46    /// not the device. For compressed output this counts *compressed* bytes,
47    /// which is the right signal: it is the byte volume the device has to
48    /// absorb.
49    pub bytes_acked: u64,
50    /// Cumulative time the producer spent blocked on a full writer channel.
51    pub send_stall: Duration,
52}
53
54/// Test-only rate limiter (token bucket) shared by all sinks of one pool.
55///
56/// Enabled by the hidden env `SQL_SPLITTER_TEST_THROTTLE_MBPS`; it makes the
57/// *output device* deterministic for adaptation tests, because the throttle —
58/// not the machine — becomes the limiter. Never active in normal use.
59struct Throttle {
60    bytes_per_sec: f64,
61    start: Instant,
62    written: u64,
63}
64
65impl Throttle {
66    fn from_env() -> Option<Arc<Mutex<Self>>> {
67        std::env::var("SQL_SPLITTER_TEST_THROTTLE_MBPS")
68            .ok()
69            .and_then(|v| v.parse::<f64>().ok())
70            .filter(|&r| r > 0.0)
71            .map(|mbps| {
72                Arc::new(Mutex::new(Self {
73                    bytes_per_sec: mbps * 1024.0 * 1024.0,
74                    start: Instant::now(),
75                    written: 0,
76                }))
77            })
78    }
79
80    /// Account `len` bytes and sleep until the global rate permits them.
81    fn admit(&mut self, len: usize) {
82        self.written += len as u64;
83        let due = self.written as f64 / self.bytes_per_sec;
84        let elapsed = self.start.elapsed().as_secs_f64();
85        if due > elapsed {
86            std::thread::sleep(Duration::from_secs_f64(due - elapsed));
87        }
88    }
89}
90
91/// A `File` that coalesces writes into [`ProfileValues::file_buf`]-sized
92/// operations. On rotational and op-limited media the size of each write
93/// *operation* dominates throughput (64 MB writes measured 2.3× faster than
94/// 256 KB writes on a USB HDD), so the buffer threshold is read from the
95/// shared profile values at every write — an atomic swap by the controller
96/// retunes open files mid-run.
97///
98/// The buffer grows lazily (a cold table that only ever receives 10 KB uses
99/// 10 KB, not a preallocated 64 MB), and writes at or above the threshold
100/// bypass it entirely, so the FAST profile behaves like the previous
101/// unbuffered code.
102struct ProfiledFile {
103    file: File,
104    buf: Vec<u8>,
105    values: Arc<ProfileValues>,
106    throttle: Option<Arc<Mutex<Throttle>>>,
107    /// Shared [`WriterStats::bytes_acked`] counter, incremented *after* the
108    /// `write(2)` to the output file returns (pre-fsync). Counting here — not
109    /// when a chunk is enqueued or copied into this coalescing buffer — is
110    /// what makes the controller's throughput signal reflect the device: with
111    /// 64 MB slow-profile buffers, counting buffer fills would measure RAM
112    /// speed (~600 MB/s on a 77 MB/s drive) and fake a fast device.
113    bytes_acked: Arc<AtomicU64>,
114}
115
116impl ProfiledFile {
117    fn new(
118        file: File,
119        values: Arc<ProfileValues>,
120        throttle: Option<Arc<Mutex<Throttle>>>,
121        bytes_acked: Arc<AtomicU64>,
122    ) -> Self {
123        Self {
124            file,
125            buf: Vec::new(),
126            values,
127            throttle,
128            bytes_acked,
129        }
130    }
131
132    fn write_to_file(&mut self, data: &[u8]) -> std::io::Result<()> {
133        if let Some(throttle) = &self.throttle {
134            if let Ok(mut t) = throttle.lock() {
135                t.admit(data.len());
136            }
137        }
138        self.file.write_all(data)?;
139        self.bytes_acked
140            .fetch_add(data.len() as u64, Ordering::Relaxed);
141        Ok(())
142    }
143
144    fn flush_buf(&mut self) -> std::io::Result<()> {
145        if !self.buf.is_empty() {
146            // Split the borrow: move the buffer out so write_to_file can take
147            // &mut self without cloning the data.
148            let pending = std::mem::take(&mut self.buf);
149            let result = self.write_to_file(&pending);
150            // Keep the allocation for the next fill.
151            self.buf = pending;
152            self.buf.clear();
153            result?;
154        }
155        Ok(())
156    }
157}
158
159impl Write for ProfiledFile {
160    fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
161        let cap = self.values.file_buf();
162        if self.buf.len() + data.len() > cap {
163            self.flush_buf()?;
164        }
165        if data.len() >= cap {
166            self.write_to_file(data)?;
167        } else {
168            self.buf.extend_from_slice(data);
169        }
170        Ok(data.len())
171    }
172
173    fn flush(&mut self) -> std::io::Result<()> {
174        self.flush_buf()?;
175        self.file.flush()
176    }
177}
178
179/// A per-table output stream: a plain file, or a streaming compressor over one.
180/// Compressing per file keeps every output independent, so the writer pool
181/// still runs fully in parallel — and the compression work parallelizes with it.
182///
183/// Every variant bottoms out in a [`ProfiledFile`], so the physical write size
184/// follows the active profile for compressed output too.
185enum TableSink {
186    Raw(ProfiledFile),
187    #[cfg(feature = "compression")]
188    Gzip(flate2::write::GzEncoder<ProfiledFile>),
189    #[cfg(feature = "compression")]
190    Bzip2(bzip2::write::BzEncoder<ProfiledFile>),
191    #[cfg(feature = "compression")]
192    Xz(xz2::write::XzEncoder<ProfiledFile>),
193    #[cfg(feature = "compression")]
194    Zstd(zstd::stream::write::Encoder<'static, ProfiledFile>),
195}
196
197impl TableSink {
198    /// Create the `<table>.sql[.ext]` file and wrap it in the chosen encoder.
199    fn create(
200        dir: &Path,
201        table: &str,
202        format: Compression,
203        values: &Arc<ProfileValues>,
204        throttle: &Option<Arc<Mutex<Throttle>>>,
205        bytes_acked: &Arc<AtomicU64>,
206    ) -> std::io::Result<Self> {
207        let path = dir.join(format!("{}.sql{}", table, format.output_extension()));
208        let file = ProfiledFile::new(
209            File::create(&path)?,
210            Arc::clone(values),
211            throttle.clone(),
212            Arc::clone(bytes_acked),
213        );
214        Ok(match format {
215            Compression::None => TableSink::Raw(file),
216            #[cfg(feature = "compression")]
217            Compression::Gzip => TableSink::Gzip(flate2::write::GzEncoder::new(
218                file,
219                flate2::Compression::default(),
220            )),
221            #[cfg(feature = "compression")]
222            Compression::Bzip2 => TableSink::Bzip2(bzip2::write::BzEncoder::new(
223                file,
224                bzip2::Compression::default(),
225            )),
226            #[cfg(feature = "compression")]
227            Compression::Xz => TableSink::Xz(xz2::write::XzEncoder::new(file, 6)),
228            #[cfg(feature = "compression")]
229            Compression::Zstd => TableSink::Zstd(zstd::stream::write::Encoder::new(file, 3)?),
230            // Zip is never selected as per-table output compression:
231            // `Compression::parse_output` has no "zip" case, so `--compress
232            // zip` stays rejected at the CLI layer (archive output uses `-o
233            // dump.zip` instead, see `crate::archive`).
234            Compression::Zip => {
235                return Err(std::io::Error::new(
236                    std::io::ErrorKind::Unsupported,
237                    "zip is not a valid per-file output compression",
238                ))
239            }
240            #[cfg(not(feature = "compression"))]
241            _ => {
242                return Err(std::io::Error::new(
243                    std::io::ErrorKind::Unsupported,
244                    "compressed output requires the `compression` feature",
245                ))
246            }
247        })
248    }
249
250    fn write_all(&mut self, data: &[u8]) -> std::io::Result<()> {
251        match self {
252            TableSink::Raw(f) => f.write_all(data),
253            #[cfg(feature = "compression")]
254            TableSink::Gzip(e) => e.write_all(data),
255            #[cfg(feature = "compression")]
256            TableSink::Bzip2(e) => e.write_all(data),
257            #[cfg(feature = "compression")]
258            TableSink::Xz(e) => e.write_all(data),
259            #[cfg(feature = "compression")]
260            TableSink::Zstd(e) => e.write_all(data),
261        }
262    }
263
264    /// Finalize the stream, flushing the compressor's epilogue (required for a
265    /// valid archive — especially zstd, which writes a frame footer) and then
266    /// draining the coalescing buffer beneath it.
267    fn finish(self) -> std::io::Result<()> {
268        match self {
269            TableSink::Raw(mut f) => f.flush(),
270            #[cfg(feature = "compression")]
271            TableSink::Gzip(e) => e.finish().and_then(|mut f| f.flush()),
272            #[cfg(feature = "compression")]
273            TableSink::Bzip2(e) => e.finish().and_then(|mut f| f.flush()),
274            #[cfg(feature = "compression")]
275            TableSink::Xz(e) => e.finish().and_then(|mut f| f.flush()),
276            #[cfg(feature = "compression")]
277            TableSink::Zstd(e) => e.finish().and_then(|mut f| f.flush()),
278        }
279    }
280}
281
282/// Parallel, pipelined writer pool.
283///
284/// The producer (parser thread) stages per-table bytes and ships ~256KB chunks
285/// over bounded channels to `N` writer threads, each owning a disjoint shard of
286/// tables (sharded by name hash). This overlaps parsing with writing (a
287/// pipeline / double-buffer) and keeps several writes in flight so a single
288/// synchronous thread doesn't bottleneck a fast SSD (queue depth > 1). Batching
289/// into large chunks keeps per-statement channel overhead negligible.
290///
291/// Output is byte-identical to a single-threaded writer: each table's
292/// file is written by exactly one thread, in input order. A table's shard is
293/// assigned once (on first ship) and never changes, so growing the pool
294/// mid-run ([`grow_to`](Self::grow_to)) preserves per-table ordering by
295/// construction: already-seen tables keep their owner, only tables first seen
296/// after the growth hash across the new shard count.
297pub struct ParallelWriters {
298    senders: Vec<SyncSender<Chunk>>,
299    handles: Vec<JoinHandle<std::io::Result<()>>>,
300    error_flag: Arc<AtomicBool>,
301    intern: AHashMap<String, Arc<str>>,
302    stage: AHashMap<Arc<str>, Vec<u8>>,
303    /// Sticky table → shard assignment (fixed at first ship).
304    shards: AHashMap<Arc<str>, usize>,
305    /// Total bytes currently staged across all tables (bounded by
306    /// [`ProfileValues::stage_cap`]).
307    staged_bytes: usize,
308    /// Bytes written to sinks by the writer threads (shared, monotonically
309    /// increasing). One atomic add per ~256KB chunk, so contention is nil.
310    bytes_acked: Arc<AtomicU64>,
311    /// Nanoseconds the producer spent blocked on full writer channels.
312    /// Producer-only, so a plain counter; timing happens only on the slow
313    /// path (channel already full), keeping the hot path free of clock reads.
314    stall_nanos: u64,
315    /// Runtime-swappable profile values shared with the writer threads.
316    values: Arc<ProfileValues>,
317    /// Everything needed to spawn additional writers later (grow-only).
318    output_dir: PathBuf,
319    format: Compression,
320    capacity: usize,
321    throttle: Option<Arc<Mutex<Throttle>>>,
322}
323
324impl ParallelWriters {
325    /// Spawn `num_writers` writer threads targeting `output_dir`, compressing
326    /// each per-table file with `format`. `capacity` is the per-shard channel
327    /// depth (chunks in flight); `values` carries the active profile's
328    /// staging/buffer sizes and may be retuned mid-run by the controller.
329    pub fn new(
330        output_dir: PathBuf,
331        num_writers: usize,
332        capacity: usize,
333        format: Compression,
334        values: Arc<ProfileValues>,
335    ) -> std::io::Result<Self> {
336        fs::create_dir_all(&output_dir)?;
337        let mut writers = Self {
338            senders: Vec::new(),
339            handles: Vec::new(),
340            error_flag: Arc::new(AtomicBool::new(false)),
341            intern: AHashMap::new(),
342            stage: AHashMap::new(),
343            shards: AHashMap::new(),
344            staged_bytes: 0,
345            bytes_acked: Arc::new(AtomicU64::new(0)),
346            stall_nanos: 0,
347            values,
348            output_dir,
349            format,
350            capacity: capacity.max(1),
351            throttle: Throttle::from_env(),
352        };
353        for _ in 0..num_writers.max(1) {
354            writers.spawn_writer();
355        }
356        Ok(writers)
357    }
358
359    fn spawn_writer(&mut self) {
360        let (tx, rx) = sync_channel::<Chunk>(self.capacity);
361        self.senders.push(tx);
362        let dir = self.output_dir.clone();
363        let ef = Arc::clone(&self.error_flag);
364        let acked = Arc::clone(&self.bytes_acked);
365        let values = Arc::clone(&self.values);
366        let throttle = self.throttle.clone();
367        let format = self.format;
368        self.handles.push(std::thread::spawn(move || {
369            writer_loop(rx, dir, ef, format, acked, values, throttle)
370        }));
371    }
372
373    /// Number of writer threads currently running.
374    pub fn writer_count(&self) -> usize {
375        self.senders.len()
376    }
377
378    /// Grow the pool to `n` writer threads (never shrinks — a table's owner
379    /// thread must not change mid-run, see the type-level docs). Used by the
380    /// adaptive controller's deferred writer spawn: auto mode opens at W=1
381    /// and only pays for parallelism once the device has proven fast.
382    pub fn grow_to(&mut self, n: usize) {
383        while self.senders.len() < n {
384            self.spawn_writer();
385        }
386    }
387
388    /// Snapshot the pipeline's instrumentation counters (monotonic since
389    /// construction). Cheap enough to call at every epoch boundary.
390    pub fn stats(&self) -> WriterStats {
391        WriterStats {
392            bytes_acked: self.bytes_acked.load(Ordering::Relaxed),
393            send_stall: Duration::from_nanos(self.stall_nanos),
394        }
395    }
396
397    /// True once any writer thread has hit an I/O error, so the producer can
398    /// stop early; the actual error surfaces from [`finish`](Self::finish).
399    #[inline]
400    pub fn errored(&self) -> bool {
401        self.error_flag.load(Ordering::Relaxed)
402    }
403
404    /// Stage a statement for its table, appending `suffix` (e.g. `b";"`) and a
405    /// newline, shipping a chunk once the table's buffer crosses the threshold.
406    pub fn write(&mut self, table_name: &str, stmt: &[u8], suffix: &[u8]) {
407        let arc = match self.intern.get(table_name) {
408            Some(a) => Arc::clone(a),
409            None => {
410                let a: Arc<str> = Arc::from(table_name);
411                self.intern.insert(table_name.to_string(), Arc::clone(&a));
412                a
413            }
414        };
415        let flush_chunk = self.values.flush_chunk();
416        let stage_cap = self.values.stage_cap();
417        let buf = self.stage.entry(Arc::clone(&arc)).or_default();
418        buf.extend_from_slice(stmt);
419        buf.extend_from_slice(suffix);
420        buf.push(b'\n');
421        self.staged_bytes += stmt.len() + suffix.len() + 1;
422        if buf.len() >= flush_chunk {
423            let data = std::mem::take(buf);
424            self.staged_bytes -= data.len();
425            self.ship(&arc, data);
426        } else if self.staged_bytes >= stage_cap {
427            // Many tables, each under the per-table threshold: flush everything
428            // so total staging memory stays bounded by the cap.
429            let stage = std::mem::take(&mut self.stage);
430            for (table, data) in stage {
431                if !data.is_empty() {
432                    self.ship(&table, data);
433                }
434            }
435            self.staged_bytes = 0;
436        }
437    }
438
439    fn ship(&mut self, table: &Arc<str>, data: Vec<u8>) {
440        // Sticky assignment: hash against the shard count at first ship, then
441        // stay put forever — this is what makes grow_to() ordering-safe.
442        let shard = match self.shards.entry(Arc::clone(table)) {
443            Entry::Occupied(e) => *e.get(),
444            Entry::Vacant(e) => *e.insert(shard_index(table, self.senders.len())),
445        };
446        let chunk = Chunk {
447            table: Arc::clone(table),
448            data,
449        };
450        // Fast path: the channel has room, no clock read at all. Only when the
451        // writer is backed up do we time the blocking send — that time *is*
452        // the `send_stall` backpressure signal. A dead writer's receiver is
453        // dropped, so sends error; the real error is surfaced by `finish`,
454        // so send failures are ignored here.
455        match self.senders[shard].try_send(chunk) {
456            Ok(()) => {}
457            Err(TrySendError::Full(chunk)) => {
458                let blocked = Instant::now();
459                let _ = self.senders[shard].send(chunk);
460                self.stall_nanos += blocked.elapsed().as_nanos() as u64;
461            }
462            Err(TrySendError::Disconnected(_)) => {}
463        }
464    }
465
466    /// Flush all staged data, join the writer threads, and return the first
467    /// I/O error encountered (if any).
468    pub fn finish(mut self) -> std::io::Result<()> {
469        let stage = std::mem::take(&mut self.stage);
470        for (table, data) in stage {
471            if !data.is_empty() {
472                self.ship(&table, data);
473            }
474        }
475        drop(self.senders);
476
477        let mut first_err: Option<std::io::Error> = None;
478        for handle in self.handles {
479            match handle.join() {
480                Ok(Ok(())) => {}
481                Ok(Err(e)) => {
482                    first_err.get_or_insert(e);
483                }
484                Err(_) => {
485                    first_err
486                        .get_or_insert_with(|| std::io::Error::other("writer thread panicked"));
487                }
488            }
489        }
490        match first_err {
491            Some(e) => Err(e),
492            None => Ok(()),
493        }
494    }
495}
496
497/// FNV-1a hash of the table name → shard index. Deterministic within a run so a
498/// table always maps to the same writer (preserving per-file order).
499#[inline]
500fn shard_index(table: &str, n: usize) -> usize {
501    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
502    for &b in table.as_bytes() {
503        h ^= b as u64;
504        h = h.wrapping_mul(0x0000_0100_0000_01b3);
505    }
506    (h % n as u64) as usize
507}
508
509fn writer_loop(
510    rx: Receiver<Chunk>,
511    output_dir: PathBuf,
512    error_flag: Arc<AtomicBool>,
513    format: Compression,
514    bytes_acked: Arc<AtomicU64>,
515    values: Arc<ProfileValues>,
516    throttle: Option<Arc<Mutex<Throttle>>>,
517) -> std::io::Result<()> {
518    // Chunks arrive pre-batched at the profile's flush size; the ProfiledFile
519    // beneath each sink coalesces them further up to the profile's file_buf.
520    let mut sinks: AHashMap<Arc<str>, TableSink> = AHashMap::new();
521    let mut first_err: Option<std::io::Error> = None;
522
523    for chunk in rx {
524        if first_err.is_some() {
525            continue; // keep draining so the producer never blocks
526        }
527        let sink = match sinks.entry(Arc::clone(&chunk.table)) {
528            Entry::Occupied(e) => e.into_mut(),
529            Entry::Vacant(e) => {
530                match TableSink::create(
531                    &output_dir,
532                    &chunk.table,
533                    format,
534                    &values,
535                    &throttle,
536                    &bytes_acked,
537                ) {
538                    Ok(s) => e.insert(s),
539                    Err(err) => {
540                        error_flag.store(true, Ordering::Relaxed);
541                        first_err = Some(err);
542                        continue;
543                    }
544                }
545            }
546        };
547        // `bytes_acked` is NOT counted here: this write may land in the
548        // sink's coalescing buffer (or a compressor's internal state), and
549        // counting buffered bytes as "written" would report RAM speed to the
550        // controller. The [`ProfiledFile`] at the bottom of every sink counts
551        // bytes as its `write(2)` calls to the output file return.
552        if let Err(err) = sink.write_all(&chunk.data) {
553            error_flag.store(true, Ordering::Relaxed);
554            first_err = Some(err);
555        }
556    }
557
558    // Finalize every sink so compressor epilogues are flushed (best effort even
559    // after an error, so files close cleanly).
560    for (_, sink) in sinks.drain() {
561        if let Err(err) = sink.finish() {
562            error_flag.store(true, Ordering::Relaxed);
563            if first_err.is_none() {
564                first_err = Some(err);
565            }
566        }
567    }
568
569    match first_err {
570        Some(e) => Err(e),
571        None => Ok(()),
572    }
573}