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, AHashSet};
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
197/// Reduce a parsed table name to a safe single filename component before it is
198/// used to build an output path. A quoted identifier can contain path
199/// separators or `..` segments (e.g. `` `../../evil` ``); joined verbatim these
200/// would escape the output directory, and an absolute-path-like name would even
201/// replace the base directory. Taking the final path component and neutralizing
202/// all-dot names prevents that while leaving ordinary table names unchanged.
203fn sanitize_table_filename(table: &str) -> String {
204    let last = table
205        .rsplit(['/', '\\'])
206        .find(|s| !s.is_empty())
207        .unwrap_or("");
208    // A NUL byte would truncate the path at the OS boundary; neutralize it.
209    let cleaned: String = last.replace('\0', "_");
210    // Names consisting only of dots (`.`, `..`, …) are not usable filenames.
211    if cleaned.trim_matches('.').is_empty() {
212        "_unnamed".to_string()
213    } else {
214        cleaned
215    }
216}
217
218/// Claim a case-fold-unique filename for `table` under `dir`, so two tables
219/// differing only by case (or otherwise colliding after sanitizing) don't map
220/// to one file on a case-insensitive filesystem. The clean `<stem>.sql[.ext]`
221/// name is used when free; on collision a suffix derived from the exact table
222/// name (deterministic across runs) disambiguates.
223fn claim_table_filename(table: &str, ext: &str, reserved: &Mutex<AHashSet<String>>) -> String {
224    let stem = sanitize_table_filename(table);
225    let mut reserved = reserved.lock().unwrap_or_else(|e| e.into_inner());
226    let base = format!("{stem}.sql{ext}");
227    if reserved.insert(base.to_lowercase()) {
228        return base;
229    }
230    // Collision: disambiguate by a stable hash of the exact table name (two
231    // colliding names have different spellings → different hashes).
232    let mut candidate = format!("{stem}-{:08x}.sql{ext}", fnv1a(table));
233    let mut n = 2u32;
234    while !reserved.insert(candidate.to_lowercase()) {
235        candidate = format!("{stem}-{:08x}-{n}.sql{ext}", fnv1a(table));
236        n += 1;
237    }
238    candidate
239}
240
241impl TableSink {
242    /// Create the `<table>.sql[.ext]` file and wrap it in the chosen encoder.
243    #[allow(clippy::too_many_arguments)]
244    fn create(
245        dir: &Path,
246        table: &str,
247        format: Compression,
248        values: &Arc<ProfileValues>,
249        throttle: &Option<Arc<Mutex<Throttle>>>,
250        bytes_acked: &Arc<AtomicU64>,
251        reserved_names: &Mutex<AHashSet<String>>,
252    ) -> std::io::Result<Self> {
253        let filename = claim_table_filename(table, format.output_extension(), reserved_names);
254        let path = dir.join(filename);
255        let file = ProfiledFile::new(
256            File::create(&path)?,
257            Arc::clone(values),
258            throttle.clone(),
259            Arc::clone(bytes_acked),
260        );
261        Ok(match format {
262            Compression::None => TableSink::Raw(file),
263            #[cfg(feature = "compression")]
264            Compression::Gzip => TableSink::Gzip(flate2::write::GzEncoder::new(
265                file,
266                flate2::Compression::default(),
267            )),
268            #[cfg(feature = "compression")]
269            Compression::Bzip2 => TableSink::Bzip2(bzip2::write::BzEncoder::new(
270                file,
271                bzip2::Compression::default(),
272            )),
273            #[cfg(feature = "compression")]
274            Compression::Xz => TableSink::Xz(xz2::write::XzEncoder::new(file, 6)),
275            #[cfg(feature = "compression")]
276            Compression::Zstd => TableSink::Zstd(zstd::stream::write::Encoder::new(file, 3)?),
277            // Zip is never selected as per-table output compression:
278            // `Compression::parse_output` has no "zip" case, so `--compress
279            // zip` stays rejected at the CLI layer (archive output uses `-o
280            // dump.zip` instead, see `crate::archive`).
281            Compression::Zip => {
282                return Err(std::io::Error::new(
283                    std::io::ErrorKind::Unsupported,
284                    "zip is not a valid per-file output compression",
285                ))
286            }
287            #[cfg(not(feature = "compression"))]
288            _ => {
289                return Err(std::io::Error::new(
290                    std::io::ErrorKind::Unsupported,
291                    "compressed output requires the `compression` feature",
292                ))
293            }
294        })
295    }
296
297    fn write_all(&mut self, data: &[u8]) -> std::io::Result<()> {
298        match self {
299            TableSink::Raw(f) => f.write_all(data),
300            #[cfg(feature = "compression")]
301            TableSink::Gzip(e) => e.write_all(data),
302            #[cfg(feature = "compression")]
303            TableSink::Bzip2(e) => e.write_all(data),
304            #[cfg(feature = "compression")]
305            TableSink::Xz(e) => e.write_all(data),
306            #[cfg(feature = "compression")]
307            TableSink::Zstd(e) => e.write_all(data),
308        }
309    }
310
311    /// Finalize the stream, flushing the compressor's epilogue (required for a
312    /// valid archive — especially zstd, which writes a frame footer) and then
313    /// draining the coalescing buffer beneath it.
314    fn finish(self) -> std::io::Result<()> {
315        match self {
316            TableSink::Raw(mut f) => f.flush(),
317            #[cfg(feature = "compression")]
318            TableSink::Gzip(e) => e.finish().and_then(|mut f| f.flush()),
319            #[cfg(feature = "compression")]
320            TableSink::Bzip2(e) => e.finish().and_then(|mut f| f.flush()),
321            #[cfg(feature = "compression")]
322            TableSink::Xz(e) => e.finish().and_then(|mut f| f.flush()),
323            #[cfg(feature = "compression")]
324            TableSink::Zstd(e) => e.finish().and_then(|mut f| f.flush()),
325        }
326    }
327}
328
329/// Parallel, pipelined writer pool.
330///
331/// The producer (parser thread) stages per-table bytes and ships ~256KB chunks
332/// over bounded channels to `N` writer threads, each owning a disjoint shard of
333/// tables (sharded by name hash). This overlaps parsing with writing (a
334/// pipeline / double-buffer) and keeps several writes in flight so a single
335/// synchronous thread doesn't bottleneck a fast SSD (queue depth > 1). Batching
336/// into large chunks keeps per-statement channel overhead negligible.
337///
338/// Output is byte-identical to a single-threaded writer: each table's
339/// file is written by exactly one thread, in input order. A table's shard is
340/// assigned once (on first ship) and never changes, so growing the pool
341/// mid-run ([`grow_to`](Self::grow_to)) preserves per-table ordering by
342/// construction: already-seen tables keep their owner, only tables first seen
343/// after the growth hash across the new shard count.
344pub struct ParallelWriters {
345    senders: Vec<SyncSender<Chunk>>,
346    handles: Vec<JoinHandle<std::io::Result<()>>>,
347    error_flag: Arc<AtomicBool>,
348    intern: AHashMap<String, Arc<str>>,
349    stage: AHashMap<Arc<str>, Vec<u8>>,
350    /// Sticky table → shard assignment (fixed at first ship).
351    shards: AHashMap<Arc<str>, usize>,
352    /// Total bytes currently staged across all tables (bounded by
353    /// [`ProfileValues::stage_cap`]).
354    staged_bytes: usize,
355    /// Bytes written to sinks by the writer threads (shared, monotonically
356    /// increasing). One atomic add per ~256KB chunk, so contention is nil.
357    bytes_acked: Arc<AtomicU64>,
358    /// Nanoseconds the producer spent blocked on full writer channels.
359    /// Producer-only, so a plain counter; timing happens only on the slow
360    /// path (channel already full), keeping the hot path free of clock reads.
361    stall_nanos: u64,
362    /// Runtime-swappable profile values shared with the writer threads.
363    values: Arc<ProfileValues>,
364    /// Everything needed to spawn additional writers later (grow-only).
365    output_dir: PathBuf,
366    format: Compression,
367    capacity: usize,
368    throttle: Option<Arc<Mutex<Throttle>>>,
369    /// Case-folded output filenames already claimed this run, shared across the
370    /// writer threads. Ensures two tables whose names differ only by case (or
371    /// otherwise collide after sanitizing) don't map to one file on a
372    /// case-insensitive filesystem.
373    reserved_names: Arc<Mutex<AHashSet<String>>>,
374}
375
376impl ParallelWriters {
377    /// Spawn `num_writers` writer threads targeting `output_dir`, compressing
378    /// each per-table file with `format`. `capacity` is the per-shard channel
379    /// depth (chunks in flight); `values` carries the active profile's
380    /// staging/buffer sizes and may be retuned mid-run by the controller.
381    pub fn new(
382        output_dir: PathBuf,
383        num_writers: usize,
384        capacity: usize,
385        format: Compression,
386        values: Arc<ProfileValues>,
387    ) -> std::io::Result<Self> {
388        fs::create_dir_all(&output_dir)?;
389        let mut writers = Self {
390            senders: Vec::new(),
391            handles: Vec::new(),
392            error_flag: Arc::new(AtomicBool::new(false)),
393            intern: AHashMap::new(),
394            stage: AHashMap::new(),
395            shards: AHashMap::new(),
396            reserved_names: Arc::new(Mutex::new(AHashSet::new())),
397            staged_bytes: 0,
398            bytes_acked: Arc::new(AtomicU64::new(0)),
399            stall_nanos: 0,
400            values,
401            output_dir,
402            format,
403            capacity: capacity.max(1),
404            throttle: Throttle::from_env(),
405        };
406        for _ in 0..num_writers.max(1) {
407            writers.spawn_writer();
408        }
409        Ok(writers)
410    }
411
412    fn spawn_writer(&mut self) {
413        let (tx, rx) = sync_channel::<Chunk>(self.capacity);
414        self.senders.push(tx);
415        let dir = self.output_dir.clone();
416        let ef = Arc::clone(&self.error_flag);
417        let acked = Arc::clone(&self.bytes_acked);
418        let values = Arc::clone(&self.values);
419        let throttle = self.throttle.clone();
420        let format = self.format;
421        let reserved = Arc::clone(&self.reserved_names);
422        self.handles.push(std::thread::spawn(move || {
423            writer_loop(rx, dir, ef, format, acked, values, throttle, reserved)
424        }));
425    }
426
427    /// Number of writer threads currently running.
428    pub fn writer_count(&self) -> usize {
429        self.senders.len()
430    }
431
432    /// Grow the pool to `n` writer threads (never shrinks — a table's owner
433    /// thread must not change mid-run, see the type-level docs). Used by the
434    /// adaptive controller's deferred writer spawn: auto mode opens at W=1
435    /// and only pays for parallelism once the device has proven fast.
436    pub fn grow_to(&mut self, n: usize) {
437        while self.senders.len() < n {
438            self.spawn_writer();
439        }
440    }
441
442    /// Snapshot the pipeline's instrumentation counters (monotonic since
443    /// construction). Cheap enough to call at every epoch boundary.
444    pub fn stats(&self) -> WriterStats {
445        WriterStats {
446            bytes_acked: self.bytes_acked.load(Ordering::Relaxed),
447            send_stall: Duration::from_nanos(self.stall_nanos),
448        }
449    }
450
451    /// True once any writer thread has hit an I/O error, so the producer can
452    /// stop early; the actual error surfaces from [`finish`](Self::finish).
453    #[inline]
454    pub fn errored(&self) -> bool {
455        self.error_flag.load(Ordering::Relaxed)
456    }
457
458    /// Stage a statement for its table, appending `suffix` (e.g. `b";"`) and a
459    /// newline, shipping a chunk once the table's buffer crosses the threshold.
460    pub fn write(&mut self, table_name: &str, stmt: &[u8], suffix: &[u8]) {
461        let arc = match self.intern.get(table_name) {
462            Some(a) => Arc::clone(a),
463            None => {
464                let a: Arc<str> = Arc::from(table_name);
465                self.intern.insert(table_name.to_string(), Arc::clone(&a));
466                a
467            }
468        };
469        let flush_chunk = self.values.flush_chunk();
470        let stage_cap = self.values.stage_cap();
471        let buf = self.stage.entry(Arc::clone(&arc)).or_default();
472        buf.extend_from_slice(stmt);
473        buf.extend_from_slice(suffix);
474        buf.push(b'\n');
475        self.staged_bytes += stmt.len() + suffix.len() + 1;
476        if buf.len() >= flush_chunk {
477            let data = std::mem::take(buf);
478            self.staged_bytes -= data.len();
479            self.ship(&arc, data);
480        } else if self.staged_bytes >= stage_cap {
481            // Many tables, each under the per-table threshold: flush everything
482            // so total staging memory stays bounded by the cap.
483            let stage = std::mem::take(&mut self.stage);
484            for (table, data) in stage {
485                if !data.is_empty() {
486                    self.ship(&table, data);
487                }
488            }
489            self.staged_bytes = 0;
490        }
491    }
492
493    fn ship(&mut self, table: &Arc<str>, data: Vec<u8>) {
494        // Sticky assignment: hash against the shard count at first ship, then
495        // stay put forever — this is what makes grow_to() ordering-safe.
496        let shard = match self.shards.entry(Arc::clone(table)) {
497            Entry::Occupied(e) => *e.get(),
498            Entry::Vacant(e) => *e.insert(shard_index(table, self.senders.len())),
499        };
500        let chunk = Chunk {
501            table: Arc::clone(table),
502            data,
503        };
504        // Fast path: the channel has room, no clock read at all. Only when the
505        // writer is backed up do we time the blocking send — that time *is*
506        // the `send_stall` backpressure signal. A dead writer's receiver is
507        // dropped, so sends error; the real error is surfaced by `finish`,
508        // so send failures are ignored here.
509        match self.senders[shard].try_send(chunk) {
510            Ok(()) => {}
511            Err(TrySendError::Full(chunk)) => {
512                let blocked = Instant::now();
513                let _ = self.senders[shard].send(chunk);
514                self.stall_nanos += blocked.elapsed().as_nanos() as u64;
515            }
516            Err(TrySendError::Disconnected(_)) => {}
517        }
518    }
519
520    /// Flush all staged data, join the writer threads, and return the first
521    /// I/O error encountered (if any).
522    pub fn finish(mut self) -> std::io::Result<()> {
523        let stage = std::mem::take(&mut self.stage);
524        for (table, data) in stage {
525            if !data.is_empty() {
526                self.ship(&table, data);
527            }
528        }
529        drop(self.senders);
530
531        let mut first_err: Option<std::io::Error> = None;
532        for handle in self.handles {
533            match handle.join() {
534                Ok(Ok(())) => {}
535                Ok(Err(e)) => {
536                    first_err.get_or_insert(e);
537                }
538                Err(_) => {
539                    first_err
540                        .get_or_insert_with(|| std::io::Error::other("writer thread panicked"));
541                }
542            }
543        }
544        match first_err {
545            Some(e) => Err(e),
546            None => Ok(()),
547        }
548    }
549}
550
551/// FNV-1a hash of a string. Deterministic within (and across) runs of the same
552/// binary, so both shard assignment and filename disambiguation are stable.
553#[inline]
554fn fnv1a(s: &str) -> u64 {
555    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
556    for &b in s.as_bytes() {
557        h ^= b as u64;
558        h = h.wrapping_mul(0x0000_0100_0000_01b3);
559    }
560    h
561}
562
563/// FNV-1a hash of the table name → shard index. Deterministic within a run so a
564/// table always maps to the same writer (preserving per-file order).
565#[inline]
566fn shard_index(table: &str, n: usize) -> usize {
567    (fnv1a(table) % n as u64) as usize
568}
569
570#[allow(clippy::too_many_arguments)]
571fn writer_loop(
572    rx: Receiver<Chunk>,
573    output_dir: PathBuf,
574    error_flag: Arc<AtomicBool>,
575    format: Compression,
576    bytes_acked: Arc<AtomicU64>,
577    values: Arc<ProfileValues>,
578    throttle: Option<Arc<Mutex<Throttle>>>,
579    reserved_names: Arc<Mutex<AHashSet<String>>>,
580) -> std::io::Result<()> {
581    // Chunks arrive pre-batched at the profile's flush size; the ProfiledFile
582    // beneath each sink coalesces them further up to the profile's file_buf.
583    let mut sinks: AHashMap<Arc<str>, TableSink> = AHashMap::new();
584    let mut first_err: Option<std::io::Error> = None;
585
586    for chunk in rx {
587        if first_err.is_some() {
588            continue; // keep draining so the producer never blocks
589        }
590        let sink = match sinks.entry(Arc::clone(&chunk.table)) {
591            Entry::Occupied(e) => e.into_mut(),
592            Entry::Vacant(e) => {
593                match TableSink::create(
594                    &output_dir,
595                    &chunk.table,
596                    format,
597                    &values,
598                    &throttle,
599                    &bytes_acked,
600                    &reserved_names,
601                ) {
602                    Ok(s) => e.insert(s),
603                    Err(err) => {
604                        error_flag.store(true, Ordering::Relaxed);
605                        first_err = Some(err);
606                        continue;
607                    }
608                }
609            }
610        };
611        // `bytes_acked` is NOT counted here: this write may land in the
612        // sink's coalescing buffer (or a compressor's internal state), and
613        // counting buffered bytes as "written" would report RAM speed to the
614        // controller. The [`ProfiledFile`] at the bottom of every sink counts
615        // bytes as its `write(2)` calls to the output file return.
616        if let Err(err) = sink.write_all(&chunk.data) {
617            error_flag.store(true, Ordering::Relaxed);
618            first_err = Some(err);
619        }
620    }
621
622    // Finalize every sink so compressor epilogues are flushed (best effort even
623    // after an error, so files close cleanly).
624    for (_, sink) in sinks.drain() {
625        if let Err(err) = sink.finish() {
626            error_flag.store(true, Ordering::Relaxed);
627            if first_err.is_none() {
628                first_err = Some(err);
629            }
630        }
631    }
632
633    match first_err {
634        Some(e) => Err(e),
635        None => Ok(()),
636    }
637}