Skip to main content

sql_splitter/writer/
profile.rs

1//! Adaptive I/O strategys: named writer configurations plus the shared,
2//! atomically-swappable runtime values that let the controller retune the
3//! write pipeline mid-run without stopping writer threads.
4//!
5//! Design: `docs/features/ADAPTIVE_IO_PROFILES.md`. One configuration cannot
6//! serve NVMe (wants parallel writers, small buffers), spinning disks (wants
7//! one writer, huge sequential writes), and cheap flash / network mounts
8//! (wants the fewest write *operations*). The three named profiles capture
9//! those device classes; `--io-strategy auto` opens with a probe-chosen
10//! profile and lets the feedback controller own the truth afterwards.
11
12use std::io::Write;
13use std::path::Path;
14use std::sync::atomic::{AtomicUsize, Ordering};
15use std::time::Instant;
16
17const KIB: usize = 1024;
18const MIB: usize = 1024 * 1024;
19
20/// The three device-class states of the adaptive controller.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum ProfileKind {
23    /// NVMe/SSD: parallel writers, small buffers (today's defaults).
24    Ssd,
25    /// Rotational media / same-spindle read+write: one writer, big
26    /// sequential writes so the head seeks as rarely as possible.
27    SlowSeek,
28    /// Cheap flash and network filesystems: per-operation cost dominates, so
29    /// issue the fewest, largest write operations we can.
30    SlowOps,
31}
32
33impl ProfileKind {
34    /// Human-readable name used in transition log lines and `--io-strategy`.
35    /// `ssd` (not "fast") because it names the device class the settings are
36    /// tuned for — on a spinning disk the SSD settings are the *slow* choice.
37    pub fn label(self) -> &'static str {
38        match self {
39            ProfileKind::Ssd => "ssd",
40            ProfileKind::SlowSeek => "hdd",
41            ProfileKind::SlowOps => "cheap",
42        }
43    }
44}
45
46/// The `--io-strategy` CLI choice: a pinned named profile, or `auto`
47/// (probe + feedback controller).
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
49pub enum IoStrategy {
50    #[default]
51    Auto,
52    Ssd,
53    Hdd,
54    Cheap,
55}
56
57impl IoStrategy {
58    /// Parse the `--io-strategy` flag value.
59    pub fn parse(s: &str) -> Result<Self, String> {
60        match s.to_lowercase().as_str() {
61            "auto" | "" => Ok(IoStrategy::Auto),
62            // `fast` is a compatibility alias for `ssd` (the pre-rename name).
63            "ssd" => Ok(IoStrategy::Ssd),
64            "hdd" => Ok(IoStrategy::Hdd),
65            // The honest name. The aliases are for everyone who has ever fought
66            // a no-name USB stick from a conference and knows exactly which
67            // profile they need.
68            "cheap" | "potato" => Ok(IoStrategy::Cheap),
69            other => Err(format!(
70                "Unknown I/O strategy '{other}'. Valid: auto, ssd, hdd, cheap"
71            )),
72        }
73    }
74
75    /// The pinned profile kind, or `None` for `auto`.
76    pub fn pinned(self) -> Option<ProfileKind> {
77        match self {
78            IoStrategy::Auto => None,
79            IoStrategy::Ssd => Some(ProfileKind::Ssd),
80            IoStrategy::Hdd => Some(ProfileKind::SlowSeek),
81            IoStrategy::Cheap => Some(ProfileKind::SlowOps),
82        }
83    }
84}
85
86/// A concrete writer configuration: everything that used to be hard-coded
87/// consts (`STAGE_FLUSH`, `STAGE_TOTAL_CAP`) or env-only knobs, as one value.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct WriterProfile {
90    /// Number of writer threads (target; growth is deferred in auto mode).
91    pub writers: usize,
92    /// Per-table staging threshold: a table's staged bytes ship to its writer
93    /// once they cross this size.
94    pub flush_chunk: usize,
95    /// Per-file output buffer: writer threads coalesce chunks up to this size
96    /// before issuing the actual file write.
97    pub file_buf: usize,
98    /// Cap on total bytes staged across all tables on the producer side.
99    pub stage_cap: usize,
100}
101
102impl WriterProfile {
103    /// The named profile table from the design doc.
104    ///
105    /// `compressing` matters only for `Fast`: compression is CPU-bound on
106    /// fast media, so it gets all cores there. Per the 2026-07-16 amendment,
107    /// the slow profiles pin writers to 1 *unconditionally* — on seek-bound
108    /// media extra compression writers thrash the spindle and end up slower
109    /// than plain output (measured 22.1 vs 34.5 MB/s at 100 GB scale).
110    pub fn for_kind(kind: ProfileKind, cores: usize, compressing: bool) -> Self {
111        match kind {
112            ProfileKind::Ssd => Self {
113                writers: if compressing { cores } else { cores.min(4) },
114                flush_chunk: 256 * KIB,
115                file_buf: 256 * KIB,
116                stage_cap: 32 * MIB,
117            },
118            ProfileKind::SlowSeek => Self {
119                writers: 1,
120                flush_chunk: 8 * MIB,
121                file_buf: 64 * MIB,
122                stage_cap: 256 * MIB,
123            },
124            ProfileKind::SlowOps => Self {
125                writers: 1,
126                flush_chunk: 32 * MIB,
127                file_buf: 64 * MIB,
128                stage_cap: 512 * MIB,
129            },
130        }
131    }
132
133    /// Apply the expert env overrides. Precedence: env > explicit flag >
134    /// auto — these two knobs predate the profiles and keep working, pinning
135    /// their value across every profile the controller may switch to.
136    ///
137    /// - `SQL_SPLITTER_WRITERS`: writer count (also disables deferred growth).
138    /// - `SQL_SPLITTER_WRITE_BUF`: per-file output buffer size in bytes.
139    pub fn with_env_overrides(mut self) -> Self {
140        if let Some(n) = env_writer_count() {
141            self.writers = n;
142        }
143        if let Some(n) = env_usize("SQL_SPLITTER_WRITE_BUF").filter(|&n| n >= 4096) {
144            self.file_buf = n;
145        }
146        self
147    }
148}
149
150/// The `SQL_SPLITTER_WRITERS` env override, if set to a valid count. When
151/// present it pins the writer count in every mode, which also disables the
152/// controller's deferred writer growth.
153pub fn env_writer_count() -> Option<usize> {
154    env_usize("SQL_SPLITTER_WRITERS").filter(|&n| n >= 1)
155}
156
157/// Parse an env var as `usize`, treating absence and garbage the same.
158fn env_usize(name: &str) -> Option<usize> {
159    std::env::var(name).ok().and_then(|v| v.parse().ok())
160}
161
162/// The runtime-swappable subset of a [`WriterProfile`], shared between the
163/// producer, the writer threads, and the controller.
164///
165/// Writer *count* is deliberately absent: it can only grow (each table is
166/// owned by one thread, and that ownership is what keeps output
167/// byte-identical), so growth is a structural operation on the pool, not a
168/// value swap. Everything else is a plain number read at flush points, so a
169/// relaxed atomic swap retunes the pipeline mid-run with zero coordination.
170#[derive(Debug)]
171pub struct ProfileValues {
172    flush_chunk: AtomicUsize,
173    file_buf: AtomicUsize,
174    stage_cap: AtomicUsize,
175}
176
177impl ProfileValues {
178    /// Initialize from a profile.
179    pub fn new(profile: &WriterProfile) -> Self {
180        Self {
181            flush_chunk: AtomicUsize::new(profile.flush_chunk),
182            file_buf: AtomicUsize::new(profile.file_buf),
183            stage_cap: AtomicUsize::new(profile.stage_cap),
184        }
185    }
186
187    /// Swap in a new profile's values (a controller transition).
188    pub fn apply(&self, profile: &WriterProfile) {
189        self.flush_chunk
190            .store(profile.flush_chunk, Ordering::Relaxed);
191        self.file_buf.store(profile.file_buf, Ordering::Relaxed);
192        self.stage_cap.store(profile.stage_cap, Ordering::Relaxed);
193    }
194
195    #[inline]
196    pub fn flush_chunk(&self) -> usize {
197        self.flush_chunk.load(Ordering::Relaxed)
198    }
199
200    #[inline]
201    pub fn file_buf(&self) -> usize {
202        self.file_buf.load(Ordering::Relaxed)
203    }
204
205    #[inline]
206    pub fn stage_cap(&self) -> usize {
207        self.stage_cap.load(Ordering::Relaxed)
208    }
209}
210
211/// Bytes written (and fsynced) by the startup probe.
212const PROBE_BYTES: usize = 8 * MIB;
213
214/// Probe the output directory to choose `auto`'s *opening* profile: write and
215/// fsync 8 MB, classify by the sustained rate. This is a hint only — the
216/// feedback controller owns the truth once the pipeline is running. Costs
217/// ~100 ms on NVMe; on slow media the cost is itself the signal.
218///
219/// The hidden env `SQL_SPLITTER_IO_PROBE` (`ssd` | `hdd` | `cheap`)
220/// forces the verdict without touching the disk — the deterministic seam the
221/// integration tests use.
222///
223/// Errors are swallowed into a `Fast` verdict: a probe failure (exotic
224/// filesystem, permissions race) must never fail the actual split.
225pub fn probe_output_dir(dir: &Path) -> ProfileKind {
226    if let Ok(forced) = std::env::var("SQL_SPLITTER_IO_PROBE") {
227        if let Ok(profile) = IoStrategy::parse(&forced) {
228            if let Some(kind) = profile.pinned() {
229                return kind;
230            }
231        }
232    }
233    match run_probe(dir) {
234        Ok(mbps) => {
235            if mbps > 80.0 {
236                ProfileKind::Ssd
237            } else if mbps >= 10.0 {
238                ProfileKind::SlowSeek
239            } else {
240                ProfileKind::SlowOps
241            }
242        }
243        Err(_) => ProfileKind::Ssd,
244    }
245}
246
247/// Write + fsync [`PROBE_BYTES`] into `dir`, returning the observed MB/s.
248fn run_probe(dir: &Path) -> std::io::Result<f64> {
249    std::fs::create_dir_all(dir)?;
250    let path = dir.join(".sqlsplit-io-probe");
251    let result = (|| {
252        let mut file = std::fs::File::create(&path)?;
253        let block = vec![0u8; MIB];
254        let start = Instant::now();
255        for _ in 0..(PROBE_BYTES / MIB) {
256            file.write_all(&block)?;
257        }
258        file.sync_all()?;
259        let secs = start.elapsed().as_secs_f64().max(1e-9);
260        Ok(PROBE_BYTES as f64 / MIB as f64 / secs)
261    })();
262    // Best-effort cleanup either way; the verdict matters, the file doesn't.
263    let _ = std::fs::remove_file(&path);
264    result
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270
271    #[test]
272    fn profile_table_matches_design_doc() {
273        let fast = WriterProfile::for_kind(ProfileKind::Ssd, 8, false);
274        assert_eq!(fast.writers, 4);
275        assert_eq!(fast.flush_chunk, 256 * KIB);
276        assert_eq!(fast.file_buf, 256 * KIB);
277        assert_eq!(fast.stage_cap, 32 * MIB);
278
279        let seek = WriterProfile::for_kind(ProfileKind::SlowSeek, 8, false);
280        assert_eq!(
281            seek,
282            WriterProfile {
283                writers: 1,
284                flush_chunk: 8 * MIB,
285                file_buf: 64 * MIB,
286                stage_cap: 256 * MIB,
287            }
288        );
289
290        let ops = WriterProfile::for_kind(ProfileKind::SlowOps, 8, false);
291        assert_eq!(
292            ops,
293            WriterProfile {
294                writers: 1,
295                flush_chunk: 32 * MIB,
296                file_buf: 64 * MIB,
297                stage_cap: 512 * MIB,
298            }
299        );
300    }
301
302    #[test]
303    fn fast_profile_uses_all_cores_when_compressing() {
304        assert_eq!(
305            WriterProfile::for_kind(ProfileKind::Ssd, 8, true).writers,
306            8
307        );
308        assert_eq!(
309            WriterProfile::for_kind(ProfileKind::Ssd, 2, false).writers,
310            2
311        );
312    }
313
314    /// 2026-07-16 amendment: slow profiles pin W=1 even for compression.
315    #[test]
316    fn slow_profiles_cap_compression_writers_at_one() {
317        assert_eq!(
318            WriterProfile::for_kind(ProfileKind::SlowSeek, 16, true).writers,
319            1
320        );
321        assert_eq!(
322            WriterProfile::for_kind(ProfileKind::SlowOps, 16, true).writers,
323            1
324        );
325    }
326
327    #[test]
328    fn io_profile_parsing() {
329        assert_eq!(IoStrategy::parse("auto"), Ok(IoStrategy::Auto));
330        assert_eq!(IoStrategy::parse("ssd"), Ok(IoStrategy::Ssd));
331        assert_eq!(IoStrategy::parse("HDD"), Ok(IoStrategy::Hdd));
332        assert_eq!(IoStrategy::parse("potato"), Ok(IoStrategy::Cheap));
333        assert!(IoStrategy::parse("turbo").is_err());
334    }
335
336    #[test]
337    fn profile_values_swap() {
338        let fast = WriterProfile::for_kind(ProfileKind::Ssd, 4, false);
339        let seek = WriterProfile::for_kind(ProfileKind::SlowSeek, 4, false);
340        let values = ProfileValues::new(&fast);
341        assert_eq!(values.flush_chunk(), fast.flush_chunk);
342        values.apply(&seek);
343        assert_eq!(values.flush_chunk(), seek.flush_chunk);
344        assert_eq!(values.file_buf(), seek.file_buf);
345        assert_eq!(values.stage_cap(), seek.stage_cap);
346    }
347}