1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum ProfileKind {
23 Ssd,
25 SlowSeek,
28 SlowOps,
31}
32
33impl ProfileKind {
34 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#[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 pub fn parse(s: &str) -> Result<Self, String> {
60 match s.to_lowercase().as_str() {
61 "auto" | "" => Ok(IoStrategy::Auto),
62 "ssd" => Ok(IoStrategy::Ssd),
64 "hdd" => Ok(IoStrategy::Hdd),
65 "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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct WriterProfile {
90 pub writers: usize,
92 pub flush_chunk: usize,
95 pub file_buf: usize,
98 pub stage_cap: usize,
100}
101
102impl WriterProfile {
103 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 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
150pub fn env_writer_count() -> Option<usize> {
154 env_usize("SQL_SPLITTER_WRITERS").filter(|&n| n >= 1)
155}
156
157fn env_usize(name: &str) -> Option<usize> {
159 std::env::var(name).ok().and_then(|v| v.parse().ok())
160}
161
162#[derive(Debug)]
171pub struct ProfileValues {
172 flush_chunk: AtomicUsize,
173 file_buf: AtomicUsize,
174 stage_cap: AtomicUsize,
175}
176
177impl ProfileValues {
178 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 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
211const PROBE_BYTES: usize = 8 * MIB;
213
214pub 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
247fn 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 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 #[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}