Skip to main content

common/
config.rs

1//! Configuration types for runtime and execution settings
2
3use serde::{Deserialize, Serialize};
4use std::num::NonZeroUsize;
5
6pub const MIN_DEFAULT_FILES_IN_FLIGHT: usize = 4;
7
8#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
9pub enum ConcurrencyLimit {
10    Unlimited,
11    Limited(std::num::NonZeroUsize),
12}
13
14impl ConcurrencyLimit {
15    #[must_use]
16    pub fn meet(self, other: Self) -> Self {
17        match (self, other) {
18            (Self::Unlimited, limit) | (limit, Self::Unlimited) => limit,
19            (Self::Limited(left), Self::Limited(right)) => {
20                Self::Limited(std::cmp::min(left, right))
21            }
22        }
23    }
24}
25
26impl std::fmt::Display for ConcurrencyLimit {
27    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28        match self {
29            Self::Unlimited => formatter.write_str("unlimited"),
30            Self::Limited(value) => value.fmt(formatter),
31        }
32    }
33}
34
35#[derive(Clone, Copy, Debug, Eq, PartialEq)]
36pub enum FilesInFlightSource {
37    Automatic,
38    Explicit,
39    DeprecatedMaxOpenFiles,
40}
41
42#[derive(Clone, Copy, Debug, Eq, PartialEq)]
43pub struct ResolvedFilesInFlight {
44    limit: ConcurrencyLimit,
45    source: FilesInFlightSource,
46    warn_deprecated_max_open_files: bool,
47}
48
49fn default_files_in_flight_from(available: Option<NonZeroUsize>) -> NonZeroUsize {
50    let available = available.map_or(1, NonZeroUsize::get);
51    NonZeroUsize::new(available.max(MIN_DEFAULT_FILES_IN_FLIGHT))
52        .expect("the minimum files-in-flight value is nonzero")
53}
54
55fn default_files_in_flight() -> NonZeroUsize {
56    default_files_in_flight_from(std::thread::available_parallelism().ok())
57}
58
59impl ResolvedFilesInFlight {
60    pub fn automatic() -> Self {
61        Self::automatic_with(default_files_in_flight())
62    }
63
64    pub const fn automatic_with(value: NonZeroUsize) -> Self {
65        Self {
66            limit: ConcurrencyLimit::Limited(value),
67            source: FilesInFlightSource::Automatic,
68            warn_deprecated_max_open_files: false,
69        }
70    }
71
72    pub const fn explicit(value: NonZeroUsize) -> Self {
73        Self::explicit_limit(ConcurrencyLimit::Limited(value))
74    }
75
76    pub const fn explicit_limit(limit: ConcurrencyLimit) -> Self {
77        Self {
78            limit,
79            source: FilesInFlightSource::Explicit,
80            warn_deprecated_max_open_files: false,
81        }
82    }
83
84    pub const fn unlimited() -> Self {
85        Self::explicit_limit(ConcurrencyLimit::Unlimited)
86    }
87
88    pub fn legacy(value: usize) -> Self {
89        Self::legacy_with_warning(value, true)
90    }
91
92    pub fn forwarded_legacy(value: usize) -> Self {
93        Self::legacy_with_warning(value, false)
94    }
95
96    fn legacy_with_warning(value: usize, warn_deprecated_max_open_files: bool) -> Self {
97        Self {
98            limit: NonZeroUsize::new(value)
99                .map_or(ConcurrencyLimit::Unlimited, ConcurrencyLimit::Limited),
100            source: FilesInFlightSource::DeprecatedMaxOpenFiles,
101            warn_deprecated_max_open_files,
102        }
103    }
104
105    pub const fn limit(self) -> ConcurrencyLimit {
106        self.limit
107    }
108
109    pub const fn source(self) -> FilesInFlightSource {
110        self.source
111    }
112}
113
114/// Dry-run mode for previewing operations without executing them
115#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, Serialize, Deserialize)]
116pub enum DryRunMode {
117    /// show only what would be copied/linked/removed
118    #[value(name = "brief")]
119    Brief,
120    /// also show skipped files
121    #[value(name = "all")]
122    All,
123    /// show skipped files with the pattern that caused the skip
124    #[value(name = "explain")]
125    Explain,
126}
127
128/// Runtime configuration for tokio and thread pools
129#[derive(Debug, Clone, Copy, Default)]
130pub struct RuntimeConfig {
131    /// Number of worker threads (0 = number of CPU cores)
132    pub max_workers: usize,
133    /// Number of blocking threads (0 = tokio default of 512)
134    pub max_blocking_threads: usize,
135}
136
137/// Tunables for the adaptive metadata-throttle control loop.
138///
139/// Populated from CLI flags when `--auto-meta-throttle` is set; otherwise
140/// this field is `None` on [`ThrottleConfig`] and the control loop is not
141/// spawned. Serializable so that `rcp` can propagate the settings to
142/// remote `rcpd` processes over the control channel.
143#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
144pub struct AutoMetaThrottleConfig {
145    pub initial_cwnd: u32,
146    pub min_cwnd: u32,
147    pub max_cwnd: u32,
148    pub alpha: f64,
149    pub beta: f64,
150    pub increase_step: u32,
151    pub decrease_step: u32,
152    /// Percentile (in `[0.0, 1.0)`) applied to the long-horizon window
153    /// to derive the baseline statistic. Must be `<= current_percentile`.
154    pub baseline_percentile: f64,
155    /// Percentile (in `[0.0, 1.0)`) applied to the short-horizon window
156    /// to derive the current statistic. Must be `>= baseline_percentile`.
157    pub current_percentile: f64,
158    /// Long-horizon window age. Drives the baseline statistic.
159    pub long_window: std::time::Duration,
160    /// Short-horizon window age. Drives the current statistic.
161    pub short_window: std::time::Duration,
162    pub tick_interval: std::time::Duration,
163}
164
165/// Descriptor admission appropriate to the work performed by this process.
166#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
167pub enum AdmissionPolicy {
168    #[default]
169    Local,
170    /// Jointly reserve leaf, directory, and socket capacity for a remote endpoint.
171    Remote {
172        streams: std::num::NonZeroUsize,
173        pending: std::num::NonZeroUsize,
174    },
175}
176
177/// Throttling configuration for resource control
178#[derive(Debug, Clone)]
179pub struct ThrottleConfig {
180    /// User-selected ceiling for file-like work, including its source for compatibility warnings.
181    pub files_in_flight: ResolvedFilesInFlight,
182    /// Whether this process performs file work governed by `files_in_flight`.
183    pub apply_files_in_flight: bool,
184    /// The operation-specific descriptor ownership model used during runtime setup.
185    pub admission_policy: AdmissionPolicy,
186    /// Operations per second throttle (0 = no throttle)
187    pub ops_throttle: usize,
188    /// I/O operations per second throttle (0 = no throttle)
189    pub iops_throttle: usize,
190    /// Chunk size for I/O operations (bytes)
191    pub chunk_size: u64,
192    /// Adaptive metadata-ops throttle, if enabled via `--auto-meta-throttle`.
193    pub auto_meta: Option<AutoMetaThrottleConfig>,
194    /// Enables in-memory HDR histograms for the auto-meta probes (live
195    /// display panel + driver for the optional log file). Implied by
196    /// `histogram_log_path.is_some()`.
197    pub histogram_enabled: bool,
198    /// When set, the auto-meta histogram logger appends a binary record
199    /// stream to this path on each snapshot tick. See
200    /// `docs/congestion_control.md` for the format.
201    pub histogram_log_path: Option<std::path::PathBuf>,
202    /// Snapshot cadence for the histogram logger. Drives both the live
203    /// panel and the log file. Range `[100ms, 60s]`.
204    pub histogram_interval: std::time::Duration,
205}
206
207impl Default for ThrottleConfig {
208    fn default() -> Self {
209        Self {
210            files_in_flight: ResolvedFilesInFlight::automatic(),
211            apply_files_in_flight: true,
212            admission_policy: AdmissionPolicy::Local,
213            ops_throttle: 0,
214            iops_throttle: 0,
215            chunk_size: 0,
216            auto_meta: None,
217            histogram_enabled: false,
218            histogram_log_path: None,
219            histogram_interval: std::time::Duration::from_secs(1),
220        }
221    }
222}
223
224/// Minimum static `--ops-throttle` when `--auto-meta-throttle` is on.
225///
226/// Auto-meta forces the ops-throttle to a fixed 100ms replenish interval
227/// so the adapter's `Decision::rate_per_sec` → tokens-per-interval
228/// conversion is always correct. That means the per-interval token count
229/// is `rate / 10` and rounds to zero for rates below 10 ops/sec — which
230/// would silently pause the gate after the initial drain. Reject the
231/// combination explicitly so the user hits a clear error instead of
232/// mysterious quiescence.
233pub const AUTO_META_MIN_OPS_THROTTLE: usize = 10;
234
235impl ThrottleConfig {
236    #[must_use]
237    pub fn deprecated_max_open_files_warning(&self) -> Option<&'static str> {
238        if !self.files_in_flight.warn_deprecated_max_open_files {
239            return None;
240        }
241        match self.files_in_flight.limit() {
242            ConcurrencyLimit::Unlimited => Some(
243                "--max-open-files=0 is deprecated; use --max-files-in-flight=unlimited instead. It removes the user ceiling but no longer disables descriptor safety.",
244            ),
245            ConcurrencyLimit::Limited(_) => {
246                Some("--max-open-files is deprecated; use --max-files-in-flight instead.")
247            }
248        }
249    }
250    /// Validate configuration and return errors if invalid
251    pub fn validate(&self) -> Result<(), String> {
252        if self.iops_throttle > 0 && self.chunk_size == 0 {
253            return Err("chunk_size must be specified when using iops_throttle".to_string());
254        }
255        if let Some(auto) = &self.auto_meta {
256            if auto.max_cwnd == 0 {
257                return Err("auto-meta-max-cwnd must be > 0".to_string());
258            }
259            if auto.min_cwnd == 0 {
260                return Err("auto-meta-min-cwnd must be >= 1".to_string());
261            }
262            if auto.min_cwnd > auto.max_cwnd {
263                return Err("auto-meta-min-cwnd must be <= auto-meta-max-cwnd".to_string());
264            }
265            if !(0.0..1.0).contains(&auto.baseline_percentile) {
266                return Err("auto-meta-baseline-percentile must be in [0.0, 1.0)".to_string());
267            }
268            if !(0.0..1.0).contains(&auto.current_percentile) {
269                return Err("auto-meta-current-percentile must be in [0.0, 1.0)".to_string());
270            }
271            if auto.baseline_percentile > auto.current_percentile {
272                return Err(
273                    "auto-meta-baseline-percentile must be <= auto-meta-current-percentile"
274                        .to_string(),
275                );
276            }
277            // alpha and beta gate the ratio = current / baseline:
278            // ratio < alpha → grow, ratio > beta → shrink. The only
279            // hard invariant is `0 < alpha < beta`. The "natural" placement
280            // of alpha and beta relative to 1.0 depends on the percentile
281            // pair: matched percentiles produce a steady-state ratio
282            // near 1.0, while cross percentiles produce a steady-state
283            // ratio above 1.0 set by the inter-quantile spread of the
284            // latency distribution. Either case may want alpha below or
285            // above 1.0 depending on whether the operator wants the
286            // controller to actively probe past the knee or sit passively
287            // until queueing crosses the beta threshold.
288            if !auto.alpha.is_finite() || auto.alpha <= 0.0 {
289                return Err("auto-meta-alpha must be a finite value > 0".to_string());
290            }
291            if !auto.beta.is_finite() || auto.beta <= 0.0 {
292                return Err("auto-meta-beta must be a finite value > 0".to_string());
293            }
294            if auto.alpha >= auto.beta {
295                return Err("auto-meta-alpha must be < auto-meta-beta".to_string());
296            }
297            if auto.tick_interval.is_zero() {
298                return Err("auto-meta-tick-interval must be > 0".to_string());
299            }
300            if auto.long_window.is_zero() {
301                return Err("auto-meta-long-window must be > 0".to_string());
302            }
303            if auto.short_window.is_zero() {
304                return Err("auto-meta-short-window must be > 0".to_string());
305            }
306            if auto.short_window >= auto.long_window {
307                return Err("auto-meta-short-window must be < auto-meta-long-window".to_string());
308            }
309            if self.ops_throttle > 0 && self.ops_throttle < AUTO_META_MIN_OPS_THROTTLE {
310                return Err(format!(
311                    "--auto-meta-throttle is incompatible with --ops-throttle={} \
312                     (auto-meta uses a fixed 100ms replenish interval; rates below \
313                     {} ops/sec round to zero tokens per interval and would pause \
314                     the throttle after the initial token). Either raise ops-throttle \
315                     to >= {} or drop --auto-meta-throttle to get the legacy adaptive \
316                     interval.",
317                    self.ops_throttle, AUTO_META_MIN_OPS_THROTTLE, AUTO_META_MIN_OPS_THROTTLE,
318                ));
319            }
320        }
321        let histogram_active = self.histogram_enabled || self.histogram_log_path.is_some();
322        if histogram_active && self.auto_meta.is_none() {
323            return Err(
324                "--auto-meta-histogram and --auto-meta-histogram-log require \
325                 --auto-meta-throttle to be enabled"
326                    .into(),
327            );
328        }
329        if histogram_active {
330            let min = std::time::Duration::from_millis(100);
331            let max = std::time::Duration::from_secs(60);
332            if self.histogram_interval < min || self.histogram_interval > max {
333                return Err(format!(
334                    "--auto-meta-histogram-interval must be in [{}ms, {}s]",
335                    min.as_millis(),
336                    max.as_secs(),
337                ));
338            }
339            if let Some(path) = &self.histogram_log_path {
340                // Path::parent() of "foo.hdr" returns Some("") — empty path,
341                // not None. Treat that the same as None (i.e. current dir).
342                let parent = match path.parent() {
343                    Some(p) if p.as_os_str().is_empty() => std::path::Path::new("."),
344                    Some(p) => p,
345                    None => std::path::Path::new("."),
346                };
347                if !parent.exists() {
348                    return Err(format!(
349                        "--auto-meta-histogram-log parent directory does not exist: {parent:?}",
350                    ));
351                }
352                if !parent.is_dir() {
353                    return Err(format!(
354                        "--auto-meta-histogram-log parent is not a directory: {parent:?}",
355                    ));
356                }
357                // Probe writability: try to create a tiny temp file in the parent.
358                // We don't pre-create the actual log file because the spawn step
359                // adds a trace-identifier suffix.
360                //
361                // Use create_new (O_EXCL) and a random suffix so:
362                //   1. a pre-created symlink with the predictable probe name
363                //      can't redirect the create to an attacker-chosen path, and
364                //   2. two concurrent validations never collide on the probe name.
365                let suffix: u64 = rand::random();
366                let probe = parent.join(format!(
367                    ".rcp-auto-meta-probe-{}-{:016x}",
368                    std::process::id(),
369                    suffix,
370                ));
371                match std::fs::OpenOptions::new()
372                    .create_new(true)
373                    .write(true)
374                    .open(&probe)
375                {
376                    Ok(_) => {
377                        let _ = std::fs::remove_file(&probe);
378                    }
379                    Err(err) => {
380                        return Err(format!(
381                            "--auto-meta-histogram-log parent {parent:?} is not writable: {err:#}",
382                        ));
383                    }
384                }
385            }
386        }
387        Ok(())
388    }
389}
390
391/// Output and logging configuration
392#[derive(Debug, Clone, Copy, Default)]
393pub struct OutputConfig {
394    /// Suppress error output
395    pub quiet: bool,
396    /// Verbosity level: 0=ERROR, 1=INFO, 2=DEBUG, 3=TRACE
397    pub verbose: u8,
398    /// Print summary statistics at the end
399    pub print_summary: bool,
400    /// When true, `run()` will not print text runtime stats after the summary.
401    /// Used when the summary itself includes runtime stats (e.g. JSON format).
402    pub suppress_runtime_stats: bool,
403    /// Prefix pre-tracing configuration failures with a machine-readable startup record.
404    pub startup_error_prefix: Option<&'static str>,
405}
406
407/// Warnings and adjustments for dry-run mode.
408///
409/// When dry-run is active, progress is suppressed (it interferes with stdout
410/// output) and `--summary` is suppressed unless `-v` is also active (verbose
411/// independently enables summary in `common::run()`). This struct collects
412/// warnings about the suppressed flags to print after the operation completes.
413pub struct DryRunWarnings {
414    warnings: Vec<String>,
415}
416impl DryRunWarnings {
417    /// Build dry-run warnings based on which flags were specified.
418    ///
419    /// `has_progress` — whether any progress flags were specified.
420    /// `has_summary` — whether --summary was specified.
421    /// `verbose` — verbosity level; when > 0 summary is printed by `common::run()`
422    ///   regardless of `print_summary`, so we skip the "ignored" warning.
423    /// `has_overwrite` — whether --overwrite was specified (not applicable to rrm).
424    /// `has_filters` — whether --include/--exclude/--filter-file was specified.
425    /// `has_destination` — true for rcp/rlink (copy/link to destination), false for rrm.
426    /// `has_ignore_existing` — whether --ignore-existing was specified (checks destination state).
427    #[must_use]
428    pub fn new(
429        has_progress: bool,
430        has_summary: bool,
431        verbose: u8,
432        has_overwrite: bool,
433        has_filters: bool,
434        has_destination: bool,
435        has_ignore_existing: bool,
436    ) -> Self {
437        let mut warnings = Vec::new();
438        if has_progress {
439            warnings.push("dry-run: --progress was ignored".to_string());
440        }
441        if has_summary && verbose == 0 {
442            warnings.push("dry-run: --summary was ignored".to_string());
443        }
444        if has_overwrite {
445            warnings.push(
446                "dry-run: --overwrite was ignored; dry-run does not evaluate overwrite decisions"
447                    .to_string(),
448            );
449        }
450        if !has_filters && !has_ignore_existing {
451            if has_destination {
452                warnings.push(
453                    "dry-run: no filtering specified. dry-run is primarily useful to preview \
454                     --include/--exclude/--filter-file filtering; it does not check whether \
455                     files already exist at the destination."
456                        .to_string(),
457                );
458            } else {
459                warnings.push(
460                    "dry-run: no filtering specified. dry-run is primarily useful to preview \
461                     --include/--exclude/--filter-file filtering."
462                        .to_string(),
463                );
464            }
465        }
466        Self { warnings }
467    }
468    /// Print all collected warnings to stderr.
469    pub fn print(&self) {
470        for warning in &self.warnings {
471            eprintln!("{warning}");
472        }
473    }
474}
475/// Tracing configuration for debugging and profiling
476#[derive(Debug)]
477pub struct TracingConfig {
478    /// Remote tracing layer for distributed tracing
479    pub remote_layer: Option<crate::remote_tracing::RemoteTracingLayer>,
480    /// Debug log file path
481    pub debug_log_file: Option<String>,
482    /// Chrome trace output prefix (produces JSON viewable in Perfetto UI)
483    pub chrome_trace_prefix: Option<String>,
484    /// Elapsed timing summary output prefix.
485    pub timings_prefix: Option<String>,
486    /// Include detailed per-file timing scopes.
487    pub timings_detail: bool,
488    /// Flamegraph output prefix (produces folded stacks for inferno)
489    pub flamegraph_prefix: Option<String>,
490    /// Identifier for trace filenames (e.g., "rcp-master", "rcpd-source", "rcpd-destination")
491    pub trace_identifier: String,
492    /// Log level for profiling layers (chrome trace, flamegraph)
493    /// Defaults to "trace" when profiling is enabled
494    pub profile_level: Option<String>,
495    /// Enable tokio-console for live async debugging
496    pub tokio_console: bool,
497    /// Port for tokio-console server (default: 6669)
498    pub tokio_console_port: Option<u16>,
499}
500
501impl TracingConfig {
502    /// Minimal tracing config for the simple local-only tools (`rrm`, `rchm`, `rcmp`, `rlink`,
503    /// `filegen`): no remote layer, no profiling, no tokio-console — only the trace identifier
504    /// varies between them.
505    #[must_use]
506    pub fn local(trace_identifier: &str) -> Self {
507        Self {
508            remote_layer: None,
509            debug_log_file: None,
510            chrome_trace_prefix: None,
511            timings_prefix: None,
512            timings_detail: false,
513            flamegraph_prefix: None,
514            trace_identifier: trace_identifier.to_string(),
515            profile_level: None,
516            tokio_console: false,
517            tokio_console_port: None,
518        }
519    }
520}
521
522impl Default for TracingConfig {
523    fn default() -> Self {
524        Self {
525            remote_layer: None,
526            debug_log_file: None,
527            chrome_trace_prefix: None,
528            timings_prefix: None,
529            timings_detail: false,
530            flamegraph_prefix: None,
531            trace_identifier: "unknown".to_string(),
532            profile_level: None,
533            tokio_console: false,
534            tokio_console_port: None,
535        }
536    }
537}
538
539#[cfg(test)]
540mod files_in_flight_policy_tests {
541    use super::*;
542    use std::num::NonZeroUsize;
543
544    #[test]
545    fn limit_meet_uses_the_lower_finite_value() {
546        let four = ConcurrencyLimit::Limited(NonZeroUsize::new(4).unwrap());
547        let eight = ConcurrencyLimit::Limited(NonZeroUsize::new(8).unwrap());
548        assert_eq!(four.meet(eight), four);
549        assert_eq!(ConcurrencyLimit::Unlimited.meet(eight), eight);
550        assert_eq!(eight.meet(ConcurrencyLimit::Unlimited), eight);
551        assert_eq!(
552            ConcurrencyLimit::Unlimited.meet(ConcurrencyLimit::Unlimited),
553            ConcurrencyLimit::Unlimited,
554        );
555    }
556
557    #[test]
558    fn concurrency_limit_display_is_operator_friendly() {
559        let eight = ConcurrencyLimit::Limited(NonZeroUsize::new(8).unwrap());
560        assert_eq!(eight.to_string(), "8");
561        assert_eq!(ConcurrencyLimit::Unlimited.to_string(), "unlimited");
562    }
563
564    #[test]
565    fn explicit_unlimited_file_ceiling_removes_only_the_user_cap() {
566        let limit = ResolvedFilesInFlight::unlimited();
567        assert_eq!(limit.limit(), ConcurrencyLimit::Unlimited);
568        assert_eq!(limit.source(), FilesInFlightSource::Explicit);
569    }
570
571    #[test]
572    fn automatic_files_in_flight_has_a_floor_of_four() {
573        assert_eq!(default_files_in_flight_from(None).get(), 4);
574        assert_eq!(default_files_in_flight_from(NonZeroUsize::new(2)).get(), 4);
575        assert_eq!(default_files_in_flight_from(NonZeroUsize::new(4)).get(), 4);
576        assert_eq!(
577            default_files_in_flight_from(NonZeroUsize::new(12)).get(),
578            12
579        );
580    }
581
582    #[test]
583    fn injected_automatic_file_limit_retains_automatic_provenance() {
584        let limit = ResolvedFilesInFlight::automatic_with(NonZeroUsize::new(12).unwrap());
585        assert_eq!(
586            limit.limit(),
587            ConcurrencyLimit::Limited(NonZeroUsize::new(12).unwrap())
588        );
589        assert_eq!(limit.source(), FilesInFlightSource::Automatic);
590    }
591
592    #[test]
593    fn forwarded_legacy_finite_retains_origin_without_a_duplicate_warning() {
594        let files_in_flight = ResolvedFilesInFlight::forwarded_legacy(7);
595        let throttle = ThrottleConfig {
596            files_in_flight,
597            ..ThrottleConfig::default()
598        };
599        assert_eq!(
600            files_in_flight.limit(),
601            ConcurrencyLimit::Limited(NonZeroUsize::new(7).unwrap())
602        );
603        assert_eq!(
604            files_in_flight.source(),
605            FilesInFlightSource::DeprecatedMaxOpenFiles
606        );
607        assert_eq!(throttle.deprecated_max_open_files_warning(), None);
608    }
609
610    #[test]
611    fn forwarded_legacy_unlimited_retains_origin_without_a_duplicate_warning() {
612        let files_in_flight = ResolvedFilesInFlight::forwarded_legacy(0);
613        let throttle = ThrottleConfig {
614            files_in_flight,
615            ..ThrottleConfig::default()
616        };
617        assert_eq!(files_in_flight.limit(), ConcurrencyLimit::Unlimited);
618        assert_eq!(
619            files_in_flight.source(),
620            FilesInFlightSource::DeprecatedMaxOpenFiles
621        );
622        assert_eq!(throttle.deprecated_max_open_files_warning(), None);
623    }
624}
625
626#[cfg(test)]
627mod auto_meta_validation_tests {
628    use super::*;
629
630    fn valid_auto_meta() -> AutoMetaThrottleConfig {
631        AutoMetaThrottleConfig {
632            initial_cwnd: 1,
633            min_cwnd: 1,
634            max_cwnd: 4096,
635            alpha: 1.3,
636            beta: 1.8,
637            increase_step: 1,
638            decrease_step: 1,
639            baseline_percentile: 0.1,
640            current_percentile: 0.5,
641            long_window: std::time::Duration::from_secs(10),
642            short_window: std::time::Duration::from_secs(1),
643            tick_interval: std::time::Duration::from_millis(50),
644        }
645    }
646
647    fn config_with(auto: AutoMetaThrottleConfig) -> ThrottleConfig {
648        ThrottleConfig {
649            files_in_flight: ResolvedFilesInFlight::automatic(),
650            apply_files_in_flight: true,
651            admission_policy: AdmissionPolicy::Local,
652            ops_throttle: 0,
653            iops_throttle: 0,
654            chunk_size: 0,
655            auto_meta: Some(auto),
656            histogram_enabled: false,
657            histogram_log_path: None,
658            histogram_interval: std::time::Duration::from_secs(1),
659        }
660    }
661
662    #[test]
663    fn defaults_validate() {
664        assert!(config_with(valid_auto_meta()).validate().is_ok());
665    }
666
667    #[test]
668    fn min_cwnd_zero_is_rejected() {
669        let mut auto = valid_auto_meta();
670        auto.min_cwnd = 0;
671        let err = config_with(auto).validate().unwrap_err();
672        assert!(err.contains("min-cwnd"), "got: {err}");
673    }
674
675    #[test]
676    fn alpha_at_or_below_zero_is_rejected() {
677        let mut auto = valid_auto_meta();
678        auto.alpha = 0.0;
679        assert!(config_with(auto).validate().is_err());
680        let mut auto = valid_auto_meta();
681        auto.alpha = -0.5;
682        assert!(config_with(auto).validate().is_err());
683    }
684
685    #[test]
686    fn alpha_below_one_is_accepted() {
687        // Passive-controller mode: alpha < 1.0 means "grow only when
688        // recent is meaningfully faster than baseline" — the explicit
689        // use case for relaxing the previous alpha > 1.0 constraint.
690        let mut auto = valid_auto_meta();
691        auto.alpha = 0.9;
692        auto.beta = 1.1;
693        assert!(config_with(auto).validate().is_ok());
694    }
695
696    #[test]
697    fn beta_at_or_below_zero_is_rejected() {
698        let mut auto = valid_auto_meta();
699        auto.alpha = 0.5;
700        auto.beta = 0.0;
701        let err = config_with(auto).validate().unwrap_err();
702        assert!(err.contains("beta"), "got: {err}");
703    }
704
705    #[test]
706    fn cross_percentile_config_validates() {
707        // Cross-percentile mode: baseline at p40, current at p60, with
708        // alpha/beta straddling the steady-state ratio. The validator
709        // accepts both percentiles in (0, 1) with baseline <= current.
710        let mut auto = valid_auto_meta();
711        auto.baseline_percentile = 0.4;
712        auto.current_percentile = 0.6;
713        assert!(config_with(auto).validate().is_ok());
714    }
715
716    #[test]
717    fn baseline_percentile_above_current_is_rejected() {
718        let mut auto = valid_auto_meta();
719        auto.baseline_percentile = 0.6;
720        auto.current_percentile = 0.4;
721        let err = config_with(auto).validate().unwrap_err();
722        assert!(
723            err.contains("baseline-percentile") && err.contains("current-percentile"),
724            "got: {err}",
725        );
726    }
727
728    #[test]
729    fn baseline_percentile_out_of_range_is_rejected() {
730        let mut auto = valid_auto_meta();
731        auto.baseline_percentile = 1.0;
732        let err = config_with(auto).validate().unwrap_err();
733        assert!(err.contains("baseline-percentile"), "got: {err}");
734    }
735
736    #[test]
737    fn non_finite_alpha_or_beta_is_rejected() {
738        // NaN comparisons return false in either direction, so a plain
739        // `auto.alpha <= 0.0` check would silently pass NaN through and
740        // the controller would freeze in the hold band forever. The
741        // `is_finite()` guard catches that.
742        for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
743            let mut auto = valid_auto_meta();
744            auto.alpha = bad;
745            assert!(
746                config_with(auto).validate().is_err(),
747                "alpha={bad} must be rejected",
748            );
749            let mut auto = valid_auto_meta();
750            auto.beta = bad;
751            assert!(
752                config_with(auto).validate().is_err(),
753                "beta={bad} must be rejected",
754            );
755        }
756    }
757
758    #[test]
759    fn current_percentile_out_of_range_is_rejected() {
760        let mut auto = valid_auto_meta();
761        auto.current_percentile = 1.0;
762        let err = config_with(auto).validate().unwrap_err();
763        assert!(err.contains("current-percentile"), "got: {err}");
764    }
765
766    #[test]
767    fn ops_throttle_below_floor_is_rejected_under_auto_meta() {
768        let mut config = config_with(valid_auto_meta());
769        config.ops_throttle = 5;
770        let err = config.validate().unwrap_err();
771        assert!(
772            err.contains("ops-throttle") && err.contains("auto-meta-throttle"),
773            "got: {err}",
774        );
775    }
776
777    #[test]
778    fn ops_throttle_at_or_above_floor_is_accepted_under_auto_meta() {
779        let mut config = config_with(valid_auto_meta());
780        config.ops_throttle = AUTO_META_MIN_OPS_THROTTLE;
781        assert!(config.validate().is_ok());
782        config.ops_throttle = AUTO_META_MIN_OPS_THROTTLE + 100;
783        assert!(config.validate().is_ok());
784    }
785
786    #[test]
787    fn ops_throttle_below_floor_is_fine_without_auto_meta() {
788        // The floor only applies when auto-meta forces a fixed 100ms
789        // cadence. Without auto-meta, the adaptive get_replenish_interval
790        // picks an interval that works for any rate.
791        let config = ThrottleConfig {
792            files_in_flight: ResolvedFilesInFlight::automatic(),
793            apply_files_in_flight: true,
794            admission_policy: AdmissionPolicy::Local,
795            ops_throttle: 5,
796            iops_throttle: 0,
797            chunk_size: 0,
798            auto_meta: None,
799            histogram_enabled: false,
800            histogram_log_path: None,
801            histogram_interval: std::time::Duration::from_secs(1),
802        };
803        assert!(config.validate().is_ok());
804    }
805
806    #[test]
807    fn alpha_greater_than_beta_is_rejected() {
808        let mut auto = valid_auto_meta();
809        auto.alpha = 1.6;
810        auto.beta = 1.5;
811        let err = config_with(auto).validate().unwrap_err();
812        assert!(err.contains("alpha") && err.contains("beta"), "got: {err}");
813    }
814
815    #[test]
816    fn histogram_log_without_throttle_is_rejected() {
817        // Recording a log requires the throttle pipeline to be live.
818        let config = ThrottleConfig {
819            files_in_flight: ResolvedFilesInFlight::automatic(),
820            apply_files_in_flight: true,
821            admission_policy: AdmissionPolicy::Local,
822            ops_throttle: 0,
823            iops_throttle: 0,
824            chunk_size: 0,
825            auto_meta: None,
826            histogram_log_path: Some("/tmp/x.hdr".into()),
827            histogram_enabled: false,
828            histogram_interval: std::time::Duration::from_secs(1),
829        };
830        let err = config.validate().unwrap_err();
831        assert!(
832            err.contains("histogram") && err.contains("auto-meta-throttle"),
833            "got: {err}"
834        );
835    }
836
837    #[test]
838    fn histogram_enabled_without_throttle_is_rejected() {
839        // --auto-meta-histogram alone (no log path) without --auto-meta-throttle
840        // is rejected for the same reason: nothing to histogram.
841        let config = ThrottleConfig {
842            files_in_flight: ResolvedFilesInFlight::automatic(),
843            apply_files_in_flight: true,
844            admission_policy: AdmissionPolicy::Local,
845            ops_throttle: 0,
846            iops_throttle: 0,
847            chunk_size: 0,
848            auto_meta: None,
849            histogram_enabled: true,
850            histogram_log_path: None,
851            histogram_interval: std::time::Duration::from_secs(1),
852        };
853        let err = config.validate().unwrap_err();
854        assert!(
855            err.contains("histogram") && err.contains("auto-meta-throttle"),
856            "got: {err}"
857        );
858    }
859
860    #[test]
861    fn histogram_interval_below_floor_is_rejected() {
862        let mut config = config_with(valid_auto_meta());
863        config.histogram_enabled = true;
864        config.histogram_interval = std::time::Duration::from_millis(50);
865        let err = config.validate().unwrap_err();
866        assert!(err.contains("histogram-interval"), "got: {err}");
867    }
868
869    #[test]
870    fn histogram_interval_above_ceiling_is_rejected() {
871        let mut config = config_with(valid_auto_meta());
872        config.histogram_enabled = true;
873        config.histogram_interval = std::time::Duration::from_secs(120);
874        let err = config.validate().unwrap_err();
875        assert!(err.contains("histogram-interval"), "got: {err}");
876    }
877
878    #[test]
879    fn histogram_defaults_pass_validation() {
880        let mut config = config_with(valid_auto_meta());
881        config.histogram_enabled = true;
882        config.histogram_interval = std::time::Duration::from_secs(1);
883        assert!(config.validate().is_ok());
884    }
885
886    #[test]
887    fn histogram_log_with_missing_parent_is_rejected() {
888        let mut config = config_with(valid_auto_meta());
889        config.histogram_log_path = Some("/nonexistent-dir-12345/foo.hdr".into());
890        let err = config.validate().unwrap_err();
891        assert!(
892            err.contains("histogram-log") && err.contains("parent"),
893            "got: {err}",
894        );
895    }
896
897    #[test]
898    fn histogram_log_with_writable_parent_is_accepted() {
899        let dir = tempfile::tempdir().unwrap();
900        let mut config = config_with(valid_auto_meta());
901        config.histogram_log_path = Some(dir.path().join("foo.hdr"));
902        assert!(config.validate().is_ok());
903    }
904
905    #[test]
906    fn histogram_log_with_bare_filename_is_accepted() {
907        // Path::parent() of "foo.hdr" returns Some("") — empty path, not
908        // None. The validator must treat that as the current directory,
909        // not as a missing parent.
910        let mut config = config_with(valid_auto_meta());
911        config.histogram_log_path = Some("bare-filename.hdr".into());
912        assert!(
913            config.validate().is_ok(),
914            "validate err: {:?}",
915            config.validate(),
916        );
917    }
918
919    #[test]
920    fn histogram_log_validation_uses_unique_probe_per_call() {
921        // Two consecutive validations with the same path must succeed —
922        // proving the probe file is removed cleanly and the filename
923        // doesn't collide with itself.
924        let dir = tempfile::tempdir().unwrap();
925        let mut config = config_with(valid_auto_meta());
926        config.histogram_log_path = Some(dir.path().join("log.hdr"));
927        assert!(config.validate().is_ok());
928        assert!(config.validate().is_ok());
929    }
930}