sql-splitter 1.16.1

High-performance CLI tool for splitting large SQL dump files into individual table files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
//! Buffered file writers for splitting SQL statements into per-table files.

pub mod controller;
pub mod profile;

// `MockClock` is the deterministic-test seam for `Splitter::with_io_clock`
// (see docs/features/ADAPTIVE_IO_PROFILES.md): only integration tests name
// it, so the `sql-splitter` bin target sees it as unused.
#[allow(unused_imports)]
pub use controller::{Clock, Controller, EpochMeasurement, MockClock, RealClock};
pub use profile::{
    env_writer_count, probe_output_dir, IoStrategy, ProfileKind, ProfileValues, WriterProfile,
};

use crate::splitter::Compression;
use ahash::{AHashMap, AHashSet};
use std::collections::hash_map::Entry;
use std::fs::{self, File};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{sync_channel, Receiver, SyncSender, TrySendError};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

/// A batched write job: pre-assembled bytes for one table.
struct Chunk {
    table: Arc<str>,
    data: Vec<u8>,
}

/// Point-in-time snapshot of the writer pipeline's instrumentation counters.
///
/// These are the two signals the adaptive I/O controller samples per epoch
/// (see `docs/features/ADAPTIVE_IO_PROFILES.md`): how fast the writer threads
/// actually drain (`bytes_acked`) and how long the producer sat blocked
/// shipping chunks (`send_stall`). Near-zero stall combined with low
/// throughput means the *input* side is the bottleneck, so the write profile
/// must not react to it.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct WriterStats {
    /// Bytes actually written to output files: counted after each `write(2)`
    /// returns (pre-fsync), *not* when chunks are enqueued or land in a
    /// sink's coalescing buffer — buffered bytes would measure RAM speed,
    /// not the device. For compressed output this counts *compressed* bytes,
    /// which is the right signal: it is the byte volume the device has to
    /// absorb.
    pub bytes_acked: u64,
    /// Cumulative time the producer spent blocked on a full writer channel.
    pub send_stall: Duration,
}

/// Test-only rate limiter (token bucket) shared by all sinks of one pool.
///
/// Enabled by the hidden env `SQL_SPLITTER_TEST_THROTTLE_MBPS`; it makes the
/// *output device* deterministic for adaptation tests, because the throttle —
/// not the machine — becomes the limiter. Never active in normal use.
struct Throttle {
    bytes_per_sec: f64,
    start: Instant,
    written: u64,
}

impl Throttle {
    fn from_env() -> Option<Arc<Mutex<Self>>> {
        std::env::var("SQL_SPLITTER_TEST_THROTTLE_MBPS")
            .ok()
            .and_then(|v| v.parse::<f64>().ok())
            .filter(|&r| r > 0.0)
            .map(|mbps| {
                Arc::new(Mutex::new(Self {
                    bytes_per_sec: mbps * 1024.0 * 1024.0,
                    start: Instant::now(),
                    written: 0,
                }))
            })
    }

    /// Account `len` bytes and sleep until the global rate permits them.
    fn admit(&mut self, len: usize) {
        self.written += len as u64;
        let due = self.written as f64 / self.bytes_per_sec;
        let elapsed = self.start.elapsed().as_secs_f64();
        if due > elapsed {
            std::thread::sleep(Duration::from_secs_f64(due - elapsed));
        }
    }
}

/// A `File` that coalesces writes into [`ProfileValues::file_buf`]-sized
/// operations. On rotational and op-limited media the size of each write
/// *operation* dominates throughput (64 MB writes measured 2.3× faster than
/// 256 KB writes on a USB HDD), so the buffer threshold is read from the
/// shared profile values at every write — an atomic swap by the controller
/// retunes open files mid-run.
///
/// The buffer grows lazily (a cold table that only ever receives 10 KB uses
/// 10 KB, not a preallocated 64 MB), and writes at or above the threshold
/// bypass it entirely, so the FAST profile behaves like the previous
/// unbuffered code.
struct ProfiledFile {
    file: File,
    buf: Vec<u8>,
    values: Arc<ProfileValues>,
    throttle: Option<Arc<Mutex<Throttle>>>,
    /// Shared [`WriterStats::bytes_acked`] counter, incremented *after* the
    /// `write(2)` to the output file returns (pre-fsync). Counting here — not
    /// when a chunk is enqueued or copied into this coalescing buffer — is
    /// what makes the controller's throughput signal reflect the device: with
    /// 64 MB slow-profile buffers, counting buffer fills would measure RAM
    /// speed (~600 MB/s on a 77 MB/s drive) and fake a fast device.
    bytes_acked: Arc<AtomicU64>,
}

impl ProfiledFile {
    fn new(
        file: File,
        values: Arc<ProfileValues>,
        throttle: Option<Arc<Mutex<Throttle>>>,
        bytes_acked: Arc<AtomicU64>,
    ) -> Self {
        Self {
            file,
            buf: Vec::new(),
            values,
            throttle,
            bytes_acked,
        }
    }

    fn write_to_file(&mut self, data: &[u8]) -> std::io::Result<()> {
        if let Some(throttle) = &self.throttle {
            if let Ok(mut t) = throttle.lock() {
                t.admit(data.len());
            }
        }
        self.file.write_all(data)?;
        self.bytes_acked
            .fetch_add(data.len() as u64, Ordering::Relaxed);
        Ok(())
    }

    fn flush_buf(&mut self) -> std::io::Result<()> {
        if !self.buf.is_empty() {
            // Split the borrow: move the buffer out so write_to_file can take
            // &mut self without cloning the data.
            let pending = std::mem::take(&mut self.buf);
            let result = self.write_to_file(&pending);
            // Keep the allocation for the next fill.
            self.buf = pending;
            self.buf.clear();
            result?;
        }
        Ok(())
    }
}

impl Write for ProfiledFile {
    fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
        let cap = self.values.file_buf();
        if self.buf.len() + data.len() > cap {
            self.flush_buf()?;
        }
        if data.len() >= cap {
            self.write_to_file(data)?;
        } else {
            self.buf.extend_from_slice(data);
        }
        Ok(data.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.flush_buf()?;
        self.file.flush()
    }
}

/// A per-table output stream: a plain file, or a streaming compressor over one.
/// Compressing per file keeps every output independent, so the writer pool
/// still runs fully in parallel — and the compression work parallelizes with it.
///
/// Every variant bottoms out in a [`ProfiledFile`], so the physical write size
/// follows the active profile for compressed output too.
enum TableSink {
    Raw(ProfiledFile),
    #[cfg(feature = "compression")]
    Gzip(flate2::write::GzEncoder<ProfiledFile>),
    #[cfg(feature = "compression")]
    Bzip2(bzip2::write::BzEncoder<ProfiledFile>),
    #[cfg(feature = "compression")]
    Xz(xz2::write::XzEncoder<ProfiledFile>),
    #[cfg(feature = "compression")]
    Zstd(zstd::stream::write::Encoder<'static, ProfiledFile>),
}

/// Reduce a parsed table name to a safe single filename component before it is
/// used to build an output path. A quoted identifier can contain path
/// separators or `..` segments (e.g. `` `../../evil` ``); joined verbatim these
/// would escape the output directory, and an absolute-path-like name would even
/// replace the base directory. Taking the final path component and neutralizing
/// all-dot names prevents that while leaving ordinary table names unchanged.
fn sanitize_table_filename(table: &str) -> String {
    let last = table
        .rsplit(['/', '\\'])
        .find(|s| !s.is_empty())
        .unwrap_or("");
    // A NUL byte would truncate the path at the OS boundary; neutralize it.
    let cleaned: String = last.replace('\0', "_");
    // Names consisting only of dots (`.`, `..`, …) are not usable filenames.
    if cleaned.trim_matches('.').is_empty() {
        "_unnamed".to_string()
    } else {
        cleaned
    }
}

/// Claim a case-fold-unique filename for `table` under `dir`, so two tables
/// differing only by case (or otherwise colliding after sanitizing) don't map
/// to one file on a case-insensitive filesystem. The clean `<stem>.sql[.ext]`
/// name is used when free; on collision a suffix derived from the exact table
/// name (deterministic across runs) disambiguates.
fn claim_table_filename(table: &str, ext: &str, reserved: &Mutex<AHashSet<String>>) -> String {
    let stem = sanitize_table_filename(table);
    let mut reserved = reserved.lock().unwrap_or_else(|e| e.into_inner());
    let base = format!("{stem}.sql{ext}");
    if reserved.insert(base.to_lowercase()) {
        return base;
    }
    // Collision: disambiguate by a stable hash of the exact table name (two
    // colliding names have different spellings → different hashes).
    let mut candidate = format!("{stem}-{:08x}.sql{ext}", fnv1a(table));
    let mut n = 2u32;
    while !reserved.insert(candidate.to_lowercase()) {
        candidate = format!("{stem}-{:08x}-{n}.sql{ext}", fnv1a(table));
        n += 1;
    }
    candidate
}

impl TableSink {
    /// Create the `<table>.sql[.ext]` file and wrap it in the chosen encoder.
    #[allow(clippy::too_many_arguments)]
    fn create(
        dir: &Path,
        table: &str,
        format: Compression,
        values: &Arc<ProfileValues>,
        throttle: &Option<Arc<Mutex<Throttle>>>,
        bytes_acked: &Arc<AtomicU64>,
        reserved_names: &Mutex<AHashSet<String>>,
    ) -> std::io::Result<Self> {
        let filename = claim_table_filename(table, format.output_extension(), reserved_names);
        let path = dir.join(filename);
        let file = ProfiledFile::new(
            File::create(&path)?,
            Arc::clone(values),
            throttle.clone(),
            Arc::clone(bytes_acked),
        );
        Ok(match format {
            Compression::None => TableSink::Raw(file),
            #[cfg(feature = "compression")]
            Compression::Gzip => TableSink::Gzip(flate2::write::GzEncoder::new(
                file,
                flate2::Compression::default(),
            )),
            #[cfg(feature = "compression")]
            Compression::Bzip2 => TableSink::Bzip2(bzip2::write::BzEncoder::new(
                file,
                bzip2::Compression::default(),
            )),
            #[cfg(feature = "compression")]
            Compression::Xz => TableSink::Xz(xz2::write::XzEncoder::new(file, 6)),
            #[cfg(feature = "compression")]
            Compression::Zstd => TableSink::Zstd(zstd::stream::write::Encoder::new(file, 3)?),
            // Zip is never selected as per-table output compression:
            // `Compression::parse_output` has no "zip" case, so `--compress
            // zip` stays rejected at the CLI layer (archive output uses `-o
            // dump.zip` instead, see `crate::archive`).
            Compression::Zip => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::Unsupported,
                    "zip is not a valid per-file output compression",
                ))
            }
            #[cfg(not(feature = "compression"))]
            _ => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::Unsupported,
                    "compressed output requires the `compression` feature",
                ))
            }
        })
    }

    fn write_all(&mut self, data: &[u8]) -> std::io::Result<()> {
        match self {
            TableSink::Raw(f) => f.write_all(data),
            #[cfg(feature = "compression")]
            TableSink::Gzip(e) => e.write_all(data),
            #[cfg(feature = "compression")]
            TableSink::Bzip2(e) => e.write_all(data),
            #[cfg(feature = "compression")]
            TableSink::Xz(e) => e.write_all(data),
            #[cfg(feature = "compression")]
            TableSink::Zstd(e) => e.write_all(data),
        }
    }

    /// Finalize the stream, flushing the compressor's epilogue (required for a
    /// valid archive — especially zstd, which writes a frame footer) and then
    /// draining the coalescing buffer beneath it.
    fn finish(self) -> std::io::Result<()> {
        match self {
            TableSink::Raw(mut f) => f.flush(),
            #[cfg(feature = "compression")]
            TableSink::Gzip(e) => e.finish().and_then(|mut f| f.flush()),
            #[cfg(feature = "compression")]
            TableSink::Bzip2(e) => e.finish().and_then(|mut f| f.flush()),
            #[cfg(feature = "compression")]
            TableSink::Xz(e) => e.finish().and_then(|mut f| f.flush()),
            #[cfg(feature = "compression")]
            TableSink::Zstd(e) => e.finish().and_then(|mut f| f.flush()),
        }
    }
}

/// Parallel, pipelined writer pool.
///
/// The producer (parser thread) stages per-table bytes and ships ~256KB chunks
/// over bounded channels to `N` writer threads, each owning a disjoint shard of
/// tables (sharded by name hash). This overlaps parsing with writing (a
/// pipeline / double-buffer) and keeps several writes in flight so a single
/// synchronous thread doesn't bottleneck a fast SSD (queue depth > 1). Batching
/// into large chunks keeps per-statement channel overhead negligible.
///
/// Output is byte-identical to a single-threaded writer: each table's
/// file is written by exactly one thread, in input order. A table's shard is
/// assigned once (on first ship) and never changes, so growing the pool
/// mid-run ([`grow_to`](Self::grow_to)) preserves per-table ordering by
/// construction: already-seen tables keep their owner, only tables first seen
/// after the growth hash across the new shard count.
pub struct ParallelWriters {
    senders: Vec<SyncSender<Chunk>>,
    handles: Vec<JoinHandle<std::io::Result<()>>>,
    error_flag: Arc<AtomicBool>,
    intern: AHashMap<String, Arc<str>>,
    stage: AHashMap<Arc<str>, Vec<u8>>,
    /// Sticky table → shard assignment (fixed at first ship).
    shards: AHashMap<Arc<str>, usize>,
    /// Total bytes currently staged across all tables (bounded by
    /// [`ProfileValues::stage_cap`]).
    staged_bytes: usize,
    /// Bytes written to sinks by the writer threads (shared, monotonically
    /// increasing). One atomic add per ~256KB chunk, so contention is nil.
    bytes_acked: Arc<AtomicU64>,
    /// Nanoseconds the producer spent blocked on full writer channels.
    /// Producer-only, so a plain counter; timing happens only on the slow
    /// path (channel already full), keeping the hot path free of clock reads.
    stall_nanos: u64,
    /// Runtime-swappable profile values shared with the writer threads.
    values: Arc<ProfileValues>,
    /// Everything needed to spawn additional writers later (grow-only).
    output_dir: PathBuf,
    format: Compression,
    capacity: usize,
    throttle: Option<Arc<Mutex<Throttle>>>,
    /// Case-folded output filenames already claimed this run, shared across the
    /// writer threads. Ensures two tables whose names differ only by case (or
    /// otherwise collide after sanitizing) don't map to one file on a
    /// case-insensitive filesystem.
    reserved_names: Arc<Mutex<AHashSet<String>>>,
}

impl ParallelWriters {
    /// Spawn `num_writers` writer threads targeting `output_dir`, compressing
    /// each per-table file with `format`. `capacity` is the per-shard channel
    /// depth (chunks in flight); `values` carries the active profile's
    /// staging/buffer sizes and may be retuned mid-run by the controller.
    pub fn new(
        output_dir: PathBuf,
        num_writers: usize,
        capacity: usize,
        format: Compression,
        values: Arc<ProfileValues>,
    ) -> std::io::Result<Self> {
        fs::create_dir_all(&output_dir)?;
        let mut writers = Self {
            senders: Vec::new(),
            handles: Vec::new(),
            error_flag: Arc::new(AtomicBool::new(false)),
            intern: AHashMap::new(),
            stage: AHashMap::new(),
            shards: AHashMap::new(),
            reserved_names: Arc::new(Mutex::new(AHashSet::new())),
            staged_bytes: 0,
            bytes_acked: Arc::new(AtomicU64::new(0)),
            stall_nanos: 0,
            values,
            output_dir,
            format,
            capacity: capacity.max(1),
            throttle: Throttle::from_env(),
        };
        for _ in 0..num_writers.max(1) {
            writers.spawn_writer();
        }
        Ok(writers)
    }

    fn spawn_writer(&mut self) {
        let (tx, rx) = sync_channel::<Chunk>(self.capacity);
        self.senders.push(tx);
        let dir = self.output_dir.clone();
        let ef = Arc::clone(&self.error_flag);
        let acked = Arc::clone(&self.bytes_acked);
        let values = Arc::clone(&self.values);
        let throttle = self.throttle.clone();
        let format = self.format;
        let reserved = Arc::clone(&self.reserved_names);
        self.handles.push(std::thread::spawn(move || {
            writer_loop(rx, dir, ef, format, acked, values, throttle, reserved)
        }));
    }

    /// Number of writer threads currently running.
    pub fn writer_count(&self) -> usize {
        self.senders.len()
    }

    /// Grow the pool to `n` writer threads (never shrinks — a table's owner
    /// thread must not change mid-run, see the type-level docs). Used by the
    /// adaptive controller's deferred writer spawn: auto mode opens at W=1
    /// and only pays for parallelism once the device has proven fast.
    pub fn grow_to(&mut self, n: usize) {
        while self.senders.len() < n {
            self.spawn_writer();
        }
    }

    /// Snapshot the pipeline's instrumentation counters (monotonic since
    /// construction). Cheap enough to call at every epoch boundary.
    pub fn stats(&self) -> WriterStats {
        WriterStats {
            bytes_acked: self.bytes_acked.load(Ordering::Relaxed),
            send_stall: Duration::from_nanos(self.stall_nanos),
        }
    }

    /// True once any writer thread has hit an I/O error, so the producer can
    /// stop early; the actual error surfaces from [`finish`](Self::finish).
    #[inline]
    pub fn errored(&self) -> bool {
        self.error_flag.load(Ordering::Relaxed)
    }

    /// Stage a statement for its table, appending `suffix` (e.g. `b";"`) and a
    /// newline, shipping a chunk once the table's buffer crosses the threshold.
    pub fn write(&mut self, table_name: &str, stmt: &[u8], suffix: &[u8]) {
        let arc = match self.intern.get(table_name) {
            Some(a) => Arc::clone(a),
            None => {
                let a: Arc<str> = Arc::from(table_name);
                self.intern.insert(table_name.to_string(), Arc::clone(&a));
                a
            }
        };
        let flush_chunk = self.values.flush_chunk();
        let stage_cap = self.values.stage_cap();
        let buf = self.stage.entry(Arc::clone(&arc)).or_default();
        buf.extend_from_slice(stmt);
        buf.extend_from_slice(suffix);
        buf.push(b'\n');
        self.staged_bytes += stmt.len() + suffix.len() + 1;
        if buf.len() >= flush_chunk {
            let data = std::mem::take(buf);
            self.staged_bytes -= data.len();
            self.ship(&arc, data);
        } else if self.staged_bytes >= stage_cap {
            // Many tables, each under the per-table threshold: flush everything
            // so total staging memory stays bounded by the cap.
            let stage = std::mem::take(&mut self.stage);
            for (table, data) in stage {
                if !data.is_empty() {
                    self.ship(&table, data);
                }
            }
            self.staged_bytes = 0;
        }
    }

    fn ship(&mut self, table: &Arc<str>, data: Vec<u8>) {
        // Sticky assignment: hash against the shard count at first ship, then
        // stay put forever — this is what makes grow_to() ordering-safe.
        let shard = match self.shards.entry(Arc::clone(table)) {
            Entry::Occupied(e) => *e.get(),
            Entry::Vacant(e) => *e.insert(shard_index(table, self.senders.len())),
        };
        let chunk = Chunk {
            table: Arc::clone(table),
            data,
        };
        // Fast path: the channel has room, no clock read at all. Only when the
        // writer is backed up do we time the blocking send — that time *is*
        // the `send_stall` backpressure signal. A dead writer's receiver is
        // dropped, so sends error; the real error is surfaced by `finish`,
        // so send failures are ignored here.
        match self.senders[shard].try_send(chunk) {
            Ok(()) => {}
            Err(TrySendError::Full(chunk)) => {
                let blocked = Instant::now();
                let _ = self.senders[shard].send(chunk);
                self.stall_nanos += blocked.elapsed().as_nanos() as u64;
            }
            Err(TrySendError::Disconnected(_)) => {}
        }
    }

    /// Flush all staged data, join the writer threads, and return the first
    /// I/O error encountered (if any).
    pub fn finish(mut self) -> std::io::Result<()> {
        let stage = std::mem::take(&mut self.stage);
        for (table, data) in stage {
            if !data.is_empty() {
                self.ship(&table, data);
            }
        }
        drop(self.senders);

        let mut first_err: Option<std::io::Error> = None;
        for handle in self.handles {
            match handle.join() {
                Ok(Ok(())) => {}
                Ok(Err(e)) => {
                    first_err.get_or_insert(e);
                }
                Err(_) => {
                    first_err
                        .get_or_insert_with(|| std::io::Error::other("writer thread panicked"));
                }
            }
        }
        match first_err {
            Some(e) => Err(e),
            None => Ok(()),
        }
    }
}

/// FNV-1a hash of a string. Deterministic within (and across) runs of the same
/// binary, so both shard assignment and filename disambiguation are stable.
#[inline]
fn fnv1a(s: &str) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for &b in s.as_bytes() {
        h ^= b as u64;
        h = h.wrapping_mul(0x0000_0100_0000_01b3);
    }
    h
}

/// FNV-1a hash of the table name → shard index. Deterministic within a run so a
/// table always maps to the same writer (preserving per-file order).
#[inline]
fn shard_index(table: &str, n: usize) -> usize {
    (fnv1a(table) % n as u64) as usize
}

#[allow(clippy::too_many_arguments)]
fn writer_loop(
    rx: Receiver<Chunk>,
    output_dir: PathBuf,
    error_flag: Arc<AtomicBool>,
    format: Compression,
    bytes_acked: Arc<AtomicU64>,
    values: Arc<ProfileValues>,
    throttle: Option<Arc<Mutex<Throttle>>>,
    reserved_names: Arc<Mutex<AHashSet<String>>>,
) -> std::io::Result<()> {
    // Chunks arrive pre-batched at the profile's flush size; the ProfiledFile
    // beneath each sink coalesces them further up to the profile's file_buf.
    let mut sinks: AHashMap<Arc<str>, TableSink> = AHashMap::new();
    let mut first_err: Option<std::io::Error> = None;

    for chunk in rx {
        if first_err.is_some() {
            continue; // keep draining so the producer never blocks
        }
        let sink = match sinks.entry(Arc::clone(&chunk.table)) {
            Entry::Occupied(e) => e.into_mut(),
            Entry::Vacant(e) => {
                match TableSink::create(
                    &output_dir,
                    &chunk.table,
                    format,
                    &values,
                    &throttle,
                    &bytes_acked,
                    &reserved_names,
                ) {
                    Ok(s) => e.insert(s),
                    Err(err) => {
                        error_flag.store(true, Ordering::Relaxed);
                        first_err = Some(err);
                        continue;
                    }
                }
            }
        };
        // `bytes_acked` is NOT counted here: this write may land in the
        // sink's coalescing buffer (or a compressor's internal state), and
        // counting buffered bytes as "written" would report RAM speed to the
        // controller. The [`ProfiledFile`] at the bottom of every sink counts
        // bytes as its `write(2)` calls to the output file return.
        if let Err(err) = sink.write_all(&chunk.data) {
            error_flag.store(true, Ordering::Relaxed);
            first_err = Some(err);
        }
    }

    // Finalize every sink so compressor epilogues are flushed (best effort even
    // after an error, so files close cleanly).
    for (_, sink) in sinks.drain() {
        if let Err(err) = sink.finish() {
            error_flag.store(true, Ordering::Relaxed);
            if first_err.is_none() {
                first_err = Some(err);
            }
        }
    }

    match first_err {
        Some(e) => Err(e),
        None => Ok(()),
    }
}