rivet-cli 0.14.0

Rivet: PostgreSQL/MySQL/SQL Server → Parquet/CSV (local, S3, GCS, Azure). Crate name rivet-cli; binary rivet.
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
//! Tuning profiles and the resolved `SourceTuning` config.
//!
//! Three baked-in profiles (`Fast`, `Balanced`, `Safe`) ship per-field defaults;
//! a YAML `TuningConfig` can override individual fields and the chosen profile.
//! `from_config_with_default_profile` is the production entry point and is
//! wired in [`crate::plan::build`] to honour `source.environment:` —
//! `Local` → `Fast`, `Replica`/`Production` → `Balanced`.

use arrow::datatypes::SchemaRef;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::memory::{compute_batch_size_from_memory, estimate_row_bytes};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourceTuning {
    pub batch_size: usize,
    pub batch_size_memory_mb: Option<usize>,
    pub throttle_ms: u64,
    pub statement_timeout_s: u64,
    pub max_retries: u32,
    pub retry_backoff_ms: u64,
    pub lock_timeout_s: u64,
    /// RSS limit in MB before chunk processing throttles. `0` = no limit (disabled).
    pub memory_threshold_mb: usize,
    /// Hard cap on a single Arrow batch in MB. `None` = no cap.
    pub max_batch_memory_mb: Option<usize>,
    pub on_batch_memory_exceeded: BatchMemoryPolicy,
    /// When true, Rivet samples DB pressure metrics every
    /// [`super::ADAPTIVE_SAMPLE_INTERVAL`] batches and shrinks/restores the
    /// fetch size in response. Default: false.
    pub adaptive: bool,
    /// Floor for the OPT-2 concurrency governor: the lowest worker/connection
    /// count it will back parallelism down to under source pressure. `None`
    /// ⇒ 1. The ceiling is the export's configured `parallel`. Only consulted
    /// when `adaptive` is on and `parallel > 1`.
    pub min_parallel: Option<usize>,
    /// Hard ceiling on a single cell/value in MB (OPT-1 memory hardening): a
    /// variable-length value (text/JSON/blob) larger than this aborts the run
    /// with `RIVET_VALUE_TOO_LARGE` instead of risking OOM, since the
    /// average-based batch cap can't bound one giant cell. `Some(0)` / `None`
    /// disable the guard. Default: 256 MiB.
    pub max_value_mb: Option<usize>,
    configured_profile: TuningProfile,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TuningProfile {
    Fast,
    Balanced,
    Safe,
}

/// Action taken when a single Arrow batch exceeds `max_batch_memory_mb`.
#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum BatchMemoryPolicy {
    /// Log a warning and continue. (default)
    #[default]
    Warn,
    /// Return an error — the export fails immediately.
    Fail,
    /// Split the oversized batch in half recursively until each sub-batch fits,
    /// then process them individually. Transparent to the rest of the pipeline.
    AutoShrink,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema, Default, Clone)]
#[serde(deny_unknown_fields)]
pub struct TuningConfig {
    pub profile: Option<TuningProfile>,
    pub batch_size: Option<usize>,
    /// Target memory per batch in MB. Mutually exclusive with batch_size.
    pub batch_size_memory_mb: Option<usize>,
    pub throttle_ms: Option<u64>,
    pub statement_timeout_s: Option<u64>,
    pub max_retries: Option<u32>,
    pub retry_backoff_ms: Option<u64>,
    pub lock_timeout_s: Option<u64>,
    pub memory_threshold_mb: Option<usize>,
    /// Hard cap on Arrow batch memory in MB. When a batch exceeds this limit,
    /// `on_batch_memory_exceeded` determines the response.
    pub max_batch_memory_mb: Option<usize>,
    /// Policy applied when a batch exceeds `max_batch_memory_mb`. Default: `warn`.
    pub on_batch_memory_exceeded: Option<BatchMemoryPolicy>,
    /// Enable real-time batch size adaptation based on DB pressure metrics.
    /// Postgres: samples `pg_stat_bgwriter`. MySQL: samples `Innodb_log_waits`.
    /// Also arms the OPT-2 concurrency governor when `parallel > 1`.
    pub adaptive: Option<bool>,
    /// Floor for the concurrency governor (lowest parallelism under pressure).
    /// Default 1. Ceiling is the export's `parallel`.
    pub min_parallel: Option<usize>,
    /// Hard per-value size ceiling in MB. A single text/JSON/blob cell larger
    /// than this aborts the run with `RIVET_VALUE_TOO_LARGE`. `0` disables the
    /// guard. Default: 256.
    pub max_value_mb: Option<usize>,
}

/// Layer `export` on top of `source`: each field uses export when set, otherwise source.
/// `None` only when both inputs are `None`.
pub fn merge_tuning_config(
    source: Option<&TuningConfig>,
    export: Option<&TuningConfig>,
) -> Option<TuningConfig> {
    match (source, export) {
        (None, None) => None,
        (Some(s), None) => Some(s.clone()),
        (None, Some(e)) => Some(e.clone()),
        (Some(s), Some(e)) => Some(TuningConfig {
            profile: e.profile.or(s.profile),
            batch_size: e.batch_size.or(s.batch_size),
            batch_size_memory_mb: e.batch_size_memory_mb.or(s.batch_size_memory_mb),
            throttle_ms: e.throttle_ms.or(s.throttle_ms),
            statement_timeout_s: e.statement_timeout_s.or(s.statement_timeout_s),
            max_retries: e.max_retries.or(s.max_retries),
            retry_backoff_ms: e.retry_backoff_ms.or(s.retry_backoff_ms),
            lock_timeout_s: e.lock_timeout_s.or(s.lock_timeout_s),
            memory_threshold_mb: e.memory_threshold_mb.or(s.memory_threshold_mb),
            max_batch_memory_mb: e.max_batch_memory_mb.or(s.max_batch_memory_mb),
            on_batch_memory_exceeded: e.on_batch_memory_exceeded.or(s.on_batch_memory_exceeded),
            adaptive: e.adaptive.or(s.adaptive),
            min_parallel: e.min_parallel.or(s.min_parallel),
            max_value_mb: e.max_value_mb.or(s.max_value_mb),
        }),
    }
}

impl SourceTuning {
    /// The per-value byte ceiling: `max_value_mb` converted to bytes, with
    /// `Some(0)` / `None` meaning "disabled". Single source of truth shared by
    /// the sink's post-materialization guard (`sink::check_value_ceiling`) and
    /// the per-engine pre-allocation guard (`source::value_within_ceiling`), so
    /// the two definitions of "0 disables" can never drift apart.
    pub(crate) fn max_value_bytes(&self) -> Option<usize> {
        self.max_value_mb
            .filter(|&mb| mb > 0)
            .map(|mb| mb * 1024 * 1024)
    }

    /// Build tuning with the legacy `Balanced` fallback. Public for downstream
    /// callers and tests; production resolution in [`crate::plan::build`] uses
    /// [`Self::from_config_with_default_profile`] so that `source.environment:`
    /// can pick the right default.
    #[allow(dead_code)]
    pub fn from_config(config: Option<&TuningConfig>) -> Self {
        Self::from_config_with_default_profile(config, TuningProfile::Balanced)
    }

    /// Like [`Self::from_config`] but lets the caller override the fallback
    /// profile used when `config.profile` is unset.
    pub fn from_config_with_default_profile(
        config: Option<&TuningConfig>,
        fallback_profile: TuningProfile,
    ) -> Self {
        let profile = config.and_then(|c| c.profile).unwrap_or(fallback_profile);

        let mut tuning = Self::from_profile(profile);
        tuning.configured_profile = profile;

        if let Some(cfg) = config {
            if let Some(v) = cfg.batch_size {
                tuning.batch_size = v;
            }
            tuning.batch_size_memory_mb = cfg.batch_size_memory_mb;
            if let Some(v) = cfg.throttle_ms {
                tuning.throttle_ms = v;
            }
            if let Some(v) = cfg.statement_timeout_s {
                tuning.statement_timeout_s = v;
            }
            if let Some(v) = cfg.max_retries {
                tuning.max_retries = v;
            }
            if let Some(v) = cfg.retry_backoff_ms {
                tuning.retry_backoff_ms = v;
            }
            if let Some(v) = cfg.lock_timeout_s {
                tuning.lock_timeout_s = v;
            }
            if let Some(v) = cfg.memory_threshold_mb {
                tuning.memory_threshold_mb = v;
            }
            tuning.max_batch_memory_mb = cfg.max_batch_memory_mb;
            if let Some(v) = cfg.on_batch_memory_exceeded {
                tuning.on_batch_memory_exceeded = v;
            }
            if let Some(v) = cfg.adaptive {
                tuning.adaptive = v;
            }
            if cfg.min_parallel.is_some() {
                tuning.min_parallel = cfg.min_parallel;
            }
            if cfg.max_value_mb.is_some() {
                tuning.max_value_mb = cfg.max_value_mb;
            }
        }

        tuning
    }

    fn from_profile(profile: TuningProfile) -> Self {
        match profile {
            TuningProfile::Fast => Self {
                // Memory-driven, 2× Balanced's target (see its note). Narrow tables
                // still clamp to 150k; the larger target only sizes up wide ones.
                batch_size: 50_000,
                batch_size_memory_mb: Some(64),
                throttle_ms: 0,
                statement_timeout_s: 0,
                max_retries: 1,
                retry_backoff_ms: 1_000,
                lock_timeout_s: 0,
                memory_threshold_mb: 0,
                max_batch_memory_mb: None,
                on_batch_memory_exceeded: BatchMemoryPolicy::Warn,
                adaptive: false,
                min_parallel: None,
                max_value_mb: Some(256),
                configured_profile: TuningProfile::Fast,
            },
            TuningProfile::Balanced => Self {
                // Memory-driven batch by default: a 32 MB-per-flush target sizes the
                // batch to the row width — large for narrow tables (where the 150k
                // hard-max in `compute_batch_size_from_memory`, not this target, binds
                // and bounds the raw-row accumulator's RSS), small for wide ones. 32
                // not 64 MB: a 64 MB target grew medium-wide tables (~2.6 KB/row) to
                // ~21k rows — ~6% slower for zero flush-count gain — while 32 MB lands
                // them near the old static 10k; narrow tables are unaffected (clamp
                // binds either way). The static `batch_size` below is the no-schema
                // fallback + advisory base.
                batch_size: 10_000,
                batch_size_memory_mb: Some(32),
                throttle_ms: 50,
                statement_timeout_s: 300,
                max_retries: 3,
                retry_backoff_ms: 2_000,
                lock_timeout_s: 30,
                memory_threshold_mb: 4_096,
                max_batch_memory_mb: None,
                on_batch_memory_exceeded: BatchMemoryPolicy::Warn,
                adaptive: false,
                min_parallel: None,
                max_value_mb: Some(256),
                configured_profile: TuningProfile::Balanced,
            },
            TuningProfile::Safe => Self {
                batch_size: 2_000,
                batch_size_memory_mb: None,
                throttle_ms: 500,
                statement_timeout_s: 120,
                max_retries: 5,
                retry_backoff_ms: 5_000,
                lock_timeout_s: 10,
                memory_threshold_mb: 2_048,
                max_batch_memory_mb: None,
                on_batch_memory_exceeded: BatchMemoryPolicy::Warn,
                adaptive: false,
                min_parallel: None,
                max_value_mb: Some(256),
                configured_profile: TuningProfile::Safe,
            },
        }
    }

    pub fn profile_name(&self) -> &'static str {
        match self.configured_profile {
            TuningProfile::Fast => "fast",
            TuningProfile::Balanced => "balanced",
            TuningProfile::Safe => "safe",
        }
    }

    /// If `batch_size_memory_mb` is set, compute and return an adjusted batch_size
    /// from the schema; otherwise return the configured `batch_size`.
    pub fn effective_batch_size(&self, schema: Option<&SchemaRef>) -> usize {
        if let (Some(mem_mb), Some(schema)) = (self.batch_size_memory_mb, schema) {
            let computed = compute_batch_size_from_memory(mem_mb, schema);
            log::info!(
                "batch_size_memory_mb={}: estimated row ~{}B, computed batch_size={}",
                mem_mb,
                estimate_row_bytes(schema),
                computed
            );
            computed
        } else {
            self.batch_size
        }
    }

    /// Return the actual Arrow memory footprint of a batch in bytes.
    ///
    /// Sums `get_array_memory_size()` across all columns — includes buffers for
    /// validity bitmaps, offsets, and value data. Does not include Arrow struct
    /// overhead (~few hundred bytes) which is negligible at batch scale.
    pub fn batch_memory_bytes(batch: &arrow::record_batch::RecordBatch) -> usize {
        batch
            .columns()
            .iter()
            .map(|col| col.get_array_memory_size())
            .sum()
    }

    /// Produce a `ResourceSummary` from the resolved tuning settings.
    ///
    /// The summary requires no database connection. It reports two batch-memory
    /// bounds based on narrow-table (~200 B/row) and wide-table (~10 KB/row)
    /// heuristics. A `wide_table_risk` flag is set when the upper bound exceeds
    /// 128 MB per batch.
    pub fn resource_summary(&self) -> ResourceSummary {
        const NARROW_BYTES: f64 = 200.0;
        const WIDE_BYTES: f64 = 10_240.0;
        let batch = self.batch_size as f64;
        let batch_narrow_mb = batch * NARROW_BYTES / (1024.0 * 1024.0);
        let batch_wide_mb = batch * WIDE_BYTES / (1024.0 * 1024.0);
        ResourceSummary {
            profile: self.profile_name().to_string(),
            batch_size: self.batch_size,
            batch_size_memory_mb: self.batch_size_memory_mb,
            memory_threshold_mb: self.memory_threshold_mb,
            throttle_ms: self.throttle_ms,
            batch_narrow_mb,
            batch_wide_mb,
            wide_table_risk: batch_wide_mb > 128.0,
        }
    }
}

impl std::fmt::Display for SourceTuning {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "profile={}, batch_size={}, throttle={}ms, timeout={}s, retries={}, lock_timeout={}s",
            self.profile_name(),
            self.batch_size,
            self.throttle_ms,
            self.statement_timeout_s,
            self.max_retries,
            self.lock_timeout_s,
        )
    }
}

/// Resource estimate computed from tuning settings alone (no DB connection required).
///
/// `batch_narrow_mb` and `batch_wide_mb` bracket the expected per-batch memory:
/// - narrow table: ~200 B/row (int-heavy, no text blobs)
/// - wide table  : ~10 KB/row (many text/JSON/binary columns)
///
/// Use `wide_table_risk` to decide whether to recommend `adaptive_batch` or a
/// lower `batch_size`.
#[derive(Debug, Clone)]
pub struct ResourceSummary {
    #[allow(dead_code)]
    pub profile: String,
    pub batch_size: usize,
    pub batch_size_memory_mb: Option<usize>,
    pub memory_threshold_mb: usize,
    pub throttle_ms: u64,
    pub batch_narrow_mb: f64,
    pub batch_wide_mb: f64,
    pub wide_table_risk: bool,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cfg_with_profile(profile: TuningProfile) -> TuningConfig {
        TuningConfig {
            profile: Some(profile),
            ..Default::default()
        }
    }

    #[test]
    fn default_config_uses_balanced_profile() {
        let t = SourceTuning::from_config(None);
        assert_eq!(t.batch_size, 10_000);
        assert_eq!(t.throttle_ms, 50);
        assert_eq!(t.statement_timeout_s, 300);
        assert_eq!(t.max_retries, 3);
        assert_eq!(t.retry_backoff_ms, 2_000);
        assert_eq!(t.lock_timeout_s, 30);
    }

    #[test]
    fn fallback_profile_used_when_no_profile_in_config() {
        let t = SourceTuning::from_config_with_default_profile(None, TuningProfile::Fast);
        assert_eq!(t.batch_size, 50_000);
        assert_eq!(t.throttle_ms, 0, "fallback to Fast must zero the throttle");
        assert_eq!(t.profile_name(), "fast");

        let t = SourceTuning::from_config_with_default_profile(None, TuningProfile::Safe);
        assert_eq!(t.throttle_ms, 500);
        assert_eq!(t.profile_name(), "safe");
    }

    #[test]
    fn explicit_profile_wins_over_fallback() {
        let cfg = cfg_with_profile(TuningProfile::Balanced);
        let t = SourceTuning::from_config_with_default_profile(Some(&cfg), TuningProfile::Fast);
        assert_eq!(
            t.throttle_ms, 50,
            "explicit balanced profile must keep its throttle"
        );
        assert_eq!(t.profile_name(), "balanced");
    }

    #[test]
    fn fast_profile_favors_throughput() {
        let t = SourceTuning::from_config(Some(&cfg_with_profile(TuningProfile::Fast)));
        assert_eq!(t.batch_size, 50_000);
        assert_eq!(t.throttle_ms, 0);
        assert_eq!(t.statement_timeout_s, 0);
        assert_eq!(t.max_retries, 1);
    }

    #[test]
    fn safe_profile_limits_impact() {
        let t = SourceTuning::from_config(Some(&cfg_with_profile(TuningProfile::Safe)));
        assert_eq!(t.batch_size, 2_000);
        assert_eq!(t.throttle_ms, 500);
        assert_eq!(t.statement_timeout_s, 120);
        assert_eq!(t.max_retries, 5);
        assert_eq!(t.retry_backoff_ms, 5_000);
        assert_eq!(t.lock_timeout_s, 10);
    }

    #[test]
    fn explicit_fields_override_profile_defaults() {
        let cfg = TuningConfig {
            profile: Some(TuningProfile::Safe),
            batch_size: Some(3_000),
            throttle_ms: Some(250),
            ..Default::default()
        };
        let t = SourceTuning::from_config(Some(&cfg));
        assert_eq!(t.batch_size, 3_000, "explicit batch_size should win");
        assert_eq!(t.throttle_ms, 250, "explicit throttle_ms should win");
        assert_eq!(
            t.statement_timeout_s, 120,
            "non-overridden field stays at safe default"
        );
        assert_eq!(
            t.max_retries, 5,
            "non-overridden field stays at safe default"
        );
    }

    #[test]
    fn profile_name_fast() {
        let t = SourceTuning::from_config(Some(&cfg_with_profile(TuningProfile::Fast)));
        assert_eq!(t.profile_name(), "fast");
    }

    #[test]
    fn profile_name_balanced() {
        let t = SourceTuning::from_config(None);
        assert_eq!(t.profile_name(), "balanced");
    }

    #[test]
    fn profile_name_safe() {
        let t = SourceTuning::from_config(Some(&cfg_with_profile(TuningProfile::Safe)));
        assert_eq!(t.profile_name(), "safe");
    }

    #[test]
    fn display_contains_all_fields() {
        let t = SourceTuning::from_config(None);
        let s = t.to_string();
        assert!(s.contains("profile=balanced"), "missing profile in: {s}");
        assert!(s.contains("batch_size=10000"), "missing batch_size in: {s}");
        assert!(s.contains("throttle=50ms"), "missing throttle in: {s}");
        assert!(s.contains("timeout=300s"), "missing timeout in: {s}");
        assert!(s.contains("retries=3"), "missing retries in: {s}");
        assert!(
            s.contains("lock_timeout=30s"),
            "missing lock_timeout in: {s}"
        );
    }

    #[test]
    fn merge_tuning_export_overrides_source_fields() {
        let source = TuningConfig {
            profile: Some(TuningProfile::Fast),
            batch_size: Some(1_000),
            throttle_ms: Some(0),
            ..Default::default()
        };
        let export = TuningConfig {
            profile: Some(TuningProfile::Safe),
            batch_size: None,
            ..Default::default()
        };
        let m = merge_tuning_config(Some(&source), Some(&export)).expect("merged");
        assert_eq!(m.profile, Some(TuningProfile::Safe));
        assert_eq!(
            m.batch_size,
            Some(1_000),
            "export omitted batch_size -> keep source"
        );
        assert_eq!(m.throttle_ms, Some(0));
    }

    #[test]
    fn merge_tuning_export_only() {
        let e = cfg_with_profile(TuningProfile::Fast);
        let m = merge_tuning_config(None, Some(&e)).expect("merged");
        assert_eq!(m.profile, Some(TuningProfile::Fast));
    }

    #[test]
    fn effective_batch_size_without_memory() {
        let t = SourceTuning::from_config(None);
        assert_eq!(t.effective_batch_size(None), 10_000);
    }

    #[test]
    fn effective_batch_size_with_memory() {
        use arrow::datatypes::{DataType, Field, Schema};
        use std::sync::Arc;
        let cfg = TuningConfig {
            batch_size_memory_mb: Some(256),
            ..Default::default()
        };
        let t = SourceTuning::from_config(Some(&cfg));
        let schema = Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int64, false),
            Field::new("name", DataType::Utf8, true),
        ]));
        let bs = t.effective_batch_size(Some(&schema));
        assert!((1_000..=150_000).contains(&bs), "got {bs}");
        // 256MB / 266B ≈ 1_009_022, clamped to 150_000
        assert_eq!(bs, 150_000);
    }

    #[test]
    fn resource_summary_balanced_profile() {
        let t = SourceTuning::from_config(None);
        let r = t.resource_summary();
        assert_eq!(r.profile, "balanced");
        assert_eq!(r.batch_size, 10_000);
        // Balanced drives batch sizing from a 32 MB-per-flush target by default
        // (the static batch_size above is the no-schema fallback). 32 not 64 MB:
        // 64 overshot medium-wide tables; 32 keeps the narrow win (clamp-bound)
        // while landing wide tables near the old static size — see profile note.
        assert_eq!(r.batch_size_memory_mb, Some(32));
        assert_eq!(r.memory_threshold_mb, 4_096);
        assert_eq!(r.throttle_ms, 50);
        // narrow: 10_000 × 200 B = ~1.9 MB
        assert!(
            r.batch_narrow_mb < 5.0,
            "narrow too high: {}",
            r.batch_narrow_mb
        );
        // wide: 10_000 × 10 KB = ~95 MB — no risk (< 128 MB)
        assert!(
            !r.wide_table_risk,
            "balanced 10k should not trigger wide_table_risk"
        );
    }

    #[test]
    fn resource_summary_fast_profile_triggers_wide_table_risk() {
        let t = SourceTuning::from_config(Some(&TuningConfig {
            profile: Some(TuningProfile::Fast),
            ..Default::default()
        }));
        let r = t.resource_summary();
        assert_eq!(r.batch_size, 50_000);
        // wide: 50_000 × 10 KB = ~476 MB → high risk
        assert!(r.wide_table_risk, "fast 50k should trigger wide_table_risk");
    }

    #[test]
    fn resource_summary_with_adaptive_batch() {
        let cfg = TuningConfig {
            batch_size_memory_mb: Some(64),
            ..Default::default()
        };
        let t = SourceTuning::from_config(Some(&cfg));
        let r = t.resource_summary();
        assert_eq!(r.batch_size_memory_mb, Some(64));
    }
}