Skip to main content

common/
runtime_setup.rs

1//! Runtime, tracing, and throttle bring-up used by [`crate::run`].
2//!
3//! This module gathers the process-startup plumbing that configures the
4//! tokio runtime, installs the tracing subscriber, primes the throttle
5//! replenishers, and wires the adaptive metadata-ops control loops. It is
6//! kept separate from the crate root purely to keep `lib.rs` focused on the
7//! public surface.
8
9use crate::config::{
10    AdmissionPolicy, AutoMetaThrottleConfig, ConcurrencyLimit, RuntimeConfig, ThrottleConfig,
11    TracingConfig,
12};
13use crate::{
14    PBAR, PROGRESS, REMOTE_RUNTIME_STATS, RuntimeStats, auto_meta, histogram_logger, is_localhost,
15    observability, progress, store_logger_cancel, store_logger_handle, walk,
16};
17use anyhow::Context;
18use tracing_subscriber::fmt::format::FmtSpan;
19use tracing_subscriber::prelude::*;
20
21struct LocalTimeFormatter;
22
23impl tracing_subscriber::fmt::time::FormatTime for LocalTimeFormatter {
24    fn format_time(
25        &self,
26        writer: &mut tracing_subscriber::fmt::format::Writer<'_>,
27    ) -> std::fmt::Result {
28        let now = chrono::Local::now();
29        writer.write_str(&now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
30    }
31}
32
33struct ProgWriter {}
34
35impl ProgWriter {
36    fn new() -> Self {
37        Self {}
38    }
39}
40
41impl std::io::Write for ProgWriter {
42    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
43        PBAR.suspend(|| std::io::stdout().write(buf))
44    }
45    fn flush(&mut self) -> std::io::Result<()> {
46        std::io::stdout().flush()
47    }
48}
49
50fn get_hostname() -> String {
51    nix::unistd::gethostname()
52        .ok()
53        .and_then(|os_str| os_str.into_string().ok())
54        .unwrap_or_else(|| "unknown".to_string())
55}
56
57fn read_env_or_default<T: std::str::FromStr>(name: &str, default: T) -> T {
58    match std::env::var(name) {
59        Ok(val) => match val.parse() {
60            Ok(val) => val,
61            Err(_) => default,
62        },
63        Err(_) => default,
64    }
65}
66
67/// collects runtime statistics (CPU time, memory) for the current process
68#[must_use]
69pub fn collect_runtime_stats() -> RuntimeStats {
70    collect_runtime_stats_inner(procfs::process::Process::myself().ok())
71}
72
73fn collect_runtime_stats_inner(process: Option<procfs::process::Process>) -> RuntimeStats {
74    let Some(process) = process else {
75        return RuntimeStats::default();
76    };
77    collect_runtime_stats_for_process(&process).unwrap_or_default()
78}
79
80fn collect_runtime_stats_for_process(
81    process: &procfs::process::Process,
82) -> anyhow::Result<RuntimeStats> {
83    let stat = process.stat()?;
84    let clock_ticks = procfs::ticks_per_second() as f64;
85    // vmhwm from /proc/[pid]/status is in kB, convert to bytes
86    let vmhwm_kb = process.status()?.vmhwm.unwrap_or(0);
87    Ok(RuntimeStats {
88        cpu_time_user_ms: ((stat.utime as f64 / clock_ticks) * 1000.0) as u64,
89        cpu_time_kernel_ms: ((stat.stime as f64 / clock_ticks) * 1000.0) as u64,
90        peak_rss_bytes: vmhwm_kb * 1024,
91    })
92}
93
94fn print_runtime_stats_for_role(prefix: &str, stats: &RuntimeStats) {
95    let cpu_total =
96        std::time::Duration::from_millis(stats.cpu_time_user_ms + stats.cpu_time_kernel_ms);
97    let cpu_kernel = std::time::Duration::from_millis(stats.cpu_time_kernel_ms);
98    let cpu_user = std::time::Duration::from_millis(stats.cpu_time_user_ms);
99    println!(
100        "{prefix}cpu time : {:.2?} | k: {:.2?} | u: {:.2?}",
101        cpu_total, cpu_kernel, cpu_user
102    );
103    println!(
104        "{prefix}peak RSS : {}",
105        bytesize::ByteSize(stats.peak_rss_bytes)
106    );
107}
108
109#[rustfmt::skip]
110pub(crate) fn print_runtime_stats() -> Result<(), anyhow::Error> {
111    // check if we have remote runtime stats (from a remote copy operation)
112    let remote_stats = REMOTE_RUNTIME_STATS.lock().unwrap().take();
113    if let Some(remote) = remote_stats {
114        // print global walltime first
115        println!("walltime : {:.2?}", &PROGRESS.get_duration());
116        println!();
117        let source_is_local = is_localhost(&remote.source_host);
118        let dest_is_local = is_localhost(&remote.dest_host);
119        // collect master stats
120        let master_stats = collect_runtime_stats();
121        // print non-localhost roles first
122        if !source_is_local {
123            println!("SOURCE ({}):", remote.source_host);
124            print_runtime_stats_for_role("  ", &remote.source_stats);
125            println!();
126        }
127        if !dest_is_local {
128            println!("DESTINATION ({}):", remote.dest_host);
129            print_runtime_stats_for_role("  ", &remote.dest_stats);
130            println!();
131        }
132        // print combined localhost section
133        match (source_is_local, dest_is_local) {
134            (true, true) => {
135                println!("MASTER + SOURCE + DESTINATION (localhost):");
136                print_runtime_stats_for_role("  master ", &master_stats);
137                print_runtime_stats_for_role("  source ", &remote.source_stats);
138                print_runtime_stats_for_role("  dest   ", &remote.dest_stats);
139            }
140            (true, false) => {
141                println!("MASTER + SOURCE (localhost):");
142                print_runtime_stats_for_role("  master ", &master_stats);
143                print_runtime_stats_for_role("  source ", &remote.source_stats);
144            }
145            (false, true) => {
146                println!("MASTER + DESTINATION (localhost):");
147                print_runtime_stats_for_role("  master ", &master_stats);
148                print_runtime_stats_for_role("  dest   ", &remote.dest_stats);
149            }
150            (false, false) => {
151                println!("MASTER (localhost):");
152                print_runtime_stats_for_role("  ", &master_stats);
153            }
154        }
155        return Ok(());
156    }
157    // local operation - print stats for this process only
158    let process = procfs::process::Process::myself()?;
159    let stat = process.stat()?;
160    // The time is in clock ticks, so we need to convert it to seconds
161    let clock_ticks_per_second = procfs::ticks_per_second();
162    let ticks_to_duration = |ticks: u64| {
163        std::time::Duration::from_secs_f64(ticks as f64 / clock_ticks_per_second as f64)
164    };
165    // vmhwm from /proc/[pid]/status is in kB, convert to bytes
166    let vmhwm_kb = process.status()?.vmhwm.unwrap_or(0);
167    println!("walltime : {:.2?}", &PROGRESS.get_duration(),);
168    println!("cpu time : {:.2?} | k: {:.2?} | u: {:.2?}", ticks_to_duration(stat.utime + stat.stime), ticks_to_duration(stat.stime), ticks_to_duration(stat.utime));
169    println!("peak RSS : {:.2?}", bytesize::ByteSize(vmhwm_kb * 1024));
170    Ok(())
171}
172
173/// Raise the soft descriptor limit to the inherited hard ceiling when permitted.
174fn raise_open_file_limit() -> Result<u64, std::io::Error> {
175    let mut rlim = libc::rlimit {
176        rlim_cur: 0,
177        rlim_max: 0,
178    };
179    // safety: we pass a valid "rlim" pointer and the result is checked
180    let result = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut rlim) };
181    if result != 0 {
182        return Err(std::io::Error::last_os_error());
183    }
184    Ok(raise_soft_limit(rlim, |limit| {
185        // safety: `limit` is valid for reads; only the process soft limit changes
186        if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, limit) } == 0 {
187            Ok(())
188        } else {
189            Err(std::io::Error::last_os_error())
190        }
191    }))
192}
193
194/// Return the effective soft limit, retaining the observed limit if raising it fails.
195fn raise_soft_limit(
196    mut limit: libc::rlimit,
197    set_limit: impl FnOnce(&libc::rlimit) -> Result<(), std::io::Error>,
198) -> u64 {
199    let inherited_soft = limit.rlim_cur;
200    if inherited_soft < limit.rlim_max {
201        limit.rlim_cur = limit.rlim_max;
202        match set_limit(&limit) {
203            Ok(()) => tracing::info!(
204                "Raised soft descriptor limit from {inherited_soft} to {}",
205                limit.rlim_cur,
206            ),
207            Err(error) => {
208                tracing::warn!(target: NOTICE_TARGET,
209                    "Could not raise soft RLIMIT_NOFILE from {inherited_soft} to inherited hard limit {}; using {inherited_soft}: {error:#}",
210                    limit.rlim_max,
211                );
212                return inherited_soft;
213            }
214        }
215    }
216    limit.rlim_cur
217}
218
219#[must_use]
220pub fn generate_debug_log_filename(prefix: &str) -> String {
221    let now = chrono::Utc::now();
222    let timestamp = now.format("%Y-%m-%dT%H:%M:%S").to_string();
223    let process_id = std::process::id();
224    format!("{prefix}-{timestamp}-{process_id}")
225}
226
227/// Generate a trace filename with identifier, hostname, PID, and timestamp.
228///
229/// `identifier` should be "rcp", "rcpd-source", or "rcpd-destination"
230#[must_use]
231pub fn generate_trace_filename(prefix: &str, identifier: &str, extension: &str) -> String {
232    let hostname = get_hostname();
233    let pid = std::process::id();
234    let timestamp = chrono::Utc::now().format("%Y-%m-%dT%H-%M-%SZ");
235    format!("{prefix}-{identifier}-{hostname}-{pid}-{timestamp}.{extension}")
236}
237
238/// The tracing target for rcp's own user-facing NOTICES: advice about the invocation that a user
239/// must see without having to ask for it with `-v`.
240///
241/// The verbose-level filter (`build_verbose_env_filter`, below) gives this target its own `warn`
242/// directive, which is more specific than the global level, so a notice renders at the DEFAULT
243/// verbosity while everything else stays at `error`. That targeting is the whole point. Raising the
244/// global default to `warn` instead would also expose per-entry warnings, so one failed subtree
245/// could print thousands of lines.
246///
247/// **The bar for putting an event here** is that it is advice about the INVOCATION — constant in
248/// volume however large the tree, and actionable by changing the command line. A per-entry event
249/// does not qualify, however important it looks. Current notices cover source-root ACL heuristics,
250/// deprecated options, explicit concurrency clamps, profiling artifacts, and startup safety
251/// fallbacks.
252///
253/// Three things hold, deliberately:
254///
255/// - `--quiet` suppresses it, along with ordinary logs. Only an explicitly requested timing
256///   summary installs a subscriber in quiet mode, and that subscriber has no notice/log layer.
257/// - `RUST_LOG` does NOT suppress it. The directive is added after `EnvFilter::from_default_env`
258///   and replaces any directive for the same target, exactly as the `tokio` / `quinn` / `rustls` /
259///   `h2` directives and the verbosity level itself already do. `RUST_LOG` still raises verbosity
260///   for targets this filter does not name.
261/// - It is a `warn!` and not an `error!`: the operation can still succeed and its exit code is
262///   unchanged. A notice is advice; some notices also describe heuristics rather than failures.
263pub const NOTICE_TARGET: &str = "rcp::notice";
264
265/// Build the verbose-level [`tracing_subscriber::EnvFilter`] used by every
266/// non-profile tracing layer (file, fmt, remote). Excludes noisy deps that are
267/// rarely useful when debugging rcp.
268fn build_verbose_env_filter(verbose: u8) -> tracing_subscriber::EnvFilter {
269    let level_directive = match verbose {
270        0 => "error".parse().unwrap(),
271        1 => "info".parse().unwrap(),
272        2 => "debug".parse().unwrap(),
273        _ => "trace".parse().unwrap(),
274    };
275    tracing_subscriber::EnvFilter::from_default_env()
276        .add_directive(level_directive)
277        // rcp's own notices, visible at every verbosity including the default. Built from the
278        // constant rather than spelled out, so the target and the directive cannot drift apart.
279        // This layer builder is shared by the master's console/file layers AND by an rcpd's
280        // forwarding layer, so one directive covers both ends of a remote copy: without it here,
281        // an rcpd at the default verbosity would never even SEND the notice.
282        .add_directive(format!("{NOTICE_TARGET}=warn").parse().unwrap())
283        .add_directive("tokio=info".parse().unwrap())
284        .add_directive("runtime=info".parse().unwrap())
285        .add_directive("quinn=warn".parse().unwrap())
286        .add_directive("rustls=warn".parse().unwrap())
287        .add_directive("h2=warn".parse().unwrap())
288        .add_directive("rcp::timing=off".parse().unwrap())
289}
290
291/// Build the [`tracing_subscriber::EnvFilter`] used by chrome/flame profile
292/// layers. Profiling layers don't share the verbose-level filter because they
293/// have their own `--profile-level`. Returns the formatted filter string —
294/// callers re-parse it per layer because EnvFilter isn't Clone.
295fn build_profile_filter_str(profile_level: Option<&str>) -> anyhow::Result<String> {
296    let level_str = profile_level.unwrap_or("trace");
297    let valid_levels = ["trace", "debug", "info", "warn", "error", "off"];
298    if !valid_levels.contains(&level_str.to_lowercase().as_str()) {
299        anyhow::bail!(
300            "Invalid --profile-level '{level_str}'. Valid values: trace, debug, info, warn, error, off"
301        );
302    }
303    Ok(format!(
304        "tokio=off,quinn=off,h2=off,hyper=off,rustls=off,rcp::timing=off,{level_str}"
305    ))
306}
307
308/// Guards from chrome/flame tracing layers that must outlive the runtime to
309/// flush traces on shutdown. Hold the returned struct for the lifetime of the
310/// run.
311#[allow(dead_code)] // fields are kept alive only for their Drop side-effects
312pub(crate) struct TracingGuards {
313    chrome: Option<tracing_chrome::FlushGuard>,
314    flame: Option<tracing_flame::FlushGuard<std::io::BufWriter<std::fs::File>>>,
315    timing: Option<crate::timing::TimingGuard>,
316}
317
318impl TracingGuards {
319    pub(crate) fn finish(&mut self) -> anyhow::Result<()> {
320        if let Some(timing) = &mut self.timing {
321            timing.finish()?;
322        }
323        Ok(())
324    }
325}
326
327fn open_timing_output(
328    prefix: &str,
329    identifier: &str,
330    extension: &str,
331) -> anyhow::Result<(std::fs::File, String)> {
332    let filename = generate_trace_filename(prefix, identifier, extension);
333    let file = std::fs::File::create(&filename)
334        .with_context(|| format!("failed to create timing output at '{filename}'"))?;
335    Ok((file, filename))
336}
337
338/// Install the global [`tracing_subscriber`] registry from a [`TracingConfig`].
339/// Caller must hold the returned [`TracingGuards`] until the run finishes so
340/// that chrome/flame traces are flushed before the file handles close.
341///
342/// Quiet mode installs only explicitly requested timing summaries; ordinary logs stay disabled.
343pub(crate) fn install_tracing_subscriber(
344    quiet: bool,
345    verbose: u8,
346    tracing_config: TracingConfig,
347) -> anyhow::Result<TracingGuards> {
348    if quiet {
349        assert!(
350            verbose == 0,
351            "Quiet mode and verbose mode are mutually exclusive"
352        );
353        let timing = if let Some(prefix) = &tracing_config.timings_prefix {
354            let (file, _) =
355                open_timing_output(prefix, &tracing_config.trace_identifier, "timings.json")?;
356            let (layer, guard) =
357                crate::timing::TimingLayer::new(tracing_config.trace_identifier, Some(file), None);
358            tracing_subscriber::registry()
359                .with(
360                    layer.with_filter(crate::timing::timing_filter(tracing_config.timings_detail)),
361                )
362                .init();
363            Some(guard)
364        } else {
365            None
366        };
367        return Ok(TracingGuards {
368            chrome: None,
369            flame: None,
370            timing,
371        });
372    }
373    let TracingConfig {
374        remote_layer: remote_tracing_layer,
375        debug_log_file,
376        chrome_trace_prefix,
377        timings_prefix,
378        timings_detail,
379        flamegraph_prefix,
380        trace_identifier,
381        profile_level,
382        tokio_console,
383        tokio_console_port,
384    } = tracing_config;
385    let file_layer = debug_log_file
386        .map(|log_file_path| {
387            let file = std::fs::OpenOptions::new()
388                .create(true)
389                .append(true)
390                .open(&log_file_path)
391                .with_context(|| format!("failed to create debug log file at '{log_file_path}'"))?;
392            anyhow::Ok(
393                tracing_subscriber::fmt::layer()
394                    .with_target(true)
395                    .with_line_number(true)
396                    .with_thread_ids(true)
397                    .with_timer(LocalTimeFormatter)
398                    .with_ansi(false)
399                    .with_writer(file)
400                    .with_filter(build_verbose_env_filter(verbose)),
401            )
402        })
403        .transpose()?;
404    // fmt_layer for local console output (when not using remote tracing)
405    let fmt_layer = if remote_tracing_layer.is_some() {
406        None
407    } else {
408        Some(
409            tracing_subscriber::fmt::layer()
410                .with_target(true)
411                .with_line_number(true)
412                .with_span_events(if verbose > 2 {
413                    FmtSpan::NEW | FmtSpan::CLOSE
414                } else {
415                    FmtSpan::NONE
416                })
417                .with_timer(LocalTimeFormatter)
418                .pretty()
419                .with_writer(ProgWriter::new)
420                .with_filter(build_verbose_env_filter(verbose)),
421        )
422    };
423    // apply env_filter to remote_tracing_layer so it respects verbose level
424    let remote_tracing_layer =
425        remote_tracing_layer.map(|layer| layer.with_filter(build_verbose_env_filter(verbose)));
426    let mut startup_notices = Vec::new();
427    let mut startup_errors = Vec::new();
428    let mut timing_guard = None;
429    let timing_layer = if timings_prefix.is_some() || chrome_trace_prefix.is_some() {
430        let summary = timings_prefix
431            .as_deref()
432            .map(|prefix| {
433                let (file, filename) =
434                    open_timing_output(prefix, &trace_identifier, "timings.json")?;
435                startup_notices.push(format!("Timing summary will be written to: {filename}"));
436                anyhow::Ok(file)
437            })
438            .transpose()?;
439        let timeline = chrome_trace_prefix
440            .as_deref()
441            .map(|prefix| {
442                let (file, filename) = open_timing_output(prefix, &trace_identifier, "scopes.json")
443                    .context("failed to create Chrome trace file for elapsed scopes")?;
444                startup_notices.push(format!(
445                    "Elapsed scope timeline will be written to: {filename}"
446                ));
447                anyhow::Ok(file)
448            })
449            .transpose()?;
450        let (layer, guard) =
451            crate::timing::TimingLayer::new(trace_identifier.clone(), summary, timeline);
452        timing_guard = Some(guard);
453        Some(layer.with_filter(crate::timing::timing_filter(timings_detail)))
454    } else {
455        None
456    };
457    let console_layer = tokio_console.then(|| {
458        let console_port = tokio_console_port.unwrap_or(6669);
459        let retention_seconds: u64 =
460            read_env_or_default("RCP_TOKIO_TRACING_CONSOLE_RETENTION_SECONDS", 60);
461        startup_notices.push(format!(
462            "Tokio console server listening on 127.0.0.1:{console_port}"
463        ));
464        console_subscriber::ConsoleLayer::builder()
465            .retention(std::time::Duration::from_secs(retention_seconds))
466            .server_addr(([127, 0, 0, 1], console_port))
467            .spawn()
468    });
469    // chrome/flame share a profile filter; build the string once and re-parse
470    // per layer (EnvFilter isn't Clone).
471    let profile_filter_str = (chrome_trace_prefix.is_some() || flamegraph_prefix.is_some())
472        .then(|| build_profile_filter_str(profile_level.as_deref()))
473        .transpose()?;
474    let make_profile_filter =
475        || tracing_subscriber::EnvFilter::new(profile_filter_str.as_ref().unwrap());
476    let mut chrome_guard = None;
477    let chrome_layer = chrome_trace_prefix
478        .as_ref()
479        .map(|prefix| {
480            let filename = generate_trace_filename(prefix, &trace_identifier, "json");
481            let file = std::fs::File::create(&filename)
482                .with_context(|| format!("failed to create Chrome trace file at '{filename}'"))?;
483            startup_notices.push(format!("Chrome trace will be written to: {filename}"));
484            let (layer, guard) = tracing_chrome::ChromeLayerBuilder::new()
485                .writer(file)
486                .include_args(true)
487                .build();
488            chrome_guard = Some(guard);
489            anyhow::Ok(layer.with_filter(make_profile_filter()))
490        })
491        .transpose()?;
492    let mut flame_guard = None;
493    let flame_layer = flamegraph_prefix.as_ref().and_then(|prefix| {
494        let filename = generate_trace_filename(prefix, &trace_identifier, "folded");
495        match tracing_flame::FlameLayer::with_file(&filename) {
496            Ok((layer, guard)) => {
497                startup_notices.push(format!("Flamegraph data will be written to: {filename}"));
498                flame_guard = Some(guard);
499                Some(layer.with_filter(make_profile_filter()))
500            }
501            Err(e) => {
502                startup_errors.push(format!("Failed to create flamegraph layer: {e:?}"));
503                None
504            }
505        }
506    });
507    tracing_subscriber::registry()
508        .with(file_layer)
509        .with(fmt_layer)
510        .with(remote_tracing_layer)
511        .with(console_layer)
512        .with(chrome_layer)
513        .with(flame_layer)
514        .with(timing_layer)
515        .init();
516    for notice in startup_notices {
517        tracing::warn!(target: NOTICE_TARGET, "{notice}");
518    }
519    for startup_error in startup_errors {
520        // rcp-error-log-allow: startup_error is an already-rendered String, not an error chain
521        tracing::error!("{startup_error}");
522    }
523    Ok(TracingGuards {
524        chrome: chrome_guard,
525        flame: flame_guard,
526        timing: timing_guard,
527    })
528}
529
530// the combined model covers both independent leaf pools, not five units per pool.
531const DESCRIPTOR_UNITS_PER_OPERATION: u64 = 5;
532const MAX_LEAF_OPERATIONS_PER_POOL: usize = 4096;
533
534/// A remote endpoint's jointly resolved leaf and directory admission.
535///
536/// Runtime setup installs `leaf_capacity` in both leaf pools before publishing this plan. The
537/// directory counts reserve each endpoint's held descriptors through peer release. An unknown
538/// soft limit permits only logical bounds and carries no descriptor-safety guarantee.
539#[derive(Clone, Copy, Debug, Eq, PartialEq)]
540pub struct RemoteResources {
541    pub soft_limit: Option<std::num::NonZeroU64>,
542    pub leaf_capacity: std::num::NonZeroUsize,
543    pub normal_directories: std::num::NonZeroUsize,
544    pub reserved_directories: std::num::NonZeroUsize,
545}
546
547impl RemoteResources {
548    /// Resolve remote work bounds from one startup limit observation and resolved concurrency.
549    pub fn for_limits(
550        soft_limit: Option<std::num::NonZeroU64>,
551        leaf_ceiling: std::num::NonZeroUsize,
552        streams: std::num::NonZeroUsize,
553        pending: std::num::NonZeroUsize,
554    ) -> anyhow::Result<Self> {
555        const SUPPORT_DESCRIPTORS: u64 = 32;
556        // source: two data/ACL fds plus two classification/readlink fds per leaf slot.
557        // destination: two data/metadata fds, one manifest fd, and one extra preparation fd
558        // beyond the two-fd allowance for each directory lifetime.
559        const LEAF_DESCRIPTORS: u64 = 4;
560        // four leaf fds plus two normal and two reserved lifetimes, at two fds apiece.
561        const DESCRIPTORS_PER_WORK_SLOT: u64 = LEAF_DESCRIPTORS + 2 * (2 + 2);
562        let maximum = tokio::sync::Semaphore::MAX_PERMITS;
563        anyhow::ensure!(
564            streams.get() <= maximum && pending.get() <= maximum,
565            "remote concurrency exceeds semaphore capacity"
566        );
567        let requested = leaf_ceiling
568            .get()
569            .min(streams.get())
570            .min(MAX_LEAF_OPERATIONS_PER_POOL);
571        let (leaf_capacity, normal, reserve) = match soft_limit {
572            Some(soft) => {
573                let streams_u64 = u64::try_from(streams.get()).unwrap_or(u64::MAX);
574                let available = soft
575                    .get()
576                    .saturating_sub(streams_u64)
577                    .saturating_sub(SUPPORT_DESCRIPTORS);
578                let minimum = streams_u64
579                    .saturating_add(SUPPORT_DESCRIPTORS)
580                    .saturating_add(DESCRIPTORS_PER_WORK_SLOT);
581                let shortfall = minimum.saturating_sub(soft.get());
582                anyhow::ensure!(
583                    available >= DESCRIPTORS_PER_WORK_SLOT,
584                    "insufficient remote descriptor headroom: soft RLIMIT_NOFILE={}, data connections={}, support reserve={SUPPORT_DESCRIPTORS}, minimum soft limit={minimum}, shortfall={shortfall}; reduce --max-connections or --max-files-in-flight, or configure a higher hard limit inherited by rcpd in the affected host's SSH session (ulimit -H -n / sshd session limits); changing only the local rcp shell limit does not change a remote daemon's limit",
585                    soft.get(),
586                    streams,
587                );
588                let work_capacity =
589                    usize::try_from(available / DESCRIPTORS_PER_WORK_SLOT).unwrap_or(usize::MAX);
590                let leaf = requested.min(work_capacity);
591                let leaf_u64 = u64::try_from(leaf).expect("the leaf-operation cap fits in u64");
592                let groups = usize::try_from((available - LEAF_DESCRIPTORS * leaf_u64) / 2)
593                    .unwrap_or(usize::MAX);
594                // a scanner can retain an ancestor path independently of pending file work.
595                // split actual headroom between parallel traversal and its progress reserve.
596                let normal = (groups / 2).min(maximum);
597                (leaf, normal, (groups - normal).min(maximum))
598            }
599            None => {
600                let logical = pending
601                    .get()
602                    .saturating_add(streams.get())
603                    .saturating_mul(2)
604                    .min(maximum);
605                (requested, logical, logical)
606            }
607        };
608        Ok(Self {
609            soft_limit,
610            leaf_capacity: std::num::NonZeroUsize::new(leaf_capacity)
611                .context("remote leaf capacity is zero")?,
612            normal_directories: std::num::NonZeroUsize::new(normal)
613                .context("normal remote directory capacity is zero")?,
614            reserved_directories: std::num::NonZeroUsize::new(reserve)
615                .context("reserved remote directory capacity is zero")?,
616        })
617    }
618}
619
620/// The endpoint admission successfully installed during runtime setup.
621///
622/// Disabled admission leaves both leaf pools unconfigured; startup still raises the process limit.
623/// A configured endpoint can have an unknown soft limit after explicit finite query fallback.
624#[derive(Clone, Copy, Debug, Eq, PartialEq)]
625pub enum EndpointAdmission {
626    Disabled,
627    Configured {
628        soft_limit: Option<std::num::NonZeroU64>,
629        leaf_capacity: std::num::NonZeroUsize,
630    },
631    Remote(RemoteResources),
632}
633
634/// Derive a conservative leaf-operation count from the process descriptor limit.
635///
636/// Local copy/link can overlap three known OpenFile descriptors during overwrite (source
637/// classification, destination planning, and source data); the model reserves a fourth unit as
638/// headroom for transient support use. Recursive rm/delete work can overlap one PendingMeta
639/// classification descriptor. Dividing an 80%-of-soft-`RLIMIT_NOFILE` budget by those five units
640/// gives the same admission count to each pool. Metadata-only tools can transiently hold two
641/// descriptors per PendingMeta operation, but do not use the OpenFile path concurrently. This is a
642/// heuristic for shipped tool workflows, not a hard process-wide ceiling: recursive directories and
643/// process support descriptors are outside leaf admission. A nonzero soft limit gets at least one
644/// operation so very small test/container limits do not silently disable backpressure.
645fn descriptor_admission_limit(soft_limit: std::num::NonZeroU64) -> ConcurrencyLimit {
646    let descriptor_budget = soft_limit.get().saturating_mul(8) / 10;
647    let leaf_operation_limit = std::cmp::min(
648        (descriptor_budget / DESCRIPTOR_UNITS_PER_OPERATION).max(1),
649        MAX_LEAF_OPERATIONS_PER_POOL as u64,
650    );
651    ConcurrencyLimit::Limited(
652        std::num::NonZeroUsize::new(
653            usize::try_from(leaf_operation_limit).expect("the leaf-operation cap fits in usize"),
654        )
655        .expect("the nonzero soft limit produces a nonzero admission cap"),
656    )
657}
658
659fn resolve_leaf_capacity(
660    files_in_flight: ConcurrencyLimit,
661    descriptor_limit: ConcurrencyLimit,
662) -> ConcurrencyLimit {
663    files_in_flight.meet(descriptor_limit)
664}
665
666#[derive(Debug, Eq, PartialEq)]
667enum DescriptorClampVisibility {
668    Notice,
669    Verbose,
670}
671
672#[derive(Debug, Eq, PartialEq)]
673struct DescriptorClampDiagnostic {
674    visibility: DescriptorClampVisibility,
675    message: String,
676}
677
678fn descriptor_clamp_diagnostic(
679    files_in_flight: crate::ResolvedFilesInFlight,
680    effective: ConcurrencyLimit,
681) -> Option<DescriptorClampDiagnostic> {
682    if files_in_flight.limit() == effective {
683        return None;
684    }
685    let ConcurrencyLimit::Limited(effective) = effective else {
686        return None;
687    };
688    let diagnostic = match (files_in_flight.source(), files_in_flight.limit()) {
689        (crate::FilesInFlightSource::Automatic, requested) => DescriptorClampDiagnostic {
690            visibility: DescriptorClampVisibility::Verbose,
691            message: format!(
692                "Automatic file admission was reduced by descriptor safety: requested={requested}, effective={}",
693                ConcurrencyLimit::Limited(effective),
694            ),
695        },
696        (crate::FilesInFlightSource::Explicit, ConcurrencyLimit::Limited(requested)) => {
697            DescriptorClampDiagnostic {
698                visibility: DescriptorClampVisibility::Notice,
699                message: format!(
700                    "Requested --max-files-in-flight={requested}, but descriptor safety reduced endpoint file admission to {effective}"
701                ),
702            }
703        }
704        (
705            crate::FilesInFlightSource::DeprecatedMaxOpenFiles,
706            ConcurrencyLimit::Limited(requested),
707        ) => DescriptorClampDiagnostic {
708            visibility: DescriptorClampVisibility::Notice,
709            message: format!(
710                "Requested --max-open-files={requested}, but descriptor safety reduced endpoint file admission to {effective}"
711            ),
712        },
713        (crate::FilesInFlightSource::DeprecatedMaxOpenFiles, ConcurrencyLimit::Unlimited) => {
714            DescriptorClampDiagnostic {
715                visibility: DescriptorClampVisibility::Notice,
716                message: format!(
717                    "Requested unlimited file admission with --max-open-files=0, but descriptor safety reduced endpoint file admission to {effective}"
718                ),
719            }
720        }
721        (crate::FilesInFlightSource::Explicit, ConcurrencyLimit::Unlimited) => {
722            DescriptorClampDiagnostic {
723                visibility: DescriptorClampVisibility::Notice,
724                message: format!(
725                    "Requested unlimited file admission with --max-files-in-flight=unlimited, but descriptor safety reduced endpoint file admission to {effective}"
726                ),
727            }
728        }
729    };
730    Some(diagnostic)
731}
732
733fn configure_leaf_admission_limit(capacity: ConcurrencyLimit) -> anyhow::Result<()> {
734    let capacity = match capacity {
735        ConcurrencyLimit::Unlimited => None,
736        ConcurrencyLimit::Limited(value) => Some(value),
737    };
738    throttle::try_set_admission_limits(capacity)
739        .context("failed to configure runtime file admission")
740}
741
742fn configure_file_admission(
743    throttle: &ThrottleConfig,
744    get_soft_limit: impl FnOnce() -> Result<u64, std::io::Error>,
745    configure_limit: impl FnOnce(ConcurrencyLimit) -> anyhow::Result<()>,
746) -> anyhow::Result<EndpointAdmission> {
747    if !throttle.apply_files_in_flight {
748        return Ok(EndpointAdmission::Disabled);
749    }
750    let soft_limit = match get_soft_limit() {
751        Ok(soft_limit) => {
752            let soft_limit = std::num::NonZeroU64::new(soft_limit).context(
753                "soft RLIMIT_NOFILE is zero; descriptor-safe file admission is impossible",
754            )?;
755            Some(soft_limit)
756        }
757        Err(error) => match (
758            throttle.files_in_flight.source(),
759            throttle.files_in_flight.limit(),
760        ) {
761            (
762                source @ (crate::FilesInFlightSource::Explicit
763                | crate::FilesInFlightSource::DeprecatedMaxOpenFiles),
764                ConcurrencyLimit::Limited(limit),
765            ) => {
766                let option = match source {
767                    crate::FilesInFlightSource::Explicit => "--max-files-in-flight",
768                    crate::FilesInFlightSource::DeprecatedMaxOpenFiles => "--max-open-files",
769                    crate::FilesInFlightSource::Automatic => unreachable!("matched above"),
770                };
771                tracing::warn!(
772                    target: NOTICE_TARGET,
773                    "Failed to query RLIMIT_NOFILE; using {option}={limit} as the endpoint file-admission ceiling without an independent descriptor-safety ceiling: {error:#}"
774                );
775                None
776            }
777            _ => {
778                return Err(error).context(
779                    "failed to query rlimit; automatic or unlimited file admission requires descriptor safety",
780                );
781            }
782        },
783    };
784    let (admission, leaf_capacity, diagnostic) = match throttle.admission_policy {
785        AdmissionPolicy::Local => {
786            let descriptor_limit = soft_limit
787                .map(descriptor_admission_limit)
788                .unwrap_or(ConcurrencyLimit::Unlimited);
789            let leaf_capacity =
790                resolve_leaf_capacity(throttle.files_in_flight.limit(), descriptor_limit);
791            let ConcurrencyLimit::Limited(leaf) = leaf_capacity else {
792                unreachable!(
793                    "descriptor admission or explicit finite fallback supplies a finite ceiling"
794                )
795            };
796            tracing::info!(
797                "Resolved file admission: file_ceiling={:?}, source={:?}, descriptor_ceiling={:?}, open_file={:?}, pending_meta={:?}",
798                throttle.files_in_flight.limit(),
799                throttle.files_in_flight.source(),
800                descriptor_limit,
801                leaf_capacity,
802                leaf_capacity,
803            );
804            (
805                EndpointAdmission::Configured {
806                    soft_limit,
807                    leaf_capacity: leaf,
808                },
809                leaf_capacity,
810                descriptor_clamp_diagnostic(throttle.files_in_flight, leaf_capacity),
811            )
812        }
813        AdmissionPolicy::Remote { streams, pending } => {
814            let leaf_ceiling = match throttle.files_in_flight.limit() {
815                ConcurrencyLimit::Limited(ceiling) => ceiling,
816                ConcurrencyLimit::Unlimited => streams,
817            };
818            let resources =
819                RemoteResources::for_limits(soft_limit, leaf_ceiling, streams, pending)?;
820            let leaf_capacity = ConcurrencyLimit::Limited(resources.leaf_capacity);
821            tracing::info!(
822                "Resolved remote admission: file_ceiling={:?}, source={:?}, streams={}, pending={}, soft_limit={:?}, open_file={}, pending_meta={}, normal_directories={}, reserved_directories={}",
823                throttle.files_in_flight.limit(),
824                throttle.files_in_flight.source(),
825                streams,
826                pending,
827                soft_limit,
828                resources.leaf_capacity,
829                resources.leaf_capacity,
830                resources.normal_directories,
831                resources.reserved_directories,
832            );
833            if soft_limit.is_none() {
834                tracing::warn!(target: NOTICE_TARGET,
835                    "Remote descriptor headroom is unavailable; using bounded logical admission with {} leaf operations, {} normal directories, and {} reserved levels, without a descriptor-safety guarantee",
836                    resources.leaf_capacity, resources.normal_directories, resources.reserved_directories);
837            }
838            // the resolved stream count already reflects the logical file and connection ceilings. Their
839            // intersection is not a descriptor-safety clamp and must not produce another notice.
840            let diagnostic = (soft_limit.is_some() && resources.leaf_capacity < streams)
841                .then(|| descriptor_clamp_diagnostic(throttle.files_in_flight, leaf_capacity))
842                .flatten();
843            (
844                EndpointAdmission::Remote(resources),
845                leaf_capacity,
846                diagnostic,
847            )
848        }
849    };
850    if let Some(diagnostic) = diagnostic {
851        match diagnostic.visibility {
852            DescriptorClampVisibility::Notice => {
853                tracing::warn!(target: NOTICE_TARGET, "{}", diagnostic.message);
854            }
855            DescriptorClampVisibility::Verbose => {
856                tracing::info!("{}", diagnostic.message);
857            }
858        }
859    }
860    configure_limit(leaf_capacity)?;
861    Ok(admission)
862}
863
864/// Build a multi-threaded tokio runtime configured per `runtime`, and apply the
865/// file-like work and descriptor-safe admission limits from `throttle`.
866pub(crate) fn build_tokio_runtime(
867    runtime: &RuntimeConfig,
868    throttle: &ThrottleConfig,
869) -> anyhow::Result<(tokio::runtime::Runtime, EndpointAdmission)> {
870    let soft_limit = raise_open_file_limit();
871    let mut builder = tokio::runtime::Builder::new_multi_thread();
872    builder.enable_all();
873    if runtime.max_workers > 0 {
874        builder.worker_threads(runtime.max_workers);
875    }
876    if runtime.max_blocking_threads > 0 {
877        builder.max_blocking_threads(runtime.max_blocking_threads);
878    }
879    let runtime = builder.build().context("failed to create Tokio runtime")?;
880    let admission =
881        configure_file_admission(throttle, || soft_limit, configure_leaf_admission_limit)?;
882    Ok((runtime, admission))
883}
884
885#[cfg(test)]
886mod default_leaf_operation_limit_tests {
887    use super::*;
888
889    #[derive(Clone, Default)]
890    struct CapturedLogs(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
891
892    struct CapturedLogWriter(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
893
894    impl std::io::Write for CapturedLogWriter {
895        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
896            self.0.lock().unwrap().extend_from_slice(bytes);
897            Ok(bytes.len())
898        }
899
900        fn flush(&mut self) -> std::io::Result<()> {
901            Ok(())
902        }
903    }
904
905    impl<'writer> tracing_subscriber::fmt::MakeWriter<'writer> for CapturedLogs {
906        type Writer = CapturedLogWriter;
907
908        fn make_writer(&'writer self) -> Self::Writer {
909            CapturedLogWriter(self.0.clone())
910        }
911    }
912
913    impl CapturedLogs {
914        fn contents(&self) -> String {
915            String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
916        }
917    }
918
919    #[cfg(target_os = "linux")]
920    const RLIMIT_CHILD_MARKER: &str = "RCP_TEST_RUNTIME_SETUP_RLIMIT_CHILD";
921    #[cfg(target_os = "linux")]
922    const RLIMIT_CHILD_MARKER_VALUE: &str = "raise-session-soft-limit-v1";
923    #[cfg(target_os = "linux")]
924    const RLIMIT_CHILD_SUCCESS: &str = "RCP_TEST_RUNTIME_SETUP_RLIMIT_CHILD:success";
925    #[cfg(target_os = "linux")]
926    const RLIMIT_CHILD_SKIP: &str = "RCP_TEST_RUNTIME_SETUP_RLIMIT_CHILD:skip";
927    #[cfg(target_os = "linux")]
928    const UNLIMITED_FILE_CEILING_CHILD_MARKER: &str =
929        "RCP_TEST_RUNTIME_SETUP_UNLIMITED_FILE_CEILING_CHILD";
930    #[cfg(target_os = "linux")]
931    const UNLIMITED_FILE_CEILING_CHILD_MARKER_VALUE: &str =
932        "uses-descriptor-safety-after-stale-admission-epoch-v1";
933    #[cfg(target_os = "linux")]
934    const UNLIMITED_FILE_CEILING_CHILD_SUCCESS: &str =
935        "RCP_TEST_RUNTIME_SETUP_UNLIMITED_FILE_CEILING_CHILD:success";
936
937    #[cfg(target_os = "linux")]
938    fn nofile_limit() -> libc::rlimit {
939        let mut limit = libc::rlimit {
940            rlim_cur: 0,
941            rlim_max: 0,
942        };
943        // safety: `limit` is valid for writes and the return value is checked
944        let result = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) };
945        assert_eq!(
946            result,
947            0,
948            "getrlimit failed: {:#}",
949            std::io::Error::last_os_error()
950        );
951        limit
952    }
953
954    #[test]
955    fn equal_descriptor_limits_do_not_require_a_setrlimit_call() {
956        let limit = raise_soft_limit(
957            libc::rlimit {
958                rlim_cur: 256,
959                rlim_max: 256,
960            },
961            |_| panic!("an unchanged limit must not require permission to set it"),
962        );
963        assert_eq!(limit, 256);
964    }
965
966    #[test]
967    fn denied_descriptor_raise_retains_known_admission_and_reports_the_cause() {
968        let captured = CapturedLogs::default();
969        let subscriber = tracing_subscriber::fmt()
970            .with_writer(captured.clone())
971            .with_ansi(false)
972            .without_time()
973            .finish();
974        tracing::subscriber::with_default(subscriber, || {
975            let soft = raise_soft_limit(
976                libc::rlimit {
977                    rlim_cur: 256,
978                    rlim_max: 512,
979                },
980                |requested| {
981                    assert_eq!(requested.rlim_cur, 512);
982                    assert_eq!(requested.rlim_max, 512);
983                    Err(std::io::Error::from_raw_os_error(libc::EPERM))
984                },
985            );
986            let admission = configure_file_admission(
987                &ThrottleConfig {
988                    files_in_flight: crate::ResolvedFilesInFlight::unlimited(),
989                    ..ThrottleConfig::default()
990                },
991                || Ok(soft),
992                |capacity| {
993                    assert_eq!(
994                        capacity,
995                        ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(40).unwrap())
996                    );
997                    Ok(())
998                },
999            )
1000            .expect("a denied raise must still permit budgeting from the known soft limit");
1001            assert_eq!(
1002                admission,
1003                EndpointAdmission::Configured {
1004                    soft_limit: std::num::NonZeroU64::new(256),
1005                    leaf_capacity: std::num::NonZeroUsize::new(40).unwrap(),
1006                }
1007            );
1008        });
1009        let logs = captured.contents();
1010        assert!(logs.contains("rcp::notice"), "{logs}");
1011        assert!(logs.contains("256") && logs.contains("512"), "{logs}");
1012        assert!(
1013            logs.contains(&std::io::Error::from_raw_os_error(libc::EPERM).to_string()),
1014            "{logs}"
1015        );
1016    }
1017
1018    #[test]
1019    fn configured_admission_reports_actual_installed_leaf_capacity() {
1020        let finite = |value| {
1021            crate::ResolvedFilesInFlight::explicit(std::num::NonZeroUsize::new(value).unwrap())
1022        };
1023        for (soft, files, leaf) in [
1024            (1024, finite(20), 20),
1025            (1024, finite(1000), 163),
1026            (1024, crate::ResolvedFilesInFlight::unlimited(), 163),
1027            (1_000_000, crate::ResolvedFilesInFlight::unlimited(), 4096),
1028            (1, finite(20), 1),
1029            (u64::MAX, crate::ResolvedFilesInFlight::unlimited(), 4096),
1030        ] {
1031            let throttle = ThrottleConfig {
1032                files_in_flight: files,
1033                ..Default::default()
1034            };
1035            let mut configured = None;
1036            let admission = configure_file_admission(
1037                &throttle,
1038                || Ok(soft),
1039                |capacity| {
1040                    configured = Some(capacity);
1041                    Ok(())
1042                },
1043            )
1044            .unwrap();
1045            assert_eq!(
1046                configured,
1047                Some(ConcurrencyLimit::Limited(
1048                    std::num::NonZeroUsize::new(leaf).unwrap()
1049                ))
1050            );
1051            assert_eq!(
1052                admission,
1053                EndpointAdmission::Configured {
1054                    soft_limit: std::num::NonZeroU64::new(soft),
1055                    leaf_capacity: std::num::NonZeroUsize::new(leaf).unwrap(),
1056                }
1057            );
1058        }
1059    }
1060
1061    #[test]
1062    fn rejected_admission_preserves_configuration_error() {
1063        let error = configure_file_admission(
1064            &ThrottleConfig::default(),
1065            || Ok(1024),
1066            |_| {
1067                Err(std::io::Error::new(
1068                    std::io::ErrorKind::PermissionDenied,
1069                    "configuration rejected",
1070                )
1071                .into())
1072            },
1073        )
1074        .expect_err("rejected configuration must not return a usable snapshot");
1075        assert_eq!(
1076            error.downcast_ref::<std::io::Error>().unwrap().kind(),
1077            std::io::ErrorKind::PermissionDenied
1078        );
1079    }
1080
1081    #[test]
1082    fn reserves_descriptor_headroom_for_each_leaf_operation() {
1083        let nonzero = |value| std::num::NonZeroU64::new(value).unwrap();
1084        assert_eq!(
1085            descriptor_admission_limit(nonzero(100)),
1086            ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(16).unwrap())
1087        );
1088        assert_eq!(
1089            descriptor_admission_limit(nonzero(4096)),
1090            ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(655).unwrap())
1091        );
1092        assert_eq!(
1093            descriptor_admission_limit(nonzero(1_000_000)),
1094            ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(4096).unwrap())
1095        );
1096        assert_eq!(
1097            descriptor_admission_limit(nonzero(u64::MAX)),
1098            ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(4096).unwrap())
1099        );
1100    }
1101
1102    #[test]
1103    fn keeps_a_small_nonzero_limit_live() {
1104        let one = ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(1).unwrap());
1105        assert_eq!(
1106            descriptor_admission_limit(std::num::NonZeroU64::new(1).unwrap()),
1107            one
1108        );
1109        assert_eq!(
1110            descriptor_admission_limit(std::num::NonZeroU64::new(4).unwrap()),
1111            one
1112        );
1113    }
1114
1115    #[test]
1116    fn file_and_descriptor_ceilings_are_intersected() {
1117        let limited =
1118            |value| ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(value).unwrap());
1119        assert_eq!(resolve_leaf_capacity(limited(8), limited(40)), limited(8));
1120        assert_eq!(resolve_leaf_capacity(limited(80), limited(40)), limited(40));
1121        assert_eq!(
1122            resolve_leaf_capacity(ConcurrencyLimit::Unlimited, limited(40)),
1123            limited(40)
1124        );
1125        assert_eq!(
1126            resolve_leaf_capacity(limited(8), ConcurrencyLimit::Unlimited),
1127            limited(8)
1128        );
1129    }
1130
1131    #[test]
1132    fn descriptor_clamp_diagnostics_preserve_file_limit_provenance() {
1133        let eight = std::num::NonZeroUsize::new(8).unwrap();
1134        let four = std::num::NonZeroUsize::new(4).unwrap();
1135        let effective = ConcurrencyLimit::Limited(four);
1136        assert_eq!(
1137            descriptor_clamp_diagnostic(
1138                crate::ResolvedFilesInFlight::legacy(eight.get()),
1139                effective
1140            ),
1141            Some(DescriptorClampDiagnostic {
1142                visibility: DescriptorClampVisibility::Notice,
1143                message: "Requested --max-open-files=8, but descriptor safety reduced endpoint file admission to 4".to_string(),
1144            })
1145        );
1146        assert_eq!(
1147            descriptor_clamp_diagnostic(crate::ResolvedFilesInFlight::legacy(0), effective),
1148            Some(DescriptorClampDiagnostic {
1149                visibility: DescriptorClampVisibility::Notice,
1150                message: "Requested unlimited file admission with --max-open-files=0, but descriptor safety reduced endpoint file admission to 4".to_string(),
1151            })
1152        );
1153        assert_eq!(
1154            descriptor_clamp_diagnostic(crate::ResolvedFilesInFlight::unlimited(), effective),
1155            Some(DescriptorClampDiagnostic {
1156                visibility: DescriptorClampVisibility::Notice,
1157                message: "Requested unlimited file admission with --max-files-in-flight=unlimited, but descriptor safety reduced endpoint file admission to 4".to_string(),
1158            })
1159        );
1160        assert_eq!(
1161            descriptor_clamp_diagnostic(
1162                crate::ResolvedFilesInFlight::automatic_with(eight), effective
1163            ),
1164            Some(DescriptorClampDiagnostic {
1165                visibility: DescriptorClampVisibility::Verbose,
1166                message: "Automatic file admission was reduced by descriptor safety: requested=8, effective=4".to_string(),
1167            })
1168        );
1169    }
1170
1171    #[test]
1172    fn runtime_admission_setup_propagates_oversized_capacity() {
1173        let oversized = ConcurrencyLimit::Limited(
1174            std::num::NonZeroUsize::new(tokio::sync::Semaphore::MAX_PERMITS + 1).unwrap(),
1175        );
1176
1177        let error = configure_leaf_admission_limit(oversized)
1178            .expect_err("oversized leaf admission must return an error");
1179
1180        assert!(
1181            error
1182                .downcast_ref::<throttle::AdmissionCapacityError>()
1183                .is_some(),
1184            "runtime setup must preserve the typed throttle error: {error:#}"
1185        );
1186    }
1187
1188    #[test]
1189    fn disabled_file_admission_does_not_query_or_configure_limits() {
1190        let throttle = ThrottleConfig {
1191            apply_files_in_flight: false,
1192            ..ThrottleConfig::default()
1193        };
1194        let mut queried = false;
1195        let mut configured = false;
1196        let admission = configure_file_admission(
1197            &throttle,
1198            || {
1199                queried = true;
1200                Err(std::io::Error::other(
1201                    "disabled admission must not query rlimit",
1202                ))
1203            },
1204            |_| {
1205                configured = true;
1206                Ok(())
1207            },
1208        )
1209        .expect("disabled file admission must not touch runtime admission state");
1210
1211        assert_eq!(admission, EndpointAdmission::Disabled);
1212        assert!(!queried, "disabled file admission queried rlimit");
1213        assert!(
1214            !configured,
1215            "disabled file admission reconfigured throttle pools"
1216        );
1217    }
1218
1219    #[test]
1220    fn finite_user_file_limits_recover_from_rlimit_query_failure() {
1221        let eight = std::num::NonZeroUsize::new(8).unwrap();
1222        let expected = ConcurrencyLimit::Limited(eight);
1223        let captured = CapturedLogs::default();
1224        let subscriber = tracing_subscriber::fmt()
1225            .with_writer(captured.clone())
1226            .with_ansi(false)
1227            .without_time()
1228            .with_target(true)
1229            .with_max_level(tracing::Level::TRACE)
1230            .finish();
1231        tracing::subscriber::with_default(subscriber, || {
1232            for files_in_flight in [
1233                crate::ResolvedFilesInFlight::explicit(eight),
1234                crate::ResolvedFilesInFlight::forwarded_legacy(eight.get()),
1235            ] {
1236                let throttle = ThrottleConfig {
1237                    files_in_flight,
1238                    ..ThrottleConfig::default()
1239                };
1240                let mut configured = None;
1241
1242                let admission = configure_file_admission(
1243                    &throttle,
1244                    || Err(std::io::Error::other("sentinel rlimit failure")),
1245                    |capacity| {
1246                        configured = Some(capacity);
1247                        Ok(())
1248                    },
1249                )
1250                .expect("a finite user ceiling must remain usable when getrlimit fails");
1251
1252                assert_eq!(configured, Some(expected));
1253                assert_eq!(
1254                    admission,
1255                    EndpointAdmission::Configured {
1256                        soft_limit: None,
1257                        leaf_capacity: eight
1258                    }
1259                );
1260            }
1261        });
1262
1263        let logs = captured.contents();
1264        for option in ["--max-files-in-flight=8", "--max-open-files=8"] {
1265            assert!(
1266                logs.lines().any(|line| {
1267                    line.contains(" WARN ")
1268                        && line.contains("rcp::notice")
1269                        && line.contains(option)
1270                        && line.contains("sentinel rlimit failure")
1271                }),
1272                "missing default-visible rlimit fallback notice for {option}: {logs}"
1273            );
1274        }
1275    }
1276
1277    #[test]
1278    fn automatic_file_limit_does_not_bypass_rlimit_query_failure() {
1279        let mut configured = false;
1280        let error = configure_file_admission(
1281            &ThrottleConfig::default(),
1282            || Err(std::io::Error::other("sentinel rlimit failure")),
1283            |_| {
1284                configured = true;
1285                Ok(())
1286            },
1287        )
1288        .expect_err("an automatic ceiling must retain descriptor-safety validation");
1289
1290        assert!(error.to_string().contains("failed to query rlimit"));
1291        assert!(
1292            !configured,
1293            "failed automatic validation configured admission"
1294        );
1295    }
1296
1297    #[test]
1298    fn unlimited_file_limit_does_not_bypass_rlimit_query_failure() {
1299        let throttle = ThrottleConfig {
1300            files_in_flight: crate::ResolvedFilesInFlight::forwarded_legacy(0),
1301            ..ThrottleConfig::default()
1302        };
1303        let mut configured = false;
1304        let error = configure_file_admission(
1305            &throttle,
1306            || Err(std::io::Error::other("sentinel rlimit failure")),
1307            |_| {
1308                configured = true;
1309                Ok(())
1310            },
1311        )
1312        .expect_err("an unlimited ceiling must retain descriptor-safety validation");
1313
1314        assert!(error.to_string().contains("failed to query rlimit"));
1315        assert!(
1316            !configured,
1317            "failed unlimited validation configured admission"
1318        );
1319    }
1320
1321    #[test]
1322    fn zero_soft_descriptor_limit_fails_closed_for_every_file_policy() {
1323        let eight = std::num::NonZeroUsize::new(8).unwrap();
1324        for files_in_flight in [
1325            crate::ResolvedFilesInFlight::automatic_with(eight),
1326            crate::ResolvedFilesInFlight::explicit(eight),
1327            crate::ResolvedFilesInFlight::forwarded_legacy(0),
1328        ] {
1329            let throttle = ThrottleConfig {
1330                files_in_flight,
1331                ..ThrottleConfig::default()
1332            };
1333            let mut configured = false;
1334            let error = configure_file_admission(
1335                &throttle,
1336                || Ok(0),
1337                |_| {
1338                    configured = true;
1339                    Ok(())
1340                },
1341            )
1342            .expect_err("a zero soft descriptor limit must fail closed");
1343
1344            assert!(error.to_string().contains("soft RLIMIT_NOFILE is zero"));
1345            assert!(!configured, "zero descriptor safety configured admission");
1346        }
1347    }
1348
1349    #[cfg(target_os = "linux")]
1350    #[test]
1351    fn build_tokio_runtime_unlimited_file_ceiling_uses_descriptor_safety_after_stale_epoch() {
1352        let is_child = std::env::var_os(UNLIMITED_FILE_CEILING_CHILD_MARKER).is_some_and(|value| {
1353            value == std::ffi::OsStr::new(UNLIMITED_FILE_CEILING_CHILD_MARKER_VALUE)
1354        });
1355        if !is_child {
1356            let output = std::process::Command::new(std::env::current_exe().unwrap())
1357                .args([
1358                    "--exact",
1359                    "runtime_setup::default_leaf_operation_limit_tests::build_tokio_runtime_unlimited_file_ceiling_uses_descriptor_safety_after_stale_epoch",
1360                    "--nocapture",
1361                ])
1362                .env(
1363                    UNLIMITED_FILE_CEILING_CHILD_MARKER,
1364                    UNLIMITED_FILE_CEILING_CHILD_MARKER_VALUE,
1365                )
1366                .output()
1367                .unwrap();
1368            let stdout = String::from_utf8_lossy(&output.stdout);
1369            let stderr = String::from_utf8_lossy(&output.stderr);
1370            assert!(
1371                output.status.success(),
1372                "child test failed:\n{stdout}\n{stderr}"
1373            );
1374            assert!(
1375                stdout.contains(UNLIMITED_FILE_CEILING_CHILD_SUCCESS)
1376                    || stderr.contains(UNLIMITED_FILE_CEILING_CHILD_SUCCESS),
1377                "child branch did not emit its sentinel:\n{stdout}\n{stderr}"
1378            );
1379            return;
1380        }
1381        let runtime = RuntimeConfig {
1382            max_workers: 1,
1383            max_blocking_threads: 1,
1384        };
1385        let old_limit = ThrottleConfig {
1386            files_in_flight: crate::ResolvedFilesInFlight::explicit(
1387                std::num::NonZeroUsize::new(1).unwrap(),
1388            ),
1389            ..ThrottleConfig::default()
1390        };
1391        let (admission_runtime, _) =
1392            build_tokio_runtime(&runtime, &old_limit).expect("runtime setup must succeed");
1393        let (old_open_file, old_pending_meta) = admission_runtime.block_on(async {
1394            tokio::join!(
1395                throttle::open_file_permit(),
1396                throttle::pending_meta_permit()
1397            )
1398        });
1399        let unlimited_file_ceiling = ThrottleConfig {
1400            files_in_flight: crate::ResolvedFilesInFlight::unlimited(),
1401            ..ThrottleConfig::default()
1402        };
1403        drop(
1404            build_tokio_runtime(&runtime, &unlimited_file_ceiling)
1405                .expect("runtime setup must succeed"),
1406        );
1407        let (new_open_file, new_pending_meta) = admission_runtime.block_on(async {
1408            let open_file = tokio::time::timeout(
1409                std::time::Duration::from_secs(1),
1410                throttle::open_file_permit(),
1411            )
1412            .await
1413            .expect("unlimited file ceiling must use descriptor safety instead of a stale OpenFile epoch");
1414            let pending_meta = tokio::time::timeout(
1415                std::time::Duration::from_secs(1),
1416                throttle::pending_meta_permit(),
1417            )
1418            .await
1419            .expect("unlimited file ceiling must use descriptor safety instead of a stale PendingMeta epoch");
1420            (open_file, pending_meta)
1421        });
1422        drop((
1423            new_open_file,
1424            new_pending_meta,
1425            old_open_file,
1426            old_pending_meta,
1427        ));
1428        throttle::set_admission_limits(None);
1429        println!("{UNLIMITED_FILE_CEILING_CHILD_SUCCESS}");
1430    }
1431
1432    #[cfg(target_os = "linux")]
1433    #[test]
1434    fn runtime_raises_soft_limit_and_budgets_without_raising_file_concurrency() {
1435        let is_child = std::env::var_os(RLIMIT_CHILD_MARKER)
1436            .is_some_and(|value| value == std::ffi::OsStr::new(RLIMIT_CHILD_MARKER_VALUE));
1437        if !is_child {
1438            let output = std::process::Command::new(std::env::current_exe().unwrap())
1439                .args([
1440                    "--exact",
1441                    "runtime_setup::default_leaf_operation_limit_tests::runtime_raises_soft_limit_and_budgets_without_raising_file_concurrency",
1442                    "--nocapture",
1443                ])
1444                .env(RLIMIT_CHILD_MARKER, RLIMIT_CHILD_MARKER_VALUE)
1445                .output()
1446                .unwrap();
1447            let stdout = String::from_utf8_lossy(&output.stdout);
1448            let stderr = String::from_utf8_lossy(&output.stderr);
1449            assert!(
1450                output.status.success(),
1451                "child test failed:\n{stdout}\n{stderr}"
1452            );
1453            assert!(
1454                stdout.contains(RLIMIT_CHILD_SUCCESS)
1455                    || stderr.contains(RLIMIT_CHILD_SUCCESS)
1456                    || stdout.contains(RLIMIT_CHILD_SKIP)
1457                    || stderr.contains(RLIMIT_CHILD_SKIP),
1458                "child branch did not emit its sentinel:\n{stdout}\n{stderr}"
1459            );
1460            return;
1461        }
1462        let original = nofile_limit();
1463        const TARGET_SOFT_LIMIT: libc::rlim_t = 256;
1464        const TARGET_HARD_LIMIT: libc::rlim_t = 512;
1465        if original.rlim_max < TARGET_HARD_LIMIT {
1466            eprintln!(
1467                "{RLIMIT_CHILD_SKIP}: current={} hard={}",
1468                original.rlim_cur, original.rlim_max
1469            );
1470            return;
1471        }
1472        let runtime = RuntimeConfig {
1473            max_workers: 1,
1474            max_blocking_threads: 1,
1475        };
1476        let eight = std::num::NonZeroUsize::new(8).unwrap();
1477        for (files_in_flight, admission_policy, capacity) in [
1478            (
1479                crate::ResolvedFilesInFlight::unlimited(),
1480                AdmissionPolicy::Local,
1481                81,
1482            ),
1483            (
1484                crate::ResolvedFilesInFlight::explicit(eight),
1485                AdmissionPolicy::Local,
1486                8,
1487            ),
1488            (
1489                crate::ResolvedFilesInFlight::explicit(eight),
1490                AdmissionPolicy::Remote {
1491                    streams: eight,
1492                    pending: std::num::NonZeroUsize::new(32).unwrap(),
1493                },
1494                8,
1495            ),
1496        ] {
1497            let lowered = libc::rlimit {
1498                rlim_cur: TARGET_SOFT_LIMIT,
1499                rlim_max: TARGET_HARD_LIMIT,
1500            };
1501            // safety: `lowered` is valid and affects only this isolated child process
1502            assert_eq!(
1503                unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &raw const lowered) },
1504                0
1505            );
1506            let throttle = ThrottleConfig {
1507                files_in_flight,
1508                admission_policy,
1509                ..ThrottleConfig::default()
1510            };
1511            let (runtime, admission) =
1512                build_tokio_runtime(&runtime, &throttle).expect("runtime setup must succeed");
1513            let after = nofile_limit();
1514            assert_eq!(
1515                after.rlim_cur, TARGET_HARD_LIMIT,
1516                "startup must raise the soft limit"
1517            );
1518            assert_eq!(
1519                after.rlim_max, TARGET_HARD_LIMIT,
1520                "startup must preserve the hard limit"
1521            );
1522            let (soft_limit, leaf_capacity) = match admission {
1523                EndpointAdmission::Configured {
1524                    soft_limit,
1525                    leaf_capacity,
1526                } => (soft_limit, leaf_capacity),
1527                EndpointAdmission::Remote(resources) => {
1528                    (resources.soft_limit, resources.leaf_capacity)
1529                }
1530                EndpointAdmission::Disabled => panic!("file admission must remain enabled"),
1531            };
1532            assert_eq!(soft_limit.unwrap().get(), 512);
1533            assert_eq!(leaf_capacity.get(), capacity);
1534            let (open_files, pending_meta) = runtime
1535                .block_on(async {
1536                    tokio::time::timeout(std::time::Duration::from_secs(3), async {
1537                        let mut open_files = Vec::with_capacity(capacity);
1538                        let mut pending_meta = Vec::with_capacity(capacity);
1539                        for _ in 0..capacity {
1540                            open_files.push(throttle::open_file_permit().await);
1541                        }
1542                        for _ in 0..capacity {
1543                            pending_meta.push(throttle::pending_meta_permit().await);
1544                        }
1545                        assert!(
1546                            tokio::time::timeout(
1547                                std::time::Duration::from_millis(50),
1548                                throttle::open_file_permit(),
1549                            )
1550                            .await
1551                            .is_err(),
1552                            "OpenFile admission must wait at the resolved capacity"
1553                        );
1554                        assert!(
1555                            tokio::time::timeout(
1556                                std::time::Duration::from_millis(50),
1557                                throttle::pending_meta_permit(),
1558                            )
1559                            .await
1560                            .is_err(),
1561                            "PendingMeta admission must wait at the resolved capacity"
1562                        );
1563                        (open_files, pending_meta)
1564                    })
1565                    .await
1566                })
1567                .expect("derived admission boundary must complete within its watchdog");
1568            drop((open_files, pending_meta));
1569            throttle::set_admission_limits(None);
1570        }
1571        println!("{RLIMIT_CHILD_SUCCESS}");
1572    }
1573}
1574
1575/// Spawn the ops/iops throttle replenisher tasks onto `runtime` if the
1576/// throttles are enabled.
1577///
1578/// When `auto_meta` is set, the ops-throttle is forced to a fixed 100ms
1579/// replenish interval (matching the constant the auto-meta adapter uses
1580/// when converting `Decision::rate_per_sec` → tokens-per-interval) *and*
1581/// is bootstrapped even if `--ops-throttle` was zero. That way:
1582///
1583/// 1. a future rate-aware controller's `rate_per_sec: Some(_)` decisions
1584///    actually gate ops instead of silently no-opping;
1585/// 2. the adapter's 100ms conversion assumption matches the thread's
1586///    real interval, regardless of the user's static `--ops-throttle`
1587///    value.
1588pub(crate) fn spawn_throttle_replenishers(
1589    runtime: &tokio::runtime::Runtime,
1590    throttle: &ThrottleConfig,
1591    trace_identifier: &str,
1592) {
1593    fn get_replenish_interval(replenish: usize) -> (usize, std::time::Duration) {
1594        let mut replenish = replenish;
1595        let mut interval = std::time::Duration::from_secs(1);
1596        while replenish > 100 && interval > std::time::Duration::from_millis(1) {
1597            replenish /= 10;
1598            interval /= 10;
1599        }
1600        (replenish, interval)
1601    }
1602    let auto_meta_on = throttle.auto_meta.is_some();
1603    if auto_meta_on {
1604        // Force the fixed 100ms cadence the adapter assumes. Bootstrap
1605        // with at least 1 token so `setup()` enables the semaphore; if
1606        // the user didn't pass `--ops-throttle`, immediately disable —
1607        // the adapter re-enables only when a rate decision arrives.
1608        let interval = std::time::Duration::from_millis(100);
1609        let initial_replenish = (throttle.ops_throttle as f64 * 0.1) as usize;
1610        throttle::init_ops_tokens(initial_replenish.max(1));
1611        if throttle.ops_throttle == 0 {
1612            throttle::disable_ops_throttle();
1613        }
1614        runtime.spawn(throttle::run_ops_replenish_thread(
1615            initial_replenish,
1616            interval,
1617        ));
1618    } else if throttle.ops_throttle > 0 {
1619        let (replenish, interval) = get_replenish_interval(throttle.ops_throttle);
1620        throttle::init_ops_tokens(replenish);
1621        runtime.spawn(throttle::run_ops_replenish_thread(replenish, interval));
1622    }
1623    if throttle.iops_throttle > 0 {
1624        let (replenish, interval) = get_replenish_interval(throttle.iops_throttle);
1625        throttle::init_iops_tokens(replenish);
1626        runtime.spawn(throttle::run_iops_replenish_thread(replenish, interval));
1627    }
1628    if let Some(auto) = throttle.auto_meta {
1629        spawn_auto_meta_throttle(
1630            runtime,
1631            auto,
1632            throttle.histogram_enabled,
1633            throttle.histogram_log_path.clone(),
1634            throttle.histogram_interval,
1635            trace_identifier,
1636        );
1637    }
1638}
1639
1640/// Compute the per-tool resolved log path by inserting `trace_identifier`
1641/// between the user-supplied stem and extension. Mirrors the
1642/// chrome_trace_prefix convention so master and rcpds don't collide on
1643/// localhost runs.
1644///
1645/// Handles three edge cases consistently with the validator:
1646/// - bare filename (`foo.hdr`): parent → `.`
1647/// - no extension (`foo`): extension → `hdr`
1648/// - no stem (`.hidden`): stem → `auto-meta`
1649///
1650/// Non-UTF-8 stem and extension components (valid on Unix) are preserved
1651/// unchanged; only genuinely absent components fall back to defaults.
1652fn resolve_log_path(path: &std::path::Path, trace_identifier: &str) -> std::path::PathBuf {
1653    let parent = match path.parent() {
1654        Some(p) if p.as_os_str().is_empty() => std::path::Path::new("."),
1655        Some(p) => p,
1656        None => std::path::Path::new("."),
1657    };
1658    let mut name: std::ffi::OsString = path
1659        .file_stem()
1660        .map(|s| s.to_os_string())
1661        .unwrap_or_else(|| std::ffi::OsString::from("auto-meta"));
1662    name.push(".");
1663    name.push(trace_identifier);
1664    name.push(".");
1665    match path.extension() {
1666        Some(e) => name.push(e),
1667        None => name.push("hdr"),
1668    }
1669    parent.join(name)
1670}
1671
1672/// Verify the resolved histogram log path can actually be opened for
1673/// writing. Called from [`run`] before any work begins so a typo or
1674/// permission issue surfaces as a configuration error rather than a
1675/// silent warning at runtime.
1676///
1677/// The check creates+truncates the file (matching what the logger
1678/// task does later) so it catches "exists as a directory", "exists
1679/// as an unwritable file", and most permission issues. The logger's
1680/// own open later in startup will reuse the same path; the double-
1681/// open is harmless (the logger truncates again).
1682pub(crate) fn validate_histogram_log_target(
1683    throttle: &ThrottleConfig,
1684    trace_identifier: &str,
1685) -> Result<(), String> {
1686    let Some(path) = &throttle.histogram_log_path else {
1687        return Ok(());
1688    };
1689    if path.is_dir() {
1690        return Err(format!(
1691            "--auto-meta-histogram-log {path:?} is a directory; expected a file path",
1692        ));
1693    }
1694    if path.file_name().is_none() {
1695        return Err(format!(
1696            "--auto-meta-histogram-log {path:?} has no filename component",
1697        ));
1698    }
1699    let resolved = resolve_log_path(path, trace_identifier);
1700    let mut open_options = std::fs::OpenOptions::new();
1701    open_options.create(true).write(true).truncate(true);
1702    #[cfg(unix)]
1703    {
1704        use std::os::unix::fs::OpenOptionsExt;
1705        open_options.custom_flags(libc::O_NOFOLLOW);
1706    }
1707    match open_options.open(&resolved) {
1708        Ok(_) => Ok(()),
1709        Err(err) => {
1710            // ELOOP from O_NOFOLLOW reads as "too many levels of symbolic links"
1711            // — make it explicit that this rejection is intentional security.
1712            #[cfg(unix)]
1713            let context = if err.raw_os_error() == Some(libc::ELOOP) {
1714                " (resolved path is a symlink, which would let a local attacker hijack the write)"
1715            } else {
1716                ""
1717            };
1718            #[cfg(not(unix))]
1719            let context = "";
1720            Err(format!(
1721                "--auto-meta-histogram-log cannot create resolved path {resolved:?}: {err:#}{context}",
1722            ))
1723        }
1724    }
1725}
1726
1727/// Stable label for a `(Side, MetadataOp)` controller.
1728///
1729/// Naming rule:
1730/// - **Lookups** (`Stat`, `ReadLink`) happen on either filesystem, so
1731///   the label always carries an explicit `src-` / `dst-` prefix to
1732///   disambiguate. Example: `src-stat`, `dst-read-link`.
1733/// - **Mutations and `open(O_CREAT)`** only ever occur on the
1734///   destination side (sources are immutable in copy/cmp/link/rm).
1735///   These labels drop the side prefix entirely. Example: `mkdir`,
1736///   `unlink`, `rmdir`, `hard-link`, `symlink`, `chmod`, `open-create`.
1737///
1738/// The result: single-filesystem tools like `rrm` show clean labels
1739/// (`src-stat`, `unlink`, `rmdir`) instead of the prior misleading
1740/// `meta-src` / `meta-dst` framing — there is no second filesystem to
1741/// distinguish from. Dual-filesystem tools (rcp, rcmp, rlink) still
1742/// disambiguate the two stat / read-link controllers cleanly.
1743///
1744/// Implemented as a `const fn` over a fixed match table so the label
1745/// set is a compile-time constant — no allocation, no `Box::leak`, and
1746/// no per-`run()` accumulation when callers invoke the runtime more
1747/// than once in a single process.
1748const fn unit_label(side: congestion::Side, op: congestion::MetadataOp) -> &'static str {
1749    use congestion::MetadataOp::*;
1750    use congestion::Side::*;
1751    match (side, op) {
1752        // Lookups: prefix with side because both sides exercise them.
1753        (Source, Stat) => "src-stat",
1754        (Destination, Stat) => "dst-stat",
1755        (Source, ReadLink) => "src-read-link",
1756        (Destination, ReadLink) => "dst-read-link",
1757        // Destination-only ops: no prefix in the active case. The
1758        // (Source, op) slot is wired but never sees a sample under
1759        // normal operation; the renderer hides it. The `src-` label is
1760        // kept so any debugging surface still disambiguates the slot
1761        // from the active destination one if it ever fires.
1762        (Destination, MkDir) => "mkdir",
1763        (Source, MkDir) => "src-mkdir",
1764        (Destination, RmDir) => "rmdir",
1765        (Source, RmDir) => "src-rmdir",
1766        (Destination, Unlink) => "unlink",
1767        (Source, Unlink) => "src-unlink",
1768        (Destination, HardLink) => "hard-link",
1769        (Source, HardLink) => "src-hard-link",
1770        (Destination, Symlink) => "symlink",
1771        (Source, Symlink) => "src-symlink",
1772        (Destination, Chmod) => "chmod",
1773        (Source, Chmod) => "src-chmod",
1774        (Destination, OpenCreate) => "open-create",
1775        (Source, OpenCreate) => "src-open-create",
1776    }
1777}
1778
1779fn build_histogram_header(
1780    auto: &AutoMetaThrottleConfig,
1781    tool_name: &str,
1782    snapshot_interval: std::time::Duration,
1783) -> congestion::format::LogHeader {
1784    use congestion::format::{AutoMetaSnapshot, HdrSnapshot, LogHeader, UnitLabel};
1785    let hostname = get_hostname();
1786    let mut unit_labels = Vec::with_capacity(congestion::N_META_RESOURCES);
1787    for &side in &congestion::Side::ALL {
1788        for &op in &congestion::MetadataOp::ALL {
1789            unit_labels.push(UnitLabel {
1790                side: side as u8,
1791                op: op as u8,
1792                label: unit_label(side, op).to_string(),
1793            });
1794        }
1795    }
1796    LogHeader {
1797        format_version: congestion::format::FORMAT_VERSION,
1798        tool: tool_name.to_string(),
1799        tool_version: env!("CARGO_PKG_VERSION").to_string(),
1800        hostname,
1801        pid: std::process::id(),
1802        start_unix_micros: std::time::SystemTime::now()
1803            .duration_since(std::time::UNIX_EPOCH)
1804            .map(|d| u64::try_from(d.as_micros()).unwrap_or(u64::MAX))
1805            .unwrap_or(0),
1806        snapshot_interval_micros: u64::try_from(snapshot_interval.as_micros()).unwrap_or(u64::MAX),
1807        auto_meta: AutoMetaSnapshot {
1808            initial_cwnd: auto.initial_cwnd,
1809            min_cwnd: auto.min_cwnd,
1810            max_cwnd: auto.max_cwnd,
1811            alpha: auto.alpha,
1812            beta: auto.beta,
1813            increase_step: auto.increase_step,
1814            decrease_step: auto.decrease_step,
1815            baseline_percentile: auto.baseline_percentile,
1816            current_percentile: auto.current_percentile,
1817            long_window_micros: u64::try_from(auto.long_window.as_micros()).unwrap_or(u64::MAX),
1818            short_window_micros: u64::try_from(auto.short_window.as_micros()).unwrap_or(u64::MAX),
1819            tick_interval_micros: u64::try_from(auto.tick_interval.as_micros()).unwrap_or(u64::MAX),
1820        },
1821        hdr: HdrSnapshot {
1822            lowest_discernible_micros: congestion::HDR_LOWEST_DISCERNIBLE_MICROS,
1823            highest_trackable_micros: congestion::HDR_HIGHEST_TRACKABLE_MICROS,
1824            significant_figures: congestion::HDR_SIGNIFICANT_FIGURES,
1825            unit: "microseconds".into(),
1826        },
1827        unit_labels,
1828    }
1829}
1830
1831/// Wire up the adaptive metadata-ops control loops — one per
1832/// `(Side, MetadataOp)` pair (18 in total):
1833///
1834/// 1. Seed every resource's `OPS_IN_FLIGHT_LIMIT_*` semaphore with the
1835///    controller's initial cwnd so the first probe on any resource
1836///    finds a permit available.
1837/// 2. Install one `RoutingSink` that fans metadata samples out to per-
1838///    `(side, op)` channels, each consumed by its own
1839///    `ControlUnit<RatioController>`. Each syscall on each side gets
1840///    an independent latency baseline and an independent cwnd, so a
1841///    saturated `unlink` path doesn't drag down `stat` (or vice versa).
1842/// 3. Spawn one combined adapter/monitor task per resource. By
1843///    convention `(Destination, Stat)` is the rate-driver — the global
1844///    `OPS_THROTTLE` is shared, so only one adapter may translate rate
1845///    decisions; all others apply concurrency only. The current
1846///    `RatioController` doesn't emit rate decisions, so the choice is
1847///    forward-looking.
1848/// 4. Each adapter exits cleanly when its control unit stops
1849///    publishing decisions, so they don't leak as unbounded background
1850///    loops.
1851///
1852/// Only one auto-meta config is supported per process. If a sample sink
1853/// was already installed, it is silently replaced.
1854fn spawn_auto_meta_throttle(
1855    runtime: &tokio::runtime::Runtime,
1856    auto: AutoMetaThrottleConfig,
1857    histogram_enabled: bool,
1858    histogram_log_path: Option<std::path::PathBuf>,
1859    histogram_interval: std::time::Duration,
1860    trace_identifier: &str,
1861) {
1862    let initial_cwnd = auto
1863        .initial_cwnd
1864        .clamp(auto.min_cwnd.max(1), auto.max_cwnd.max(1));
1865    let histogram_active = histogram_enabled || histogram_log_path.is_some();
1866    // Per-tool log path: each rcpd / master writes to its own file by
1867    // suffixing trace_identifier on the user-supplied path, mirroring
1868    // chrome_trace_prefix's convention.
1869    let resolved_log_path = histogram_log_path
1870        .as_ref()
1871        .map(|p| resolve_log_path(p, trace_identifier));
1872
1873    // Build receivers + accumulators in parallel arrays so we can pass
1874    // each accumulator both to a ControlUnit and to a LoggerUnit.
1875    let mut builder = congestion::RoutingSinkBuilder::new();
1876    struct Slot {
1877        label: &'static str,
1878        side: congestion::Side,
1879        op: congestion::MetadataOp,
1880        sample_rx: tokio::sync::mpsc::Receiver<congestion::Sample>,
1881        apply_rate: bool,
1882        accumulator: Option<std::sync::Arc<std::sync::Mutex<congestion::HistogramAccumulator>>>,
1883    }
1884    let mut slots: Vec<Slot> = Vec::with_capacity(congestion::N_META_RESOURCES);
1885    for &side in &congestion::Side::ALL {
1886        for &op in &congestion::MetadataOp::ALL {
1887            let resource = walk::meta_resource(side, op);
1888            throttle::set_max_ops_in_flight(resource, initial_cwnd as usize);
1889            let rx = builder.metadata_receiver(side, op);
1890            let apply_rate = matches!(
1891                (side, op),
1892                (congestion::Side::Destination, congestion::MetadataOp::Stat),
1893            );
1894            let accumulator = if histogram_active {
1895                let acc = std::sync::Arc::new(std::sync::Mutex::new(
1896                    congestion::HistogramAccumulator::new(),
1897                ));
1898                builder.metadata_histogram(side, op, acc.clone());
1899                Some(acc)
1900            } else {
1901                None
1902            };
1903            slots.push(Slot {
1904                label: unit_label(side, op),
1905                side,
1906                op,
1907                sample_rx: rx,
1908                apply_rate,
1909                accumulator,
1910            });
1911        }
1912    }
1913    let sink = std::sync::Arc::new(builder.build());
1914    congestion::install_sample_sink(sink.clone());
1915
1916    // Per-unit watch senders for the live histogram panel; collected into
1917    // a parallel vec so we can also build the logger's `LoggerUnit` list.
1918    let mut logger_units: Vec<histogram_logger::LoggerUnit> = Vec::new();
1919    for slot in slots {
1920        let controller = congestion::RatioController::new(congestion::RatioConfig {
1921            initial_cwnd: auto.initial_cwnd,
1922            min_cwnd: auto.min_cwnd,
1923            max_cwnd: auto.max_cwnd,
1924            alpha: auto.alpha,
1925            beta: auto.beta,
1926            increase_step: auto.increase_step,
1927            decrease_step: auto.decrease_step,
1928            baseline_percentile: auto.baseline_percentile,
1929            current_percentile: auto.current_percentile,
1930            long_window: auto.long_window,
1931            short_window: auto.short_window,
1932        });
1933        let (unit, decision_rx, snapshot_rx) = congestion::ControlUnit::new(
1934            slot.label,
1935            controller,
1936            slot.sample_rx,
1937            auto.tick_interval,
1938        );
1939        observability::register_unit(slot.label, snapshot_rx);
1940        if let Some(acc) = slot.accumulator.as_ref() {
1941            let (snap_tx, snap_rx) = tokio::sync::watch::channel(
1942                hdrhistogram::Histogram::<u64>::new_with_bounds(
1943                    congestion::HDR_LOWEST_DISCERNIBLE_MICROS,
1944                    congestion::HDR_HIGHEST_TRACKABLE_MICROS,
1945                    congestion::HDR_SIGNIFICANT_FIGURES,
1946                )
1947                .expect("histogram bounds valid"),
1948            );
1949            observability::register_histogram(slot.label, snap_rx, histogram_interval);
1950            logger_units.push(histogram_logger::LoggerUnit {
1951                label: slot.label,
1952                side: slot.side,
1953                op: slot.op,
1954                accumulator: acc.clone(),
1955                snapshot_tx: snap_tx,
1956            });
1957        }
1958        runtime.spawn(unit.run());
1959        runtime.spawn(auto_meta::run_adapter(
1960            walk::meta_resource(slot.side, slot.op),
1961            slot.apply_rate,
1962            decision_rx,
1963            sink.clone(),
1964        ));
1965    }
1966
1967    if histogram_active {
1968        let header = build_histogram_header(&auto, trace_identifier, histogram_interval);
1969        let (cancel_tx, cancel_rx) = tokio::sync::watch::channel(false);
1970        store_logger_cancel(cancel_tx);
1971        // Snapshot the global PROGRESS counters into JSON each tick so
1972        // the binary log carries throughput/files-copied alongside the
1973        // latency distributions — readers can time-align them via the
1974        // shared unix_micros field. Encoding can't realistically fail
1975        // for this struct shape, but on the off chance it does we log
1976        // and return an empty Vec — the logger treats empty as "skip
1977        // this tick" rather than writing a record readers can't parse.
1978        let progress_source: histogram_logger::ProgressSource = Box::new(|| {
1979            let snapshot = progress::SerializableProgress::from(&*PROGRESS);
1980            serde_json::to_vec(&snapshot).unwrap_or_else(|err| {
1981                tracing::warn!(
1982                    "histogram-logger: SerializableProgress JSON encode failed: {err:#}; \
1983                     dropping this tick's progress record"
1984                );
1985                Vec::new()
1986            })
1987        });
1988        let handle = runtime.spawn(histogram_logger::run_logger(
1989            histogram_logger::LoggerConfig {
1990                interval: histogram_interval,
1991                log_path: resolved_log_path,
1992                header,
1993                progress_source: Some(progress_source),
1994            },
1995            logger_units,
1996            cancel_rx,
1997        ));
1998        store_logger_handle(handle);
1999    }
2000
2001    tracing::info!(
2002        "auto-meta-throttle enabled (per-(side, op) controllers, {} total): \
2003         initial_cwnd={}, max_cwnd={}, alpha={}, beta={}, \
2004         baseline_percentile={}, current_percentile={}, \
2005         long_window={:?}, short_window={:?}, tick={:?}, \
2006         histograms={}",
2007        congestion::N_META_RESOURCES,
2008        auto.initial_cwnd,
2009        auto.max_cwnd,
2010        auto.alpha,
2011        auto.beta,
2012        auto.baseline_percentile,
2013        auto.current_percentile,
2014        auto.long_window,
2015        auto.short_window,
2016        auto.tick_interval,
2017        histogram_active,
2018    );
2019}
2020
2021#[cfg(test)]
2022mod remote_admission_tests {
2023    use super::*;
2024
2025    fn nonzero(value: usize) -> std::num::NonZeroUsize {
2026        std::num::NonZeroUsize::new(value).unwrap()
2027    }
2028
2029    fn config(files: crate::ResolvedFilesInFlight, streams: usize) -> ThrottleConfig {
2030        ThrottleConfig {
2031            files_in_flight: files,
2032            admission_policy: crate::AdmissionPolicy::Remote {
2033                streams: nonzero(streams),
2034                pending: nonzero(streams * 4),
2035            },
2036            ..Default::default()
2037        }
2038    }
2039
2040    #[test]
2041    fn larger_file_requests_preserve_remote_directory_capacity() {
2042        for files in [
2043            crate::ResolvedFilesInFlight::explicit(nonzero(20)),
2044            crate::ResolvedFilesInFlight::explicit(nonzero(163)),
2045            crate::ResolvedFilesInFlight::explicit(nonzero(200)),
2046            crate::ResolvedFilesInFlight::unlimited(),
2047        ] {
2048            let mut installed = None;
2049            let admission = configure_file_admission(
2050                &config(files, 20),
2051                || Ok(1024),
2052                |capacity| {
2053                    installed = Some(capacity);
2054                    Ok(())
2055                },
2056            )
2057            .unwrap();
2058            let EndpointAdmission::Remote(resources) = admission else {
2059                panic!("remote setup returned local admission");
2060            };
2061            assert_eq!(installed, Some(ConcurrencyLimit::Limited(nonzero(20))));
2062            assert_eq!(resources.leaf_capacity.get(), 20);
2063            assert_eq!(resources.normal_directories.get(), 223);
2064            assert_eq!(resources.reserved_directories.get(), 223);
2065        }
2066    }
2067
2068    #[test]
2069    fn known_remote_headroom_supports_normal_ancestors_independently_of_pending_files() {
2070        for (soft, streams, normal, reserve) in [
2071            (1024, 4, 243, 243),
2072            (1024, 8, 238, 238),
2073            (1024, 20, 223, 223),
2074            (1025, 4, 243, 243),
2075            (1026, 4, 243, 244),
2076        ] {
2077            for pending in [streams, streams * 4, streams * 16] {
2078                let mut configuration = config(
2079                    crate::ResolvedFilesInFlight::explicit(nonzero(streams)),
2080                    streams,
2081                );
2082                configuration.admission_policy = crate::AdmissionPolicy::Remote {
2083                    streams: nonzero(streams),
2084                    pending: nonzero(pending),
2085                };
2086                let mut installed = None;
2087                let admission = configure_file_admission(
2088                    &configuration,
2089                    || Ok(soft),
2090                    |capacity| {
2091                        installed = Some(capacity);
2092                        Ok(())
2093                    },
2094                )
2095                .unwrap();
2096                let EndpointAdmission::Remote(resources) = admission else {
2097                    panic!("remote setup returned local admission");
2098                };
2099                assert_eq!(installed, Some(ConcurrencyLimit::Limited(nonzero(streams))));
2100                assert_eq!(resources.leaf_capacity.get(), streams);
2101                assert_eq!(
2102                    resources.normal_directories.get(),
2103                    normal,
2104                    "soft={soft}, streams={streams}, pending={pending}"
2105                );
2106                assert_eq!(
2107                    resources.reserved_directories.get(),
2108                    reserve,
2109                    "soft={soft}, streams={streams}, pending={pending}"
2110                );
2111                assert!(normal >= 2 * streams && reserve >= 2 * streams);
2112                let charged = 4 * streams + 2 * (normal + reserve) + streams + 32;
2113                assert!(charged <= soft as usize);
2114                assert!(
2115                    soft as usize - charged <= 1,
2116                    "only an odd descriptor can remain unassigned"
2117                );
2118            }
2119        }
2120    }
2121
2122    #[test]
2123    fn remote_setup_preserves_scan_and_reserve_capacity_at_low_limits() {
2124        for (soft, streams, leaf, normal, reserve) in [
2125            (1024, 100, 74, 149, 149),
2126            (1024, 200, 66, 132, 132),
2127            (1024, 400, 49, 99, 99),
2128            (160, 20, 9, 18, 18),
2129            (128, 20, 6, 13, 13),
2130        ] {
2131            let mut installed = None;
2132            let admission = configure_file_admission(
2133                &config(crate::ResolvedFilesInFlight::unlimited(), streams),
2134                || Ok(soft),
2135                |capacity| {
2136                    installed = Some(capacity);
2137                    Ok(())
2138                },
2139            )
2140            .unwrap();
2141            let EndpointAdmission::Remote(resources) = admission else {
2142                panic!("remote setup returned local admission");
2143            };
2144            assert_eq!(installed, Some(ConcurrencyLimit::Limited(nonzero(leaf))));
2145            assert_eq!(resources.normal_directories.get(), normal);
2146            assert_eq!(resources.reserved_directories.get(), reserve);
2147            assert!(normal >= 2 * leaf);
2148            assert!(reserve >= 2 * leaf);
2149            assert!(4 * leaf + 2 * (normal + reserve) + streams + 32 <= soft as usize);
2150        }
2151    }
2152
2153    #[test]
2154    fn impossible_remote_socket_budget_fails_before_installing_pools() {
2155        let mut configured = false;
2156        let error = configure_file_admission(
2157            &config(crate::ResolvedFilesInFlight::unlimited(), 100),
2158            || Ok(128),
2159            |_| {
2160                configured = true;
2161                Ok(())
2162            },
2163        )
2164        .unwrap_err();
2165        let message = format!("{error:#}");
2166        assert!(
2167            message.contains("128") && message.contains("100"),
2168            "{message}"
2169        );
2170        assert!(message.contains("--max-connections"), "{message}");
2171        assert!(message.contains("minimum soft limit=144"), "{message}");
2172        assert!(message.contains("shortfall=16"), "{message}");
2173        assert!(message.contains("SSH session"), "{message}");
2174        assert!(!configured);
2175    }
2176
2177    #[test]
2178    fn unknown_remote_limit_preserves_bounded_logical_traversal() {
2179        let mut installed = None;
2180        let admission = configure_file_admission(
2181            &config(crate::ResolvedFilesInFlight::explicit(nonzero(20)), 20),
2182            || Err(std::io::Error::other("limit unavailable")),
2183            |capacity| {
2184                installed = Some(capacity);
2185                Ok(())
2186            },
2187        )
2188        .unwrap();
2189        let EndpointAdmission::Remote(resources) = admission else {
2190            panic!("remote setup returned local admission");
2191        };
2192        assert_eq!(installed, Some(ConcurrencyLimit::Limited(nonzero(20))));
2193        assert_eq!(resources.soft_limit, None);
2194        assert_eq!(resources.normal_directories.get(), 200);
2195        assert_eq!(resources.reserved_directories.get(), 200);
2196    }
2197
2198    #[test]
2199    fn unknown_remote_limit_still_rejects_automatic_and_unlimited_requests() {
2200        for files in [
2201            crate::ResolvedFilesInFlight::automatic_with(nonzero(20)),
2202            crate::ResolvedFilesInFlight::unlimited(),
2203        ] {
2204            let result = configure_file_admission(
2205                &config(files, 20),
2206                || Err(std::io::Error::other("limit unavailable")),
2207                |_| panic!("unsubstantiated admission configured pools"),
2208            );
2209            assert!(result.is_err());
2210        }
2211    }
2212
2213    #[test]
2214    fn remote_resource_arithmetic_remains_bounded_at_extreme_capacities() {
2215        let maximum = tokio::sync::Semaphore::MAX_PERMITS;
2216        let resources = RemoteResources::for_limits(
2217            std::num::NonZeroU64::new(u64::MAX),
2218            nonzero(usize::MAX),
2219            nonzero(maximum),
2220            nonzero(maximum),
2221        )
2222        .unwrap();
2223        assert_eq!(resources.leaf_capacity.get(), 4096);
2224        assert!(resources.normal_directories.get() <= maximum);
2225        assert!(resources.reserved_directories.get() <= maximum);
2226        let unknown = RemoteResources::for_limits(
2227            None,
2228            nonzero(usize::MAX),
2229            nonzero(maximum),
2230            nonzero(maximum),
2231        )
2232        .unwrap();
2233        assert_eq!(unknown.normal_directories.get(), maximum);
2234        assert_eq!(unknown.reserved_directories.get(), maximum);
2235    }
2236}
2237
2238#[cfg(test)]
2239mod unit_label_tests {
2240    use super::unit_label;
2241    use congestion::{MetadataOp, Side};
2242
2243    #[test]
2244    fn lookup_ops_carry_side_prefix() {
2245        // Stat and ReadLink can be on either side, so disambiguate.
2246        assert_eq!(unit_label(Side::Source, MetadataOp::Stat), "src-stat");
2247        assert_eq!(unit_label(Side::Destination, MetadataOp::Stat), "dst-stat");
2248        assert_eq!(
2249            unit_label(Side::Source, MetadataOp::ReadLink),
2250            "src-read-link",
2251        );
2252        assert_eq!(
2253            unit_label(Side::Destination, MetadataOp::ReadLink),
2254            "dst-read-link",
2255        );
2256    }
2257
2258    #[test]
2259    fn destination_only_ops_drop_prefix() {
2260        // Mutations + open-create only fire on the destination, so the
2261        // active label has no side prefix — single-FS tools like rrm
2262        // see "unlink", "rmdir" instead of "dst-unlink".
2263        assert_eq!(unit_label(Side::Destination, MetadataOp::MkDir), "mkdir");
2264        assert_eq!(unit_label(Side::Destination, MetadataOp::RmDir), "rmdir");
2265        assert_eq!(unit_label(Side::Destination, MetadataOp::Unlink), "unlink");
2266        assert_eq!(
2267            unit_label(Side::Destination, MetadataOp::HardLink),
2268            "hard-link",
2269        );
2270        assert_eq!(
2271            unit_label(Side::Destination, MetadataOp::Symlink),
2272            "symlink"
2273        );
2274        assert_eq!(unit_label(Side::Destination, MetadataOp::Chmod), "chmod");
2275        assert_eq!(
2276            unit_label(Side::Destination, MetadataOp::OpenCreate),
2277            "open-create",
2278        );
2279    }
2280
2281    #[test]
2282    fn unused_source_side_mutation_slots_keep_src_prefix() {
2283        // The wiring registers a controller for every (side, op) pair,
2284        // including the unused (Source, mutation) slots. Those stay
2285        // idle and are hidden by the renderer, but if they ever fired
2286        // a probe (regression / wiring mistake) the label distinguishes
2287        // them from the active destination-side variant.
2288        assert_eq!(unit_label(Side::Source, MetadataOp::Unlink), "src-unlink");
2289        assert_eq!(unit_label(Side::Source, MetadataOp::MkDir), "src-mkdir");
2290    }
2291
2292    #[test]
2293    fn labels_are_unique_across_all_resources() {
2294        // Sanity: 18 distinct (Side, MetadataOp) pairs must produce 18
2295        // distinct labels — otherwise observability::register_unit would
2296        // create ambiguous panel rows.
2297        let mut seen = std::collections::HashSet::new();
2298        for &side in &Side::ALL {
2299            for &op in &MetadataOp::ALL {
2300                let label = unit_label(side, op);
2301                assert!(seen.insert(label), "duplicate label: {label}");
2302            }
2303        }
2304        assert_eq!(seen.len(), congestion::N_META_RESOURCES);
2305    }
2306}
2307
2308#[cfg(test)]
2309mod runtime_stats_tests {
2310    use super::*;
2311    use anyhow::Result;
2312
2313    #[test]
2314    fn collect_runtime_stats_matches_procfs_snapshot() -> Result<()> {
2315        let process = procfs::process::Process::myself()?;
2316        let expected = collect_runtime_stats_for_process(&process)?;
2317        let actual = collect_runtime_stats();
2318        let cpu_tolerance_ms = 50;
2319        let rss_tolerance_bytes = 1_000_000;
2320        assert!(
2321            expected.cpu_time_user_ms.abs_diff(actual.cpu_time_user_ms) <= cpu_tolerance_ms,
2322            "user CPU deviated by more than {cpu_tolerance_ms}ms: expected {}, got {}",
2323            expected.cpu_time_user_ms,
2324            actual.cpu_time_user_ms
2325        );
2326        assert!(
2327            expected
2328                .cpu_time_kernel_ms
2329                .abs_diff(actual.cpu_time_kernel_ms)
2330                <= cpu_tolerance_ms,
2331            "kernel CPU deviated by more than {cpu_tolerance_ms}ms: expected {}, got {}",
2332            expected.cpu_time_kernel_ms,
2333            actual.cpu_time_kernel_ms
2334        );
2335        assert!(
2336            expected.peak_rss_bytes.abs_diff(actual.peak_rss_bytes) <= rss_tolerance_bytes,
2337            "peak RSS deviated by more than {rss_tolerance_bytes} bytes: expected {}, got {}",
2338            expected.peak_rss_bytes,
2339            actual.peak_rss_bytes
2340        );
2341        Ok(())
2342    }
2343
2344    #[test]
2345    fn collect_runtime_stats_returns_default_on_error() {
2346        let stats = collect_runtime_stats_inner(None);
2347        assert_eq!(stats, RuntimeStats::default());
2348
2349        let nonexistent_process = procfs::process::Process::new(i32::MAX).ok();
2350        let stats = collect_runtime_stats_inner(nonexistent_process);
2351        assert_eq!(stats, RuntimeStats::default());
2352    }
2353}
2354
2355#[cfg(test)]
2356mod resolve_log_path_tests {
2357    use super::*;
2358
2359    #[test]
2360    fn full_path_with_extension() {
2361        let p = std::path::Path::new("/tmp/foo.hdr");
2362        assert_eq!(
2363            resolve_log_path(p, "rcp"),
2364            std::path::PathBuf::from("/tmp/foo.rcp.hdr"),
2365        );
2366    }
2367
2368    #[test]
2369    fn bare_filename_resolves_to_current_dir() {
2370        let p = std::path::Path::new("foo.hdr");
2371        assert_eq!(
2372            resolve_log_path(p, "rcp"),
2373            std::path::PathBuf::from("./foo.rcp.hdr"),
2374        );
2375    }
2376
2377    #[test]
2378    fn no_extension_defaults_to_hdr() {
2379        let p = std::path::Path::new("/tmp/foo");
2380        assert_eq!(
2381            resolve_log_path(p, "rcp"),
2382            std::path::PathBuf::from("/tmp/foo.rcp.hdr"),
2383        );
2384    }
2385
2386    #[test]
2387    #[cfg(unix)]
2388    fn preserves_non_utf8_stem() {
2389        use std::os::unix::ffi::{OsStrExt, OsStringExt};
2390        // Build a path with an invalid-UTF-8 stem: /tmp/<0xFF><0xFE>.hdr
2391        let mut raw_name = vec![b'/', b't', b'm', b'p', b'/'];
2392        raw_name.extend_from_slice(&[0xFF, 0xFE]);
2393        raw_name.extend_from_slice(b".hdr");
2394        let p = std::path::PathBuf::from(std::ffi::OsString::from_vec(raw_name));
2395        let resolved = resolve_log_path(&p, "rcp");
2396        // The non-UTF-8 stem must be preserved; the suffix and extension
2397        // append cleanly.
2398        let bytes = resolved.as_os_str().as_bytes();
2399        assert!(
2400            bytes.windows(2).any(|w| w == [0xFF, 0xFE]),
2401            "non-UTF-8 bytes must survive resolution; got bytes: {bytes:?}",
2402        );
2403        assert!(
2404            bytes.ends_with(b".rcp.hdr"),
2405            "expected .rcp.hdr suffix; got bytes: {bytes:?}",
2406        );
2407    }
2408}
2409
2410#[cfg(test)]
2411mod validate_histogram_log_target_tests {
2412    use super::*;
2413
2414    fn throttle_with_log_path(path: Option<std::path::PathBuf>) -> ThrottleConfig {
2415        ThrottleConfig {
2416            histogram_enabled: path.is_some(),
2417            histogram_log_path: path,
2418            ..Default::default()
2419        }
2420    }
2421
2422    #[test]
2423    fn no_log_path_is_ok() {
2424        let throttle = throttle_with_log_path(None);
2425        assert!(validate_histogram_log_target(&throttle, "rcp").is_ok());
2426    }
2427
2428    #[test]
2429    fn writable_resolved_path_is_ok() {
2430        let dir = tempfile::tempdir().unwrap();
2431        let throttle = throttle_with_log_path(Some(dir.path().join("foo.hdr")));
2432        assert!(validate_histogram_log_target(&throttle, "rcp").is_ok());
2433    }
2434
2435    #[test]
2436    fn resolved_path_existing_as_directory_is_rejected() {
2437        // Create a directory at the exact resolved path; OpenOptions::open
2438        // with create+truncate fails when target is a directory.
2439        let dir = tempfile::tempdir().unwrap();
2440        let blocker = dir.path().join("foo.rcp.hdr");
2441        std::fs::create_dir(&blocker).unwrap();
2442        let throttle = throttle_with_log_path(Some(dir.path().join("foo.hdr")));
2443        let err = validate_histogram_log_target(&throttle, "rcp").unwrap_err();
2444        assert!(
2445            err.contains("histogram-log") && err.contains("foo.rcp.hdr"),
2446            "got: {err}",
2447        );
2448    }
2449
2450    #[test]
2451    fn resolved_path_in_missing_parent_is_rejected() {
2452        let throttle = throttle_with_log_path(Some("/nonexistent-dir-67890/foo.hdr".into()));
2453        let err = validate_histogram_log_target(&throttle, "rcp").unwrap_err();
2454        assert!(err.contains("histogram-log"), "got: {err}");
2455    }
2456
2457    #[test]
2458    fn log_path_pointing_at_existing_directory_is_rejected() {
2459        let dir = tempfile::tempdir().unwrap();
2460        let throttle = throttle_with_log_path(Some(dir.path().to_path_buf()));
2461        let err = validate_histogram_log_target(&throttle, "rcp").unwrap_err();
2462        assert!(err.contains("directory"), "got: {err}");
2463    }
2464
2465    #[test]
2466    fn log_path_with_no_filename_is_rejected() {
2467        // PathBuf::from("/") has parent() == None and file_name() == None.
2468        let throttle = throttle_with_log_path(Some(std::path::PathBuf::from("/")));
2469        let err = validate_histogram_log_target(&throttle, "rcp").unwrap_err();
2470        assert!(
2471            err.contains("filename") || err.contains("directory"),
2472            "got: {err}",
2473        );
2474    }
2475
2476    #[test]
2477    #[cfg(unix)]
2478    fn resolved_path_existing_as_symlink_is_rejected() {
2479        // Defense against symlink-based hijacking: a local attacker who
2480        // can pre-create the predictable suffixed path as a symlink must
2481        // not be able to redirect the truncating open to a victim file.
2482        let dir = tempfile::tempdir().unwrap();
2483        // The resolved path will be `<dir>/foo.rcp.hdr`. Pre-create it as
2484        // a symlink pointing somewhere else (in this test, just to a
2485        // sibling file we don't care about).
2486        let target = dir.path().join("victim.txt");
2487        std::fs::write(&target, b"do not clobber").unwrap();
2488        let resolved_path = dir.path().join("foo.rcp.hdr");
2489        std::os::unix::fs::symlink(&target, &resolved_path).unwrap();
2490        let throttle = throttle_with_log_path(Some(dir.path().join("foo.hdr")));
2491        let err = validate_histogram_log_target(&throttle, "rcp").unwrap_err();
2492        assert!(
2493            err.contains("symlink") || err.contains("ELOOP") || err.contains("Too many levels"),
2494            "got: {err}",
2495        );
2496        // Victim file content is preserved (the truncating open never reached it).
2497        let preserved = std::fs::read(&target).unwrap();
2498        assert_eq!(preserved, b"do not clobber");
2499    }
2500}
2501
2502#[cfg(test)]
2503mod timing_output_tests {
2504    #[test]
2505    fn trace_artifact_names_are_portable_for_ci_uploads() {
2506        for extension in ["json", "scopes.json", "timings.json", "folded"] {
2507            let path = super::generate_trace_filename("/tmp/trace", "rcp-master", extension);
2508            let filename = std::path::Path::new(&path)
2509                .file_name()
2510                .unwrap()
2511                .to_str()
2512                .unwrap();
2513            assert!(
2514                !filename.contains([':', '"', '<', '>', '|', '*', '?', '\\', '\r', '\n']),
2515                "artifact upload rejects non-portable filename: {filename}"
2516            );
2517        }
2518    }
2519
2520    #[test]
2521    fn shared_prefix_keeps_summary_and_both_chrome_artifacts_intact() {
2522        const CHILD: &str = "RCP_TEST_SHARED_TIMING_PREFIX";
2523        if std::env::var_os(CHILD).is_none() {
2524            let output = std::process::Command::new(std::env::current_exe().unwrap())
2525                .args([
2526                    "--exact",
2527                    "runtime_setup::timing_output_tests::shared_prefix_keeps_summary_and_both_chrome_artifacts_intact",
2528                    "--nocapture",
2529                ])
2530                .env(CHILD, "1")
2531                .output()
2532                .unwrap();
2533            assert!(
2534                output.status.success(),
2535                "{}\n{}",
2536                String::from_utf8_lossy(&output.stdout),
2537                String::from_utf8_lossy(&output.stderr)
2538            );
2539            return;
2540        }
2541        let directory = tempfile::tempdir().unwrap();
2542        let prefix = directory.path().join("shared").to_str().unwrap().to_owned();
2543        let mut guards = super::install_tracing_subscriber(
2544            false,
2545            0,
2546            crate::TracingConfig {
2547                timings_prefix: Some(prefix.clone()),
2548                chrome_trace_prefix: Some(prefix),
2549                trace_identifier: "collision-test".to_owned(),
2550                ..crate::TracingConfig::default()
2551            },
2552        )
2553        .unwrap();
2554        crate::timing_scope!("completed").finish();
2555        let span = tracing::info_span!("ordinary-poll-span");
2556        span.in_scope(|| {});
2557        drop(span);
2558        guards.finish().unwrap();
2559        drop(guards);
2560        let paths: Vec<_> = std::fs::read_dir(directory.path())
2561            .unwrap()
2562            .map(|entry| entry.unwrap().path())
2563            .collect();
2564        assert_eq!(
2565            paths.len(),
2566            3,
2567            "summary, poll trace, and elapsed trace must be independent files"
2568        );
2569        let summary = paths
2570            .iter()
2571            .find(|path| path.to_str().unwrap().ends_with(".timings.json"))
2572            .expect("summary suffix");
2573        let timeline = paths
2574            .iter()
2575            .find(|path| path.to_str().unwrap().ends_with(".scopes.json"))
2576            .expect("elapsed timeline suffix");
2577        let poll = paths
2578            .iter()
2579            .find(|path| *path != summary && *path != timeline)
2580            .unwrap();
2581        let summary: serde_json::Value =
2582            serde_json::from_reader(std::fs::File::open(summary).unwrap()).unwrap();
2583        assert_eq!(summary["scopes"][0]["name"], "completed");
2584        let timeline: serde_json::Value =
2585            serde_json::from_reader(std::fs::File::open(timeline).unwrap()).unwrap();
2586        assert_eq!(timeline[0]["name"], "completed");
2587        let poll: serde_json::Value =
2588            serde_json::from_reader(std::fs::File::open(poll).unwrap()).unwrap();
2589        assert!(poll.is_array() || poll["traceEvents"].is_array());
2590    }
2591}