use crate::config::{
AdmissionPolicy, AutoMetaThrottleConfig, ConcurrencyLimit, RuntimeConfig, ThrottleConfig,
TracingConfig,
};
use crate::{
PBAR, PROGRESS, REMOTE_RUNTIME_STATS, RuntimeStats, auto_meta, histogram_logger, is_localhost,
observability, progress, store_logger_cancel, store_logger_handle, walk,
};
use anyhow::Context;
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::prelude::*;
struct LocalTimeFormatter;
impl tracing_subscriber::fmt::time::FormatTime for LocalTimeFormatter {
fn format_time(
&self,
writer: &mut tracing_subscriber::fmt::format::Writer<'_>,
) -> std::fmt::Result {
let now = chrono::Local::now();
writer.write_str(&now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
}
}
struct ProgWriter {}
impl ProgWriter {
fn new() -> Self {
Self {}
}
}
impl std::io::Write for ProgWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
PBAR.suspend(|| std::io::stdout().write(buf))
}
fn flush(&mut self) -> std::io::Result<()> {
std::io::stdout().flush()
}
}
fn get_hostname() -> String {
nix::unistd::gethostname()
.ok()
.and_then(|os_str| os_str.into_string().ok())
.unwrap_or_else(|| "unknown".to_string())
}
fn read_env_or_default<T: std::str::FromStr>(name: &str, default: T) -> T {
match std::env::var(name) {
Ok(val) => match val.parse() {
Ok(val) => val,
Err(_) => default,
},
Err(_) => default,
}
}
#[must_use]
pub fn collect_runtime_stats() -> RuntimeStats {
collect_runtime_stats_inner(procfs::process::Process::myself().ok())
}
fn collect_runtime_stats_inner(process: Option<procfs::process::Process>) -> RuntimeStats {
let Some(process) = process else {
return RuntimeStats::default();
};
collect_runtime_stats_for_process(&process).unwrap_or_default()
}
fn collect_runtime_stats_for_process(
process: &procfs::process::Process,
) -> anyhow::Result<RuntimeStats> {
let stat = process.stat()?;
let clock_ticks = procfs::ticks_per_second() as f64;
let vmhwm_kb = process.status()?.vmhwm.unwrap_or(0);
Ok(RuntimeStats {
cpu_time_user_ms: ((stat.utime as f64 / clock_ticks) * 1000.0) as u64,
cpu_time_kernel_ms: ((stat.stime as f64 / clock_ticks) * 1000.0) as u64,
peak_rss_bytes: vmhwm_kb * 1024,
})
}
fn print_runtime_stats_for_role(prefix: &str, stats: &RuntimeStats) {
let cpu_total =
std::time::Duration::from_millis(stats.cpu_time_user_ms + stats.cpu_time_kernel_ms);
let cpu_kernel = std::time::Duration::from_millis(stats.cpu_time_kernel_ms);
let cpu_user = std::time::Duration::from_millis(stats.cpu_time_user_ms);
println!(
"{prefix}cpu time : {:.2?} | k: {:.2?} | u: {:.2?}",
cpu_total, cpu_kernel, cpu_user
);
println!(
"{prefix}peak RSS : {}",
bytesize::ByteSize(stats.peak_rss_bytes)
);
}
#[rustfmt::skip]
pub(crate) fn print_runtime_stats() -> Result<(), anyhow::Error> {
let remote_stats = REMOTE_RUNTIME_STATS.lock().unwrap().take();
if let Some(remote) = remote_stats {
println!("walltime : {:.2?}", &PROGRESS.get_duration());
println!();
let source_is_local = is_localhost(&remote.source_host);
let dest_is_local = is_localhost(&remote.dest_host);
let master_stats = collect_runtime_stats();
if !source_is_local {
println!("SOURCE ({}):", remote.source_host);
print_runtime_stats_for_role(" ", &remote.source_stats);
println!();
}
if !dest_is_local {
println!("DESTINATION ({}):", remote.dest_host);
print_runtime_stats_for_role(" ", &remote.dest_stats);
println!();
}
match (source_is_local, dest_is_local) {
(true, true) => {
println!("MASTER + SOURCE + DESTINATION (localhost):");
print_runtime_stats_for_role(" master ", &master_stats);
print_runtime_stats_for_role(" source ", &remote.source_stats);
print_runtime_stats_for_role(" dest ", &remote.dest_stats);
}
(true, false) => {
println!("MASTER + SOURCE (localhost):");
print_runtime_stats_for_role(" master ", &master_stats);
print_runtime_stats_for_role(" source ", &remote.source_stats);
}
(false, true) => {
println!("MASTER + DESTINATION (localhost):");
print_runtime_stats_for_role(" master ", &master_stats);
print_runtime_stats_for_role(" dest ", &remote.dest_stats);
}
(false, false) => {
println!("MASTER (localhost):");
print_runtime_stats_for_role(" ", &master_stats);
}
}
return Ok(());
}
let process = procfs::process::Process::myself()?;
let stat = process.stat()?;
let clock_ticks_per_second = procfs::ticks_per_second();
let ticks_to_duration = |ticks: u64| {
std::time::Duration::from_secs_f64(ticks as f64 / clock_ticks_per_second as f64)
};
let vmhwm_kb = process.status()?.vmhwm.unwrap_or(0);
println!("walltime : {:.2?}", &PROGRESS.get_duration(),);
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));
println!("peak RSS : {:.2?}", bytesize::ByteSize(vmhwm_kb * 1024));
Ok(())
}
fn raise_open_file_limit() -> Result<u64, std::io::Error> {
let mut rlim = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
let result = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut rlim) };
if result != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(raise_soft_limit(rlim, |limit| {
if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, limit) } == 0 {
Ok(())
} else {
Err(std::io::Error::last_os_error())
}
}))
}
fn raise_soft_limit(
mut limit: libc::rlimit,
set_limit: impl FnOnce(&libc::rlimit) -> Result<(), std::io::Error>,
) -> u64 {
let inherited_soft = limit.rlim_cur;
if inherited_soft < limit.rlim_max {
limit.rlim_cur = limit.rlim_max;
match set_limit(&limit) {
Ok(()) => tracing::info!(
"Raised soft descriptor limit from {inherited_soft} to {}",
limit.rlim_cur,
),
Err(error) => {
tracing::warn!(target: NOTICE_TARGET,
"Could not raise soft RLIMIT_NOFILE from {inherited_soft} to inherited hard limit {}; using {inherited_soft}: {error:#}",
limit.rlim_max,
);
return inherited_soft;
}
}
}
limit.rlim_cur
}
#[must_use]
pub fn generate_debug_log_filename(prefix: &str) -> String {
let now = chrono::Utc::now();
let timestamp = now.format("%Y-%m-%dT%H:%M:%S").to_string();
let process_id = std::process::id();
format!("{prefix}-{timestamp}-{process_id}")
}
#[must_use]
pub fn generate_trace_filename(prefix: &str, identifier: &str, extension: &str) -> String {
let hostname = get_hostname();
let pid = std::process::id();
let timestamp = chrono::Utc::now().format("%Y-%m-%dT%H-%M-%SZ");
format!("{prefix}-{identifier}-{hostname}-{pid}-{timestamp}.{extension}")
}
pub const NOTICE_TARGET: &str = "rcp::notice";
fn build_verbose_env_filter(verbose: u8) -> tracing_subscriber::EnvFilter {
let level_directive = match verbose {
0 => "error".parse().unwrap(),
1 => "info".parse().unwrap(),
2 => "debug".parse().unwrap(),
_ => "trace".parse().unwrap(),
};
tracing_subscriber::EnvFilter::from_default_env()
.add_directive(level_directive)
.add_directive(format!("{NOTICE_TARGET}=warn").parse().unwrap())
.add_directive("tokio=info".parse().unwrap())
.add_directive("runtime=info".parse().unwrap())
.add_directive("quinn=warn".parse().unwrap())
.add_directive("rustls=warn".parse().unwrap())
.add_directive("h2=warn".parse().unwrap())
.add_directive("rcp::timing=off".parse().unwrap())
}
fn build_profile_filter_str(profile_level: Option<&str>) -> anyhow::Result<String> {
let level_str = profile_level.unwrap_or("trace");
let valid_levels = ["trace", "debug", "info", "warn", "error", "off"];
if !valid_levels.contains(&level_str.to_lowercase().as_str()) {
anyhow::bail!(
"Invalid --profile-level '{level_str}'. Valid values: trace, debug, info, warn, error, off"
);
}
Ok(format!(
"tokio=off,quinn=off,h2=off,hyper=off,rustls=off,rcp::timing=off,{level_str}"
))
}
#[allow(dead_code)] pub(crate) struct TracingGuards {
chrome: Option<tracing_chrome::FlushGuard>,
flame: Option<tracing_flame::FlushGuard<std::io::BufWriter<std::fs::File>>>,
timing: Option<crate::timing::TimingGuard>,
}
impl TracingGuards {
pub(crate) fn finish(&mut self) -> anyhow::Result<()> {
if let Some(timing) = &mut self.timing {
timing.finish()?;
}
Ok(())
}
}
fn open_timing_output(
prefix: &str,
identifier: &str,
extension: &str,
) -> anyhow::Result<(std::fs::File, String)> {
let filename = generate_trace_filename(prefix, identifier, extension);
let file = std::fs::File::create(&filename)
.with_context(|| format!("failed to create timing output at '{filename}'"))?;
Ok((file, filename))
}
pub(crate) fn install_tracing_subscriber(
quiet: bool,
verbose: u8,
tracing_config: TracingConfig,
) -> anyhow::Result<TracingGuards> {
if quiet {
assert!(
verbose == 0,
"Quiet mode and verbose mode are mutually exclusive"
);
let timing = if let Some(prefix) = &tracing_config.timings_prefix {
let (file, _) =
open_timing_output(prefix, &tracing_config.trace_identifier, "timings.json")?;
let (layer, guard) =
crate::timing::TimingLayer::new(tracing_config.trace_identifier, Some(file), None);
tracing_subscriber::registry()
.with(
layer.with_filter(crate::timing::timing_filter(tracing_config.timings_detail)),
)
.init();
Some(guard)
} else {
None
};
return Ok(TracingGuards {
chrome: None,
flame: None,
timing,
});
}
let TracingConfig {
remote_layer: remote_tracing_layer,
debug_log_file,
chrome_trace_prefix,
timings_prefix,
timings_detail,
flamegraph_prefix,
trace_identifier,
profile_level,
tokio_console,
tokio_console_port,
} = tracing_config;
let file_layer = debug_log_file
.map(|log_file_path| {
let file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&log_file_path)
.with_context(|| format!("failed to create debug log file at '{log_file_path}'"))?;
anyhow::Ok(
tracing_subscriber::fmt::layer()
.with_target(true)
.with_line_number(true)
.with_thread_ids(true)
.with_timer(LocalTimeFormatter)
.with_ansi(false)
.with_writer(file)
.with_filter(build_verbose_env_filter(verbose)),
)
})
.transpose()?;
let fmt_layer = if remote_tracing_layer.is_some() {
None
} else {
Some(
tracing_subscriber::fmt::layer()
.with_target(true)
.with_line_number(true)
.with_span_events(if verbose > 2 {
FmtSpan::NEW | FmtSpan::CLOSE
} else {
FmtSpan::NONE
})
.with_timer(LocalTimeFormatter)
.pretty()
.with_writer(ProgWriter::new)
.with_filter(build_verbose_env_filter(verbose)),
)
};
let remote_tracing_layer =
remote_tracing_layer.map(|layer| layer.with_filter(build_verbose_env_filter(verbose)));
let mut startup_notices = Vec::new();
let mut startup_errors = Vec::new();
let mut timing_guard = None;
let timing_layer = if timings_prefix.is_some() || chrome_trace_prefix.is_some() {
let summary = timings_prefix
.as_deref()
.map(|prefix| {
let (file, filename) =
open_timing_output(prefix, &trace_identifier, "timings.json")?;
startup_notices.push(format!("Timing summary will be written to: {filename}"));
anyhow::Ok(file)
})
.transpose()?;
let timeline = chrome_trace_prefix
.as_deref()
.map(|prefix| {
let (file, filename) = open_timing_output(prefix, &trace_identifier, "scopes.json")
.context("failed to create Chrome trace file for elapsed scopes")?;
startup_notices.push(format!(
"Elapsed scope timeline will be written to: {filename}"
));
anyhow::Ok(file)
})
.transpose()?;
let (layer, guard) =
crate::timing::TimingLayer::new(trace_identifier.clone(), summary, timeline);
timing_guard = Some(guard);
Some(layer.with_filter(crate::timing::timing_filter(timings_detail)))
} else {
None
};
let console_layer = tokio_console.then(|| {
let console_port = tokio_console_port.unwrap_or(6669);
let retention_seconds: u64 =
read_env_or_default("RCP_TOKIO_TRACING_CONSOLE_RETENTION_SECONDS", 60);
startup_notices.push(format!(
"Tokio console server listening on 127.0.0.1:{console_port}"
));
console_subscriber::ConsoleLayer::builder()
.retention(std::time::Duration::from_secs(retention_seconds))
.server_addr(([127, 0, 0, 1], console_port))
.spawn()
});
let profile_filter_str = (chrome_trace_prefix.is_some() || flamegraph_prefix.is_some())
.then(|| build_profile_filter_str(profile_level.as_deref()))
.transpose()?;
let make_profile_filter =
|| tracing_subscriber::EnvFilter::new(profile_filter_str.as_ref().unwrap());
let mut chrome_guard = None;
let chrome_layer = chrome_trace_prefix
.as_ref()
.map(|prefix| {
let filename = generate_trace_filename(prefix, &trace_identifier, "json");
let file = std::fs::File::create(&filename)
.with_context(|| format!("failed to create Chrome trace file at '{filename}'"))?;
startup_notices.push(format!("Chrome trace will be written to: {filename}"));
let (layer, guard) = tracing_chrome::ChromeLayerBuilder::new()
.writer(file)
.include_args(true)
.build();
chrome_guard = Some(guard);
anyhow::Ok(layer.with_filter(make_profile_filter()))
})
.transpose()?;
let mut flame_guard = None;
let flame_layer = flamegraph_prefix.as_ref().and_then(|prefix| {
let filename = generate_trace_filename(prefix, &trace_identifier, "folded");
match tracing_flame::FlameLayer::with_file(&filename) {
Ok((layer, guard)) => {
startup_notices.push(format!("Flamegraph data will be written to: {filename}"));
flame_guard = Some(guard);
Some(layer.with_filter(make_profile_filter()))
}
Err(e) => {
startup_errors.push(format!("Failed to create flamegraph layer: {e:?}"));
None
}
}
});
tracing_subscriber::registry()
.with(file_layer)
.with(fmt_layer)
.with(remote_tracing_layer)
.with(console_layer)
.with(chrome_layer)
.with(flame_layer)
.with(timing_layer)
.init();
for notice in startup_notices {
tracing::warn!(target: NOTICE_TARGET, "{notice}");
}
for startup_error in startup_errors {
tracing::error!("{startup_error}");
}
Ok(TracingGuards {
chrome: chrome_guard,
flame: flame_guard,
timing: timing_guard,
})
}
const DESCRIPTOR_UNITS_PER_OPERATION: u64 = 5;
const MAX_LEAF_OPERATIONS_PER_POOL: usize = 4096;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RemoteResources {
pub soft_limit: Option<std::num::NonZeroU64>,
pub leaf_capacity: std::num::NonZeroUsize,
pub normal_directories: std::num::NonZeroUsize,
pub reserved_directories: std::num::NonZeroUsize,
}
impl RemoteResources {
pub fn for_limits(
soft_limit: Option<std::num::NonZeroU64>,
leaf_ceiling: std::num::NonZeroUsize,
streams: std::num::NonZeroUsize,
pending: std::num::NonZeroUsize,
) -> anyhow::Result<Self> {
const SUPPORT_DESCRIPTORS: u64 = 32;
const LEAF_DESCRIPTORS: u64 = 4;
const DESCRIPTORS_PER_WORK_SLOT: u64 = LEAF_DESCRIPTORS + 2 * (2 + 2);
let maximum = tokio::sync::Semaphore::MAX_PERMITS;
anyhow::ensure!(
streams.get() <= maximum && pending.get() <= maximum,
"remote concurrency exceeds semaphore capacity"
);
let requested = leaf_ceiling
.get()
.min(streams.get())
.min(MAX_LEAF_OPERATIONS_PER_POOL);
let (leaf_capacity, normal, reserve) = match soft_limit {
Some(soft) => {
let streams_u64 = u64::try_from(streams.get()).unwrap_or(u64::MAX);
let available = soft
.get()
.saturating_sub(streams_u64)
.saturating_sub(SUPPORT_DESCRIPTORS);
let minimum = streams_u64
.saturating_add(SUPPORT_DESCRIPTORS)
.saturating_add(DESCRIPTORS_PER_WORK_SLOT);
let shortfall = minimum.saturating_sub(soft.get());
anyhow::ensure!(
available >= DESCRIPTORS_PER_WORK_SLOT,
"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",
soft.get(),
streams,
);
let work_capacity =
usize::try_from(available / DESCRIPTORS_PER_WORK_SLOT).unwrap_or(usize::MAX);
let leaf = requested.min(work_capacity);
let leaf_u64 = u64::try_from(leaf).expect("the leaf-operation cap fits in u64");
let groups = usize::try_from((available - LEAF_DESCRIPTORS * leaf_u64) / 2)
.unwrap_or(usize::MAX);
let normal = (groups / 2).min(maximum);
(leaf, normal, (groups - normal).min(maximum))
}
None => {
let logical = pending
.get()
.saturating_add(streams.get())
.saturating_mul(2)
.min(maximum);
(requested, logical, logical)
}
};
Ok(Self {
soft_limit,
leaf_capacity: std::num::NonZeroUsize::new(leaf_capacity)
.context("remote leaf capacity is zero")?,
normal_directories: std::num::NonZeroUsize::new(normal)
.context("normal remote directory capacity is zero")?,
reserved_directories: std::num::NonZeroUsize::new(reserve)
.context("reserved remote directory capacity is zero")?,
})
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EndpointAdmission {
Disabled,
Configured {
soft_limit: Option<std::num::NonZeroU64>,
leaf_capacity: std::num::NonZeroUsize,
},
Remote(RemoteResources),
}
fn descriptor_admission_limit(soft_limit: std::num::NonZeroU64) -> ConcurrencyLimit {
let descriptor_budget = soft_limit.get().saturating_mul(8) / 10;
let leaf_operation_limit = std::cmp::min(
(descriptor_budget / DESCRIPTOR_UNITS_PER_OPERATION).max(1),
MAX_LEAF_OPERATIONS_PER_POOL as u64,
);
ConcurrencyLimit::Limited(
std::num::NonZeroUsize::new(
usize::try_from(leaf_operation_limit).expect("the leaf-operation cap fits in usize"),
)
.expect("the nonzero soft limit produces a nonzero admission cap"),
)
}
fn resolve_leaf_capacity(
files_in_flight: ConcurrencyLimit,
descriptor_limit: ConcurrencyLimit,
) -> ConcurrencyLimit {
files_in_flight.meet(descriptor_limit)
}
#[derive(Debug, Eq, PartialEq)]
enum DescriptorClampVisibility {
Notice,
Verbose,
}
#[derive(Debug, Eq, PartialEq)]
struct DescriptorClampDiagnostic {
visibility: DescriptorClampVisibility,
message: String,
}
fn descriptor_clamp_diagnostic(
files_in_flight: crate::ResolvedFilesInFlight,
effective: ConcurrencyLimit,
) -> Option<DescriptorClampDiagnostic> {
if files_in_flight.limit() == effective {
return None;
}
let ConcurrencyLimit::Limited(effective) = effective else {
return None;
};
let diagnostic = match (files_in_flight.source(), files_in_flight.limit()) {
(crate::FilesInFlightSource::Automatic, requested) => DescriptorClampDiagnostic {
visibility: DescriptorClampVisibility::Verbose,
message: format!(
"Automatic file admission was reduced by descriptor safety: requested={requested}, effective={}",
ConcurrencyLimit::Limited(effective),
),
},
(crate::FilesInFlightSource::Explicit, ConcurrencyLimit::Limited(requested)) => {
DescriptorClampDiagnostic {
visibility: DescriptorClampVisibility::Notice,
message: format!(
"Requested --max-files-in-flight={requested}, but descriptor safety reduced endpoint file admission to {effective}"
),
}
}
(
crate::FilesInFlightSource::DeprecatedMaxOpenFiles,
ConcurrencyLimit::Limited(requested),
) => DescriptorClampDiagnostic {
visibility: DescriptorClampVisibility::Notice,
message: format!(
"Requested --max-open-files={requested}, but descriptor safety reduced endpoint file admission to {effective}"
),
},
(crate::FilesInFlightSource::DeprecatedMaxOpenFiles, ConcurrencyLimit::Unlimited) => {
DescriptorClampDiagnostic {
visibility: DescriptorClampVisibility::Notice,
message: format!(
"Requested unlimited file admission with --max-open-files=0, but descriptor safety reduced endpoint file admission to {effective}"
),
}
}
(crate::FilesInFlightSource::Explicit, ConcurrencyLimit::Unlimited) => {
DescriptorClampDiagnostic {
visibility: DescriptorClampVisibility::Notice,
message: format!(
"Requested unlimited file admission with --max-files-in-flight=unlimited, but descriptor safety reduced endpoint file admission to {effective}"
),
}
}
};
Some(diagnostic)
}
fn configure_leaf_admission_limit(capacity: ConcurrencyLimit) -> anyhow::Result<()> {
let capacity = match capacity {
ConcurrencyLimit::Unlimited => None,
ConcurrencyLimit::Limited(value) => Some(value),
};
throttle::try_set_admission_limits(capacity)
.context("failed to configure runtime file admission")
}
fn configure_file_admission(
throttle: &ThrottleConfig,
get_soft_limit: impl FnOnce() -> Result<u64, std::io::Error>,
configure_limit: impl FnOnce(ConcurrencyLimit) -> anyhow::Result<()>,
) -> anyhow::Result<EndpointAdmission> {
if !throttle.apply_files_in_flight {
return Ok(EndpointAdmission::Disabled);
}
let soft_limit = match get_soft_limit() {
Ok(soft_limit) => {
let soft_limit = std::num::NonZeroU64::new(soft_limit).context(
"soft RLIMIT_NOFILE is zero; descriptor-safe file admission is impossible",
)?;
Some(soft_limit)
}
Err(error) => match (
throttle.files_in_flight.source(),
throttle.files_in_flight.limit(),
) {
(
source @ (crate::FilesInFlightSource::Explicit
| crate::FilesInFlightSource::DeprecatedMaxOpenFiles),
ConcurrencyLimit::Limited(limit),
) => {
let option = match source {
crate::FilesInFlightSource::Explicit => "--max-files-in-flight",
crate::FilesInFlightSource::DeprecatedMaxOpenFiles => "--max-open-files",
crate::FilesInFlightSource::Automatic => unreachable!("matched above"),
};
tracing::warn!(
target: NOTICE_TARGET,
"Failed to query RLIMIT_NOFILE; using {option}={limit} as the endpoint file-admission ceiling without an independent descriptor-safety ceiling: {error:#}"
);
None
}
_ => {
return Err(error).context(
"failed to query rlimit; automatic or unlimited file admission requires descriptor safety",
);
}
},
};
let (admission, leaf_capacity, diagnostic) = match throttle.admission_policy {
AdmissionPolicy::Local => {
let descriptor_limit = soft_limit
.map(descriptor_admission_limit)
.unwrap_or(ConcurrencyLimit::Unlimited);
let leaf_capacity =
resolve_leaf_capacity(throttle.files_in_flight.limit(), descriptor_limit);
let ConcurrencyLimit::Limited(leaf) = leaf_capacity else {
unreachable!(
"descriptor admission or explicit finite fallback supplies a finite ceiling"
)
};
tracing::info!(
"Resolved file admission: file_ceiling={:?}, source={:?}, descriptor_ceiling={:?}, open_file={:?}, pending_meta={:?}",
throttle.files_in_flight.limit(),
throttle.files_in_flight.source(),
descriptor_limit,
leaf_capacity,
leaf_capacity,
);
(
EndpointAdmission::Configured {
soft_limit,
leaf_capacity: leaf,
},
leaf_capacity,
descriptor_clamp_diagnostic(throttle.files_in_flight, leaf_capacity),
)
}
AdmissionPolicy::Remote { streams, pending } => {
let leaf_ceiling = match throttle.files_in_flight.limit() {
ConcurrencyLimit::Limited(ceiling) => ceiling,
ConcurrencyLimit::Unlimited => streams,
};
let resources =
RemoteResources::for_limits(soft_limit, leaf_ceiling, streams, pending)?;
let leaf_capacity = ConcurrencyLimit::Limited(resources.leaf_capacity);
tracing::info!(
"Resolved remote admission: file_ceiling={:?}, source={:?}, streams={}, pending={}, soft_limit={:?}, open_file={}, pending_meta={}, normal_directories={}, reserved_directories={}",
throttle.files_in_flight.limit(),
throttle.files_in_flight.source(),
streams,
pending,
soft_limit,
resources.leaf_capacity,
resources.leaf_capacity,
resources.normal_directories,
resources.reserved_directories,
);
if soft_limit.is_none() {
tracing::warn!(target: NOTICE_TARGET,
"Remote descriptor headroom is unavailable; using bounded logical admission with {} leaf operations, {} normal directories, and {} reserved levels, without a descriptor-safety guarantee",
resources.leaf_capacity, resources.normal_directories, resources.reserved_directories);
}
let diagnostic = (soft_limit.is_some() && resources.leaf_capacity < streams)
.then(|| descriptor_clamp_diagnostic(throttle.files_in_flight, leaf_capacity))
.flatten();
(
EndpointAdmission::Remote(resources),
leaf_capacity,
diagnostic,
)
}
};
if let Some(diagnostic) = diagnostic {
match diagnostic.visibility {
DescriptorClampVisibility::Notice => {
tracing::warn!(target: NOTICE_TARGET, "{}", diagnostic.message);
}
DescriptorClampVisibility::Verbose => {
tracing::info!("{}", diagnostic.message);
}
}
}
configure_limit(leaf_capacity)?;
Ok(admission)
}
pub(crate) fn build_tokio_runtime(
runtime: &RuntimeConfig,
throttle: &ThrottleConfig,
) -> anyhow::Result<(tokio::runtime::Runtime, EndpointAdmission)> {
let soft_limit = raise_open_file_limit();
let mut builder = tokio::runtime::Builder::new_multi_thread();
builder.enable_all();
if runtime.max_workers > 0 {
builder.worker_threads(runtime.max_workers);
}
if runtime.max_blocking_threads > 0 {
builder.max_blocking_threads(runtime.max_blocking_threads);
}
let runtime = builder.build().context("failed to create Tokio runtime")?;
let admission =
configure_file_admission(throttle, || soft_limit, configure_leaf_admission_limit)?;
Ok((runtime, admission))
}
#[cfg(test)]
mod default_leaf_operation_limit_tests {
use super::*;
#[derive(Clone, Default)]
struct CapturedLogs(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
struct CapturedLogWriter(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
impl std::io::Write for CapturedLogWriter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'writer> tracing_subscriber::fmt::MakeWriter<'writer> for CapturedLogs {
type Writer = CapturedLogWriter;
fn make_writer(&'writer self) -> Self::Writer {
CapturedLogWriter(self.0.clone())
}
}
impl CapturedLogs {
fn contents(&self) -> String {
String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
}
}
#[cfg(target_os = "linux")]
const RLIMIT_CHILD_MARKER: &str = "RCP_TEST_RUNTIME_SETUP_RLIMIT_CHILD";
#[cfg(target_os = "linux")]
const RLIMIT_CHILD_MARKER_VALUE: &str = "raise-session-soft-limit-v1";
#[cfg(target_os = "linux")]
const RLIMIT_CHILD_SUCCESS: &str = "RCP_TEST_RUNTIME_SETUP_RLIMIT_CHILD:success";
#[cfg(target_os = "linux")]
const RLIMIT_CHILD_SKIP: &str = "RCP_TEST_RUNTIME_SETUP_RLIMIT_CHILD:skip";
#[cfg(target_os = "linux")]
const UNLIMITED_FILE_CEILING_CHILD_MARKER: &str =
"RCP_TEST_RUNTIME_SETUP_UNLIMITED_FILE_CEILING_CHILD";
#[cfg(target_os = "linux")]
const UNLIMITED_FILE_CEILING_CHILD_MARKER_VALUE: &str =
"uses-descriptor-safety-after-stale-admission-epoch-v1";
#[cfg(target_os = "linux")]
const UNLIMITED_FILE_CEILING_CHILD_SUCCESS: &str =
"RCP_TEST_RUNTIME_SETUP_UNLIMITED_FILE_CEILING_CHILD:success";
#[cfg(target_os = "linux")]
fn nofile_limit() -> libc::rlimit {
let mut limit = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
let result = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) };
assert_eq!(
result,
0,
"getrlimit failed: {:#}",
std::io::Error::last_os_error()
);
limit
}
#[test]
fn equal_descriptor_limits_do_not_require_a_setrlimit_call() {
let limit = raise_soft_limit(
libc::rlimit {
rlim_cur: 256,
rlim_max: 256,
},
|_| panic!("an unchanged limit must not require permission to set it"),
);
assert_eq!(limit, 256);
}
#[test]
fn denied_descriptor_raise_retains_known_admission_and_reports_the_cause() {
let captured = CapturedLogs::default();
let subscriber = tracing_subscriber::fmt()
.with_writer(captured.clone())
.with_ansi(false)
.without_time()
.finish();
tracing::subscriber::with_default(subscriber, || {
let soft = raise_soft_limit(
libc::rlimit {
rlim_cur: 256,
rlim_max: 512,
},
|requested| {
assert_eq!(requested.rlim_cur, 512);
assert_eq!(requested.rlim_max, 512);
Err(std::io::Error::from_raw_os_error(libc::EPERM))
},
);
let admission = configure_file_admission(
&ThrottleConfig {
files_in_flight: crate::ResolvedFilesInFlight::unlimited(),
..ThrottleConfig::default()
},
|| Ok(soft),
|capacity| {
assert_eq!(
capacity,
ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(40).unwrap())
);
Ok(())
},
)
.expect("a denied raise must still permit budgeting from the known soft limit");
assert_eq!(
admission,
EndpointAdmission::Configured {
soft_limit: std::num::NonZeroU64::new(256),
leaf_capacity: std::num::NonZeroUsize::new(40).unwrap(),
}
);
});
let logs = captured.contents();
assert!(logs.contains("rcp::notice"), "{logs}");
assert!(logs.contains("256") && logs.contains("512"), "{logs}");
assert!(
logs.contains(&std::io::Error::from_raw_os_error(libc::EPERM).to_string()),
"{logs}"
);
}
#[test]
fn configured_admission_reports_actual_installed_leaf_capacity() {
let finite = |value| {
crate::ResolvedFilesInFlight::explicit(std::num::NonZeroUsize::new(value).unwrap())
};
for (soft, files, leaf) in [
(1024, finite(20), 20),
(1024, finite(1000), 163),
(1024, crate::ResolvedFilesInFlight::unlimited(), 163),
(1_000_000, crate::ResolvedFilesInFlight::unlimited(), 4096),
(1, finite(20), 1),
(u64::MAX, crate::ResolvedFilesInFlight::unlimited(), 4096),
] {
let throttle = ThrottleConfig {
files_in_flight: files,
..Default::default()
};
let mut configured = None;
let admission = configure_file_admission(
&throttle,
|| Ok(soft),
|capacity| {
configured = Some(capacity);
Ok(())
},
)
.unwrap();
assert_eq!(
configured,
Some(ConcurrencyLimit::Limited(
std::num::NonZeroUsize::new(leaf).unwrap()
))
);
assert_eq!(
admission,
EndpointAdmission::Configured {
soft_limit: std::num::NonZeroU64::new(soft),
leaf_capacity: std::num::NonZeroUsize::new(leaf).unwrap(),
}
);
}
}
#[test]
fn rejected_admission_preserves_configuration_error() {
let error = configure_file_admission(
&ThrottleConfig::default(),
|| Ok(1024),
|_| {
Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"configuration rejected",
)
.into())
},
)
.expect_err("rejected configuration must not return a usable snapshot");
assert_eq!(
error.downcast_ref::<std::io::Error>().unwrap().kind(),
std::io::ErrorKind::PermissionDenied
);
}
#[test]
fn reserves_descriptor_headroom_for_each_leaf_operation() {
let nonzero = |value| std::num::NonZeroU64::new(value).unwrap();
assert_eq!(
descriptor_admission_limit(nonzero(100)),
ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(16).unwrap())
);
assert_eq!(
descriptor_admission_limit(nonzero(4096)),
ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(655).unwrap())
);
assert_eq!(
descriptor_admission_limit(nonzero(1_000_000)),
ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(4096).unwrap())
);
assert_eq!(
descriptor_admission_limit(nonzero(u64::MAX)),
ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(4096).unwrap())
);
}
#[test]
fn keeps_a_small_nonzero_limit_live() {
let one = ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(1).unwrap());
assert_eq!(
descriptor_admission_limit(std::num::NonZeroU64::new(1).unwrap()),
one
);
assert_eq!(
descriptor_admission_limit(std::num::NonZeroU64::new(4).unwrap()),
one
);
}
#[test]
fn file_and_descriptor_ceilings_are_intersected() {
let limited =
|value| ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(value).unwrap());
assert_eq!(resolve_leaf_capacity(limited(8), limited(40)), limited(8));
assert_eq!(resolve_leaf_capacity(limited(80), limited(40)), limited(40));
assert_eq!(
resolve_leaf_capacity(ConcurrencyLimit::Unlimited, limited(40)),
limited(40)
);
assert_eq!(
resolve_leaf_capacity(limited(8), ConcurrencyLimit::Unlimited),
limited(8)
);
}
#[test]
fn descriptor_clamp_diagnostics_preserve_file_limit_provenance() {
let eight = std::num::NonZeroUsize::new(8).unwrap();
let four = std::num::NonZeroUsize::new(4).unwrap();
let effective = ConcurrencyLimit::Limited(four);
assert_eq!(
descriptor_clamp_diagnostic(
crate::ResolvedFilesInFlight::legacy(eight.get()),
effective
),
Some(DescriptorClampDiagnostic {
visibility: DescriptorClampVisibility::Notice,
message: "Requested --max-open-files=8, but descriptor safety reduced endpoint file admission to 4".to_string(),
})
);
assert_eq!(
descriptor_clamp_diagnostic(crate::ResolvedFilesInFlight::legacy(0), effective),
Some(DescriptorClampDiagnostic {
visibility: DescriptorClampVisibility::Notice,
message: "Requested unlimited file admission with --max-open-files=0, but descriptor safety reduced endpoint file admission to 4".to_string(),
})
);
assert_eq!(
descriptor_clamp_diagnostic(crate::ResolvedFilesInFlight::unlimited(), effective),
Some(DescriptorClampDiagnostic {
visibility: DescriptorClampVisibility::Notice,
message: "Requested unlimited file admission with --max-files-in-flight=unlimited, but descriptor safety reduced endpoint file admission to 4".to_string(),
})
);
assert_eq!(
descriptor_clamp_diagnostic(
crate::ResolvedFilesInFlight::automatic_with(eight), effective
),
Some(DescriptorClampDiagnostic {
visibility: DescriptorClampVisibility::Verbose,
message: "Automatic file admission was reduced by descriptor safety: requested=8, effective=4".to_string(),
})
);
}
#[test]
fn runtime_admission_setup_propagates_oversized_capacity() {
let oversized = ConcurrencyLimit::Limited(
std::num::NonZeroUsize::new(tokio::sync::Semaphore::MAX_PERMITS + 1).unwrap(),
);
let error = configure_leaf_admission_limit(oversized)
.expect_err("oversized leaf admission must return an error");
assert!(
error
.downcast_ref::<throttle::AdmissionCapacityError>()
.is_some(),
"runtime setup must preserve the typed throttle error: {error:#}"
);
}
#[test]
fn disabled_file_admission_does_not_query_or_configure_limits() {
let throttle = ThrottleConfig {
apply_files_in_flight: false,
..ThrottleConfig::default()
};
let mut queried = false;
let mut configured = false;
let admission = configure_file_admission(
&throttle,
|| {
queried = true;
Err(std::io::Error::other(
"disabled admission must not query rlimit",
))
},
|_| {
configured = true;
Ok(())
},
)
.expect("disabled file admission must not touch runtime admission state");
assert_eq!(admission, EndpointAdmission::Disabled);
assert!(!queried, "disabled file admission queried rlimit");
assert!(
!configured,
"disabled file admission reconfigured throttle pools"
);
}
#[test]
fn finite_user_file_limits_recover_from_rlimit_query_failure() {
let eight = std::num::NonZeroUsize::new(8).unwrap();
let expected = ConcurrencyLimit::Limited(eight);
let captured = CapturedLogs::default();
let subscriber = tracing_subscriber::fmt()
.with_writer(captured.clone())
.with_ansi(false)
.without_time()
.with_target(true)
.with_max_level(tracing::Level::TRACE)
.finish();
tracing::subscriber::with_default(subscriber, || {
for files_in_flight in [
crate::ResolvedFilesInFlight::explicit(eight),
crate::ResolvedFilesInFlight::forwarded_legacy(eight.get()),
] {
let throttle = ThrottleConfig {
files_in_flight,
..ThrottleConfig::default()
};
let mut configured = None;
let admission = configure_file_admission(
&throttle,
|| Err(std::io::Error::other("sentinel rlimit failure")),
|capacity| {
configured = Some(capacity);
Ok(())
},
)
.expect("a finite user ceiling must remain usable when getrlimit fails");
assert_eq!(configured, Some(expected));
assert_eq!(
admission,
EndpointAdmission::Configured {
soft_limit: None,
leaf_capacity: eight
}
);
}
});
let logs = captured.contents();
for option in ["--max-files-in-flight=8", "--max-open-files=8"] {
assert!(
logs.lines().any(|line| {
line.contains(" WARN ")
&& line.contains("rcp::notice")
&& line.contains(option)
&& line.contains("sentinel rlimit failure")
}),
"missing default-visible rlimit fallback notice for {option}: {logs}"
);
}
}
#[test]
fn automatic_file_limit_does_not_bypass_rlimit_query_failure() {
let mut configured = false;
let error = configure_file_admission(
&ThrottleConfig::default(),
|| Err(std::io::Error::other("sentinel rlimit failure")),
|_| {
configured = true;
Ok(())
},
)
.expect_err("an automatic ceiling must retain descriptor-safety validation");
assert!(error.to_string().contains("failed to query rlimit"));
assert!(
!configured,
"failed automatic validation configured admission"
);
}
#[test]
fn unlimited_file_limit_does_not_bypass_rlimit_query_failure() {
let throttle = ThrottleConfig {
files_in_flight: crate::ResolvedFilesInFlight::forwarded_legacy(0),
..ThrottleConfig::default()
};
let mut configured = false;
let error = configure_file_admission(
&throttle,
|| Err(std::io::Error::other("sentinel rlimit failure")),
|_| {
configured = true;
Ok(())
},
)
.expect_err("an unlimited ceiling must retain descriptor-safety validation");
assert!(error.to_string().contains("failed to query rlimit"));
assert!(
!configured,
"failed unlimited validation configured admission"
);
}
#[test]
fn zero_soft_descriptor_limit_fails_closed_for_every_file_policy() {
let eight = std::num::NonZeroUsize::new(8).unwrap();
for files_in_flight in [
crate::ResolvedFilesInFlight::automatic_with(eight),
crate::ResolvedFilesInFlight::explicit(eight),
crate::ResolvedFilesInFlight::forwarded_legacy(0),
] {
let throttle = ThrottleConfig {
files_in_flight,
..ThrottleConfig::default()
};
let mut configured = false;
let error = configure_file_admission(
&throttle,
|| Ok(0),
|_| {
configured = true;
Ok(())
},
)
.expect_err("a zero soft descriptor limit must fail closed");
assert!(error.to_string().contains("soft RLIMIT_NOFILE is zero"));
assert!(!configured, "zero descriptor safety configured admission");
}
}
#[cfg(target_os = "linux")]
#[test]
fn build_tokio_runtime_unlimited_file_ceiling_uses_descriptor_safety_after_stale_epoch() {
let is_child = std::env::var_os(UNLIMITED_FILE_CEILING_CHILD_MARKER).is_some_and(|value| {
value == std::ffi::OsStr::new(UNLIMITED_FILE_CEILING_CHILD_MARKER_VALUE)
});
if !is_child {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"runtime_setup::default_leaf_operation_limit_tests::build_tokio_runtime_unlimited_file_ceiling_uses_descriptor_safety_after_stale_epoch",
"--nocapture",
])
.env(
UNLIMITED_FILE_CEILING_CHILD_MARKER,
UNLIMITED_FILE_CEILING_CHILD_MARKER_VALUE,
)
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
output.status.success(),
"child test failed:\n{stdout}\n{stderr}"
);
assert!(
stdout.contains(UNLIMITED_FILE_CEILING_CHILD_SUCCESS)
|| stderr.contains(UNLIMITED_FILE_CEILING_CHILD_SUCCESS),
"child branch did not emit its sentinel:\n{stdout}\n{stderr}"
);
return;
}
let runtime = RuntimeConfig {
max_workers: 1,
max_blocking_threads: 1,
};
let old_limit = ThrottleConfig {
files_in_flight: crate::ResolvedFilesInFlight::explicit(
std::num::NonZeroUsize::new(1).unwrap(),
),
..ThrottleConfig::default()
};
let (admission_runtime, _) =
build_tokio_runtime(&runtime, &old_limit).expect("runtime setup must succeed");
let (old_open_file, old_pending_meta) = admission_runtime.block_on(async {
tokio::join!(
throttle::open_file_permit(),
throttle::pending_meta_permit()
)
});
let unlimited_file_ceiling = ThrottleConfig {
files_in_flight: crate::ResolvedFilesInFlight::unlimited(),
..ThrottleConfig::default()
};
drop(
build_tokio_runtime(&runtime, &unlimited_file_ceiling)
.expect("runtime setup must succeed"),
);
let (new_open_file, new_pending_meta) = admission_runtime.block_on(async {
let open_file = tokio::time::timeout(
std::time::Duration::from_secs(1),
throttle::open_file_permit(),
)
.await
.expect("unlimited file ceiling must use descriptor safety instead of a stale OpenFile epoch");
let pending_meta = tokio::time::timeout(
std::time::Duration::from_secs(1),
throttle::pending_meta_permit(),
)
.await
.expect("unlimited file ceiling must use descriptor safety instead of a stale PendingMeta epoch");
(open_file, pending_meta)
});
drop((
new_open_file,
new_pending_meta,
old_open_file,
old_pending_meta,
));
throttle::set_admission_limits(None);
println!("{UNLIMITED_FILE_CEILING_CHILD_SUCCESS}");
}
#[cfg(target_os = "linux")]
#[test]
fn runtime_raises_soft_limit_and_budgets_without_raising_file_concurrency() {
let is_child = std::env::var_os(RLIMIT_CHILD_MARKER)
.is_some_and(|value| value == std::ffi::OsStr::new(RLIMIT_CHILD_MARKER_VALUE));
if !is_child {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"runtime_setup::default_leaf_operation_limit_tests::runtime_raises_soft_limit_and_budgets_without_raising_file_concurrency",
"--nocapture",
])
.env(RLIMIT_CHILD_MARKER, RLIMIT_CHILD_MARKER_VALUE)
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
output.status.success(),
"child test failed:\n{stdout}\n{stderr}"
);
assert!(
stdout.contains(RLIMIT_CHILD_SUCCESS)
|| stderr.contains(RLIMIT_CHILD_SUCCESS)
|| stdout.contains(RLIMIT_CHILD_SKIP)
|| stderr.contains(RLIMIT_CHILD_SKIP),
"child branch did not emit its sentinel:\n{stdout}\n{stderr}"
);
return;
}
let original = nofile_limit();
const TARGET_SOFT_LIMIT: libc::rlim_t = 256;
const TARGET_HARD_LIMIT: libc::rlim_t = 512;
if original.rlim_max < TARGET_HARD_LIMIT {
eprintln!(
"{RLIMIT_CHILD_SKIP}: current={} hard={}",
original.rlim_cur, original.rlim_max
);
return;
}
let runtime = RuntimeConfig {
max_workers: 1,
max_blocking_threads: 1,
};
let eight = std::num::NonZeroUsize::new(8).unwrap();
for (files_in_flight, admission_policy, capacity) in [
(
crate::ResolvedFilesInFlight::unlimited(),
AdmissionPolicy::Local,
81,
),
(
crate::ResolvedFilesInFlight::explicit(eight),
AdmissionPolicy::Local,
8,
),
(
crate::ResolvedFilesInFlight::explicit(eight),
AdmissionPolicy::Remote {
streams: eight,
pending: std::num::NonZeroUsize::new(32).unwrap(),
},
8,
),
] {
let lowered = libc::rlimit {
rlim_cur: TARGET_SOFT_LIMIT,
rlim_max: TARGET_HARD_LIMIT,
};
assert_eq!(
unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &raw const lowered) },
0
);
let throttle = ThrottleConfig {
files_in_flight,
admission_policy,
..ThrottleConfig::default()
};
let (runtime, admission) =
build_tokio_runtime(&runtime, &throttle).expect("runtime setup must succeed");
let after = nofile_limit();
assert_eq!(
after.rlim_cur, TARGET_HARD_LIMIT,
"startup must raise the soft limit"
);
assert_eq!(
after.rlim_max, TARGET_HARD_LIMIT,
"startup must preserve the hard limit"
);
let (soft_limit, leaf_capacity) = match admission {
EndpointAdmission::Configured {
soft_limit,
leaf_capacity,
} => (soft_limit, leaf_capacity),
EndpointAdmission::Remote(resources) => {
(resources.soft_limit, resources.leaf_capacity)
}
EndpointAdmission::Disabled => panic!("file admission must remain enabled"),
};
assert_eq!(soft_limit.unwrap().get(), 512);
assert_eq!(leaf_capacity.get(), capacity);
let (open_files, pending_meta) = runtime
.block_on(async {
tokio::time::timeout(std::time::Duration::from_secs(3), async {
let mut open_files = Vec::with_capacity(capacity);
let mut pending_meta = Vec::with_capacity(capacity);
for _ in 0..capacity {
open_files.push(throttle::open_file_permit().await);
}
for _ in 0..capacity {
pending_meta.push(throttle::pending_meta_permit().await);
}
assert!(
tokio::time::timeout(
std::time::Duration::from_millis(50),
throttle::open_file_permit(),
)
.await
.is_err(),
"OpenFile admission must wait at the resolved capacity"
);
assert!(
tokio::time::timeout(
std::time::Duration::from_millis(50),
throttle::pending_meta_permit(),
)
.await
.is_err(),
"PendingMeta admission must wait at the resolved capacity"
);
(open_files, pending_meta)
})
.await
})
.expect("derived admission boundary must complete within its watchdog");
drop((open_files, pending_meta));
throttle::set_admission_limits(None);
}
println!("{RLIMIT_CHILD_SUCCESS}");
}
}
pub(crate) fn spawn_throttle_replenishers(
runtime: &tokio::runtime::Runtime,
throttle: &ThrottleConfig,
trace_identifier: &str,
) {
fn get_replenish_interval(replenish: usize) -> (usize, std::time::Duration) {
let mut replenish = replenish;
let mut interval = std::time::Duration::from_secs(1);
while replenish > 100 && interval > std::time::Duration::from_millis(1) {
replenish /= 10;
interval /= 10;
}
(replenish, interval)
}
let auto_meta_on = throttle.auto_meta.is_some();
if auto_meta_on {
let interval = std::time::Duration::from_millis(100);
let initial_replenish = (throttle.ops_throttle as f64 * 0.1) as usize;
throttle::init_ops_tokens(initial_replenish.max(1));
if throttle.ops_throttle == 0 {
throttle::disable_ops_throttle();
}
runtime.spawn(throttle::run_ops_replenish_thread(
initial_replenish,
interval,
));
} else if throttle.ops_throttle > 0 {
let (replenish, interval) = get_replenish_interval(throttle.ops_throttle);
throttle::init_ops_tokens(replenish);
runtime.spawn(throttle::run_ops_replenish_thread(replenish, interval));
}
if throttle.iops_throttle > 0 {
let (replenish, interval) = get_replenish_interval(throttle.iops_throttle);
throttle::init_iops_tokens(replenish);
runtime.spawn(throttle::run_iops_replenish_thread(replenish, interval));
}
if let Some(auto) = throttle.auto_meta {
spawn_auto_meta_throttle(
runtime,
auto,
throttle.histogram_enabled,
throttle.histogram_log_path.clone(),
throttle.histogram_interval,
trace_identifier,
);
}
}
fn resolve_log_path(path: &std::path::Path, trace_identifier: &str) -> std::path::PathBuf {
let parent = match path.parent() {
Some(p) if p.as_os_str().is_empty() => std::path::Path::new("."),
Some(p) => p,
None => std::path::Path::new("."),
};
let mut name: std::ffi::OsString = path
.file_stem()
.map(|s| s.to_os_string())
.unwrap_or_else(|| std::ffi::OsString::from("auto-meta"));
name.push(".");
name.push(trace_identifier);
name.push(".");
match path.extension() {
Some(e) => name.push(e),
None => name.push("hdr"),
}
parent.join(name)
}
pub(crate) fn validate_histogram_log_target(
throttle: &ThrottleConfig,
trace_identifier: &str,
) -> Result<(), String> {
let Some(path) = &throttle.histogram_log_path else {
return Ok(());
};
if path.is_dir() {
return Err(format!(
"--auto-meta-histogram-log {path:?} is a directory; expected a file path",
));
}
if path.file_name().is_none() {
return Err(format!(
"--auto-meta-histogram-log {path:?} has no filename component",
));
}
let resolved = resolve_log_path(path, trace_identifier);
let mut open_options = std::fs::OpenOptions::new();
open_options.create(true).write(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
open_options.custom_flags(libc::O_NOFOLLOW);
}
match open_options.open(&resolved) {
Ok(_) => Ok(()),
Err(err) => {
#[cfg(unix)]
let context = if err.raw_os_error() == Some(libc::ELOOP) {
" (resolved path is a symlink, which would let a local attacker hijack the write)"
} else {
""
};
#[cfg(not(unix))]
let context = "";
Err(format!(
"--auto-meta-histogram-log cannot create resolved path {resolved:?}: {err:#}{context}",
))
}
}
}
const fn unit_label(side: congestion::Side, op: congestion::MetadataOp) -> &'static str {
use congestion::MetadataOp::*;
use congestion::Side::*;
match (side, op) {
(Source, Stat) => "src-stat",
(Destination, Stat) => "dst-stat",
(Source, ReadLink) => "src-read-link",
(Destination, ReadLink) => "dst-read-link",
(Destination, MkDir) => "mkdir",
(Source, MkDir) => "src-mkdir",
(Destination, RmDir) => "rmdir",
(Source, RmDir) => "src-rmdir",
(Destination, Unlink) => "unlink",
(Source, Unlink) => "src-unlink",
(Destination, HardLink) => "hard-link",
(Source, HardLink) => "src-hard-link",
(Destination, Symlink) => "symlink",
(Source, Symlink) => "src-symlink",
(Destination, Chmod) => "chmod",
(Source, Chmod) => "src-chmod",
(Destination, OpenCreate) => "open-create",
(Source, OpenCreate) => "src-open-create",
}
}
fn build_histogram_header(
auto: &AutoMetaThrottleConfig,
tool_name: &str,
snapshot_interval: std::time::Duration,
) -> congestion::format::LogHeader {
use congestion::format::{AutoMetaSnapshot, HdrSnapshot, LogHeader, UnitLabel};
let hostname = get_hostname();
let mut unit_labels = Vec::with_capacity(congestion::N_META_RESOURCES);
for &side in &congestion::Side::ALL {
for &op in &congestion::MetadataOp::ALL {
unit_labels.push(UnitLabel {
side: side as u8,
op: op as u8,
label: unit_label(side, op).to_string(),
});
}
}
LogHeader {
format_version: congestion::format::FORMAT_VERSION,
tool: tool_name.to_string(),
tool_version: env!("CARGO_PKG_VERSION").to_string(),
hostname,
pid: std::process::id(),
start_unix_micros: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| u64::try_from(d.as_micros()).unwrap_or(u64::MAX))
.unwrap_or(0),
snapshot_interval_micros: u64::try_from(snapshot_interval.as_micros()).unwrap_or(u64::MAX),
auto_meta: AutoMetaSnapshot {
initial_cwnd: auto.initial_cwnd,
min_cwnd: auto.min_cwnd,
max_cwnd: auto.max_cwnd,
alpha: auto.alpha,
beta: auto.beta,
increase_step: auto.increase_step,
decrease_step: auto.decrease_step,
baseline_percentile: auto.baseline_percentile,
current_percentile: auto.current_percentile,
long_window_micros: u64::try_from(auto.long_window.as_micros()).unwrap_or(u64::MAX),
short_window_micros: u64::try_from(auto.short_window.as_micros()).unwrap_or(u64::MAX),
tick_interval_micros: u64::try_from(auto.tick_interval.as_micros()).unwrap_or(u64::MAX),
},
hdr: HdrSnapshot {
lowest_discernible_micros: congestion::HDR_LOWEST_DISCERNIBLE_MICROS,
highest_trackable_micros: congestion::HDR_HIGHEST_TRACKABLE_MICROS,
significant_figures: congestion::HDR_SIGNIFICANT_FIGURES,
unit: "microseconds".into(),
},
unit_labels,
}
}
fn spawn_auto_meta_throttle(
runtime: &tokio::runtime::Runtime,
auto: AutoMetaThrottleConfig,
histogram_enabled: bool,
histogram_log_path: Option<std::path::PathBuf>,
histogram_interval: std::time::Duration,
trace_identifier: &str,
) {
let initial_cwnd = auto
.initial_cwnd
.clamp(auto.min_cwnd.max(1), auto.max_cwnd.max(1));
let histogram_active = histogram_enabled || histogram_log_path.is_some();
let resolved_log_path = histogram_log_path
.as_ref()
.map(|p| resolve_log_path(p, trace_identifier));
let mut builder = congestion::RoutingSinkBuilder::new();
struct Slot {
label: &'static str,
side: congestion::Side,
op: congestion::MetadataOp,
sample_rx: tokio::sync::mpsc::Receiver<congestion::Sample>,
apply_rate: bool,
accumulator: Option<std::sync::Arc<std::sync::Mutex<congestion::HistogramAccumulator>>>,
}
let mut slots: Vec<Slot> = Vec::with_capacity(congestion::N_META_RESOURCES);
for &side in &congestion::Side::ALL {
for &op in &congestion::MetadataOp::ALL {
let resource = walk::meta_resource(side, op);
throttle::set_max_ops_in_flight(resource, initial_cwnd as usize);
let rx = builder.metadata_receiver(side, op);
let apply_rate = matches!(
(side, op),
(congestion::Side::Destination, congestion::MetadataOp::Stat),
);
let accumulator = if histogram_active {
let acc = std::sync::Arc::new(std::sync::Mutex::new(
congestion::HistogramAccumulator::new(),
));
builder.metadata_histogram(side, op, acc.clone());
Some(acc)
} else {
None
};
slots.push(Slot {
label: unit_label(side, op),
side,
op,
sample_rx: rx,
apply_rate,
accumulator,
});
}
}
let sink = std::sync::Arc::new(builder.build());
congestion::install_sample_sink(sink.clone());
let mut logger_units: Vec<histogram_logger::LoggerUnit> = Vec::new();
for slot in slots {
let controller = congestion::RatioController::new(congestion::RatioConfig {
initial_cwnd: auto.initial_cwnd,
min_cwnd: auto.min_cwnd,
max_cwnd: auto.max_cwnd,
alpha: auto.alpha,
beta: auto.beta,
increase_step: auto.increase_step,
decrease_step: auto.decrease_step,
baseline_percentile: auto.baseline_percentile,
current_percentile: auto.current_percentile,
long_window: auto.long_window,
short_window: auto.short_window,
});
let (unit, decision_rx, snapshot_rx) = congestion::ControlUnit::new(
slot.label,
controller,
slot.sample_rx,
auto.tick_interval,
);
observability::register_unit(slot.label, snapshot_rx);
if let Some(acc) = slot.accumulator.as_ref() {
let (snap_tx, snap_rx) = tokio::sync::watch::channel(
hdrhistogram::Histogram::<u64>::new_with_bounds(
congestion::HDR_LOWEST_DISCERNIBLE_MICROS,
congestion::HDR_HIGHEST_TRACKABLE_MICROS,
congestion::HDR_SIGNIFICANT_FIGURES,
)
.expect("histogram bounds valid"),
);
observability::register_histogram(slot.label, snap_rx, histogram_interval);
logger_units.push(histogram_logger::LoggerUnit {
label: slot.label,
side: slot.side,
op: slot.op,
accumulator: acc.clone(),
snapshot_tx: snap_tx,
});
}
runtime.spawn(unit.run());
runtime.spawn(auto_meta::run_adapter(
walk::meta_resource(slot.side, slot.op),
slot.apply_rate,
decision_rx,
sink.clone(),
));
}
if histogram_active {
let header = build_histogram_header(&auto, trace_identifier, histogram_interval);
let (cancel_tx, cancel_rx) = tokio::sync::watch::channel(false);
store_logger_cancel(cancel_tx);
let progress_source: histogram_logger::ProgressSource = Box::new(|| {
let snapshot = progress::SerializableProgress::from(&*PROGRESS);
serde_json::to_vec(&snapshot).unwrap_or_else(|err| {
tracing::warn!(
"histogram-logger: SerializableProgress JSON encode failed: {err:#}; \
dropping this tick's progress record"
);
Vec::new()
})
});
let handle = runtime.spawn(histogram_logger::run_logger(
histogram_logger::LoggerConfig {
interval: histogram_interval,
log_path: resolved_log_path,
header,
progress_source: Some(progress_source),
},
logger_units,
cancel_rx,
));
store_logger_handle(handle);
}
tracing::info!(
"auto-meta-throttle enabled (per-(side, op) controllers, {} total): \
initial_cwnd={}, max_cwnd={}, alpha={}, beta={}, \
baseline_percentile={}, current_percentile={}, \
long_window={:?}, short_window={:?}, tick={:?}, \
histograms={}",
congestion::N_META_RESOURCES,
auto.initial_cwnd,
auto.max_cwnd,
auto.alpha,
auto.beta,
auto.baseline_percentile,
auto.current_percentile,
auto.long_window,
auto.short_window,
auto.tick_interval,
histogram_active,
);
}
#[cfg(test)]
mod remote_admission_tests {
use super::*;
fn nonzero(value: usize) -> std::num::NonZeroUsize {
std::num::NonZeroUsize::new(value).unwrap()
}
fn config(files: crate::ResolvedFilesInFlight, streams: usize) -> ThrottleConfig {
ThrottleConfig {
files_in_flight: files,
admission_policy: crate::AdmissionPolicy::Remote {
streams: nonzero(streams),
pending: nonzero(streams * 4),
},
..Default::default()
}
}
#[test]
fn larger_file_requests_preserve_remote_directory_capacity() {
for files in [
crate::ResolvedFilesInFlight::explicit(nonzero(20)),
crate::ResolvedFilesInFlight::explicit(nonzero(163)),
crate::ResolvedFilesInFlight::explicit(nonzero(200)),
crate::ResolvedFilesInFlight::unlimited(),
] {
let mut installed = None;
let admission = configure_file_admission(
&config(files, 20),
|| Ok(1024),
|capacity| {
installed = Some(capacity);
Ok(())
},
)
.unwrap();
let EndpointAdmission::Remote(resources) = admission else {
panic!("remote setup returned local admission");
};
assert_eq!(installed, Some(ConcurrencyLimit::Limited(nonzero(20))));
assert_eq!(resources.leaf_capacity.get(), 20);
assert_eq!(resources.normal_directories.get(), 223);
assert_eq!(resources.reserved_directories.get(), 223);
}
}
#[test]
fn known_remote_headroom_supports_normal_ancestors_independently_of_pending_files() {
for (soft, streams, normal, reserve) in [
(1024, 4, 243, 243),
(1024, 8, 238, 238),
(1024, 20, 223, 223),
(1025, 4, 243, 243),
(1026, 4, 243, 244),
] {
for pending in [streams, streams * 4, streams * 16] {
let mut configuration = config(
crate::ResolvedFilesInFlight::explicit(nonzero(streams)),
streams,
);
configuration.admission_policy = crate::AdmissionPolicy::Remote {
streams: nonzero(streams),
pending: nonzero(pending),
};
let mut installed = None;
let admission = configure_file_admission(
&configuration,
|| Ok(soft),
|capacity| {
installed = Some(capacity);
Ok(())
},
)
.unwrap();
let EndpointAdmission::Remote(resources) = admission else {
panic!("remote setup returned local admission");
};
assert_eq!(installed, Some(ConcurrencyLimit::Limited(nonzero(streams))));
assert_eq!(resources.leaf_capacity.get(), streams);
assert_eq!(
resources.normal_directories.get(),
normal,
"soft={soft}, streams={streams}, pending={pending}"
);
assert_eq!(
resources.reserved_directories.get(),
reserve,
"soft={soft}, streams={streams}, pending={pending}"
);
assert!(normal >= 2 * streams && reserve >= 2 * streams);
let charged = 4 * streams + 2 * (normal + reserve) + streams + 32;
assert!(charged <= soft as usize);
assert!(
soft as usize - charged <= 1,
"only an odd descriptor can remain unassigned"
);
}
}
}
#[test]
fn remote_setup_preserves_scan_and_reserve_capacity_at_low_limits() {
for (soft, streams, leaf, normal, reserve) in [
(1024, 100, 74, 149, 149),
(1024, 200, 66, 132, 132),
(1024, 400, 49, 99, 99),
(160, 20, 9, 18, 18),
(128, 20, 6, 13, 13),
] {
let mut installed = None;
let admission = configure_file_admission(
&config(crate::ResolvedFilesInFlight::unlimited(), streams),
|| Ok(soft),
|capacity| {
installed = Some(capacity);
Ok(())
},
)
.unwrap();
let EndpointAdmission::Remote(resources) = admission else {
panic!("remote setup returned local admission");
};
assert_eq!(installed, Some(ConcurrencyLimit::Limited(nonzero(leaf))));
assert_eq!(resources.normal_directories.get(), normal);
assert_eq!(resources.reserved_directories.get(), reserve);
assert!(normal >= 2 * leaf);
assert!(reserve >= 2 * leaf);
assert!(4 * leaf + 2 * (normal + reserve) + streams + 32 <= soft as usize);
}
}
#[test]
fn impossible_remote_socket_budget_fails_before_installing_pools() {
let mut configured = false;
let error = configure_file_admission(
&config(crate::ResolvedFilesInFlight::unlimited(), 100),
|| Ok(128),
|_| {
configured = true;
Ok(())
},
)
.unwrap_err();
let message = format!("{error:#}");
assert!(
message.contains("128") && message.contains("100"),
"{message}"
);
assert!(message.contains("--max-connections"), "{message}");
assert!(message.contains("minimum soft limit=144"), "{message}");
assert!(message.contains("shortfall=16"), "{message}");
assert!(message.contains("SSH session"), "{message}");
assert!(!configured);
}
#[test]
fn unknown_remote_limit_preserves_bounded_logical_traversal() {
let mut installed = None;
let admission = configure_file_admission(
&config(crate::ResolvedFilesInFlight::explicit(nonzero(20)), 20),
|| Err(std::io::Error::other("limit unavailable")),
|capacity| {
installed = Some(capacity);
Ok(())
},
)
.unwrap();
let EndpointAdmission::Remote(resources) = admission else {
panic!("remote setup returned local admission");
};
assert_eq!(installed, Some(ConcurrencyLimit::Limited(nonzero(20))));
assert_eq!(resources.soft_limit, None);
assert_eq!(resources.normal_directories.get(), 200);
assert_eq!(resources.reserved_directories.get(), 200);
}
#[test]
fn unknown_remote_limit_still_rejects_automatic_and_unlimited_requests() {
for files in [
crate::ResolvedFilesInFlight::automatic_with(nonzero(20)),
crate::ResolvedFilesInFlight::unlimited(),
] {
let result = configure_file_admission(
&config(files, 20),
|| Err(std::io::Error::other("limit unavailable")),
|_| panic!("unsubstantiated admission configured pools"),
);
assert!(result.is_err());
}
}
#[test]
fn remote_resource_arithmetic_remains_bounded_at_extreme_capacities() {
let maximum = tokio::sync::Semaphore::MAX_PERMITS;
let resources = RemoteResources::for_limits(
std::num::NonZeroU64::new(u64::MAX),
nonzero(usize::MAX),
nonzero(maximum),
nonzero(maximum),
)
.unwrap();
assert_eq!(resources.leaf_capacity.get(), 4096);
assert!(resources.normal_directories.get() <= maximum);
assert!(resources.reserved_directories.get() <= maximum);
let unknown = RemoteResources::for_limits(
None,
nonzero(usize::MAX),
nonzero(maximum),
nonzero(maximum),
)
.unwrap();
assert_eq!(unknown.normal_directories.get(), maximum);
assert_eq!(unknown.reserved_directories.get(), maximum);
}
}
#[cfg(test)]
mod unit_label_tests {
use super::unit_label;
use congestion::{MetadataOp, Side};
#[test]
fn lookup_ops_carry_side_prefix() {
assert_eq!(unit_label(Side::Source, MetadataOp::Stat), "src-stat");
assert_eq!(unit_label(Side::Destination, MetadataOp::Stat), "dst-stat");
assert_eq!(
unit_label(Side::Source, MetadataOp::ReadLink),
"src-read-link",
);
assert_eq!(
unit_label(Side::Destination, MetadataOp::ReadLink),
"dst-read-link",
);
}
#[test]
fn destination_only_ops_drop_prefix() {
assert_eq!(unit_label(Side::Destination, MetadataOp::MkDir), "mkdir");
assert_eq!(unit_label(Side::Destination, MetadataOp::RmDir), "rmdir");
assert_eq!(unit_label(Side::Destination, MetadataOp::Unlink), "unlink");
assert_eq!(
unit_label(Side::Destination, MetadataOp::HardLink),
"hard-link",
);
assert_eq!(
unit_label(Side::Destination, MetadataOp::Symlink),
"symlink"
);
assert_eq!(unit_label(Side::Destination, MetadataOp::Chmod), "chmod");
assert_eq!(
unit_label(Side::Destination, MetadataOp::OpenCreate),
"open-create",
);
}
#[test]
fn unused_source_side_mutation_slots_keep_src_prefix() {
assert_eq!(unit_label(Side::Source, MetadataOp::Unlink), "src-unlink");
assert_eq!(unit_label(Side::Source, MetadataOp::MkDir), "src-mkdir");
}
#[test]
fn labels_are_unique_across_all_resources() {
let mut seen = std::collections::HashSet::new();
for &side in &Side::ALL {
for &op in &MetadataOp::ALL {
let label = unit_label(side, op);
assert!(seen.insert(label), "duplicate label: {label}");
}
}
assert_eq!(seen.len(), congestion::N_META_RESOURCES);
}
}
#[cfg(test)]
mod runtime_stats_tests {
use super::*;
use anyhow::Result;
#[test]
fn collect_runtime_stats_matches_procfs_snapshot() -> Result<()> {
let process = procfs::process::Process::myself()?;
let expected = collect_runtime_stats_for_process(&process)?;
let actual = collect_runtime_stats();
let cpu_tolerance_ms = 50;
let rss_tolerance_bytes = 1_000_000;
assert!(
expected.cpu_time_user_ms.abs_diff(actual.cpu_time_user_ms) <= cpu_tolerance_ms,
"user CPU deviated by more than {cpu_tolerance_ms}ms: expected {}, got {}",
expected.cpu_time_user_ms,
actual.cpu_time_user_ms
);
assert!(
expected
.cpu_time_kernel_ms
.abs_diff(actual.cpu_time_kernel_ms)
<= cpu_tolerance_ms,
"kernel CPU deviated by more than {cpu_tolerance_ms}ms: expected {}, got {}",
expected.cpu_time_kernel_ms,
actual.cpu_time_kernel_ms
);
assert!(
expected.peak_rss_bytes.abs_diff(actual.peak_rss_bytes) <= rss_tolerance_bytes,
"peak RSS deviated by more than {rss_tolerance_bytes} bytes: expected {}, got {}",
expected.peak_rss_bytes,
actual.peak_rss_bytes
);
Ok(())
}
#[test]
fn collect_runtime_stats_returns_default_on_error() {
let stats = collect_runtime_stats_inner(None);
assert_eq!(stats, RuntimeStats::default());
let nonexistent_process = procfs::process::Process::new(i32::MAX).ok();
let stats = collect_runtime_stats_inner(nonexistent_process);
assert_eq!(stats, RuntimeStats::default());
}
}
#[cfg(test)]
mod resolve_log_path_tests {
use super::*;
#[test]
fn full_path_with_extension() {
let p = std::path::Path::new("/tmp/foo.hdr");
assert_eq!(
resolve_log_path(p, "rcp"),
std::path::PathBuf::from("/tmp/foo.rcp.hdr"),
);
}
#[test]
fn bare_filename_resolves_to_current_dir() {
let p = std::path::Path::new("foo.hdr");
assert_eq!(
resolve_log_path(p, "rcp"),
std::path::PathBuf::from("./foo.rcp.hdr"),
);
}
#[test]
fn no_extension_defaults_to_hdr() {
let p = std::path::Path::new("/tmp/foo");
assert_eq!(
resolve_log_path(p, "rcp"),
std::path::PathBuf::from("/tmp/foo.rcp.hdr"),
);
}
#[test]
#[cfg(unix)]
fn preserves_non_utf8_stem() {
use std::os::unix::ffi::{OsStrExt, OsStringExt};
let mut raw_name = vec![b'/', b't', b'm', b'p', b'/'];
raw_name.extend_from_slice(&[0xFF, 0xFE]);
raw_name.extend_from_slice(b".hdr");
let p = std::path::PathBuf::from(std::ffi::OsString::from_vec(raw_name));
let resolved = resolve_log_path(&p, "rcp");
let bytes = resolved.as_os_str().as_bytes();
assert!(
bytes.windows(2).any(|w| w == [0xFF, 0xFE]),
"non-UTF-8 bytes must survive resolution; got bytes: {bytes:?}",
);
assert!(
bytes.ends_with(b".rcp.hdr"),
"expected .rcp.hdr suffix; got bytes: {bytes:?}",
);
}
}
#[cfg(test)]
mod validate_histogram_log_target_tests {
use super::*;
fn throttle_with_log_path(path: Option<std::path::PathBuf>) -> ThrottleConfig {
ThrottleConfig {
histogram_enabled: path.is_some(),
histogram_log_path: path,
..Default::default()
}
}
#[test]
fn no_log_path_is_ok() {
let throttle = throttle_with_log_path(None);
assert!(validate_histogram_log_target(&throttle, "rcp").is_ok());
}
#[test]
fn writable_resolved_path_is_ok() {
let dir = tempfile::tempdir().unwrap();
let throttle = throttle_with_log_path(Some(dir.path().join("foo.hdr")));
assert!(validate_histogram_log_target(&throttle, "rcp").is_ok());
}
#[test]
fn resolved_path_existing_as_directory_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let blocker = dir.path().join("foo.rcp.hdr");
std::fs::create_dir(&blocker).unwrap();
let throttle = throttle_with_log_path(Some(dir.path().join("foo.hdr")));
let err = validate_histogram_log_target(&throttle, "rcp").unwrap_err();
assert!(
err.contains("histogram-log") && err.contains("foo.rcp.hdr"),
"got: {err}",
);
}
#[test]
fn resolved_path_in_missing_parent_is_rejected() {
let throttle = throttle_with_log_path(Some("/nonexistent-dir-67890/foo.hdr".into()));
let err = validate_histogram_log_target(&throttle, "rcp").unwrap_err();
assert!(err.contains("histogram-log"), "got: {err}");
}
#[test]
fn log_path_pointing_at_existing_directory_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let throttle = throttle_with_log_path(Some(dir.path().to_path_buf()));
let err = validate_histogram_log_target(&throttle, "rcp").unwrap_err();
assert!(err.contains("directory"), "got: {err}");
}
#[test]
fn log_path_with_no_filename_is_rejected() {
let throttle = throttle_with_log_path(Some(std::path::PathBuf::from("/")));
let err = validate_histogram_log_target(&throttle, "rcp").unwrap_err();
assert!(
err.contains("filename") || err.contains("directory"),
"got: {err}",
);
}
#[test]
#[cfg(unix)]
fn resolved_path_existing_as_symlink_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("victim.txt");
std::fs::write(&target, b"do not clobber").unwrap();
let resolved_path = dir.path().join("foo.rcp.hdr");
std::os::unix::fs::symlink(&target, &resolved_path).unwrap();
let throttle = throttle_with_log_path(Some(dir.path().join("foo.hdr")));
let err = validate_histogram_log_target(&throttle, "rcp").unwrap_err();
assert!(
err.contains("symlink") || err.contains("ELOOP") || err.contains("Too many levels"),
"got: {err}",
);
let preserved = std::fs::read(&target).unwrap();
assert_eq!(preserved, b"do not clobber");
}
}
#[cfg(test)]
mod timing_output_tests {
#[test]
fn trace_artifact_names_are_portable_for_ci_uploads() {
for extension in ["json", "scopes.json", "timings.json", "folded"] {
let path = super::generate_trace_filename("/tmp/trace", "rcp-master", extension);
let filename = std::path::Path::new(&path)
.file_name()
.unwrap()
.to_str()
.unwrap();
assert!(
!filename.contains([':', '"', '<', '>', '|', '*', '?', '\\', '\r', '\n']),
"artifact upload rejects non-portable filename: {filename}"
);
}
}
#[test]
fn shared_prefix_keeps_summary_and_both_chrome_artifacts_intact() {
const CHILD: &str = "RCP_TEST_SHARED_TIMING_PREFIX";
if std::env::var_os(CHILD).is_none() {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"runtime_setup::timing_output_tests::shared_prefix_keeps_summary_and_both_chrome_artifacts_intact",
"--nocapture",
])
.env(CHILD, "1")
.output()
.unwrap();
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
return;
}
let directory = tempfile::tempdir().unwrap();
let prefix = directory.path().join("shared").to_str().unwrap().to_owned();
let mut guards = super::install_tracing_subscriber(
false,
0,
crate::TracingConfig {
timings_prefix: Some(prefix.clone()),
chrome_trace_prefix: Some(prefix),
trace_identifier: "collision-test".to_owned(),
..crate::TracingConfig::default()
},
)
.unwrap();
crate::timing_scope!("completed").finish();
let span = tracing::info_span!("ordinary-poll-span");
span.in_scope(|| {});
drop(span);
guards.finish().unwrap();
drop(guards);
let paths: Vec<_> = std::fs::read_dir(directory.path())
.unwrap()
.map(|entry| entry.unwrap().path())
.collect();
assert_eq!(
paths.len(),
3,
"summary, poll trace, and elapsed trace must be independent files"
);
let summary = paths
.iter()
.find(|path| path.to_str().unwrap().ends_with(".timings.json"))
.expect("summary suffix");
let timeline = paths
.iter()
.find(|path| path.to_str().unwrap().ends_with(".scopes.json"))
.expect("elapsed timeline suffix");
let poll = paths
.iter()
.find(|path| *path != summary && *path != timeline)
.unwrap();
let summary: serde_json::Value =
serde_json::from_reader(std::fs::File::open(summary).unwrap()).unwrap();
assert_eq!(summary["scopes"][0]["name"], "completed");
let timeline: serde_json::Value =
serde_json::from_reader(std::fs::File::open(timeline).unwrap()).unwrap();
assert_eq!(timeline[0]["name"], "completed");
let poll: serde_json::Value =
serde_json::from_reader(std::fs::File::open(poll).unwrap()).unwrap();
assert!(poll.is_array() || poll["traceEvents"].is_array());
}
}