use crate::{
discovery,
domain::*,
error::AppError,
progress::{ProgressObserver, ScanPhase},
traverse,
workspace::{self, CargoRunner},
};
use std::{
ffi::OsString,
fs, io,
path::{Path, PathBuf},
process::Command,
time::{Duration, SystemTime},
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CleanMode {
Execute,
Simulate,
CargoPreview,
}
impl CleanMode {
pub fn as_str(self) -> &'static str {
match self {
Self::CargoPreview => "preview",
Self::Simulate => "simulate",
Self::Execute => "execute",
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CleanupSelection {
All,
WorkingDirectory,
Ancestry(PathBuf),
Roots(Vec<PathBuf>),
}
impl CleanupSelection {
pub fn admits(&self, workspace_root: &Path) -> bool {
match self {
Self::All => true,
Self::WorkingDirectory => false,
Self::Ancestry(anchor) => {
workspace_root == anchor
|| workspace_root.starts_with(anchor)
|| anchor.starts_with(workspace_root)
}
Self::Roots(roots) => roots.iter().any(|root| root == workspace_root),
}
}
pub fn resolved(&self) -> Result<CleanupSelection, AppError> {
match self {
Self::WorkingDirectory => {
let cwd = std::env::current_dir().map_err(|e| AppError::InvalidRoot {
path: ".".into(),
reason: format!(
"cannot resolve the working directory for cleanup selection: {e}"
),
})?;
Ok(Self::Ancestry(cwd))
}
other => Ok(other.clone()),
}
}
pub fn describe(&self) -> Option<String> {
match self {
Self::All => None,
Self::Ancestry(anchor) => Some(format!("the working directory {}", anchor.display())),
Self::WorkingDirectory => {
Some("an unresolved working-directory anchor (internal error)".into())
}
Self::Roots(_) => Some("the interactive selection".into()),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CleanOutcome {
Previewed,
Simulated,
Cleaned,
Skipped,
Failed,
}
impl CleanOutcome {
pub fn as_str(self) -> &'static str {
match self {
Self::Previewed => "previewed",
Self::Simulated => "simulated",
Self::Cleaned => "cleaned",
Self::Skipped => "skipped",
Self::Failed => "failed",
}
}
}
#[derive(Clone, Debug)]
pub struct CleanResult {
pub display_path: PathBuf,
pub workspace_roots: Vec<PathBuf>,
pub output_roots: Vec<PathBuf>,
pub ownership: OutputOwnershipClass,
pub outcome: CleanOutcome,
pub policy_disposition: Option<PolicyDisposition>,
pub reason_code: CleanupReasonCode,
pub before_bytes: Option<u64>,
pub after_bytes: Option<u64>,
pub observed_decrease: Option<u64>,
pub detail: String,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CleanupReasonCode {
Previewed,
Simulated,
Cleaned,
BelowMinimumSize,
TooRecentForPolicy,
NotIncluded,
Excluded,
SkippedActive,
SkippedShared,
SkippedUncertain,
SkippedUnauthorized,
SkippedMarkerInvalid,
SkippedChangedBeforeCleanup,
SkippedOwnershipUnproven,
SkippedSafety,
SkippedOutsideSelection,
CargoFailed,
MeasurementFailed,
SelectorUnsupported,
SelectorInvalid,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProofFailure {
pub code: CleanupReasonCode,
pub detail: String,
}
impl ProofFailure {
pub fn new(code: CleanupReasonCode, detail: impl Into<String>) -> Self {
Self {
code,
detail: detail.into(),
}
}
}
impl From<String> for ProofFailure {
fn from(detail: String) -> Self {
let code = proof_skip_code(&detail);
Self { code, detail }
}
}
impl From<&str> for ProofFailure {
fn from(detail: &str) -> Self {
detail.to_owned().into()
}
}
impl CleanupReasonCode {
pub fn as_str(self) -> &'static str {
match self {
Self::Previewed => "previewed",
Self::Simulated => "simulated",
Self::Cleaned => "cleaned",
Self::BelowMinimumSize => "below_minimum_size",
Self::TooRecentForPolicy => "too_recent_for_policy",
Self::NotIncluded => "not_included",
Self::Excluded => "excluded",
Self::SkippedActive => "skipped_active",
Self::SkippedShared => "skipped_shared",
Self::SkippedUncertain => "skipped_uncertain",
Self::SkippedUnauthorized => "skipped_unauthorized",
Self::SkippedMarkerInvalid => "skipped_marker_invalid",
Self::SkippedChangedBeforeCleanup => "skipped_changed_before_cleanup",
Self::SkippedOwnershipUnproven => "skipped_ownership_unproven",
Self::SkippedSafety => "skipped_safety",
Self::SkippedOutsideSelection => "skipped_outside_selection",
Self::CargoFailed => "cargo_failed",
Self::MeasurementFailed => "measurement_failed",
Self::SelectorUnsupported => "selector_unsupported",
Self::SelectorInvalid => "selector_invalid",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PolicyDisposition {
Selected,
BelowMinimumSize,
TooRecentForPolicy,
NotIncluded,
Excluded,
SelectorEstimateUnavailable,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ScopeBlockReason {
IncompleteDiscovery,
OwnershipUnproven,
}
impl ScopeBlockReason {
pub fn as_str(self) -> &'static str {
match self {
Self::IncompleteDiscovery => "incomplete_discovery",
Self::OwnershipUnproven => "ownership_unproven",
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ScopeBlock {
pub reason: ScopeBlockReason,
pub message: String,
}
impl ScopeBlock {
pub fn new(reason: ScopeBlockReason, message: String) -> Self {
Self { reason, message }
}
}
#[derive(Clone, Debug)]
pub struct CleanReport {
pub results: Vec<CleanResult>,
pub diagnostics: usize,
pub failed: usize,
pub mode: CleanMode,
pub counters: ScanCounters,
pub scope_blocked: Option<ScopeBlock>,
pub unresolved_ownership: Vec<UnresolvedOwnershipParticipant>,
pub selected_roots: Vec<PathBuf>,
pub discovered_manifests: usize,
pub resolved_workspaces: usize,
pub units_considered: usize,
pub effective_policy: Option<CleanupPolicy>,
pub selector: Option<CleanupSelector>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CleanupSelector {
Profile(String),
Package(String),
}
impl CleanupSelector {
pub fn kind(&self) -> &'static str {
match self {
Self::Profile(_) => "profile",
Self::Package(_) => "package",
}
}
pub fn value(&self) -> &str {
match self {
Self::Profile(value) | Self::Package(value) => value,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct CleanupPolicy {
pub min_reclaimable_bytes: u64,
pub min_inactive_seconds: Option<u64>,
pub include: Vec<String>,
pub exclude: Vec<String>,
}
impl CleanReport {
pub fn render(&self) -> String {
let mut out = String::new();
if !self.selected_roots.is_empty() {
out.push_str(&format!(
"combined scope: {} root(s) [{}], {} manifest(s), {} resolved workspace(s), {} CleanupUnit(s), {} unresolved ownership participant(s)\n",
self.selected_roots.len(),
self.selected_roots.iter().map(|p| escaped_path(p)).collect::<Vec<_>>().join(", "),
self.discovered_manifests,
self.resolved_workspaces,
self.units_considered,
self.unresolved_ownership.len(),
));
}
if let Some(block) = &self.scope_blocked {
out.push_str(&format!("{}\n", block.message));
if block.reason == ScopeBlockReason::OwnershipUnproven
&& !self.unresolved_ownership.is_empty()
{
const MAX_LISTED: usize = 5;
const MAX_FIELD_CHARS: usize = 200;
let mut listed = 0usize;
let mut workspace_hint = false;
for participant in self.unresolved_ownership.iter().take(MAX_LISTED) {
let manifest = participant
.manifest
.display()
.to_string()
.chars()
.filter(|ch| !ch.is_control())
.take(MAX_FIELD_CHARS)
.collect::<String>();
let reason = participant
.reason
.replace('\n', " ")
.chars()
.filter(|ch| !ch.is_control())
.take(MAX_FIELD_CHARS)
.collect::<String>();
out.push_str(&format!(
" unresolved [{}] {}: {}\n",
participant.stage, manifest, reason
));
listed += 1;
if participant
.reason
.contains("believes it's in a workspace when it's not")
{
workspace_hint = true;
}
}
let remaining = self.unresolved_ownership.len().saturating_sub(listed);
if remaining > 0 {
out.push_str(&format!(" … {remaining} more unresolved participant(s)\n"));
}
if workspace_hint {
out.push_str(
" hint: a nested crate that believes it is in a workspace needs an empty `[workspace]` table or a parent `workspace.exclude` entry; otherwise clean a healthy workspace explicitly, e.g. `cargo cleanme clean ROOT`\n",
);
}
}
return out;
}
let mut previewed = 0usize;
let mut simulated = 0usize;
let mut cleaned = 0usize;
let mut skipped = 0usize;
let mut failed = 0usize;
let mut before = 0u64;
let mut after = 0u64;
let mut delta = 0u64;
let mut ordered: Vec<&CleanResult> = self.results.iter().collect();
ordered.sort_by(|a, b| {
b.before_bytes
.unwrap_or(0)
.cmp(&a.before_bytes.unwrap_or(0))
.then_with(|| a.display_path.cmp(&b.display_path))
});
for r in ordered {
match r.outcome {
CleanOutcome::Previewed => {
previewed += 1;
if let Some(n) = r.before_bytes {
before = before.saturating_add(n);
}
}
CleanOutcome::Simulated => {
simulated += 1;
if let Some(n) = r.before_bytes {
before = before.saturating_add(n);
}
}
CleanOutcome::Cleaned => {
cleaned += 1;
if let Some(n) = r.before_bytes {
before = before.saturating_add(n);
}
if let Some(n) = r.after_bytes {
after = after.saturating_add(n);
}
if let Some(n) = r.observed_decrease {
delta = delta.saturating_add(n);
}
}
CleanOutcome::Skipped => skipped += 1,
CleanOutcome::Failed => {
failed += 1;
}
}
out.push_str(&format!(
"{:?} {} [{}]",
r.outcome,
escaped_path(&r.display_path),
r.ownership.label(),
));
if r.output_roots.len() > 1 {
out.push_str(&format!(
" outputs {}",
r.output_roots
.iter()
.map(|p| escaped_path(p))
.collect::<Vec<_>>()
.join(", ")
));
} else if let Some(root) = r.output_roots.first() {
out.push_str(&format!(" output {}", escaped_path(root)));
}
if let Some(n) = r.before_bytes {
let label = if self.selector.is_some() {
"output-union before"
} else {
"before"
};
out.push_str(&format!(" {label} {}", crate::report::format_bytes(n)));
}
if let Some(n) = r.after_bytes {
let label = if self.selector.is_some() {
"output-union after"
} else {
"after"
};
out.push_str(&format!(" {label} {}", crate::report::format_bytes(n)));
}
if let Some(n) = r.observed_decrease {
out.push_str(&format!(
" observed decrease {}",
crate::report::format_bytes(n)
));
}
if !r.detail.is_empty() {
out.push_str(&format!(" — {}", r.detail.replace('\n', " ")));
}
out.push('\n');
}
match self.mode {
CleanMode::CargoPreview => {
out.push_str(&format!(
"\ncargo preview: {previewed} previewed, {skipped} skipped, {failed} failed; pre-clean estimate {}; no cleanup executed; {} filesystem diagnostics\n",
crate::report::format_bytes(before),
self.diagnostics
));
}
CleanMode::Simulate => {
out.push_str(&format!(
"\nsimulation: {simulated} would-clean, {skipped} skipped, {failed} failed; estimated would-clean {}; no `cargo clean` command was invoked; {} filesystem diagnostics\n",
crate::report::format_bytes(before),
self.diagnostics
));
}
CleanMode::Execute => {
out.push_str(&format!(
"\ncleanup: {cleaned} cleaned, {skipped} skipped, {failed} failed; pre-clean estimate {}, post-clean measured {}, observed decrease {}; {} filesystem diagnostics\n",
crate::report::format_bytes(before),
crate::report::format_bytes(after),
crate::report::format_bytes(delta),
self.diagnostics
));
}
}
out
}
}
fn escaped_path(path: &Path) -> String {
path.to_str()
.map(str::to_owned)
.unwrap_or_else(|| format!("{:?}", path.as_os_str()))
}
pub use workspace::{ProcessOutput, SystemCargoRunner};
pub trait CleanupRunner: Sync {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput>;
fn run_with_env(
&self,
cwd: &Path,
args: &[OsString],
env: &[(OsString, OsString)],
) -> io::Result<ProcessOutput>;
}
pub struct SystemCleanupRunner;
impl CargoRunner for SystemCleanupRunner {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
let output = Command::new("cargo").args(args).current_dir(cwd).output()?;
Ok(ProcessOutput {
success: output.status.success(),
code: output.status.code(),
stdout: output.stdout,
stderr: output.stderr,
})
}
}
impl CleanupRunner for SystemCleanupRunner {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
CargoRunner::run(self, cwd, args)
}
fn run_with_env(
&self,
cwd: &Path,
args: &[OsString],
env: &[(OsString, OsString)],
) -> io::Result<ProcessOutput> {
let mut cmd = Command::new("cargo");
cmd.args(args).current_dir(cwd);
for (k, v) in env {
cmd.env(k, v);
}
let output = cmd.output()?;
Ok(ProcessOutput {
success: output.status.success(),
code: output.status.code(),
stdout: output.stdout,
stderr: output.stderr,
})
}
}
fn output_text(output: &ProcessOutput) -> String {
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
[stdout.trim(), stderr.trim()]
.into_iter()
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join(" | ")
}
pub fn is_authorized(
group: &workspace::RawGroup,
clean_root: &Path,
allowed_roots: &[PathBuf],
) -> Result<bool, String> {
covering_is_authorized(group.ownership, &group.covering, clean_root, allowed_roots)
}
pub fn covering_is_authorized(
ownership: OutputOwnershipClass,
covering: &[PathBuf],
clean_root: &Path,
allowed_roots: &[PathBuf],
) -> Result<bool, String> {
covering_is_authorized_roots(
ownership,
covering,
std::slice::from_ref(&clean_root.to_path_buf()),
allowed_roots,
)
}
pub fn covering_is_authorized_roots(
ownership: OutputOwnershipClass,
covering: &[PathBuf],
clean_roots: &[PathBuf],
allowed_roots: &[PathBuf],
) -> Result<bool, String> {
if ownership != OutputOwnershipClass::PrivateBounded {
return Ok(false);
}
let mut canonical_allowed: Vec<PathBuf> = Vec::new();
for root in allowed_roots {
if !root.is_absolute() {
return Err(format!(
"cleanup authorization root must be absolute: {}",
root.display()
));
}
match fs::symlink_metadata(root) {
Err(e) if e.kind() == io::ErrorKind::NotFound => {
continue;
}
Err(e) => {
return Err(format!(
"cannot inspect cleanup authorization root {}: {e}",
root.display()
));
}
Ok(m) if m.file_type().is_symlink() || path_is_symlink(root) => {
return Err(format!(
"cleanup authorization root must not be a symlink: {}",
root.display()
));
}
Ok(m) if !m.is_dir() => {
continue;
}
Ok(_) => {}
}
match fs::canonicalize(root) {
Ok(canonical) => canonical_allowed.push(canonical),
Err(e) => {
return Err(format!(
"cannot resolve cleanup authorization root {}: {e}",
root.display()
));
}
}
}
let canonical_clean: Vec<PathBuf> = clean_roots
.iter()
.map(|root| {
fs::canonicalize(root)
.map_err(|e| format!("cannot resolve cleanup root {}: {e}", root.display()))
})
.collect::<Result<_, _>>()?;
for covering_root in covering {
if canonical_clean
.iter()
.any(|root| covering_root == root || covering_root.starts_with(root))
{
continue;
}
if canonical_allowed
.iter()
.any(|a| covering_root == a || covering_root.starts_with(a))
{
continue;
}
return Ok(false);
}
Ok(true)
}
pub fn ownership_skip_detail(ownership: OutputOwnershipClass) -> String {
match ownership {
OutputOwnershipClass::Shared => "shared output remains inventory-only".into(),
OutputOwnershipClass::Uncertain => "uncertain output remains inventory-only".into(),
OutputOwnershipClass::ExternalUnproven => {
"external output ownership is unproven; configured authorization does not establish exclusivity".into()
}
OutputOwnershipClass::PrivateBounded => {
"external output requires explicit cleanup authorization".into()
}
}
}
pub fn unit_block_reason(
unit: &workspace::CleanupUnit,
clean_root: &Path,
allowed_output_roots: &[PathBuf],
) -> Result<(), String> {
unit_block_reason_roots(
unit,
std::slice::from_ref(&clean_root.to_path_buf()),
allowed_output_roots,
)
}
fn unit_block_reason_roots(
unit: &workspace::CleanupUnit,
clean_roots: &[PathBuf],
allowed_output_roots: &[PathBuf],
) -> Result<(), String> {
if let Some(root) = unit.unmapped.first() {
return Err(format!(
"{} output {} has unproven physical identity; cleanup deferred",
match root.kind {
OutputRootKind::Target => "target",
OutputRootKind::Build => "build",
},
root.logical_path.display()
));
}
for group in &unit.groups {
if group.ownership != OutputOwnershipClass::PrivateBounded {
return Err(format!(
"{} output {} is {}; {}",
group.kind_label(),
group.display.display(),
group.ownership.label(),
ownership_skip_detail(group.ownership)
));
}
match covering_is_authorized_roots(
group.ownership,
&group.covering,
clean_roots,
allowed_output_roots,
) {
Ok(true) => {}
Ok(false) => {
return Err(format!(
"{} output {} is private but outside the authorized cleanup boundary; \
add a `cleanup.allowed_output_roots` entry or use a clean ROOT that contains it",
group.kind_label(),
group.display.display()
));
}
Err(msg) => return Err(msg),
}
if group.measured.is_none() {
let reason = group.skip.map_or("output is not eligible", |r| r.detail());
return Err(format!(
"{} output {} is not cleanable: {reason}",
group.kind_label(),
group.display.display()
));
}
}
Ok(())
}
fn is_authorization_infrastructure_error(detail: &str) -> bool {
detail.contains("cleanup authorization root") || detail.contains("cannot resolve cleanup root")
}
fn ownership_degraded_code(class: OutputOwnershipClass) -> CleanupReasonCode {
match class {
OutputOwnershipClass::Shared => CleanupReasonCode::SkippedShared,
OutputOwnershipClass::Uncertain => CleanupReasonCode::SkippedUncertain,
OutputOwnershipClass::ExternalUnproven => CleanupReasonCode::SkippedOwnershipUnproven,
OutputOwnershipClass::PrivateBounded => CleanupReasonCode::SkippedChangedBeforeCleanup,
}
}
fn covering_inspect_failure(err: io::Error) -> ProofFailure {
if err.kind() == io::ErrorKind::PermissionDenied {
return ProofFailure::new(
CleanupReasonCode::SkippedUncertain,
format!("preflight uncertain: cannot inspect covering root: {err}"),
);
}
ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
format!("preflight changed: cannot inspect covering root: {err}"),
)
}
pub fn clean(
root: &Path,
recency_seconds: u64,
allowed_output_roots: &[PathBuf],
mode: CleanMode,
) -> Result<CleanReport, AppError> {
clean_with(
root,
recency_seconds,
allowed_output_roots,
mode,
&SystemCleanupRunner,
&crate::progress::NoopObserver,
)
}
#[allow(clippy::too_many_arguments)]
pub fn clean_with(
root: &Path,
recency_seconds: u64,
allowed_output_roots: &[PathBuf],
mode: CleanMode,
runner: &dyn CleanupRunner,
observer: &dyn ProgressObserver,
) -> Result<CleanReport, AppError> {
clean_with_roots(
std::slice::from_ref(&root.to_path_buf()),
recency_seconds,
allowed_output_roots,
mode,
runner,
observer,
)
}
#[allow(clippy::too_many_arguments)]
pub fn clean_with_roots(
roots: &[PathBuf],
recency_seconds: u64,
allowed_output_roots: &[PathBuf],
mode: CleanMode,
runner: &dyn CleanupRunner,
observer: &dyn ProgressObserver,
) -> Result<CleanReport, AppError> {
clean_with_roots_policy(
roots,
recency_seconds,
allowed_output_roots,
mode,
runner,
observer,
&CleanupPolicy::default(),
)
}
#[allow(clippy::too_many_arguments)]
pub fn clean_with_roots_policy(
roots: &[PathBuf],
recency_seconds: u64,
allowed_output_roots: &[PathBuf],
mode: CleanMode,
runner: &dyn CleanupRunner,
observer: &dyn ProgressObserver,
policy: &CleanupPolicy,
) -> Result<CleanReport, AppError> {
clean_with_roots_policy_selector(
roots,
recency_seconds,
allowed_output_roots,
mode,
runner,
observer,
policy,
None,
)
}
#[allow(clippy::too_many_arguments)]
pub fn clean_with_roots_policy_selector(
roots: &[PathBuf],
recency_seconds: u64,
allowed_output_roots: &[PathBuf],
mode: CleanMode,
runner: &dyn CleanupRunner,
observer: &dyn ProgressObserver,
policy: &CleanupPolicy,
selector: Option<CleanupSelector>,
) -> Result<CleanReport, AppError> {
clean_with_roots_policy_selector_guarded(
roots,
recency_seconds,
allowed_output_roots,
mode,
runner,
observer,
policy,
selector,
None,
&CleanupSelection::All,
)
}
#[derive(Clone, Debug, Default)]
pub struct AdmissionPremise {
pub omitted: Vec<crate::policy::AutomaticOmission>,
}
struct ResolvedUniverse {
roots: Vec<PathBuf>,
cleanup_phase: ScanPhase,
counters: ScanCounters,
diagnostics: Vec<ScanDiagnostic>,
discovery_diagnostic_count: usize,
manifests: Vec<PathBuf>,
initial_manifests: Vec<PathBuf>,
workspaces: Vec<ResolvedWorkspace>,
units: Vec<workspace::CleanupUnit>,
unselected: Vec<workspace::CleanupUnit>,
unresolved_ownership: Vec<UnresolvedOwnershipParticipant>,
}
#[allow(clippy::too_many_arguments)]
fn discover_and_resolve_universe(
roots: &[PathBuf],
recency_seconds: u64,
mode: CleanMode,
runner: &dyn CleanupRunner,
observer: &dyn ProgressObserver,
selection: &CleanupSelection,
) -> Result<ResolvedUniverse, AppError> {
for root in roots {
validate_cleanup_root(root)?;
}
let roots = collapse_roots(roots.to_vec())?;
if roots.is_empty() {
return Err(AppError::InvalidRoot {
path: "<empty>".into(),
reason: "cleanup requires at least one bounded root".into(),
});
}
for root in &roots {
validate_cleanup_root(root)?;
}
let resolved = crate::domain::EffectiveScanPolicy {
recency: Duration::from_secs(recency_seconds),
scope: ScanScope::ExplicitRoots(roots.clone()),
discovery_filters: crate::domain::DiscoveryFilters::Bypassed,
};
let scan_start = SystemTime::now();
let cleanup_phase = match mode {
CleanMode::CargoPreview => ScanPhase::CleanupPreview,
CleanMode::Simulate => ScanPhase::CleanupSimulate,
CleanMode::Execute => ScanPhase::CleanupExecute,
};
observer.phase(cleanup_phase);
let discovery_start = std::time::Instant::now();
let discovered = discovery::discover_manifests(&resolved, observer)?;
let discovery_elapsed = discovery_start.elapsed();
let mut counters = discovered.counters.clone();
counters.discovery_nanos = counters
.discovery_nanos
.saturating_add(crate::domain::elapsed_nanos(discovery_elapsed));
let discovery_diagnostic_count = discovered.diagnostics.len();
let mut diagnostics: Vec<ScanDiagnostic> = discovered.diagnostics;
let manifests = discovered.manifests;
let mut initial_manifests = manifests.clone();
initial_manifests.sort();
let scope = resolve_cleanup_scope(
&manifests,
scan_start,
Duration::from_secs(recency_seconds),
runner,
&mut counters,
&mut diagnostics,
observer,
selection,
)?;
Ok(ResolvedUniverse {
roots,
cleanup_phase,
counters,
diagnostics,
discovery_diagnostic_count,
manifests,
initial_manifests,
workspaces: scope.workspaces,
units: scope.units,
unselected: scope.unselected,
unresolved_ownership: scope.unresolved,
})
}
#[allow(clippy::too_many_arguments)]
pub fn clean_with_roots_policy_selector_guarded(
roots: &[PathBuf],
recency_seconds: u64,
allowed_output_roots: &[PathBuf],
mode: CleanMode,
runner: &dyn CleanupRunner,
observer: &dyn ProgressObserver,
policy: &CleanupPolicy,
selector: Option<CleanupSelector>,
premise: Option<AdmissionPremise>,
selection: &CleanupSelection,
) -> Result<CleanReport, AppError> {
let includes = compile_policy_globs(&policy.include)?;
let excludes = compile_policy_globs(&policy.exclude)?;
let selector_capabilities = if selector.is_some() {
runtime_clean_capabilities()
} else {
CargoCleanCapabilities::default()
};
let universe =
discover_and_resolve_universe(roots, recency_seconds, mode, runner, observer, selection)?;
let ResolvedUniverse {
roots,
cleanup_phase,
mut counters,
diagnostics,
discovery_diagnostic_count,
manifests,
initial_manifests,
workspaces,
units,
unselected,
unresolved_ownership,
} = universe;
let mut report = CleanReport {
results: Vec::new(),
diagnostics: diagnostics.len(),
failed: 0,
mode,
counters: ScanCounters::default(),
scope_blocked: None,
unresolved_ownership: unresolved_ownership.clone(),
selected_roots: roots.clone(),
discovered_manifests: manifests.len(),
resolved_workspaces: workspaces.len(),
units_considered: units.len(),
effective_policy: Some(policy.clone()),
selector: selector.clone(),
};
report.counters = counters.clone();
if discovery_diagnostic_count > 0 {
report.scope_blocked = Some(ScopeBlock::new(
ScopeBlockReason::IncompleteDiscovery,
format!(
"combined cleanup ownership universe is incomplete: {} discovery diagnostic(s); resolved {} workspace(s), considered {} cleanup unit(s); no cleanup commands were run",
discovery_diagnostic_count,
workspaces.len(),
units.len()
),
));
return Ok(report);
}
if !unresolved_ownership.is_empty() {
let unresolved = unresolved_ownership.len();
report.scope_blocked = Some(ScopeBlock::new(
ScopeBlockReason::OwnershipUnproven,
format!(
"cleanup ownership could not be proven: {unresolved} discovered Cargo {} did not resolve; no cleanup commands were run",
if unresolved == 1 {
"manifest"
} else {
"manifests"
}
),
));
report.unresolved_ownership = unresolved_ownership;
report.resolved_workspaces = workspaces.len();
return Ok(report);
}
observer.units_total(cleanup_phase, units.len() as u64);
for unit in &unselected {
let anchor = selection
.describe()
.unwrap_or_else(|| "the current selection".to_string());
report.results.push(CleanResult {
display_path: unit.root.clone(),
workspace_roots: vec![unit.root.clone()],
output_roots: unit.covering.clone(),
ownership: unit_blocking_class(unit),
outcome: CleanOutcome::Skipped,
policy_disposition: None,
reason_code: CleanupReasonCode::SkippedOutsideSelection,
before_bytes: Some(unit.bytes),
after_bytes: None,
observed_decrease: None,
detail: format!("workspace is outside {anchor}; it was proven and left untouched"),
});
}
let mut hoisted: Option<ProofUniverse> = None;
for unit in &units {
let skipped = |report: &mut CleanReport,
detail: String,
disposition: Option<PolicyDisposition>,
reason_code: CleanupReasonCode| {
report.results.push(CleanResult {
display_path: unit.root.clone(),
workspace_roots: vec![unit.root.clone()],
output_roots: unit.covering.clone(),
ownership: unit_blocking_class(unit),
outcome: CleanOutcome::Skipped,
policy_disposition: disposition,
reason_code,
before_bytes: Some(unit.bytes),
after_bytes: None,
observed_decrease: None,
detail,
});
};
if !includes.is_empty() && !includes.is_match(&unit.root) {
skipped(
&mut report,
"cleanup policy: workspace root is not included".into(),
Some(PolicyDisposition::NotIncluded),
CleanupReasonCode::NotIncluded,
);
observer.unit_completed(cleanup_phase);
continue;
}
if excludes.is_match(&unit.root) {
skipped(
&mut report,
"cleanup policy: workspace root is excluded".into(),
Some(PolicyDisposition::Excluded),
CleanupReasonCode::Excluded,
);
observer.unit_completed(cleanup_phase);
continue;
}
if matches!(selector.as_ref(), Some(CleanupSelector::Package(_)))
&& !selector_capabilities.package_selector
{
skipped(
&mut report,
"runtime Cargo package-clean capability is unknown or unsupported; no Cargo clean was invoked".into(),
None,
CleanupReasonCode::SelectorUnsupported,
);
observer.unit_completed(cleanup_phase);
continue;
}
if matches!(selector.as_ref(), Some(CleanupSelector::Profile(_)))
&& !selector_capabilities.profile_selector
{
skipped(
&mut report,
"runtime Cargo profile-clean capability is unknown or unsupported; no Cargo clean was invoked".into(),
None,
CleanupReasonCode::SelectorUnsupported,
);
observer.unit_completed(cleanup_phase);
continue;
}
if let Some(CleanupSelector::Package(spec)) = selector.as_ref() {
let Some(ws) = workspaces.get(unit.workspace_idx) else {
skipped(
&mut report,
format!(
"workspace index {} is out of bounds; cleanup deferred",
unit.workspace_idx
),
None,
CleanupReasonCode::SkippedSafety,
);
observer.unit_completed(cleanup_phase);
continue;
};
if resolve_package_spec(&ws.packages, spec).is_err() {
skipped(
&mut report,
format!("package spec {spec:?} is unknown or ambiguous in this workspace"),
None,
CleanupReasonCode::SelectorInvalid,
);
observer.unit_completed(cleanup_phase);
continue;
}
}
if selector.is_some() && policy.min_reclaimable_bytes != 0 {
skipped(
&mut report,
"selector-specific reclaimable bytes are unknown; minimum-size policy cannot be evaluated".into(),
Some(PolicyDisposition::SelectorEstimateUnavailable),
CleanupReasonCode::SelectorUnsupported,
);
observer.unit_completed(cleanup_phase);
continue;
}
if unit.bytes < policy.min_reclaimable_bytes {
skipped(
&mut report,
format!(
"cleanup policy: {0} bytes is below minimum {1}",
unit.bytes, policy.min_reclaimable_bytes
),
Some(PolicyDisposition::BelowMinimumSize),
CleanupReasonCode::BelowMinimumSize,
);
observer.unit_completed(cleanup_phase);
continue;
}
if let Err(msg) = unit_block_reason_roots(unit, &roots, allowed_output_roots) {
if is_authorization_infrastructure_error(&msg) {
report.scope_blocked = Some(ScopeBlock::new(
ScopeBlockReason::OwnershipUnproven,
format!(
"cleanup authorization could not be proven: {msg}; no cleanup commands were run"
),
));
report.counters = counters.clone();
return Ok(report);
}
skipped(&mut report, msg, None, unit_skip_code(unit));
observer.unit_completed(cleanup_phase);
continue;
}
if let Some(premise) = premise.as_ref()
&& let Some((path, reason)) =
crate::policy::recheck_admission_premise(&roots, &premise.omitted)
{
report.scope_blocked = Some(ScopeBlock::new(
ScopeBlockReason::IncompleteDiscovery,
format!(
"cleanup admission premise changed for {}: {reason}; no further cleanup commands were run",
path.display()
),
));
report.counters = counters.clone();
return Ok(report);
}
let hoisted = hoisted.get_or_insert_with(|| {
ProofUniverse::refresh(&workspaces, &roots, runner, &mut counters)
});
if let Err(failure) = hoisted.get() {
report.scope_blocked = Some(ScopeBlock::new(
ScopeBlockReason::OwnershipUnproven,
format!("{}; no cleanup commands were run", failure.detail),
));
report.counters = counters.clone();
return Ok(report);
}
let proof = match final_cleanup_proof_roots(
unit,
&workspaces,
&roots,
allowed_output_roots,
runner,
recency_seconds,
hoisted,
&mut counters,
true,
) {
Ok(p) => p,
Err(failure) => {
if is_authorization_infrastructure_error(&failure.detail) {
report.scope_blocked = Some(ScopeBlock::new(
ScopeBlockReason::OwnershipUnproven,
format!(
"cleanup authorization could not be proven: {}; no cleanup commands were run",
failure.detail
),
));
report.counters = counters.clone();
return Ok(report);
}
skipped(&mut report, failure.detail, None, failure.code);
observer.unit_completed(cleanup_phase);
continue;
}
};
if proof.pre_bytes < policy.min_reclaimable_bytes {
skipped(
&mut report,
format!(
"cleanup policy: fresh size {} bytes is below minimum {}",
proof.pre_bytes, policy.min_reclaimable_bytes
),
Some(PolicyDisposition::BelowMinimumSize),
CleanupReasonCode::BelowMinimumSize,
);
observer.unit_completed(cleanup_phase);
continue;
}
if let Some(seconds) = policy.min_inactive_seconds {
let Some(activity) = proof.newest_activity else {
skipped(
&mut report,
"cleanup policy: required activity timestamp is unavailable".into(),
Some(PolicyDisposition::TooRecentForPolicy),
CleanupReasonCode::TooRecentForPolicy,
);
observer.unit_completed(cleanup_phase);
continue;
};
let cutoff = SystemTime::now()
.checked_sub(Duration::from_secs(seconds))
.ok_or_else(|| {
AppError::Config("cleanup inactivity duration exceeds system time range".into())
})?;
if activity >= cutoff {
skipped(
&mut report,
"cleanup policy: workspace is too recent".into(),
Some(PolicyDisposition::TooRecentForPolicy),
CleanupReasonCode::TooRecentForPolicy,
);
observer.unit_completed(cleanup_phase);
continue;
}
}
{
let rediscovery_policy = crate::domain::EffectiveScanPolicy {
recency: Duration::ZERO,
scope: ScanScope::ExplicitRoots(roots.clone()),
discovery_filters: crate::domain::DiscoveryFilters::Bypassed,
};
match discovery::discover_manifests(&rediscovery_policy, &crate::progress::NoopObserver)
{
Ok(fresh) if fresh.diagnostics.is_empty() => {
let mut now = fresh.manifests;
now.sort();
if now != initial_manifests {
report.scope_blocked = Some(ScopeBlock::new(
ScopeBlockReason::IncompleteDiscovery,
"cleanup ownership universe changed: manifest set differs after proof; no further cleanup commands were run".into(),
));
report.counters = counters.clone();
return Ok(report);
}
}
_ => {
report.scope_blocked = Some(ScopeBlock::new(
ScopeBlockReason::IncompleteDiscovery,
"cleanup ownership universe could not be re-discovered after proof; no further cleanup commands were run".into(),
));
report.counters = counters.clone();
return Ok(report);
}
}
}
match mode {
CleanMode::Simulate => {
report.results.push(CleanResult {
display_path: unit.root.clone(),
workspace_roots: proof.workspace_roots.clone(),
output_roots: proof.covering.clone(),
ownership: proof.ownership,
outcome: CleanOutcome::Simulated,
policy_disposition: Some(PolicyDisposition::Selected),
reason_code: CleanupReasonCode::Simulated,
before_bytes: Some(proof.pre_bytes),
after_bytes: None,
observed_decrease: None,
detail: "simulation: no `cargo clean` command was invoked".into(),
});
observe_unit_groups(observer, unit);
observer.unit_completed(cleanup_phase);
}
CleanMode::CargoPreview | CleanMode::Execute => {
if let Some(premise) = premise.as_ref()
&& let Some((path, reason)) =
crate::policy::recheck_admission_premise(&roots, &premise.omitted)
{
report.scope_blocked = Some(ScopeBlock::new(
ScopeBlockReason::IncompleteDiscovery,
format!(
"cleanup admission premise changed for {}: {reason}; no further cleanup commands were run",
path.display()
),
));
report.counters = counters.clone();
return Ok(report);
}
let frozen = proof.frozen_env.clone();
if let Err(failure) = prove_covering_roots(&proof.covering) {
skipped(&mut report, failure.detail, None, failure.code);
observer.unit_completed(cleanup_phase);
continue;
}
if let Err(failure) = require_cargo_markers(&proof.covering) {
skipped(&mut report, failure.detail, None, failure.code);
observer.unit_completed(cleanup_phase);
continue;
}
let args = clean_args(&proof, mode, selector.as_ref());
let cwd = proof.workspace_root.clone();
let spawned = if frozen.is_empty() {
runner.run(&cwd, &args)
} else {
runner.run_with_env(&cwd, &args, &frozen)
};
let output = match spawned {
Ok(o) => o,
Err(e) => {
report.failed += 1;
report.results.push(CleanResult {
display_path: unit.root.clone(),
workspace_roots: proof.workspace_roots.clone(),
output_roots: proof.covering.clone(),
ownership: proof.ownership,
outcome: CleanOutcome::Failed,
policy_disposition: Some(PolicyDisposition::Selected),
reason_code: CleanupReasonCode::CargoFailed,
before_bytes: Some(proof.pre_bytes),
after_bytes: None,
observed_decrease: None,
detail: format!("could not start Cargo: {e}"),
});
observer.unit_completed(cleanup_phase);
continue;
}
};
if !output.success {
report.failed += 1;
report.results.push(CleanResult {
display_path: unit.root.clone(),
workspace_roots: proof.workspace_roots.clone(),
output_roots: proof.covering.clone(),
ownership: proof.ownership,
outcome: CleanOutcome::Failed,
policy_disposition: Some(PolicyDisposition::Selected),
reason_code: CleanupReasonCode::CargoFailed,
before_bytes: Some(proof.pre_bytes),
after_bytes: None,
observed_decrease: None,
detail: format!("Cargo exited {:?}: {}", output.code, output_text(&output)),
});
observer.unit_completed(cleanup_phase);
continue;
}
if mode == CleanMode::CargoPreview {
report.results.push(CleanResult {
display_path: unit.root.clone(),
workspace_roots: proof.workspace_roots.clone(),
output_roots: proof.covering.clone(),
ownership: proof.ownership,
outcome: CleanOutcome::Previewed,
policy_disposition: Some(PolicyDisposition::Selected),
reason_code: CleanupReasonCode::Previewed,
before_bytes: Some(proof.pre_bytes),
after_bytes: None,
observed_decrease: None,
detail: output_text(&output),
});
} else {
match measure_union(&proof.covering) {
Ok(after) => {
let decrease = proof.pre_bytes.saturating_sub(after);
report.results.push(CleanResult {
display_path: unit.root.clone(),
workspace_roots: proof.workspace_roots.clone(),
output_roots: proof.covering.clone(),
ownership: proof.ownership,
outcome: CleanOutcome::Cleaned,
policy_disposition: Some(PolicyDisposition::Selected),
reason_code: CleanupReasonCode::Cleaned,
before_bytes: Some(proof.pre_bytes),
after_bytes: Some(after),
observed_decrease: Some(decrease),
detail: output_text(&output),
});
}
Err(e) => {
report.results.push(CleanResult {
display_path: unit.root.clone(),
workspace_roots: proof.workspace_roots.clone(),
output_roots: proof.covering.clone(),
ownership: proof.ownership,
outcome: CleanOutcome::Cleaned,
policy_disposition: Some(PolicyDisposition::Selected),
reason_code: CleanupReasonCode::MeasurementFailed,
before_bytes: Some(proof.pre_bytes),
after_bytes: None,
observed_decrease: None,
detail: format!(
"Cargo succeeded; post-clean measurement failed: {e}"
),
});
report.diagnostics += 1;
}
}
}
observe_unit_groups(observer, unit);
observer.unit_completed(cleanup_phase);
}
}
}
report.counters = counters;
Ok(report)
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CleanupCandidate {
pub root: PathBuf,
pub bytes: u64,
pub ownership: OutputOwnershipClass,
}
impl CleanupCandidate {
pub fn provably_private(&self) -> bool {
self.ownership == OutputOwnershipClass::PrivateBounded
}
}
#[derive(Clone, Debug, Default)]
pub struct CandidateListing {
pub candidates: Vec<CleanupCandidate>,
pub scope_blocked: Option<ScopeBlock>,
pub unresolved_ownership: Vec<UnresolvedOwnershipParticipant>,
pub selected_roots: Vec<PathBuf>,
pub resolved_workspaces: usize,
pub diagnostics: usize,
}
pub fn list_cleanup_candidates(
roots: &[PathBuf],
recency_seconds: u64,
mode: CleanMode,
runner: &dyn CleanupRunner,
observer: &dyn ProgressObserver,
selection: &CleanupSelection,
) -> Result<CandidateListing, AppError> {
let universe =
discover_and_resolve_universe(roots, recency_seconds, mode, runner, observer, selection)?;
let scope_blocked = if universe.discovery_diagnostic_count > 0 {
Some(ScopeBlock::new(
ScopeBlockReason::IncompleteDiscovery,
format!(
"combined cleanup ownership universe is incomplete: {} discovery diagnostic(s); resolved {} workspace(s), considered {} cleanup unit(s); nothing can be selected",
universe.discovery_diagnostic_count,
universe.workspaces.len(),
universe.units.len()
),
))
} else if !universe.unresolved_ownership.is_empty() {
let unresolved = universe.unresolved_ownership.len();
Some(ScopeBlock::new(
ScopeBlockReason::OwnershipUnproven,
format!(
"cleanup ownership could not be proven: {unresolved} discovered Cargo {} did not resolve; nothing can be selected",
if unresolved == 1 {
"manifest"
} else {
"manifests"
}
),
))
} else {
None
};
let candidates = universe
.units
.iter()
.map(|unit| CleanupCandidate {
root: unit.root.clone(),
bytes: unit.bytes,
ownership: unit_blocking_class(unit),
})
.collect();
Ok(CandidateListing {
candidates,
scope_blocked,
unresolved_ownership: universe.unresolved_ownership,
selected_roots: universe.roots,
resolved_workspaces: universe.workspaces.len(),
diagnostics: universe.diagnostics.len(),
})
}
fn compile_policy_globs(patterns: &[String]) -> Result<globset::GlobSet, AppError> {
let mut builder = globset::GlobSetBuilder::new();
for pattern in patterns {
builder.add(globset::Glob::new(pattern).map_err(|e| {
AppError::Config(format!("invalid cleanup policy glob {pattern:?}: {e}"))
})?);
}
builder
.build()
.map_err(|e| AppError::Config(format!("invalid cleanup policy patterns: {e}")))
}
fn unit_skip_code(unit: &workspace::CleanupUnit) -> CleanupReasonCode {
if !unit.unmapped.is_empty() {
return CleanupReasonCode::SkippedUncertain;
}
for group in &unit.groups {
match group.ownership {
OutputOwnershipClass::Shared => return CleanupReasonCode::SkippedShared,
OutputOwnershipClass::Uncertain => return CleanupReasonCode::SkippedUncertain,
OutputOwnershipClass::ExternalUnproven => {
return CleanupReasonCode::SkippedOwnershipUnproven;
}
OutputOwnershipClass::PrivateBounded => {}
}
if group.measured.is_none() {
return match group.skip {
Some(
workspace::GroupSkipReason::ActiveSource
| workspace::GroupSkipReason::ActiveOutput,
) => CleanupReasonCode::SkippedActive,
Some(
workspace::GroupSkipReason::UncertainSource
| workspace::GroupSkipReason::UncertainOwnership
| workspace::GroupSkipReason::UncertainMeasurement,
) => CleanupReasonCode::SkippedUncertain,
_ => CleanupReasonCode::SkippedSafety,
};
}
}
CleanupReasonCode::SkippedUnauthorized
}
fn proof_skip_code(detail: &str) -> CleanupReasonCode {
if detail.contains("became active") || detail.contains("became recent") {
CleanupReasonCode::SkippedActive
} else if detail.contains("marker")
|| detail.contains("CACHEDIR")
|| detail.contains("signature")
{
CleanupReasonCode::SkippedMarkerInvalid
} else if detail.contains("uncertain") || detail.contains("cannot be established") {
CleanupReasonCode::SkippedUncertain
} else if detail.contains("changed before cleanup")
|| detail.contains("preflight changed")
|| detail.contains("overlap")
|| detail.contains("changed identity")
|| detail.contains("vanished")
|| detail.contains("disappeared")
{
CleanupReasonCode::SkippedChangedBeforeCleanup
} else if detail.contains("re-proven") {
CleanupReasonCode::SkippedOwnershipUnproven
} else {
CleanupReasonCode::SkippedSafety
}
}
fn unit_blocking_class(unit: &workspace::CleanupUnit) -> OutputOwnershipClass {
for group in &unit.groups {
if group.ownership != OutputOwnershipClass::PrivateBounded {
return group.ownership;
}
}
OutputOwnershipClass::PrivateBounded
}
fn observe_unit_groups(observer: &dyn ProgressObserver, unit: &workspace::CleanupUnit) {
for group in &unit.groups {
if let Some(m) = &group.measured {
observer.reportable_group(&group.display, m.bytes);
}
}
}
struct CleanupScope {
workspaces: Vec<ResolvedWorkspace>,
units: Vec<workspace::CleanupUnit>,
unselected: Vec<workspace::CleanupUnit>,
unresolved: Vec<UnresolvedOwnershipParticipant>,
}
#[allow(clippy::too_many_arguments)]
fn resolve_cleanup_scope(
manifests: &[PathBuf],
scan_start: SystemTime,
recency: Duration,
runner: &dyn CleanupRunner,
counters: &mut ScanCounters,
diagnostics: &mut Vec<ScanDiagnostic>,
observer: &dyn ProgressObserver,
selection: &CleanupSelection,
) -> Result<CleanupScope, AppError> {
let adapter = WorkspaceCleanupAdapter { runner };
let coverage = workspace::resolve_workspaces_with_coverage(
manifests,
&adapter,
counters,
diagnostics,
observer,
);
let unresolved = coverage.unresolved;
counters.unresolved_ownership = unresolved.len() as u64;
let workspaces = coverage.workspaces;
if !unresolved.is_empty() {
return Ok(CleanupScope {
workspaces,
units: Vec::new(),
unselected: Vec::new(),
unresolved,
});
}
let groups = workspace::build_groups(&workspaces);
let clock_cutoff = scan_start
.checked_sub(recency)
.ok_or_else(|| AppError::Config("recency window exceeds system time range".into()))?;
let outcomes = workspace::analyze_groups_detailed(
&workspaces,
groups,
scan_start,
clock_cutoff,
recency,
counters,
diagnostics,
observer,
);
let all_units = workspace::build_cleanup_units(&workspaces, &outcomes);
let mut units = Vec::with_capacity(all_units.len());
let mut unselected = Vec::new();
for unit in all_units {
if selection.admits(&unit.root) {
units.push(unit);
} else {
unselected.push(unit);
}
}
Ok(CleanupScope {
workspaces,
units,
unselected,
unresolved,
})
}
struct WorkspaceCleanupAdapter<'a> {
runner: &'a dyn CleanupRunner,
}
impl CargoRunner for WorkspaceCleanupAdapter<'_> {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<workspace::ProcessOutput> {
let out = CleanupRunner::run(self.runner, cwd, args)?;
Ok(workspace::ProcessOutput {
success: out.success,
code: out.code,
stdout: out.stdout,
stderr: out.stderr,
})
}
}
#[derive(Clone, Debug)]
pub struct ExecutionProof {
pub workspace_roots: Vec<PathBuf>,
pub workspace_root: PathBuf,
pub root_manifest: PathBuf,
pub canonical_members: Vec<PathBuf>,
pub target: PathBuf,
pub build: Option<PathBuf>,
pub capability: CargoCapabilities,
pub covering: Vec<PathBuf>,
pub pre_bytes: u64,
pub newest_activity: Option<SystemTime>,
pub ownership: OutputOwnershipClass,
pub frozen_env: Vec<(OsString, OsString)>,
}
type RevalidatedContext = ExecutionProof;
fn canon(path: &Path) -> PathBuf {
fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}
fn canon_strict(path: &Path) -> Option<PathBuf> {
fs::canonicalize(path).ok()
}
fn output_identity_strict(physical: &Option<PathBuf>, logical: &Path) -> Option<PathBuf> {
match physical {
Some(p) => Some(p.clone()),
None => canon_strict(logical),
}
}
fn output_identity_pair(
old: &OutputRoot,
new: &OutputRoot,
kind: &str,
unit_root: &Path,
) -> Result<(PathBuf, PathBuf), ProofFailure> {
if !old.exists && !new.exists {
if old.logical_path == new.logical_path {
return Ok((old.logical_path.clone(), new.logical_path.clone()));
}
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
format!(
"workspace changed before cleanup; skipped: {kind} changed (was {}, now {})",
old.logical_path.display(),
new.logical_path.display()
),
));
}
if old.exists != new.exists {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
format!(
"workspace changed before cleanup; skipped: {kind} appeared or disappeared (was {}, now {})",
old.logical_path.display(),
new.logical_path.display()
),
));
}
let old_canon =
output_identity_strict(&old.physical_path, &old.logical_path).ok_or_else(|| {
ProofFailure::new(
CleanupReasonCode::SkippedOwnershipUnproven,
format!(
"ownership could not be re-proven: {kind} of workspace {} cannot be resolved",
unit_root.display()
),
)
})?;
let new_canon =
output_identity_strict(&new.physical_path, &new.logical_path).ok_or_else(|| {
ProofFailure::new(
CleanupReasonCode::SkippedOwnershipUnproven,
format!(
"ownership could not be re-proven: {kind} of workspace {} cannot be resolved",
unit_root.display()
),
)
})?;
Ok((old_canon, new_canon))
}
fn path_is_symlink(path: &Path) -> bool {
if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
return true;
}
let mut spelling = path.as_os_str().to_string_lossy().into_owned();
loop {
let trimmed = spelling.trim_end_matches(['/', '\\']).to_owned();
if trimmed.ends_with("/.") || trimmed.ends_with("\\.") {
spelling = trimmed[..trimmed.len() - 1].to_owned();
continue;
}
spelling = trimmed;
break;
}
if !spelling.is_empty()
&& fs::symlink_metadata(&spelling).is_ok_and(|m| m.file_type().is_symlink())
{
return true;
}
false
}
fn validate_cleanup_root(root: &Path) -> Result<(), AppError> {
if !root.is_absolute() {
return Err(AppError::InvalidRoot {
path: root.display().to_string(),
reason: "cleanup requires an absolute sandbox root".into(),
});
}
let meta = fs::symlink_metadata(root).map_err(|e| AppError::InvalidRoot {
path: root.display().to_string(),
reason: e.to_string(),
})?;
if !meta.is_dir() || meta.file_type().is_symlink() || path_is_symlink(root) {
return Err(AppError::InvalidRoot {
path: root.display().to_string(),
reason: "expected a real directory".into(),
});
}
Ok(())
}
fn collapse_roots(roots: Vec<PathBuf>) -> Result<Vec<PathBuf>, AppError> {
let mut canonical = Vec::with_capacity(roots.len());
for p in roots {
match fs::canonicalize(&p) {
Ok(c) => canonical.push(c),
Err(e) => {
return Err(AppError::InvalidRoot {
path: p.display().to_string(),
reason: format!("cleanup root changed before collapse: {e}"),
});
}
}
}
let mut roots = canonical;
roots.sort();
roots.dedup();
let mut out: Vec<PathBuf> = Vec::new();
for root in roots {
if !out.iter().any(|parent| root.starts_with(parent)) {
out.push(root);
}
}
Ok(out)
}
fn resolve_as_far_as_possible(path: &Path) -> PathBuf {
if let Ok(canonical) = fs::canonicalize(path) {
return canonical;
}
let mut current = path;
let mut tail: Vec<OsString> = Vec::new();
while let Some(name) = current.file_name() {
tail.push(name.to_os_string());
let Some(parent) = current.parent() else {
break;
};
if let Ok(canonical) = fs::canonicalize(parent) {
let mut resolved = canonical;
for part in tail.iter().rev() {
resolved.push(part);
}
return resolved;
}
if parent.as_os_str().is_empty() {
break;
}
current = parent;
}
path.to_path_buf()
}
fn provable_output_paths(root: &OutputRoot) -> Vec<PathBuf> {
if let Some(physical) = &root.physical_path {
return vec![physical.clone()];
}
vec![resolve_as_far_as_possible(&root.logical_path)]
}
fn sorted_same(left: &[PathBuf], right: &[PathBuf]) -> bool {
let mut a = left.to_vec();
let mut b = right.to_vec();
a.sort();
b.sort();
a == b
}
const PROOF_REFRESH_CONCURRENCY_CAP: usize = 4;
struct ProofRefreshMeter<'a> {
runner: &'a dyn CleanupRunner,
active: &'a std::sync::atomic::AtomicUsize,
peak: &'a std::sync::atomic::AtomicUsize,
}
impl CleanupRunner for ProofRefreshMeter<'_> {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
let metadata = args.first().is_some_and(|arg| arg == "metadata");
if metadata {
let active = self
.active
.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
+ 1;
self.peak
.fetch_max(active, std::sync::atomic::Ordering::SeqCst);
}
let result = self.runner.run(cwd, args);
if metadata {
self.active
.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
}
result
}
fn run_with_env(
&self,
cwd: &Path,
args: &[OsString],
env: &[(OsString, OsString)],
) -> io::Result<ProcessOutput> {
self.runner.run_with_env(cwd, args, env)
}
}
fn refresh_one_proof_workspace(
workspace: &ResolvedWorkspace,
runner: &dyn CleanupRunner,
) -> (ScanCounters, Option<ResolvedWorkspace>) {
let adapter = WorkspaceCleanupAdapter { runner };
let mut proof_counters = ScanCounters::default();
let mut proof_diagnostics = Vec::new();
let fresh = workspace::refresh_workspace_from_root_manifest(
&workspace.root_manifest,
&adapter,
&mut proof_counters,
&mut proof_diagnostics,
&crate::progress::NoopObserver,
);
(proof_counters, fresh)
}
fn refresh_proof_universe(
universe: &[ResolvedWorkspace],
runner: &dyn CleanupRunner,
counters: &mut ScanCounters,
) -> Result<Vec<ResolvedWorkspace>, ProofFailure> {
refresh_proof_universe_with_limit(
universe,
runner,
counters,
std::thread::available_parallelism()
.map_or(1, usize::from)
.clamp(1, PROOF_REFRESH_CONCURRENCY_CAP),
)
}
struct ProofUniverse {
fresh: Option<Vec<ResolvedWorkspace>>,
failure: Option<ProofFailure>,
}
impl ProofUniverse {
fn refresh(
universe: &[ResolvedWorkspace],
clean_roots: &[PathBuf],
runner: &dyn CleanupRunner,
counters: &mut ScanCounters,
) -> Self {
match refresh_combined_universe(universe, clean_roots, runner, counters) {
Ok(fresh) => Self {
fresh: Some(fresh),
failure: None,
},
Err(reason) => Self {
fresh: None,
failure: Some(reason),
},
}
}
fn get(&self) -> Result<&[ResolvedWorkspace], ProofFailure> {
match (&self.fresh, &self.failure) {
(Some(fresh), _) => Ok(fresh),
(None, Some(reason)) => Err(reason.clone()),
(None, None) => Err(ProofFailure::new(
CleanupReasonCode::SkippedOwnershipUnproven,
"ownership could not be re-proven: no refreshed universe",
)),
}
}
}
fn refresh_combined_universe(
initial: &[ResolvedWorkspace],
roots: &[PathBuf],
runner: &dyn CleanupRunner,
counters: &mut ScanCounters,
) -> Result<Vec<ResolvedWorkspace>, ProofFailure> {
let policy = crate::domain::EffectiveScanPolicy {
recency: Duration::ZERO,
scope: ScanScope::ExplicitRoots(roots.to_vec()),
discovery_filters: crate::domain::DiscoveryFilters::Bypassed,
};
let discovered = discovery::discover_manifests(&policy, &crate::progress::NoopObserver)
.map_err(|e| {
ProofFailure::new(
CleanupReasonCode::SkippedOwnershipUnproven,
format!("ownership could not be re-proven: combined root discovery failed: {e}"),
)
})?;
if !discovered.diagnostics.is_empty() {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedOwnershipUnproven,
"ownership could not be re-proven: combined selected-root discovery is incomplete",
));
}
let adapter = WorkspaceCleanupAdapter { runner };
let mut diagnostics = Vec::new();
let mut refreshed_counters = ScanCounters::default();
let coverage = workspace::resolve_workspaces_with_coverage(
&discovered.manifests,
&adapter,
&mut refreshed_counters,
&mut diagnostics,
&crate::progress::NoopObserver,
);
counters.proof_cargo_metadata_calls = counters
.proof_cargo_metadata_calls
.saturating_add(refreshed_counters.cargo_metadata_calls);
counters.proof_cargo_metadata_nanos = counters
.proof_cargo_metadata_nanos
.saturating_add(refreshed_counters.cargo_metadata_nanos);
counters.proof_cargo_locate_calls = counters
.proof_cargo_locate_calls
.saturating_add(refreshed_counters.cargo_locate_calls);
counters.proof_cargo_locate_nanos = counters
.proof_cargo_locate_nanos
.saturating_add(refreshed_counters.cargo_locate_nanos);
if !coverage.unresolved.is_empty() {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedOwnershipUnproven,
format!(
"ownership could not be re-proven: combined selected-root universe has {} unresolved manifest(s); a workspace did not re-resolve",
coverage.unresolved.len()
),
));
}
let fresh = coverage.workspaces;
let ids: std::collections::HashSet<_> = fresh.iter().map(|w| w.id.clone()).collect();
if initial.iter().any(|w| !ids.contains(&w.id)) {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
"ownership could not be re-proven: a workspace changed identity or disappeared from the initial combined universe",
));
}
refresh_proof_universe(&fresh, runner, counters)
}
fn refresh_proof_universe_with_limit(
universe: &[ResolvedWorkspace],
runner: &dyn CleanupRunner,
counters: &mut ScanCounters,
worker_limit: usize,
) -> Result<Vec<ResolvedWorkspace>, ProofFailure> {
let concurrency = worker_limit.clamp(1, PROOF_REFRESH_CONCURRENCY_CAP);
let mut refreshed_universe = Vec::with_capacity(universe.len());
let mut peak_concurrency = 0usize;
for batch in universe.chunks(concurrency) {
let active = std::sync::atomic::AtomicUsize::new(0);
let peak = std::sync::atomic::AtomicUsize::new(0);
let outcomes = if batch.len() == 1 {
let meter = ProofRefreshMeter {
runner,
active: &active,
peak: &peak,
};
vec![refresh_one_proof_workspace(&batch[0], &meter)]
} else {
std::thread::scope(|scope| {
let handles: Vec<_> = batch
.iter()
.map(|ws| {
let meter = ProofRefreshMeter {
runner,
active: &active,
peak: &peak,
};
scope.spawn(move || refresh_one_proof_workspace(ws, &meter))
})
.collect();
handles
.into_iter()
.map(|handle| {
handle
.join()
.unwrap_or_else(|_| (ScanCounters::default(), None))
})
.collect::<Vec<_>>()
})
};
peak_concurrency = peak_concurrency.max(peak.load(std::sync::atomic::Ordering::SeqCst));
let mut failure: Option<ProofFailure> = None;
for (workspace, (proof_counters, fresh)) in batch.iter().zip(outcomes) {
counters.merge_proof(&proof_counters);
counters.proof_workspaces_refreshed =
counters.proof_workspaces_refreshed.saturating_add(1);
match fresh {
Some(fresh) if fresh.id == workspace.id && fresh.root == workspace.root => {
refreshed_universe.push(fresh);
}
Some(_) => {
failure.get_or_insert_with(|| {
ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
format!(
"ownership could not be re-proven: workspace {} changed identity",
workspace.root.display()
),
)
});
}
None => {
failure.get_or_insert_with(|| {
ProofFailure::new(
CleanupReasonCode::SkippedOwnershipUnproven,
format!(
"ownership could not be re-proven: workspace {} did not re-resolve",
workspace.root.display()
),
)
});
}
}
}
if let Some(reason) = failure {
counters.proof_metadata_peak_concurrency = counters
.proof_metadata_peak_concurrency
.max(peak_concurrency as u64);
return Err(reason);
}
}
counters.proof_metadata_peak_concurrency = counters
.proof_metadata_peak_concurrency
.max(peak_concurrency as u64);
refreshed_universe.sort_by(|a, b| a.root.cmp(&b.root));
Ok(refreshed_universe)
}
#[allow(clippy::too_many_arguments)]
pub fn final_cleanup_proof(
unit: &workspace::CleanupUnit,
universe: &[ResolvedWorkspace],
clean_root: &Path,
allowed_output_roots: &[PathBuf],
runner: &dyn CleanupRunner,
recency_seconds: u64,
counters: &mut ScanCounters,
) -> Result<ExecutionProof, ProofFailure> {
let clean_root_owned = clean_root.to_path_buf();
let clean_roots = std::slice::from_ref(&clean_root_owned);
let hoisted = ProofUniverse::refresh(universe, clean_roots, runner, counters);
final_cleanup_proof_roots(
unit,
universe,
clean_roots,
allowed_output_roots,
runner,
recency_seconds,
&hoisted,
counters,
false,
)
}
#[allow(clippy::too_many_arguments)]
fn final_cleanup_proof_roots(
unit: &workspace::CleanupUnit,
universe: &[ResolvedWorkspace],
clean_roots: &[PathBuf],
allowed_output_roots: &[PathBuf],
runner: &dyn CleanupRunner,
recency_seconds: u64,
hoisted: &ProofUniverse,
counters: &mut ScanCounters,
refresh_candidate: bool,
) -> Result<ExecutionProof, ProofFailure> {
if let Err(detail) = unit_block_reason_roots(unit, clean_roots, allowed_output_roots) {
let code = if is_authorization_infrastructure_error(&detail) {
CleanupReasonCode::SkippedSafety
} else {
unit_skip_code(unit)
};
return Err(ProofFailure::new(code, detail));
}
let hoisted_universe = hoisted.get()?;
let mut fresh_universe = hoisted_universe.to_vec();
if refresh_candidate {
let Some(index) = fresh_universe.iter().position(|w| w.id == unit.id) else {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedOwnershipUnproven,
"ownership could not be re-proven: workspace is outside the cleanup universe",
));
};
let (candidate_counters, fresh_candidate) =
refresh_one_proof_workspace(&fresh_universe[index], runner);
counters.merge_proof(&candidate_counters);
counters.proof_workspaces_refreshed = counters.proof_workspaces_refreshed.saturating_add(1);
match fresh_candidate {
Some(fresh) if fresh.id == unit.id && fresh.root == unit.root => {
fresh_universe[index] = fresh;
}
Some(_) => {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
format!(
"ownership could not be re-proven: workspace {} changed identity",
unit.root.display()
),
));
}
None => {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedOwnershipUnproven,
format!(
"ownership could not be re-proven: workspace {} did not re-resolve",
unit.root.display()
),
));
}
}
}
let fresh_groups = workspace::build_groups(&fresh_universe);
let fresh_ws = fresh_universe
.iter()
.find(|w| w.id == unit.id)
.ok_or_else(|| {
ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
format!(
"ownership could not be re-proven: workspace {} vanished",
unit.root.display()
),
)
})?;
let candidate = universe.iter().find(|w| w.id == unit.id).ok_or_else(|| {
ProofFailure::new(
CleanupReasonCode::SkippedOwnershipUnproven,
format!(
"ownership could not be re-proven: workspace {} is outside the cleanup universe",
unit.root.display()
),
)
})?;
let mut old_members: Vec<PathBuf> = Vec::with_capacity(candidate.members.len());
for m in &candidate.members {
let Some(c) = canon_strict(&m.source_root) else {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedOwnershipUnproven,
format!(
"ownership could not be re-proven: member source {} of workspace {} cannot be resolved",
m.source_root.display(),
unit.root.display()
),
));
};
old_members.push(c);
}
let mut new_members: Vec<PathBuf> = Vec::with_capacity(fresh_ws.members.len());
for m in &fresh_ws.members {
let Some(c) = canon_strict(&m.source_root) else {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedOwnershipUnproven,
format!(
"ownership could not be re-proven: member source {} of workspace {} cannot be resolved",
m.source_root.display(),
unit.root.display()
),
));
};
new_members.push(c);
}
old_members.sort();
new_members.sort();
if old_members != new_members {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
"workspace changed before cleanup; skipped: member set changed",
));
}
if candidate.packages != fresh_ws.packages {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
"workspace changed before cleanup; skipped: Cargo package identity set changed",
));
}
let (old_target_canon, new_target_canon) = output_identity_pair(
&candidate.output.target,
&fresh_ws.output.target,
"target",
&unit.root,
)?;
let (old_build_canon, new_build_canon) = output_identity_pair(
&candidate.output.build,
&fresh_ws.output.build,
"build-dir",
&unit.root,
)?;
if old_target_canon != new_target_canon {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
format!(
"workspace changed before cleanup; skipped: target changed (was {}, now {})",
old_target_canon.display(),
new_target_canon.display()
),
));
}
if old_build_canon != new_build_canon {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
format!(
"workspace changed before cleanup; skipped: build-dir changed (was {}, now {})",
old_build_canon.display(),
new_build_canon.display()
),
));
}
let fresh_affected = workspace::map_workspace_groups(fresh_ws, &fresh_groups);
if fresh_affected.len() != unit.groups.len() {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
"workspace changed before cleanup; skipped: physical output group set changed",
));
}
let mut fresh_covering: Vec<PathBuf> = Vec::new();
for gi in &fresh_affected {
let Some(g) = fresh_groups.get(*gi) else {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedSafety,
"fresh output graph index is out of bounds; cleanup deferred",
));
};
if g.ownership != OutputOwnershipClass::PrivateBounded {
return Err(ProofFailure::new(
ownership_degraded_code(g.ownership),
format!(
"ownership changed before cleanup; skipped: output {} is now {}; {}",
g.display.display(),
g.ownership.label(),
ownership_skip_detail(g.ownership)
),
));
}
fresh_covering.extend(g.covering.iter().cloned());
}
fresh_covering = workspace::outermost(&fresh_covering);
if !sorted_same(&fresh_covering, &unit.covering) {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
"workspace changed before cleanup; skipped: physical output shape changed",
));
}
for other in &fresh_universe {
if other.id == unit.id {
continue;
}
for root in [&other.output.target, &other.output.build] {
for other_path in provable_output_paths(root) {
if unit.covering.iter().any(|c| {
other_path == *c || other_path.starts_with(c) || c.starts_with(&other_path)
}) {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
format!(
"ownership changed before cleanup; skipped: another discovered workspace ({}) now overlaps cleaned output {}",
other.root.display(),
other_path.display()
),
));
}
}
}
for member in &other.members {
if let Some(c) = unit
.covering
.iter()
.find(|c| member.source_root == **c || member.source_root.starts_with(c))
{
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
format!(
"ownership changed before cleanup; skipped: source tree {} of another discovered workspace ({}) lies inside cleaned output {}",
member.source_root.display(),
other.root.display(),
c.display()
),
));
}
}
}
prove_covering_roots(&unit.covering)?;
let start = SystemTime::now();
let cutoff = start
.checked_sub(Duration::from_secs(recency_seconds))
.ok_or_else(|| {
ProofFailure::new(
CleanupReasonCode::SkippedSafety,
"recency window exceeds system time range",
)
})?;
let mut all_outputs: Vec<PathBuf> = Vec::new();
for other in &fresh_universe {
for root in [&other.output.target, &other.output.build] {
match &root.physical_path {
Some(p) => all_outputs.push(p.clone()),
None => all_outputs.push(root.logical_path.clone()),
}
}
}
let activity_start = std::time::Instant::now();
let mut newest_activity: Option<SystemTime> = None;
for member_root in workspace::workspace_member_roots(fresh_ws) {
match traverse::workspace_member_activity(&member_root, &all_outputs, start, cutoff) {
Ok(traverse::SourceActivity::Recent(_)) => {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedActive,
"workspace changed before cleanup; skipped: source became active",
));
}
Ok(traverse::SourceActivity::Quiet(t)) => {
if let Some(t) = t {
newest_activity = Some(newest_activity.map_or(t, |old| old.max(t)));
}
}
Err(()) => {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedUncertain,
"revalidation source activity uncertain",
));
}
}
}
counters.proof_source_activity_nanos = counters
.proof_source_activity_nanos
.saturating_add(crate::domain::elapsed_nanos(activity_start.elapsed()));
let sizing_start = std::time::Instant::now();
let mut fresh_bytes = 0u64;
for covering in &unit.covering {
let stats = traverse::measure_single_target(covering);
if stats.uncertain {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedUncertain,
"revalidation output measurement uncertain",
));
}
if stats.newest.is_some_and(|t| t >= cutoff || t > start) {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedActive,
"workspace changed before cleanup; skipped: output became active",
));
}
fresh_bytes = fresh_bytes.saturating_add(stats.bytes);
if let Some(t) = stats.newest {
newest_activity = Some(newest_activity.map_or(t, |old| old.max(t)));
}
}
counters.proof_output_sizing_nanos = counters
.proof_output_sizing_nanos
.saturating_add(crate::domain::elapsed_nanos(sizing_start.elapsed()));
require_cargo_markers(&unit.covering)?;
let target = fresh_ws
.output
.target
.physical_path
.clone()
.unwrap_or_else(|| fresh_ws.output.target.logical_path.clone());
let build = fresh_ws.output.build.physical_path.clone().or_else(|| {
if fresh_ws.output.build.logical_path != fresh_ws.output.target.logical_path {
Some(fresh_ws.output.build.logical_path.clone())
} else {
None
}
});
let build = if build.as_ref() == Some(&target) {
None
} else {
build
};
let provisional = ExecutionProof {
workspace_roots: vec![unit.root.clone()],
workspace_root: fresh_ws.root.clone(),
root_manifest: fresh_ws.root_manifest.clone(),
canonical_members: {
let mut v: Vec<PathBuf> = fresh_ws
.members
.iter()
.map(|m| canon(&m.source_root))
.collect();
v.sort();
v.dedup();
v
},
target,
build,
capability: fresh_ws.capability,
covering: unit.covering.clone(),
pre_bytes: fresh_bytes,
newest_activity,
ownership: OutputOwnershipClass::PrivateBounded,
frozen_env: Vec::new(),
};
let frozen = frozen_env(&provisional)?;
Ok(ExecutionProof {
frozen_env: frozen,
..provisional
})
}
fn prove_covering_roots(covering: &[PathBuf]) -> Result<(), ProofFailure> {
for root in covering {
match fs::symlink_metadata(root) {
Err(e) if e.kind() == io::ErrorKind::NotFound => {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
"preflight changed: covering root disappeared",
));
}
Err(e) => {
return Err(covering_inspect_failure(e));
}
Ok(m) if m.file_type().is_symlink() || path_is_symlink(root) => {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
"preflight changed: covering root became symlink",
));
}
Ok(m) if !m.is_dir() => {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedChangedBeforeCleanup,
"preflight changed: covering root changed type",
));
}
Ok(_) => {}
}
}
Ok(())
}
pub fn execute_pre_spawn_decision(
unit: &workspace::CleanupUnit,
universe: &[ResolvedWorkspace],
clean_root: &Path,
allowed_output_roots: &[PathBuf],
runner: &dyn CleanupRunner,
recency_seconds: u64,
) -> Result<ExecutionProof, ProofFailure> {
let mut counters = ScanCounters::default();
final_cleanup_proof(
unit,
universe,
clean_root,
allowed_output_roots,
runner,
recency_seconds,
&mut counters,
)
}
fn frozen_env(ctx: &RevalidatedContext) -> Result<Vec<(OsString, OsString)>, ProofFailure> {
if ctx.capability.env_build_dir_set
&& ctx.capability.build_dir == CargoBuildDirCapability::Unavailable
{
return Err(ProofFailure::new(
CleanupReasonCode::SkippedSafety,
"CARGO_BUILD_BUILD_DIR is set but runtime Cargo cannot prove separate build-dir; cleanup deferred",
));
}
let mut env = vec![(
OsString::from("CARGO_TARGET_DIR"),
ctx.target.as_os_str().to_owned(),
)];
match &ctx.build {
Some(build) => match ctx.capability.build_dir {
CargoBuildDirCapability::Distinct | CargoBuildDirCapability::Equal => env.push((
OsString::from("CARGO_BUILD_BUILD_DIR"),
build.as_os_str().to_owned(),
)),
CargoBuildDirCapability::Unavailable | CargoBuildDirCapability::Unknown => {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedSafety,
"Cargo reports a separate build directory without stable support; cleanup deferred",
));
}
},
None => env.push((
OsString::from("CARGO_BUILD_BUILD_DIR"),
ctx.target.as_os_str().to_owned(),
)),
}
Ok(env)
}
fn clean_args(
ctx: &RevalidatedContext,
mode: CleanMode,
selector: Option<&CleanupSelector>,
) -> Vec<OsString> {
let mut args = vec![OsString::from("clean")];
if mode == CleanMode::CargoPreview {
args.push(OsString::from("--dry-run"));
args.push(OsString::from("--verbose"));
}
args.push(OsString::from("--offline"));
args.push(OsString::from("--locked"));
args.push(OsString::from("--manifest-path"));
args.push(ctx.root_manifest.as_os_str().to_owned());
args.push(OsString::from("--target-dir"));
args.push(ctx.target.as_os_str().to_owned());
if let Some(CleanupSelector::Profile(profile)) = selector {
args.push(OsString::from("--profile"));
args.push(OsString::from(profile));
}
if let Some(CleanupSelector::Package(package)) = selector {
args.push(OsString::from("--package"));
args.push(OsString::from(package));
}
args
}
fn runtime_clean_capabilities() -> CargoCleanCapabilities {
let Ok(output) = Command::new("cargo").arg("--version").output() else {
return CargoCleanCapabilities::default();
};
if !output.status.success() {
return CargoCleanCapabilities::default();
}
let text = String::from_utf8_lossy(&output.stdout);
let Some(version) = text.split_whitespace().nth(1) else {
return CargoCleanCapabilities::default();
};
workspace::clean_capabilities_from_version(version)
}
fn resolve_package_spec<'a>(
packages: &'a [WorkspacePackage],
spec: &str,
) -> Result<&'a WorkspacePackage, PackageSpecResolutionError> {
let matches: Vec<_> = packages
.iter()
.filter(|package| {
package.name == spec
|| package.id == spec
|| format!("{}@{}", package.name, package.version) == spec
|| package_spec_name_version(spec).is_some_and(|(name, version)| {
package.name == name && semver_spec_matches(&package.version, version)
})
})
.collect();
let package = match matches.as_slice() {
[] => return Err(PackageSpecResolutionError::Unknown),
[package] => *package,
_ => return Err(PackageSpecResolutionError::Ambiguous),
};
if packages
.iter()
.filter(|candidate| candidate.name == package.name)
.count()
!= 1
{
return Err(PackageSpecResolutionError::Ambiguous);
}
Ok(package)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PackageSpecResolutionError {
Unknown,
Ambiguous,
}
fn package_spec_name_version(spec: &str) -> Option<(&str, &str)> {
let (name, version) = spec.split_once('@').or_else(|| spec.split_once(':'))?;
(!name.is_empty() && !version.is_empty() && !name.contains('+') && !name.contains("://"))
.then_some((name, version))
}
fn semver_spec_matches(actual: &str, requested: &str) -> bool {
if actual == requested {
return true;
}
let actual_parts: Vec<_> = actual.split('.').collect();
let requested_parts: Vec<_> = requested.split('.').collect();
(1..=2).contains(&requested_parts.len())
&& requested_parts
.iter()
.all(|part| part.bytes().all(|byte| byte.is_ascii_digit()))
&& actual_parts.len() == 3
&& actual_parts
.iter()
.all(|part| part.bytes().all(|byte| byte.is_ascii_digit()))
&& actual_parts
.iter()
.zip(requested_parts)
.all(|(actual, requested)| actual == &requested)
}
fn require_cargo_markers(covering: &[PathBuf]) -> Result<(), ProofFailure> {
for root in covering {
let tag = root.join("CACHEDIR.TAG");
let meta = fs::symlink_metadata(&tag).map_err(|_| {
ProofFailure::new(
CleanupReasonCode::SkippedMarkerInvalid,
"Cargo CACHEDIR.TAG marker is missing; cleanup deferred",
)
})?;
if !meta.is_file() || meta.file_type().is_symlink() {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedMarkerInvalid,
"Cargo CACHEDIR.TAG is not a regular file; cleanup deferred",
));
}
let bytes = fs::read(&tag).map_err(|e| {
ProofFailure::new(
CleanupReasonCode::SkippedMarkerInvalid,
format!("cannot read Cargo cache marker: {e}"),
)
})?;
if !bytes.starts_with(b"Signature: 8a477f597d28d172789f06886806bc55") {
return Err(ProofFailure::new(
CleanupReasonCode::SkippedMarkerInvalid,
"target directory does not have Cargo's cache marker signature; cleanup deferred",
));
}
}
Ok(())
}
fn measure_union(covering: &[PathBuf]) -> io::Result<u64> {
let mut total = 0u64;
for root in covering {
match fs::symlink_metadata(root) {
Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
Err(e) => return Err(e),
Ok(m) if !m.is_dir() || m.file_type().is_symlink() => {
return Err(io::Error::other("output path changed type"));
}
Ok(_) => {}
}
let stats = traverse::measure_single_target(root);
if stats.uncertain {
return Err(io::Error::other("post-clean measurement was uncertain"));
}
total = total.saturating_add(stats.bytes);
}
Ok(total)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::progress::NoopObserver;
use std::ffi::OsStr;
use std::sync::Mutex;
use tempfile::TempDir;
#[test]
fn ancestry_selection_matches_in_both_directions() {
let member = Path::new("/home/u/projects");
assert!(
CleanupSelection::Ancestry(member.to_path_buf())
.admits(Path::new("/home/u/projects/crates/inner")),
"a workspace containing the anchor must be selected"
);
assert!(
CleanupSelection::Ancestry(member.to_path_buf())
.admits(Path::new("/home/u/projects/crates/inner")),
"a workspace below the anchor must be selected"
);
assert!(
CleanupSelection::Ancestry(member.to_path_buf()).admits(member),
"the anchor itself must be selected"
);
assert!(
!CleanupSelection::Ancestry(member.to_path_buf())
.admits(Path::new("/var/tmp/elsewhere")),
"an unrelated workspace must not be selected"
);
assert!(
!CleanupSelection::Ancestry(member.to_path_buf())
.admits(Path::new("/home/u/projects-old")),
"a string-prefix sibling must not be selected"
);
}
#[test]
fn roots_selection_matches_exactly() {
let selection =
CleanupSelection::Roots(vec![PathBuf::from("/a/one"), PathBuf::from("/a/two")]);
assert!(selection.admits(Path::new("/a/one")));
assert!(selection.admits(Path::new("/a/two")));
assert!(
!selection.admits(Path::new("/a/one/nested")),
"an exact-root selection must not sweep in children"
);
assert!(!selection.admits(Path::new("/a/three")));
}
#[test]
fn outside_selection_is_reported_rather_than_silently_dropped() {
assert_eq!(
CleanupReasonCode::SkippedOutsideSelection.as_str(),
"skipped_outside_selection"
);
for other in [
CleanupReasonCode::SkippedShared,
CleanupReasonCode::SkippedOwnershipUnproven,
CleanupReasonCode::SkippedSafety,
] {
assert_ne!(other.as_str(), "skipped_outside_selection");
}
}
#[test]
fn missing_output_identity_pair_compares_equal_not_unproven() {
use crate::domain::OutputRootKind;
let missing = |logical: PathBuf| OutputRoot {
kind: OutputRootKind::Build,
logical_path: logical,
physical_path: None,
exists: false,
is_symlink: false,
};
let unit_root = PathBuf::from("/ws");
let old = missing(PathBuf::from("/ws/build"));
let new = missing(PathBuf::from("/ws/build"));
let (a, b) = output_identity_pair(&old, &new, "build-dir", &unit_root).unwrap();
assert_eq!(a, b);
let present = OutputRoot {
kind: OutputRootKind::Build,
logical_path: PathBuf::from("/ws/build"),
physical_path: Some(PathBuf::from("/ws/build")),
exists: true,
is_symlink: false,
};
let err = output_identity_pair(&old, &present, "build-dir", &unit_root).unwrap_err();
assert_eq!(err.code, CleanupReasonCode::SkippedChangedBeforeCleanup);
}
type RecordedCall = (PathBuf, Vec<OsString>, Vec<(OsString, OsString)>);
struct FakeCleanupRunner {
calls: Mutex<Vec<RecordedCall>>,
workspace_root: PathBuf,
target: PathBuf,
build: Option<PathBuf>,
members: usize,
remove_on_execute: bool,
unresolved_manifest: Option<PathBuf>,
}
impl FakeCleanupRunner {
fn new(root: &Path, target: &Path, members: usize) -> Self {
Self {
calls: Mutex::new(Vec::new()),
workspace_root: root.to_path_buf(),
target: target.to_path_buf(),
build: None,
members,
remove_on_execute: false,
unresolved_manifest: None,
}
}
fn calls(&self) -> Vec<RecordedCall> {
self.calls.lock().unwrap().clone()
}
fn clean_calls(&self) -> Vec<RecordedCall> {
self.calls()
.into_iter()
.filter(|(_, args, _)| args.first().is_some_and(|a| a == "clean"))
.collect()
}
}
impl CargoRunner for FakeCleanupRunner {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
self.calls
.lock()
.unwrap()
.push((cwd.to_path_buf(), args.to_vec(), Vec::new()));
if args.first().is_some_and(|a| a == "locate-project") {
if self.unresolved_manifest.as_ref().is_some_and(|p| {
args.last()
.is_some_and(|arg| canon(Path::new(arg)) == canon(p))
}) {
return Ok(ProcessOutput {
success: false,
code: Some(1),
stdout: Vec::new(),
stderr: b"unresolved participant".to_vec(),
});
}
let root_manifest = self.workspace_root.join("Cargo.toml");
let json = serde_json::json!({"root": root_manifest});
return Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: serde_json::to_vec(&json).unwrap(),
stderr: Vec::new(),
});
}
if args.first().is_some_and(|a| a == "metadata") {
let members: Vec<String> = (0..self.members).map(|i| format!("m{i}")).collect();
let mut packages = Vec::new();
for i in 0..self.members {
let mp = self.workspace_root.join(format!("member{i}/Cargo.toml"));
packages.push(serde_json::json!({
"id": format!("m{i}"),
"name": format!("m{i}"),
"manifest_path": mp,
}));
}
if self.members == 1 {
packages = vec![serde_json::json!({
"id": "m0",
"name": "m0",
"manifest_path": self.workspace_root.join("Cargo.toml"),
})];
}
let mut json = serde_json::json!({
"packages": packages,
"workspace_members": members,
"workspace_root": self.workspace_root,
"target_directory": self.target,
});
if let Some(b) = &self.build {
json["build_directory"] = serde_json::json!(b);
}
return Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: serde_json::to_vec(&json).unwrap(),
stderr: Vec::new(),
});
}
if self.remove_on_execute && !args.iter().any(|a| a == "--dry-run") {
let target = args
.windows(2)
.find(|pair| pair[0] == "--target-dir")
.map(|pair| PathBuf::from(&pair[1]));
if let Some(t) = target
&& t.join("artifact.bin").exists()
{
let _ = fs::remove_file(t.join("artifact.bin"));
}
}
Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: b"mock cargo clean success".to_vec(),
stderr: Vec::new(),
})
}
}
impl CleanupRunner for FakeCleanupRunner {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
CargoRunner::run(self, cwd, args)
}
fn run_with_env(
&self,
cwd: &Path,
args: &[OsString],
env: &[(OsString, OsString)],
) -> io::Result<ProcessOutput> {
self.calls
.lock()
.unwrap()
.push((cwd.to_path_buf(), args.to_vec(), env.to_vec()));
if args.first().is_some_and(|a| a == "clean") {
if self.remove_on_execute && !args.iter().any(|a| a == "--dry-run") {
let target = args
.windows(2)
.find(|pair| pair[0] == "--target-dir")
.map(|pair| PathBuf::from(&pair[1]));
if let Some(t) = target
&& t.join("artifact.bin").exists()
{
let _ = fs::remove_file(t.join("artifact.bin"));
}
}
return Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: b"mock cargo clean success".to_vec(),
stderr: Vec::new(),
});
}
CargoRunner::run(self, cwd, args)
}
}
fn valid_fixture(members: usize) -> (TempDir, PathBuf, PathBuf) {
let d = tempfile::Builder::new()
.prefix("cargo-cleanme-m005b-")
.tempdir()
.unwrap();
let root = d.path().join("ws");
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(
root.join("Cargo.toml"),
"[package]\nname='ws'\nversion='0.1.0'\nedition='2021'\n",
)
.unwrap();
std::fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap();
std::fs::write(root.join("Cargo.lock"), "version = 4\n").unwrap();
let target = root.join("target");
std::fs::create_dir_all(&target).unwrap();
std::fs::write(
target.join("CACHEDIR.TAG"),
b"Signature: 8a477f597d28d172789f06886806bc55\n",
)
.unwrap();
std::fs::write(target.join("artifact.bin"), vec![7u8; 4096]).unwrap();
let old = SystemTime::now() - Duration::from_secs(3600);
backdate(d.path(), old);
let _ = members;
(d, root, target)
}
fn backdate(path: &Path, old: SystemTime) {
let mut stack = vec![path.to_path_buf()];
while let Some(current) = stack.pop() {
if let Ok(meta) = fs::symlink_metadata(¤t) {
if meta.file_type().is_symlink() {
continue;
}
if meta.is_dir()
&& let Ok(children) = fs::read_dir(¤t)
{
for child in children.flatten() {
stack.push(child.path());
}
}
}
if let Ok(f) = fs::OpenOptions::new().write(true).open(¤t) {
let _ = f.set_modified(old);
} else if let Ok(dir) = fs::File::open(¤t) {
let _ = dir.set_modified(old);
}
}
if let Ok(dir) = fs::File::open(path) {
let _ = dir.set_modified(old);
}
}
#[test]
fn cli_modes_map_to_preview_simulate_execute() {
assert_eq!(CleanMode::CargoPreview.as_str(), "preview");
assert_eq!(CleanMode::Simulate.as_str(), "simulate");
assert_eq!(CleanMode::Execute.as_str(), "execute");
assert_ne!(CleanMode::CargoPreview, CleanMode::Simulate);
assert_ne!(CleanMode::Simulate, CleanMode::Execute);
assert_eq!(
crate::cli::clean_mode(false, false, false),
CleanMode::Execute,
"absent a mode flag, cleanup executes"
);
assert_eq!(
crate::cli::clean_mode(true, false, false),
CleanMode::Simulate
);
assert_eq!(
crate::cli::clean_mode(false, true, false),
CleanMode::CargoPreview
);
assert_eq!(
crate::cli::clean_mode(false, false, true),
CleanMode::Simulate,
"the hidden --dryrun alias maps to the canonical Simulate mode"
);
}
#[test]
fn policy_dispositions_have_stable_json_names() {
let values = [
(PolicyDisposition::Selected, "selected"),
(PolicyDisposition::BelowMinimumSize, "below_minimum_size"),
(
PolicyDisposition::TooRecentForPolicy,
"too_recent_for_policy",
),
(PolicyDisposition::NotIncluded, "not_included"),
(PolicyDisposition::Excluded, "excluded"),
];
for (value, expected) in values {
assert_eq!(
serde_json::to_string(&value).unwrap(),
format!("\"{expected}\"")
);
}
}
#[test]
fn cleanup_reason_codes_have_stable_contract_names() {
use CleanupReasonCode::*;
let expected = [
(Previewed, "previewed"),
(Simulated, "simulated"),
(Cleaned, "cleaned"),
(BelowMinimumSize, "below_minimum_size"),
(TooRecentForPolicy, "too_recent_for_policy"),
(NotIncluded, "not_included"),
(Excluded, "excluded"),
(SkippedActive, "skipped_active"),
(SkippedShared, "skipped_shared"),
(SkippedUncertain, "skipped_uncertain"),
(SkippedUnauthorized, "skipped_unauthorized"),
(SkippedMarkerInvalid, "skipped_marker_invalid"),
(
SkippedChangedBeforeCleanup,
"skipped_changed_before_cleanup",
),
(SkippedSafety, "skipped_safety"),
(CargoFailed, "cargo_failed"),
(MeasurementFailed, "measurement_failed"),
];
for (code, stable) in expected {
assert_eq!(code.as_str(), stable);
}
}
#[test]
fn profile_selector_capability_is_bounded_to_qualified_runtime_versions() {
assert!(workspace::clean_capabilities_from_version("1.89.0").profile_selector);
assert!(workspace::clean_capabilities_from_version("1.90.0").profile_selector);
assert!(workspace::clean_capabilities_from_version("1.95.0").profile_selector);
assert!(workspace::clean_capabilities_from_version("1.99.0").profile_selector);
assert!(!workspace::clean_capabilities_from_version("1.88.0").profile_selector);
assert!(!workspace::clean_capabilities_from_version("1.96.0").profile_selector);
assert!(!workspace::clean_capabilities_from_version("1.99.1").profile_selector);
assert!(!workspace::clean_capabilities_from_version("2.0.0").profile_selector);
assert!(!workspace::clean_capabilities_from_version("unknown").profile_selector);
assert!(workspace::clean_capabilities_from_version("1.98.1").package_selector);
assert!(workspace::clean_capabilities_from_version("1.99.0").package_selector);
assert!(!workspace::clean_capabilities_from_version("1.100.0").package_selector);
assert!(!workspace::clean_capabilities_from_version("1.99.0-nightly").package_selector);
}
#[test]
fn package_specs_require_one_authoritative_workspace_identity() {
let packages = vec![
WorkspacePackage {
id: "path+file:///tmp/ws#alpha@0.1.0".into(),
name: "alpha".into(),
version: "0.1.0".into(),
manifest_path: PathBuf::from("/tmp/ws/alpha/Cargo.toml"),
},
WorkspacePackage {
id: "path+file:///tmp/ws#shared@0.2.0".into(),
name: "shared".into(),
version: "0.2.0".into(),
manifest_path: PathBuf::from("/tmp/ws/shared/Cargo.toml"),
},
];
assert_eq!(
resolve_package_spec(&packages, "alpha").unwrap().name,
"alpha"
);
assert_eq!(
resolve_package_spec(&packages, "alpha@0.1").unwrap().name,
"alpha"
);
assert_eq!(
resolve_package_spec(&packages, "alpha@0.1.0").unwrap().id,
packages[0].id
);
assert_eq!(
resolve_package_spec(&packages, &packages[1].id)
.unwrap()
.name,
"shared"
);
assert!(resolve_package_spec(&packages, "missing").is_err());
let mut duplicate = packages.clone();
duplicate.push(WorkspacePackage {
id: "registry+https://example.invalid#alpha@0.3.0".into(),
name: "alpha".into(),
version: "0.3.0".into(),
manifest_path: PathBuf::from("/tmp/ws/alpha2/Cargo.toml"),
});
assert!(resolve_package_spec(&duplicate, "alpha").is_err());
assert!(resolve_package_spec(&duplicate, "alpha@0.3.0").is_err());
}
fn mixed_ownership_fixture() -> (TempDir, PathBuf, PathBuf, PathBuf, PathBuf) {
let d = tempfile::Builder::new()
.prefix("cargo-cleanme-m014-")
.tempdir()
.unwrap();
let root = d.path().canonicalize().unwrap().join("projects"); let mut workspaces = Vec::new();
for name in ["alpha", "beta", "gamma"] {
let ws = root.join(name);
std::fs::create_dir_all(ws.join("src")).unwrap();
std::fs::write(
ws.join("Cargo.toml"),
format!("[package]\nname='{name}'\nversion='0.1.0'\nedition='2021'\n"),
)
.unwrap();
std::fs::write(ws.join("src/main.rs"), "fn main() {}\n").unwrap();
std::fs::write(ws.join("Cargo.lock"), "version = 4\n").unwrap();
workspaces.push(ws);
}
for name in ["alpha", "beta"] {
let target = root.join(name).join("target");
std::fs::create_dir_all(&target).unwrap();
std::fs::write(
target.join("CACHEDIR.TAG"),
b"Signature: 8a477f597d28d172789f06886806bc55\n",
)
.unwrap();
std::fs::write(target.join("artifact.bin"), vec![7u8; 4096]).unwrap();
}
let redirected = root.join("alpha").join("target").display().to_string();
std::fs::create_dir_all(root.join("gamma").join(".cargo")).unwrap();
std::fs::write(
root.join("gamma").join(".cargo/config.toml"),
format!("[build]\ntarget-dir = {redirected:?}\n"), )
.unwrap();
let old = SystemTime::now() - Duration::from_secs(3600);
backdate(d.path(), old);
(
d,
root,
workspaces[0].clone(),
workspaces[1].clone(),
workspaces[2].clone(),
)
}
#[test]
fn the_candidate_listing_is_the_engines_own_unit_set() {
let (_d, root, _alpha, beta, _gamma) = mixed_ownership_fixture();
let noop = NoopObserver;
let all = list_cleanup_candidates(
std::slice::from_ref(&root),
0,
CleanMode::Simulate,
&SystemCleanupRunner,
&noop,
&CleanupSelection::All,
)
.unwrap();
assert!(all.scope_blocked.is_none(), "{:?}", all.scope_blocked);
assert_eq!(
all.candidates.len(),
3,
"every resolved unit must be offered: {:?}",
all.candidates
);
assert!(
all.candidates.iter().all(|c| c.bytes > 0),
"rows carry real measured bytes: {:?}",
all.candidates
);
assert!(
all.candidates
.iter()
.any(|c| c.ownership != OutputOwnershipClass::PrivateBounded),
"the fixture must include a non-private unit: {:?}",
all.candidates
);
let report = clean_with_roots_policy_selector_guarded(
std::slice::from_ref(&root),
0,
&[],
CleanMode::Simulate,
&SystemCleanupRunner,
&noop,
&CleanupPolicy::default(),
None,
None,
&CleanupSelection::All,
)
.unwrap();
let mut listed: Vec<(PathBuf, u64, &'static str)> = all
.candidates
.iter()
.map(|c| (c.root.clone(), c.bytes, c.ownership.label()))
.collect();
listed.sort_by(|a, b| a.0.cmp(&b.0));
let mut engine: Vec<(PathBuf, u64, &'static str)> = report
.results
.iter()
.filter(|r| r.reason_code != CleanupReasonCode::SkippedOutsideSelection)
.map(|r| {
(
r.display_path.clone(),
r.before_bytes.unwrap_or(0),
r.ownership.label(),
)
})
.collect();
engine.sort_by(|a, b| a.0.cmp(&b.0));
assert_eq!(
listed, engine,
"the interactive list and the engine must agree on units, bytes, and ownership"
);
let narrowed = CleanupSelection::Roots(vec![beta.clone()]);
let listed_narrow = list_cleanup_candidates(
std::slice::from_ref(&root),
0,
CleanMode::Simulate,
&SystemCleanupRunner,
&noop,
&narrowed,
)
.unwrap();
assert_eq!(
listed_narrow.candidates.len(),
1,
"the listing honours the selection: {:?}",
listed_narrow.candidates
);
assert_eq!(listed_narrow.candidates[0].root, beta);
let engine_narrow = clean_with_roots_policy_selector_guarded(
std::slice::from_ref(&root),
0,
&[],
CleanMode::Simulate,
&SystemCleanupRunner,
&noop,
&CleanupPolicy::default(),
None,
None,
&narrowed,
)
.unwrap();
let considered: Vec<&PathBuf> = engine_narrow
.results
.iter()
.filter(|r| r.reason_code != CleanupReasonCode::SkippedOutsideSelection)
.map(|r| &r.display_path)
.collect();
let excluded: Vec<&PathBuf> = engine_narrow
.results
.iter()
.filter(|r| r.reason_code == CleanupReasonCode::SkippedOutsideSelection)
.map(|r| &r.display_path)
.collect();
assert_eq!(considered, vec![&beta], "the engine honours it too");
assert_eq!(
excluded.len(),
2,
"every deselected unit is reported, not silently dropped: {excluded:?}"
);
}
#[test]
fn the_listing_never_spawns_a_clean() {
let (_d, root, alpha, beta, _gamma) = mixed_ownership_fixture();
let listing = list_cleanup_candidates(
std::slice::from_ref(&root),
0,
CleanMode::Execute,
&SystemCleanupRunner,
&NoopObserver,
&CleanupSelection::All,
)
.unwrap();
assert_eq!(listing.candidates.len(), 3);
for ws in [alpha, beta] {
assert!(
ws.join("target").join("artifact.bin").exists(),
"{} survived the listing",
ws.display()
);
}
}
#[test]
fn an_unproven_universe_blocks_the_listing_rather_than_offering_rows() {
let (_d, root, target) = valid_fixture(1);
let mut runner = FakeCleanupRunner::new(&root, &target, 1);
runner.unresolved_manifest = Some(root.join("Cargo.toml"));
let noop = NoopObserver;
let listing = list_cleanup_candidates(
std::slice::from_ref(&root),
0,
CleanMode::Simulate,
&runner,
&noop,
&CleanupSelection::All,
)
.unwrap();
let block = listing
.scope_blocked
.expect("an unresolved manifest must block the listing");
assert_eq!(block.reason, ScopeBlockReason::OwnershipUnproven);
assert!(
!listing.unresolved_ownership.is_empty(),
"the block must name the participant, not only count it"
);
assert!(
listing.candidates.is_empty(),
"no rows may be offered from an unproven universe: {:?}",
listing.candidates
);
assert!(runner.clean_calls().is_empty());
}
#[test]
fn a_candidate_row_states_when_it_cannot_be_cleaned() {
let shared = CleanupCandidate {
root: PathBuf::from("/ws/shared"),
bytes: 10,
ownership: OutputOwnershipClass::Shared,
};
let private = CleanupCandidate {
root: PathBuf::from("/ws/private"),
bytes: 10,
ownership: OutputOwnershipClass::PrivateBounded,
};
let uncertain = CleanupCandidate {
root: PathBuf::from("/ws/uncertain"),
bytes: 10,
ownership: OutputOwnershipClass::Uncertain,
};
assert!(!shared.provably_private());
assert!(!uncertain.provably_private());
assert!(private.provably_private());
let mut empty = private.clone();
empty.bytes = 0;
assert!(
empty.provably_private(),
"byte size must not affect an ownership projection"
);
let external = CleanupCandidate {
root: PathBuf::from("/ws/external"),
bytes: 10,
ownership: OutputOwnershipClass::ExternalUnproven,
};
assert!(
!external.provably_private(),
"unproven-by-construction output is never cleanable"
);
}
#[test]
fn preview_is_default_and_simulate_invokes_no_clean() {
let (_d, root, target) = valid_fixture(1);
let runner = FakeCleanupRunner::new(&root, &target, 1);
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::CargoPreview, &runner, &noop).unwrap();
assert_eq!(report.results.len(), 1);
assert_eq!(report.results[0].outcome, CleanOutcome::Previewed);
assert!(
runner
.clean_calls()
.iter()
.any(|(_, args, _)| { args.iter().any(|a| a == "--dry-run") })
);
assert!(target.join("artifact.bin").exists());
let runner2 = FakeCleanupRunner::new(&root, &target, 1);
let report = clean_with(&root, 0, &[], CleanMode::Simulate, &runner2, &noop).unwrap();
assert_eq!(report.results.len(), 1);
assert_eq!(report.results[0].outcome, CleanOutcome::Simulated);
assert!(
runner2.clean_calls().is_empty(),
"simulation must not invoke clean"
);
assert!(target.join("artifact.bin").exists());
assert!(
report
.render()
.contains("no `cargo clean` command was invoked")
);
assert!(!report.render().contains("recovered"));
}
#[test]
fn unresolved_discovered_manifest_blocks_every_cleanup_mode_before_clean() {
for mode in [
CleanMode::CargoPreview,
CleanMode::Simulate,
CleanMode::Execute,
] {
let (_d, root, target) = valid_fixture(1);
let unresolved = root.join("unresolved/Cargo.toml");
std::fs::create_dir_all(unresolved.parent().unwrap()).unwrap();
std::fs::write(
&unresolved,
"[package]\nname='unresolved'\nversion='0.1.0'\n",
)
.unwrap();
let mut runner = FakeCleanupRunner::new(&root, &target, 1);
runner.unresolved_manifest = Some(unresolved);
let report = clean_with(&root, 0, &[], mode, &runner, &NoopObserver).unwrap();
assert_eq!(
report.counters.unresolved_ownership, 1,
"{mode:?} {report:?}"
);
assert_eq!(report.unresolved_ownership.len(), 1, "{mode:?}");
assert_eq!(
report.unresolved_ownership[0].manifest,
canon(&root.join("unresolved/Cargo.toml"))
);
assert!(
report
.counters
.stats_line()
.contains("unresolved_ownership=1")
);
assert!(
report.results.is_empty(),
"blocked scope must report no cleanable bytes: {mode:?}"
);
assert_eq!(
report.scope_blocked.as_ref().map(|b| b.message.as_str()),
Some(
"cleanup ownership could not be proven: 1 discovered Cargo manifest did not resolve; no cleanup commands were run"
),
"{mode:?}"
);
assert_eq!(
report.diagnostics, 1,
"participant diagnostic retained: {mode:?}"
);
assert!(
runner.clean_calls().is_empty(),
"{mode:?}: zero clean and dry-run invocations"
);
assert_eq!(
report
.render()
.matches("cleanup ownership could not be proven")
.count(),
1
);
assert!(report.render().contains("no cleanup commands were run"));
}
}
#[test]
fn blocked_scope_render_lists_unresolved_participants_with_workspace_hint() {
let report = CleanReport {
results: Vec::new(),
diagnostics: 2,
failed: 0,
mode: CleanMode::Simulate,
counters: ScanCounters::default(),
scope_blocked: Some(ScopeBlock::new(
ScopeBlockReason::OwnershipUnproven,
"cleanup ownership could not be proven: 2 discovered Cargo manifests did not resolve; no cleanup commands were run".into(),
)),
unresolved_ownership: vec![
UnresolvedOwnershipParticipant {
manifest: PathBuf::from("/work/a/website/Cargo.toml"),
stage: "locate",
reason: "cargo locate-project failed: error: current package believes it's in a workspace when it's not: current: /work/a/website/Cargo.toml".into(),
},
UnresolvedOwnershipParticipant {
manifest: PathBuf::from("/work/b/Cargo.toml"),
stage: "metadata",
reason: "cargo metadata failed: something else".into(),
},
],
selected_roots: vec![PathBuf::from("/work")],
discovered_manifests: 3,
resolved_workspaces: 1,
units_considered: 0,
effective_policy: None,
selector: None,
};
let text = report.render();
assert!(
text.contains("cleanup ownership could not be proven"),
"block message retained: {text}"
);
assert_eq!(
text.matches("cleanup ownership could not be proven")
.count(),
1,
"hint text must not repeat the block phrase: {text}"
);
assert!(
text.contains("unresolved [locate] /work/a/website/Cargo.toml:"),
"first participant listed with stage: {text}"
);
assert!(
text.contains("unresolved [metadata] /work/b/Cargo.toml:"),
"second participant listed with stage: {text}"
);
assert!(
text.contains("empty `[workspace]` table"),
"workspace-detach hint for the believes-in-workspace class: {text}"
);
}
#[test]
fn blocked_scope_render_bounds_unresolved_participant_listing() {
let unresolved_ownership: Vec<UnresolvedOwnershipParticipant> = (0..7)
.map(|i| UnresolvedOwnershipParticipant {
manifest: PathBuf::from(format!("/work/p{i}/Cargo.toml")),
stage: "locate",
reason: "cargo locate-project failed".into(),
})
.collect();
let report = CleanReport {
results: Vec::new(),
diagnostics: 7,
failed: 0,
mode: CleanMode::Simulate,
counters: ScanCounters::default(),
scope_blocked: Some(ScopeBlock::new(
ScopeBlockReason::OwnershipUnproven,
"cleanup ownership could not be proven: 7 discovered Cargo manifests did not resolve; no cleanup commands were run".into(),
)),
unresolved_ownership,
selected_roots: vec![PathBuf::from("/work")],
discovered_manifests: 8,
resolved_workspaces: 1,
units_considered: 0,
effective_policy: None,
selector: None,
};
let text = report.render();
assert_eq!(
text.matches("unresolved [locate]").count(),
5,
"exactly five participant rows: {text}"
);
assert!(
text.contains("… 2 more unresolved participant(s)"),
"bounded overflow line: {text}"
);
assert!(
!text.contains("empty `[workspace]` table"),
"no workspace hint without the workspace-belief reason: {text}"
);
}
#[test]
fn simulation_candidate_set_matches_execute_preflight() {
let (_d, root, target) = valid_fixture(1);
let sim_runner = FakeCleanupRunner::new(&root, &target, 1);
let exec_runner = FakeCleanupRunner::new(&root, &target, 1);
let noop = NoopObserver;
let sim = clean_with(&root, 0, &[], CleanMode::Simulate, &sim_runner, &noop).unwrap();
let exec = clean_with(&root, 0, &[], CleanMode::CargoPreview, &exec_runner, &noop).unwrap();
assert_eq!(sim.results.len(), exec.results.len());
assert_eq!(sim.results[0].display_path, exec.results[0].display_path);
}
#[test]
fn external_unproven_inside_root_remains_inventory_only() {
let d = tempfile::tempdir().unwrap();
let root = d.path().join("root");
let proj = root.join("proj");
std::fs::create_dir_all(proj.join("src")).unwrap();
std::fs::write(
proj.join("Cargo.toml"),
"[package]\nname='proj'\nversion='0.1.0'\nedition='2021'\n",
)
.unwrap();
std::fs::write(proj.join("src/main.rs"), "fn main() {}\n").unwrap();
let redirected = root.join("external-target");
std::fs::create_dir_all(&redirected).unwrap();
std::fs::write(redirected.join("artifact.bin"), vec![1u8; 512]).unwrap();
let old = SystemTime::now() - Duration::from_secs(3600);
backdate(d.path(), old);
let canonical = fs::canonicalize(&redirected).unwrap();
let canonical_root = fs::canonicalize(&root).unwrap();
for ownership in [
OutputOwnershipClass::ExternalUnproven,
OutputOwnershipClass::Shared,
OutputOwnershipClass::Uncertain,
] {
let raw = workspace::RawGroup {
physicals: vec![canonical.clone()],
covering: vec![canonical.clone()],
display: canonical.clone(),
owners: vec![0],
ownership,
source_overlap: false,
};
let _ws = ResolvedWorkspace {
id: WorkspaceId(canonical_root.clone()),
root: canonical_root.clone(),
root_manifest: proj.join("Cargo.toml"),
members: vec![],
packages: vec![],
output: OutputSet {
target: OutputRoot {
kind: OutputRootKind::Target,
logical_path: redirected.clone(),
physical_path: Some(canonical.clone()),
exists: true,
is_symlink: false,
},
build: OutputRoot {
kind: OutputRootKind::Build,
logical_path: redirected.clone(),
physical_path: Some(canonical.clone()),
exists: true,
is_symlink: false,
},
},
capability: CargoCapabilities {
build_dir: CargoBuildDirCapability::Equal,
metadata_had_build_directory: true,
env_build_dir_set: false,
},
};
assert!(
!is_authorized(&raw, &root, &[]).unwrap(),
"{ownership:?} inside ROOT must remain inventory-only"
);
assert!(
!is_authorized(&raw, &root, std::slice::from_ref(&redirected)).unwrap(),
"{ownership:?} inside allowed root must remain inventory-only"
);
assert!(!is_authorized(&raw, &root, &[root.clone(), redirected.clone()]).unwrap());
}
let canonical_target = fs::canonicalize(&proj).unwrap().join("target");
std::fs::create_dir_all(&canonical_target).unwrap();
let private_raw = workspace::RawGroup {
physicals: vec![canonical_target.clone()],
covering: vec![canonical_target.clone()],
display: canonical_target.clone(),
owners: vec![0],
ownership: OutputOwnershipClass::PrivateBounded,
source_overlap: false,
};
let private_ws = ResolvedWorkspace {
id: WorkspaceId(canonical_root.clone()),
root: canonical_root.clone(),
root_manifest: proj.join("Cargo.toml"),
members: vec![],
packages: vec![],
output: OutputSet {
target: OutputRoot {
kind: OutputRootKind::Target,
logical_path: canonical_target.clone(),
physical_path: Some(canonical_target.clone()),
exists: true,
is_symlink: false,
},
build: OutputRoot {
kind: OutputRootKind::Build,
logical_path: canonical_target.clone(),
physical_path: Some(canonical_target.clone()),
exists: true,
is_symlink: false,
},
},
capability: CargoCapabilities {
build_dir: CargoBuildDirCapability::Equal,
metadata_had_build_directory: true,
env_build_dir_set: false,
},
};
let ws_root_contains = fs::canonicalize(&proj).unwrap();
let private_ws2 = ResolvedWorkspace {
id: WorkspaceId(ws_root_contains.clone()),
root: ws_root_contains,
..private_ws
};
let _ = private_ws2;
let _ = private_raw;
}
#[test]
fn private_bounded_inside_workspace_is_authorized() {
let d = tempfile::tempdir().unwrap();
let root = d.path().join("root");
let proj = root.join("proj");
let target = proj.join("target");
std::fs::create_dir_all(&target).unwrap();
std::fs::create_dir_all(&root).unwrap();
let canonical_target = fs::canonicalize(&target).unwrap();
let canonical_proj = fs::canonicalize(&proj).unwrap();
let raw = workspace::RawGroup {
physicals: vec![canonical_target.clone()],
covering: vec![canonical_target.clone()],
display: canonical_target.clone(),
owners: vec![0],
ownership: OutputOwnershipClass::PrivateBounded,
source_overlap: false,
};
let _ws = ResolvedWorkspace {
id: WorkspaceId(canonical_proj.clone()),
root: canonical_proj,
root_manifest: proj.join("Cargo.toml"),
members: vec![],
packages: vec![],
output: OutputSet {
target: OutputRoot {
kind: OutputRootKind::Target,
logical_path: target.clone(),
physical_path: Some(canonical_target.clone()),
exists: true,
is_symlink: false,
},
build: OutputRoot {
kind: OutputRootKind::Build,
logical_path: target.clone(),
physical_path: Some(canonical_target),
exists: true,
is_symlink: false,
},
},
capability: CargoCapabilities {
build_dir: CargoBuildDirCapability::Equal,
metadata_had_build_directory: true,
env_build_dir_set: false,
},
};
assert!(is_authorized(&raw, &root, &[]).unwrap());
}
#[test]
fn external_unproven_outside_root_never_authorized_by_allowed_root() {
let d = tempfile::tempdir().unwrap();
let root = d.path().join("root");
let outside = d.path().join("outside-target");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let canonical_out = fs::canonicalize(&outside).unwrap();
let raw = workspace::RawGroup {
physicals: vec![canonical_out.clone()],
covering: vec![canonical_out.clone()],
display: canonical_out.clone(),
owners: vec![0],
ownership: OutputOwnershipClass::ExternalUnproven,
source_overlap: false,
};
let ws_root = d.path().join("ws");
std::fs::create_dir_all(&ws_root).unwrap();
let _ws = ResolvedWorkspace {
id: WorkspaceId(ws_root.clone()),
root: ws_root,
root_manifest: PathBuf::from("/x/Cargo.toml"),
members: vec![],
packages: vec![],
output: OutputSet {
target: OutputRoot {
kind: OutputRootKind::Target,
logical_path: outside.clone(),
physical_path: Some(canonical_out.clone()),
exists: true,
is_symlink: false,
},
build: OutputRoot {
kind: OutputRootKind::Build,
logical_path: outside.clone(),
physical_path: Some(canonical_out),
exists: true,
is_symlink: false,
},
},
capability: CargoCapabilities {
build_dir: CargoBuildDirCapability::Equal,
metadata_had_build_directory: true,
env_build_dir_set: false,
},
};
assert!(!is_authorized(&raw, &root, &[]).unwrap());
assert!(!is_authorized(&raw, &root, &[outside]).unwrap());
let detail = ownership_skip_detail(OutputOwnershipClass::ExternalUnproven);
assert!(detail.contains("unproven"));
assert!(detail.contains("authorization does not establish"));
}
#[test]
fn symlink_allowed_root_rejected_and_shared_forbidden() {
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
let d = tempfile::tempdir().unwrap();
let real = d.path().join("real");
std::fs::create_dir(&real).unwrap();
let link = d.path().join("link");
symlink(&real, &link).unwrap();
let canonical_target = fs::canonicalize(&real).unwrap();
let raw = workspace::RawGroup {
physicals: vec![canonical_target.clone()],
covering: vec![canonical_target.clone()],
display: canonical_target.clone(),
owners: vec![0],
ownership: OutputOwnershipClass::PrivateBounded,
source_overlap: false,
};
let _ws = ResolvedWorkspace {
id: WorkspaceId(d.path().join("ws")),
root: d.path().join("ws"),
root_manifest: PathBuf::from("/x/Cargo.toml"),
members: vec![],
packages: vec![],
output: OutputSet {
target: OutputRoot {
kind: OutputRootKind::Target,
logical_path: real.clone(),
physical_path: Some(canonical_target),
exists: true,
is_symlink: false,
},
build: OutputRoot {
kind: OutputRootKind::Build,
logical_path: real.clone(),
physical_path: None,
exists: false,
is_symlink: false,
},
},
capability: CargoCapabilities {
build_dir: CargoBuildDirCapability::Equal,
metadata_had_build_directory: true,
env_build_dir_set: false,
},
};
let root = d.path().join("root");
std::fs::create_dir(&root).unwrap();
assert!(is_authorized(&raw, &root, &[link]).is_err());
let shared_raw = workspace::RawGroup {
physicals: vec![real.clone()],
covering: vec![real.clone()],
display: real.clone(),
owners: vec![0, 1],
ownership: OutputOwnershipClass::Shared,
source_overlap: false,
};
assert!(!is_authorized(&shared_raw, &root, std::slice::from_ref(&real)).unwrap());
let uncertain_raw = workspace::RawGroup {
physicals: vec![real.clone()],
covering: vec![real],
display: PathBuf::from("/x"),
owners: vec![0],
ownership: OutputOwnershipClass::Uncertain,
source_overlap: false,
};
assert!(!is_authorized(&uncertain_raw, &root, &[d.path().to_path_buf()]).unwrap());
}
}
#[test]
fn frozen_env_sets_target_and_build_dir() {
let ctx = RevalidatedContext {
workspace_roots: vec![PathBuf::from("/ws")],
workspace_root: PathBuf::from("/ws"),
root_manifest: PathBuf::from("/ws/Cargo.toml"),
canonical_members: vec![PathBuf::from("/ws")],
target: PathBuf::from("/cache/target"),
build: Some(PathBuf::from("/cache/build")),
capability: CargoCapabilities {
build_dir: CargoBuildDirCapability::Distinct,
metadata_had_build_directory: true,
env_build_dir_set: false,
},
covering: vec![PathBuf::from("/cache/target")],
pre_bytes: 0,
newest_activity: None,
ownership: OutputOwnershipClass::PrivateBounded,
frozen_env: Vec::new(),
};
let env = frozen_env(&ctx).unwrap();
assert!(
env.iter()
.any(|(k, v)| k == "CARGO_TARGET_DIR" && v == "/cache/target")
);
assert!(
env.iter()
.any(|(k, v)| k == "CARGO_BUILD_BUILD_DIR" && v == "/cache/build")
);
let ctx2 = RevalidatedContext {
capability: CargoCapabilities {
build_dir: CargoBuildDirCapability::Unknown,
metadata_had_build_directory: false,
env_build_dir_set: false,
},
..ctx
};
assert!(frozen_env(&ctx2).is_err());
}
#[test]
fn execution_reports_observed_decrease_deduped() {
let (_d, root, target) = valid_fixture(1);
let mut runner = FakeCleanupRunner::new(&root, &target, 1);
runner.remove_on_execute = true;
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::Execute, &runner, &noop).unwrap();
assert_eq!(report.results[0].outcome, CleanOutcome::Cleaned);
assert!(report.results[0].before_bytes.unwrap() > report.results[0].after_bytes.unwrap());
assert!(!target.join("artifact.bin").exists());
assert!(report.render().contains("observed decrease"));
assert!(!report.render().contains("would-clean"));
}
#[test]
fn clean_requires_absolute_root() {
let runner = FakeCleanupRunner::new(Path::new("/x"), Path::new("/x/target"), 1);
let noop = NoopObserver;
let err = clean_with(
Path::new("."),
0,
&[],
CleanMode::CargoPreview,
&runner,
&noop,
)
.unwrap_err();
assert!(err.to_string().contains("absolute sandbox root"));
assert!(runner.calls().is_empty());
}
#[test]
#[cfg(unix)]
fn cleanup_root_symlink_with_trailing_slash_is_refused() {
use std::os::unix::fs::symlink;
let d = tempfile::tempdir().unwrap();
let real = d.path().join("real");
fs::create_dir(&real).unwrap();
let link = d.path().join("link");
symlink(&real, &link).unwrap();
assert!(validate_cleanup_root(&link).is_err());
let with_slash = PathBuf::from(format!("{}/", link.display()));
assert!(
validate_cleanup_root(&with_slash).is_err(),
"a symlinked root with a trailing slash must be refused exactly like without one"
);
let with_dot = PathBuf::from(format!("{}/.", link.display()));
assert!(
validate_cleanup_root(&with_dot).is_err(),
"a symlinked root with a trailing /. must be refused exactly like without one"
);
assert!(validate_cleanup_root(&real).is_ok());
}
#[test]
fn collapse_roots_fails_closed_when_a_root_no_longer_resolves() {
let d = tempfile::tempdir().unwrap();
let gone = d.path().join("gone");
assert!(collapse_roots(vec![gone]).is_err());
let real = d.path().join("real");
fs::create_dir(&real).unwrap();
assert_eq!(
collapse_roots(vec![real.clone()]).unwrap(),
vec![fs::canonicalize(&real).unwrap()]
);
}
#[test]
fn external_unproven_skip_code_names_ownership_not_authorization() {
let d = tempfile::tempdir().unwrap();
let base = fs::canonicalize(d.path()).unwrap();
for (class, expected) in [
(
OutputOwnershipClass::Shared,
CleanupReasonCode::SkippedShared,
),
(
OutputOwnershipClass::Uncertain,
CleanupReasonCode::SkippedUncertain,
),
(
OutputOwnershipClass::ExternalUnproven,
CleanupReasonCode::SkippedOwnershipUnproven,
),
] {
let unit = synthetic_mixed_unit(&base, OutputOwnershipClass::PrivateBounded, class);
assert_eq!(unit_skip_code(&unit), expected, "{class:?}");
}
}
#[test]
fn prove_covering_roots_refuses_symlink_swap_with_change_code() {
let d = tempfile::tempdir().unwrap();
let target = d.path().join("target");
fs::create_dir(&target).unwrap();
assert!(prove_covering_roots(std::slice::from_ref(&target)).is_ok());
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
let other = d.path().join("other");
fs::create_dir(&other).unwrap();
fs::remove_dir(&target).unwrap();
symlink(&other, &target).unwrap();
let failure = prove_covering_roots(std::slice::from_ref(&target)).unwrap_err();
assert_eq!(failure.code, CleanupReasonCode::SkippedChangedBeforeCleanup);
assert!(failure.detail.contains("symlink"), "{}", failure.detail);
}
let missing = d.path().join("missing");
let failure = prove_covering_roots(std::slice::from_ref(&missing)).unwrap_err();
assert_eq!(failure.code, CleanupReasonCode::SkippedChangedBeforeCleanup);
}
#[test]
fn proof_fails_closed_when_a_member_source_no_longer_resolves() {
let (_d, root, target) = valid_fixture(1);
let runner = FakeCleanupRunner::new(&root, &target, 1);
let noop = NoopObserver;
let mut counters = ScanCounters::default();
let mut diags = Vec::new();
let scope = resolve_cleanup_scope(
&[root.join("Cargo.toml")],
SystemTime::now(),
Duration::from_secs(0),
&runner,
&mut counters,
&mut diags,
&noop,
&CleanupSelection::All,
)
.unwrap();
assert_eq!(scope.units.len(), 1);
let mut workspaces = scope.workspaces;
workspaces[0].members[0].source_root = workspaces[0].root.join("vanished-member");
let failure = final_cleanup_proof(
&scope.units[0],
&workspaces,
&root,
&[],
&runner,
0,
&mut counters,
)
.unwrap_err();
assert_eq!(
failure.code,
CleanupReasonCode::SkippedOwnershipUnproven,
"{}",
failure.detail
);
}
#[test]
fn missing_and_file_allowed_roots_authorize_nothing_but_are_not_fatal() {
let d = tempfile::tempdir().unwrap();
let base = fs::canonicalize(d.path()).unwrap();
let clean = base.join("clean");
fs::create_dir(&clean).unwrap();
let outside = base.join("outside");
fs::create_dir(&outside).unwrap();
let missing = base.join("missing");
assert!(
!covering_is_authorized_roots(
OutputOwnershipClass::PrivateBounded,
std::slice::from_ref(&outside),
std::slice::from_ref(&clean),
std::slice::from_ref(&missing),
)
.unwrap()
);
let file = base.join("file");
fs::write(&file, b"x").unwrap();
assert!(
!covering_is_authorized_roots(
OutputOwnershipClass::PrivateBounded,
std::slice::from_ref(&outside),
std::slice::from_ref(&clean),
std::slice::from_ref(&file),
)
.unwrap()
);
}
struct ChangingTargetRunner {
base: FakeCleanupRunner,
calls: std::sync::atomic::AtomicU64,
second_target: PathBuf,
}
impl CargoRunner for ChangingTargetRunner {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
if args.first().is_some_and(|a| a == "metadata") {
let n = self
.calls
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if n == 0 {
return CargoRunner::run(&self.base, cwd, args);
}
let mut fake2 =
FakeCleanupRunner::new(&self.base.workspace_root, &self.second_target, 1);
fake2.build = self.base.build.clone();
return CargoRunner::run(&fake2, cwd, args);
}
CargoRunner::run(&self.base, cwd, args)
}
}
impl CleanupRunner for ChangingTargetRunner {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
CargoRunner::run(self, cwd, args)
}
fn run_with_env(
&self,
cwd: &Path,
args: &[OsString],
env: &[(OsString, OsString)],
) -> io::Result<ProcessOutput> {
self.base.run_with_env(cwd, args, env)
}
}
#[test]
fn revalidation_detects_changed_target_and_skips() {
let (_d, root, target) = valid_fixture(1);
let other = root.parent().unwrap().join("other-target");
std::fs::create_dir_all(&other).unwrap();
let base = FakeCleanupRunner::new(&root, &target, 1);
let runner = ChangingTargetRunner {
base,
calls: std::sync::atomic::AtomicU64::new(0),
second_target: other,
};
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::CargoPreview, &runner, &noop).unwrap();
assert_eq!(report.results.len(), 1);
assert_eq!(report.results[0].outcome, CleanOutcome::Skipped);
assert!(report.results[0].detail.contains("changed"));
assert!(runner.base.clean_calls().is_empty());
}
#[test]
fn violated_admission_premise_blocks_with_zero_cargo_spawns() {
let (_d, root, target) = valid_fixture(1);
let noop = NoopObserver;
let policy = CleanupPolicy::default();
let absent = root.parent().unwrap().join("still-absent");
assert!(!absent.exists());
let runner = FakeCleanupRunner::new(&root, &target, 1);
let ok = clean_with_roots_policy_selector_guarded(
std::slice::from_ref(&root),
0,
&[],
CleanMode::Simulate,
&runner,
&noop,
&policy,
None,
Some(AdmissionPremise {
omitted: vec![crate::policy::AutomaticOmission::NotFound(absent.clone())],
}),
&CleanupSelection::All,
)
.unwrap();
assert!(ok.scope_blocked.is_none());
assert!(runner.clean_calls().is_empty());
std::fs::create_dir(&absent).unwrap();
let runner2 = FakeCleanupRunner::new(&root, &target, 1);
let blocked = clean_with_roots_policy_selector_guarded(
std::slice::from_ref(&root),
0,
&[],
CleanMode::Simulate,
&runner2,
&noop,
&policy,
None,
Some(AdmissionPremise {
omitted: vec![crate::policy::AutomaticOmission::NotFound(absent.clone())],
}),
&CleanupSelection::All,
)
.unwrap();
assert_eq!(
blocked.scope_blocked.as_ref().map(|b| b.reason),
Some(ScopeBlockReason::IncompleteDiscovery)
);
assert!(runner2.clean_calls().is_empty());
assert!(
blocked
.scope_blocked
.as_ref()
.is_some_and(|b| b.message.contains("no further cleanup commands were run"))
);
std::fs::remove_dir(&absent).unwrap();
let gone = root.parent().unwrap().join("admitted-then-deleted");
std::fs::create_dir(&gone).unwrap();
std::fs::remove_dir(&gone).unwrap();
let violation = crate::policy::recheck_admission_premise(
std::slice::from_ref(&gone),
std::slice::from_ref(&crate::policy::AutomaticOmission::NotFound(absent.clone())),
);
assert!(
violation.is_some(),
"a disappeared admitted root invalidates the premise"
);
}
#[test]
fn unresolved_cargo_manifest_blocks_entire_cleanup_scope() {
struct PerPathFailRunner {
good_root: PathBuf,
good_target: PathBuf,
}
impl CargoRunner for PerPathFailRunner {
fn run(&self, _cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
if args.first().is_some_and(|a| a == "locate-project") {
let manifest_arg = args.last().unwrap().to_string_lossy().into_owned();
if manifest_arg.contains("bad") {
return Ok(ProcessOutput {
success: false,
code: Some(1),
stdout: Vec::new(),
stderr: b"locate failed".to_vec(),
});
}
let json = serde_json::json!({"root": self.good_root.join("Cargo.toml")});
return Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: serde_json::to_vec(&json).unwrap(),
stderr: Vec::new(),
});
}
if args.first().is_some_and(|a| a == "metadata") {
let json = serde_json::json!({
"packages": [{"id": "m0", "name": "m0", "manifest_path": self.good_root.join("Cargo.toml")}],
"workspace_members": ["m0"],
"workspace_root": self.good_root,
"target_directory": self.good_target,
});
return Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: serde_json::to_vec(&json).unwrap(),
stderr: Vec::new(),
});
}
Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: b"ok".to_vec(),
stderr: Vec::new(),
})
}
}
impl CleanupRunner for PerPathFailRunner {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
CargoRunner::run(self, cwd, args)
}
fn run_with_env(
&self,
cwd: &Path,
args: &[OsString],
_env: &[(OsString, OsString)],
) -> io::Result<ProcessOutput> {
CargoRunner::run(self, cwd, args)
}
}
let d = tempfile::tempdir().unwrap();
let good = d.path().join("good");
std::fs::create_dir_all(good.join("src")).unwrap();
std::fs::write(
good.join("Cargo.toml"),
"[package]\nname='good'\nversion='0.1.0'\nedition='2021'\n",
)
.unwrap();
std::fs::write(good.join("src/main.rs"), "fn main() {}\n").unwrap();
let target = good.join("target");
std::fs::create_dir_all(&target).unwrap();
std::fs::write(
target.join("CACHEDIR.TAG"),
b"Signature: 8a477f597d28d172789f06886806bc55\n",
)
.unwrap();
std::fs::write(target.join("a.bin"), vec![1u8; 256]).unwrap();
let old = SystemTime::now() - Duration::from_secs(3600);
backdate(d.path(), old);
let bad_manifest = d.path().join("bad/Cargo.toml");
std::fs::create_dir_all(bad_manifest.parent().unwrap()).unwrap();
std::fs::write(&bad_manifest, "").unwrap();
let runner = PerPathFailRunner {
good_root: good.clone(),
good_target: target.clone(),
};
let noop = NoopObserver;
let report = clean_with(d.path(), 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
assert_eq!(report.counters.unresolved_ownership, 1);
assert!(report.results.is_empty());
assert!(
report
.render()
.contains("cleanup ownership could not be proven")
);
}
#[test]
fn final_report_lists_all_groups_and_deduped_total() {
let mut report = CleanReport {
results: Vec::new(),
diagnostics: 0,
failed: 0,
mode: CleanMode::Execute,
counters: ScanCounters::default(),
scope_blocked: None,
unresolved_ownership: Vec::new(),
selected_roots: Vec::new(),
discovered_manifests: 0,
resolved_workspaces: 0,
units_considered: 0,
effective_policy: None,
selector: None,
};
for i in 0..7 {
report.results.push(CleanResult {
display_path: PathBuf::from(format!("/tmp/g{i}")),
workspace_roots: vec![PathBuf::from("/ws")],
output_roots: vec![PathBuf::from(format!("/tmp/g{i}"))],
ownership: OutputOwnershipClass::PrivateBounded,
outcome: CleanOutcome::Cleaned,
policy_disposition: Some(PolicyDisposition::Selected),
reason_code: CleanupReasonCode::Cleaned,
before_bytes: Some(100),
after_bytes: Some(20),
observed_decrease: Some(80),
detail: String::new(),
});
}
let text = report.render();
for i in 0..7 {
assert!(text.contains(&format!("/tmp/g{i}")));
}
assert!(text.contains("observed decrease"));
assert!(text.contains("cleanup: 7 cleaned"));
assert!(!text.contains("would-clean"));
assert!(!text.contains("no `cargo clean`"));
}
#[test]
fn real_temp_project_preview_and_execute_with_redirected_target() {
let d = tempfile::tempdir().unwrap();
let root = d.path().join("root");
let proj = root.join("proj");
std::fs::create_dir_all(proj.join("src")).unwrap();
std::fs::write(
proj.join("Cargo.toml"),
"[package]\nname='proj'\nversion='0.1.0'\nedition='2021'\n",
)
.unwrap();
std::fs::write(proj.join("src/main.rs"), "fn main() {}\n").unwrap();
std::fs::write(proj.join("Cargo.lock"), "version = 4\n").unwrap();
let external = proj.join("ext-target");
std::fs::create_dir_all(&external).unwrap();
std::fs::write(
external.join("CACHEDIR.TAG"),
b"Signature: 8a477f597d28d172789f06886806bc55\n",
)
.unwrap();
std::fs::write(external.join("artifact.bin"), vec![1u8; 2048]).unwrap();
std::fs::create_dir_all(proj.join(".cargo")).unwrap();
let external_toml = external.display().to_string().replace('\\', "/");
std::fs::write(
proj.join(".cargo/config.toml"),
format!("[build]\ntarget-dir = \"{external_toml}\"\n"),
)
.unwrap();
let old = SystemTime::now() - Duration::from_secs(3600);
backdate(d.path(), old);
let noop = NoopObserver;
let runner = SystemCleanupRunner;
let policy = CleanupPolicy {
min_reclaimable_bytes: u64::MAX,
..Default::default()
};
let small = clean_with_roots_policy(
std::slice::from_ref(&root),
0,
&[],
CleanMode::Simulate,
&runner,
&noop,
&policy,
)
.unwrap();
assert_eq!(
small.results[0].policy_disposition,
Some(PolicyDisposition::BelowMinimumSize)
);
let policy = CleanupPolicy {
min_inactive_seconds: Some(7200),
..Default::default()
};
let young = clean_with_roots_policy(
std::slice::from_ref(&root),
0,
&[],
CleanMode::Simulate,
&runner,
&noop,
&policy,
)
.unwrap();
assert_eq!(
young.results[0].policy_disposition,
Some(PolicyDisposition::TooRecentForPolicy)
);
let policy = CleanupPolicy {
include: vec!["**/proj".into()],
exclude: vec!["**/proj".into()],
..Default::default()
};
let excluded = clean_with_roots_policy(
std::slice::from_ref(&root),
0,
&[],
CleanMode::Simulate,
&runner,
&noop,
&policy,
)
.unwrap();
assert_eq!(
excluded.results[0].policy_disposition,
Some(PolicyDisposition::Excluded)
);
let preview = clean_with(&root, 0, &[], CleanMode::CargoPreview, &runner, &noop).unwrap();
assert_eq!(
preview.results.len(),
1,
"preview results: {:?}",
preview.results
);
assert_eq!(
preview.results[0].outcome,
CleanOutcome::Previewed,
"preview detail: {}",
preview.results[0].detail
);
assert!(external.join("artifact.bin").exists());
assert!(preview.render().contains("no cleanup executed"));
let profile_preview = clean_with_roots_policy_selector(
std::slice::from_ref(&root),
0,
&[],
CleanMode::CargoPreview,
&runner,
&noop,
&CleanupPolicy::default(),
Some(CleanupSelector::Profile("dev".into())),
)
.unwrap();
assert_eq!(profile_preview.results[0].outcome, CleanOutcome::Previewed);
assert!(profile_preview.render().contains("output-union before"));
assert!(external.join("artifact.bin").exists());
let sim = clean_with(&root, 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
assert_eq!(sim.results.len(), 1);
assert_eq!(sim.results[0].outcome, CleanOutcome::Simulated);
assert_eq!(sim.results[0].display_path, preview.results[0].display_path);
assert!(external.join("artifact.bin").exists());
let exec = clean_with(&root, 0, &[], CleanMode::Execute, &runner, &noop).unwrap();
assert_eq!(exec.results.len(), 1);
assert_eq!(exec.results[0].outcome, CleanOutcome::Cleaned);
assert!(exec.results[0].observed_decrease.unwrap() > 0);
assert!(!external.join("artifact.bin").exists());
}
#[test]
fn real_cargo_package_selector_preserves_sibling_workspace_artifacts() {
let version = Command::new("cargo").arg("--version").output().unwrap();
assert!(
version.status.success(),
"cargo --version failed: {}",
String::from_utf8_lossy(&version.stderr)
);
let version = String::from_utf8_lossy(&version.stdout);
let reported = version
.split_whitespace()
.nth(1)
.unwrap_or_else(|| panic!("cargo --version printed no version: {version:?}"));
let supported = workspace::clean_capabilities_from_version(reported).package_selector;
if !supported {
eprintln!(
"skipping real_cargo_package_selector_preserves_sibling_workspace_artifacts: \
cargo {reported} has no `clean --package` support"
);
return;
}
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("workspace");
for package in ["app-a", "app-b", "shared"] {
fs::create_dir_all(root.join(package).join("src")).unwrap();
}
fs::write(
root.join("Cargo.toml"),
"[workspace]\nmembers = [\"app-a\", \"app-b\", \"shared\"]\nresolver = \"2\"\n",
)
.unwrap();
fs::write(
root.join("shared/Cargo.toml"),
"[package]\nname = \"shared\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
)
.unwrap();
fs::write(
root.join("shared/src/lib.rs"),
"pub fn value() -> u32 { 1 }\n",
)
.unwrap();
for package in ["app-a", "app-b"] {
let (dependency, import) = if package == "app-a" {
(
"shared_alias = { package = \"shared\", path = \"../shared\" }",
"shared_alias",
)
} else {
("shared = { path = \"../shared\" }", "shared")
};
fs::write(
root.join(package).join("Cargo.toml"),
format!("[package]\nname = \"{package}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n[dependencies]\n{dependency}\n"),
)
.unwrap();
fs::write(
root.join(package).join("src/main.rs"),
format!("fn main() {{ println!(\"{{}}\", {import}::value()); }}\n"),
)
.unwrap();
}
for args in [
vec!["generate-lockfile", "--offline", "--manifest-path"],
vec![
"build",
"--workspace",
"--offline",
"--locked",
"--manifest-path",
],
] {
let mut command = Command::new("cargo");
command.args(&args).arg(root.join("Cargo.toml"));
let output = command.output().unwrap();
assert!(
output.status.success(),
"cargo {:?} failed: {}",
args,
String::from_utf8_lossy(&output.stderr)
);
}
backdate(&root, SystemTime::now() - Duration::from_secs(3600));
let target = root.join("target/debug");
let executable =
|name: &str| target.join(format!("{name}{}", std::env::consts::EXE_SUFFIX));
assert!(executable("app-a").exists());
assert!(executable("app-b").exists());
let report = clean_with_roots_policy_selector(
std::slice::from_ref(&root),
0,
&[],
CleanMode::Execute,
&SystemCleanupRunner,
&NoopObserver,
&CleanupPolicy::default(),
Some(CleanupSelector::Package("app-a@0.1.0".into())),
)
.unwrap();
assert_eq!(report.results.len(), 1, "{:?}", report.results);
assert_eq!(report.results[0].outcome, CleanOutcome::Cleaned);
assert!(!executable("app-a").exists());
assert!(executable("app-b").exists());
}
#[test]
fn multi_member_private_workspace_can_be_cleaned() {
let (_d, root, target) = valid_fixture(1);
for i in 0..2 {
let member = root.join(format!("member{i}"));
std::fs::create_dir_all(&member).unwrap();
std::fs::write(member.join("lib.rs"), "old").unwrap();
}
let old = SystemTime::now() - Duration::from_secs(3600);
backdate(&root, old);
let runner = FakeCleanupRunner::new(&root, &target, 2);
let noop = NoopObserver;
for mode in [CleanMode::CargoPreview, CleanMode::Simulate] {
let report = clean_with(&root, 0, &[], mode, &runner, &noop).unwrap();
assert_eq!(report.results.len(), 1);
let expected = if mode == CleanMode::CargoPreview {
CleanOutcome::Previewed
} else {
CleanOutcome::Simulated
};
assert_eq!(report.results[0].outcome, expected);
}
}
#[test]
fn external_outside_root_allowed_via_configured_root() {
let d = tempfile::tempdir().unwrap();
let root = d.path().join("root");
let proj = root.join("proj");
std::fs::create_dir_all(proj.join("src")).unwrap();
std::fs::write(
proj.join("Cargo.toml"),
"[package]\nname='proj'\nversion='0.1.0'\nedition='2021'\n",
)
.unwrap();
std::fs::write(proj.join("src/main.rs"), "fn main() {}\n").unwrap();
std::fs::write(proj.join("Cargo.lock"), "version = 4\n").unwrap();
let outside = d.path().join("outside-target");
std::fs::create_dir_all(&outside).unwrap();
std::fs::write(outside.join("artifact.bin"), vec![1u8; 1024]).unwrap();
std::fs::create_dir_all(proj.join(".cargo")).unwrap();
let outside_toml = outside.display().to_string().replace('\\', "/");
std::fs::write(
proj.join(".cargo/config.toml"),
format!("[build]\ntarget-dir = \"{outside_toml}\"\n"),
)
.unwrap();
let old = SystemTime::now() - Duration::from_secs(3600);
backdate(d.path(), old);
let noop = NoopObserver;
let runner = SystemCleanupRunner;
let skipped = clean_with(&root, 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
assert_eq!(skipped.results.len(), 1);
assert_eq!(skipped.results[0].outcome, CleanOutcome::Skipped);
let allowed = clean_with(
&root,
0,
std::slice::from_ref(&outside),
CleanMode::Simulate,
&runner,
&noop,
)
.unwrap();
assert_eq!(allowed.results.len(), 1);
assert_eq!(allowed.results[0].outcome, CleanOutcome::Skipped);
assert!(
allowed.results[0]
.detail
.contains("authorization does not establish")
|| allowed.results[0].detail.contains("unproven")
);
}
#[test]
fn missing_marker_skips_instead_of_failing() {
let (_d, root, target) = valid_fixture(1);
std::fs::remove_file(target.join("CACHEDIR.TAG")).unwrap();
let old = SystemTime::now() - Duration::from_secs(3600);
backdate(&root, old);
let runner = FakeCleanupRunner::new(&root, &target, 1);
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::CargoPreview, &runner, &noop).unwrap();
assert_eq!(report.results.len(), 1);
assert_eq!(report.results[0].outcome, CleanOutcome::Skipped);
assert!(report.results[0].detail.contains("CACHEDIR.TAG"));
assert!(runner.clean_calls().is_empty());
}
fn touch_future(path: &Path) {
let future = SystemTime::now() + Duration::from_secs(3600);
if let Ok(f) = fs::OpenOptions::new().write(true).open(path) {
let _ = f.set_modified(future);
}
if let Some(parent) = path.parent()
&& let Ok(dir) = fs::File::open(parent)
{
let _ = dir.set_modified(future);
}
}
fn simulate_disposition(
root: &Path,
_target: &Path,
runner: &FakeCleanupRunner,
mode: CleanMode,
) -> CleanOutcome {
let noop = NoopObserver;
let report = clean_with(root, 0, &[], mode, runner, &noop).unwrap();
assert_eq!(report.results.len(), 1);
report.results[0].outcome
}
#[test]
fn simulation_parity_missing_and_invalid_markers_both_skip() {
{
let (_d, root, target) = valid_fixture(1);
std::fs::remove_file(target.join("CACHEDIR.TAG")).unwrap();
backdate(&root, SystemTime::now() - Duration::from_secs(3600));
let sim_runner = FakeCleanupRunner::new(&root, &target, 1);
let exec_runner = FakeCleanupRunner::new(&root, &target, 1);
assert_eq!(
simulate_disposition(&root, &target, &sim_runner, CleanMode::Simulate),
CleanOutcome::Skipped
);
assert!(sim_runner.clean_calls().is_empty());
let adapter = WorkspaceCleanupAdapter {
runner: &exec_runner as &dyn CleanupRunner,
};
let mut counters = ScanCounters::default();
let mut diags = Vec::new();
let noop = NoopObserver;
let ws = workspace::resolve_workspaces(
&[root.join("Cargo.toml")],
&adapter,
&mut counters,
&mut diags,
&noop,
);
let exec_report =
clean_with(&root, 0, &[], CleanMode::Simulate, &exec_runner, &noop).unwrap();
assert_eq!(exec_report.results[0].outcome, CleanOutcome::Skipped);
assert!(exec_report.results[0].detail.contains("CACHEDIR.TAG"));
let _ = (ws, target);
}
{
let (_d, root, target) = valid_fixture(1);
std::fs::write(target.join("CACHEDIR.TAG"), b"bad signature\n").unwrap();
backdate(&root, SystemTime::now() - Duration::from_secs(3600));
backdate(&root, SystemTime::now() - Duration::from_secs(3600));
let runner = FakeCleanupRunner::new(&root, &target, 1);
let noop = NoopObserver;
for mode in [CleanMode::Simulate, CleanMode::CargoPreview] {
let report = clean_with(&root, 0, &[], mode, &runner, &noop).unwrap();
assert_eq!(report.results[0].outcome, CleanOutcome::Skipped);
assert!(
report.results[0].detail.contains("marker")
|| report.results[0].detail.contains("CACHEDIR")
|| report.results[0].detail.contains("signature")
|| report.results[0].detail.contains("cache")
);
}
assert!(runner.clean_calls().is_empty());
}
}
#[test]
fn simulation_parity_valid_private_reaches_cleanable_with_zero_clean_calls() {
let (_d, root, target) = valid_fixture(1);
let sim_runner = FakeCleanupRunner::new(&root, &target, 1);
let noop = NoopObserver;
let sim = clean_with(&root, 0, &[], CleanMode::Simulate, &sim_runner, &noop).unwrap();
assert_eq!(sim.results[0].outcome, CleanOutcome::Simulated);
assert!(sim_runner.clean_calls().is_empty());
let exec_runner = FakeCleanupRunner::new(&root, &target, 1);
let mut counters = ScanCounters::default();
let mut diags = Vec::new();
let scope = resolve_cleanup_scope(
&[root.join("Cargo.toml")],
SystemTime::now(),
Duration::from_secs(0),
&exec_runner,
&mut counters,
&mut diags,
&noop,
&CleanupSelection::All,
)
.unwrap();
let workspaces = scope.workspaces;
let units = scope.units;
let unresolved = scope.unresolved;
assert_eq!(workspaces.len(), 1);
assert!(unresolved.is_empty());
assert_eq!(
units.len(),
1,
"valid private workspace is one cleanup unit"
);
let proof = final_cleanup_proof(
&units[0],
&workspaces,
&root,
&[],
&exec_runner,
0,
&mut counters,
);
assert!(
proof.is_ok(),
"valid private must prove cleanable: {proof:?}"
);
}
#[test]
fn simulation_parity_recent_source_and_output_both_skip() {
{
let (_d, root, target) = valid_fixture(1);
let src = root.join("src/main.rs");
touch_future(&src);
let runner = FakeCleanupRunner::new(&root, &target, 1);
let noop = NoopObserver;
for mode in [CleanMode::Simulate, CleanMode::CargoPreview] {
let report = clean_with(&root, 0, &[], mode, &runner, &noop).unwrap();
assert!(
report.results.is_empty()
|| report
.results
.iter()
.all(|r| r.outcome == CleanOutcome::Skipped),
"recent source must not be cleanable: {:?}",
report.results
);
for r in &report.results {
assert_ne!(r.outcome, CleanOutcome::Simulated);
assert_ne!(r.outcome, CleanOutcome::Previewed);
}
}
assert!(runner.clean_calls().is_empty());
}
{
let (_d, root, target) = valid_fixture(1);
touch_future(&target.join("artifact.bin"));
let runner = FakeCleanupRunner::new(&root, &target, 1);
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
for r in &report.results {
assert_ne!(r.outcome, CleanOutcome::Simulated);
}
assert!(runner.clean_calls().is_empty());
}
}
struct RaceRunner {
base_root: PathBuf,
base_target: PathBuf,
calls: std::sync::atomic::AtomicU64,
clean_calls: std::sync::atomic::AtomicU64,
mutate: Box<dyn Fn() + Send + Sync>,
second_target: Option<PathBuf>,
second_build: Option<PathBuf>,
}
impl RaceRunner {
fn new(root: &Path, target: &Path, mutate: impl Fn() + Send + Sync + 'static) -> Self {
Self {
base_root: root.to_path_buf(),
base_target: target.to_path_buf(),
calls: std::sync::atomic::AtomicU64::new(0),
clean_calls: std::sync::atomic::AtomicU64::new(0),
mutate: Box::new(mutate),
second_target: None,
second_build: None,
}
}
fn with_second_target(root: &Path, target: &Path, second: PathBuf) -> Self {
Self {
base_root: root.to_path_buf(),
base_target: target.to_path_buf(),
calls: std::sync::atomic::AtomicU64::new(0),
clean_calls: std::sync::atomic::AtomicU64::new(0),
mutate: Box::new(|| {}),
second_target: Some(second),
second_build: None,
}
}
}
impl CargoRunner for RaceRunner {
fn run(&self, _cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
if args.first().is_some_and(|a| a == "clean") {
self.clean_calls
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
if args.first().is_some_and(|a| a == "locate-project") {
let json = serde_json::json!({"root": self.base_root.join("Cargo.toml")});
return Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: serde_json::to_vec(&json).unwrap(),
stderr: Vec::new(),
});
}
if args.first().is_some_and(|a| a == "metadata") {
let n = self
.calls
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if n >= 1 {
(self.mutate)();
if let Some(second) = &self.second_target {
let json = serde_json::json!({
"packages": [{"id": "m0", "name": "m0", "manifest_path": self.base_root.join("Cargo.toml")}],
"workspace_members": ["m0"],
"workspace_root": self.base_root,
"target_directory": second,
});
return Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: serde_json::to_vec(&json).unwrap(),
stderr: Vec::new(),
});
}
}
let mut json = serde_json::json!({
"packages": [{"id": "m0", "name": "m0", "manifest_path": self.base_root.join("Cargo.toml")}],
"workspace_members": ["m0"],
"workspace_root": self.base_root,
"target_directory": self.base_target,
});
if let Some(b) = &self.second_build
&& n >= 1
{
json["build_directory"] = serde_json::json!(b);
}
return Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: serde_json::to_vec(&json).unwrap(),
stderr: Vec::new(),
});
}
Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: b"mock cargo clean success".to_vec(),
stderr: Vec::new(),
})
}
}
impl CleanupRunner for RaceRunner {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
CargoRunner::run(self, cwd, args)
}
fn run_with_env(
&self,
cwd: &Path,
args: &[OsString],
_env: &[(OsString, OsString)],
) -> io::Result<ProcessOutput> {
CargoRunner::run(self, cwd, args)
}
}
#[test]
fn race_target_replacement_skips_before_clean() {
let (_d, root, target) = valid_fixture(1);
let other_base = root.parent().unwrap().join("other-target-race");
std::fs::create_dir_all(&other_base).unwrap();
std::fs::write(
other_base.join("CACHEDIR.TAG"),
b"Signature: 8a477f597d28d172789f06886806bc55\n",
)
.unwrap();
let noop = NoopObserver;
for mode in [
CleanMode::Simulate,
CleanMode::CargoPreview,
CleanMode::Execute,
] {
let runner = RaceRunner::with_second_target(&root, &target, other_base.clone());
let report = clean_with(&root, 0, &[], mode, &runner, &noop).unwrap();
assert_eq!(report.results.len(), 1, "{mode:?}");
assert_eq!(report.results[0].outcome, CleanOutcome::Skipped, "{mode:?}");
assert!(report.results[0].detail.contains("changed"), "{mode:?}");
}
}
#[test]
fn direct_metadata_refresh_detects_workspace_root_and_member_changes() {
for mutation_kind in ["root", "member", "malformed"] {
for mode in [
CleanMode::CargoPreview,
CleanMode::Simulate,
CleanMode::Execute,
] {
let (_d, root, target) = valid_fixture(1);
let mutation = if mutation_kind == "root" {
MetadataMutation::WorkspaceRoot(
root.parent().unwrap().join("changed-workspace"),
)
} else if mutation_kind == "member" {
let member_manifest = root.join("new-member/Cargo.toml");
MetadataMutation::AddMember(member_manifest)
} else {
MetadataMutation::Malformed
};
let mut inner = StagedCargo::new();
inner.add(&root, target, None);
let runner = MetadataMutationRunner {
inner,
metadata_calls: std::sync::atomic::AtomicUsize::new(0),
mutation,
};
let report = clean_with(&root, 0, &[], mode, &runner, &NoopObserver).unwrap();
if mutation_kind == "member" {
assert_eq!(report.results.len(), 1, "{mutation_kind} {mode:?}");
assert_eq!(
report.results[0].outcome,
CleanOutcome::Skipped,
"{mutation_kind} {mode:?}: {}",
report.results[0].detail
);
assert!(
report.results[0].detail.contains("member set changed"),
"{}",
report.results[0].detail
);
assert!(report.scope_blocked.is_none(), "{mutation_kind} {mode:?}");
} else {
assert!(
report.scope_blocked.is_some(),
"{mutation_kind} {mode:?}: hoisted failure must scope-block: {report:?}"
);
assert_eq!(
report.scope_blocked.as_ref().map(|b| b.reason),
Some(ScopeBlockReason::OwnershipUnproven),
"{mutation_kind} {mode:?}"
);
assert!(
report
.scope_blocked
.as_ref()
.is_some_and(|b| b.message.contains("could not be re-proven")),
"{mutation_kind} {mode:?}: {:?}",
report.scope_blocked
);
assert!(
report.results.is_empty(),
"{mutation_kind} {mode:?}: blocked scope has no rows"
);
if mutation_kind == "root" {
assert!(
report
.scope_blocked
.as_ref()
.is_some_and(|b| b.message.contains("changed identity")),
"{:?}",
report.scope_blocked
);
} else {
assert!(
report
.scope_blocked
.as_ref()
.is_some_and(|b| b.message.contains("did not re-resolve")),
"{:?}",
report.scope_blocked
);
}
}
assert_eq!(report.counters.proof_cargo_locate_calls, 1);
assert_eq!(
report.counters.proof_cargo_metadata_calls,
if mutation_kind == "member" { 3 } else { 1 }
);
assert!(
runner.inner.clean_calls().is_empty(),
"{mutation_kind} {mode:?}"
);
}
}
}
#[test]
fn simulation_parity_changed_build_dir_and_unsupported_capability_both_skip() {
{
let (_d, root, target) = valid_fixture(1);
let build_a = target.clone();
let build_b = root.parent().unwrap().join("other-build-race");
std::fs::create_dir_all(&build_b).unwrap();
std::fs::write(
build_b.join("CACHEDIR.TAG"),
b"Signature: 8a477f597d28d172789f06886806bc55\n",
)
.unwrap();
struct BuildChangingRunner {
root: PathBuf,
target: PathBuf,
build_b: PathBuf,
calls: std::sync::atomic::AtomicU64,
}
impl CargoRunner for BuildChangingRunner {
fn run(&self, _cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
if args.first().is_some_and(|a| a == "locate-project") {
let json = serde_json::json!({"root": self.root.join("Cargo.toml")});
return Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: serde_json::to_vec(&json).unwrap(),
stderr: Vec::new(),
});
}
if args.first().is_none_or(|a| a != "metadata") {
return Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: b"mock cargo clean success".to_vec(),
stderr: Vec::new(),
});
}
let n = self
.calls
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let build = if n == 0 {
self.target.clone()
} else {
self.build_b.clone()
};
let json = serde_json::json!({
"packages": [{"id": "m0", "name": "m0", "manifest_path": self.root.join("Cargo.toml")}],
"workspace_members": ["m0"],
"workspace_root": self.root,
"target_directory": self.target,
"build_directory": build,
});
Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: serde_json::to_vec(&json).unwrap(),
stderr: Vec::new(),
})
}
}
impl CleanupRunner for BuildChangingRunner {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
CargoRunner::run(self, cwd, args)
}
fn run_with_env(
&self,
cwd: &Path,
args: &[OsString],
_env: &[(OsString, OsString)],
) -> io::Result<ProcessOutput> {
CargoRunner::run(self, cwd, args)
}
}
let noop = NoopObserver;
for mode in [CleanMode::Simulate, CleanMode::CargoPreview] {
let runner = BuildChangingRunner {
root: root.clone(),
target: target.clone(),
build_b: build_b.clone(),
calls: std::sync::atomic::AtomicU64::new(0),
};
let report = clean_with(&root, 0, &[], mode, &runner, &noop).unwrap();
assert!(
report.results.is_empty()
|| report
.results
.iter()
.all(|r| r.outcome == CleanOutcome::Skipped),
"{mode:?}: {report:?}"
);
}
let _ = build_a;
}
}
#[test]
fn race_covering_root_disappears_skips() {
let (_d, root, target) = valid_fixture(1);
let target_clone = target.clone();
let runner = RaceRunner::new(&root, &target, move || {
let _ = fs::remove_dir_all(&target_clone);
});
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
for r in &report.results {
assert_ne!(r.outcome, CleanOutcome::Simulated);
}
}
#[test]
fn race_output_becomes_recent_skips() {
let (_d, root, target) = valid_fixture(1);
let target_clone = target.clone();
let runner = RaceRunner::new(&root, &target, move || {
let p = target_clone.join("artifact.bin");
let future = SystemTime::now() + Duration::from_secs(3600);
if let Ok(f) = fs::OpenOptions::new().write(true).open(&p) {
let _ = f.set_modified(future);
}
if let Ok(dir) = fs::File::open(&target_clone) {
let _ = dir.set_modified(future);
}
});
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
for r in &report.results {
assert_ne!(r.outcome, CleanOutcome::Simulated);
}
}
#[test]
fn race_source_becomes_recent_skips() {
let (_d, root, target) = valid_fixture(1);
let root_clone = root.clone();
let runner = RaceRunner::new(&root, &target, move || {
let p = root_clone.join("src/main.rs");
let future = SystemTime::now() + Duration::from_secs(3600);
if let Ok(f) = fs::OpenOptions::new().write(true).open(&p) {
let _ = f.set_modified(future);
}
});
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
for r in &report.results {
assert_ne!(r.outcome, CleanOutcome::Simulated);
}
}
#[test]
fn fresh_size_policy_rejects_shrunk_output_before_any_cargo_clean() {
for mode in [
CleanMode::CargoPreview,
CleanMode::Simulate,
CleanMode::Execute,
] {
let (_d, root, target) = valid_fixture(1);
let changed_target = target.clone();
let did_shrink = std::sync::atomic::AtomicBool::new(false);
let runner = RaceRunner::new(&root, &target, move || {
if !did_shrink.swap(true, std::sync::atomic::Ordering::Relaxed) {
fs::remove_file(changed_target.join("artifact.bin")).unwrap();
backdate(
&changed_target,
SystemTime::now() - Duration::from_secs(3600),
);
}
});
let policy = CleanupPolicy {
min_reclaimable_bytes: 6000,
..Default::default()
};
let report = clean_with_roots_policy(
std::slice::from_ref(&root),
0,
&[],
mode,
&runner,
&NoopObserver,
&policy,
)
.unwrap();
assert_eq!(report.results.len(), 1, "{mode:?}");
assert_eq!(
report.results[0].policy_disposition,
Some(PolicyDisposition::BelowMinimumSize),
"{mode:?}: {}",
report.results[0].detail
);
assert_eq!(
runner
.clean_calls
.load(std::sync::atomic::Ordering::Relaxed),
0,
"{mode:?}"
);
}
}
#[test]
fn fresh_source_and_output_age_policy_rejects_before_any_cargo_clean() {
for change_output in [false, true] {
for mode in [
CleanMode::CargoPreview,
CleanMode::Simulate,
CleanMode::Execute,
] {
let (_d, root, target) = valid_fixture(1);
let changed_root = root.clone();
let changed_target = target.clone();
let runner = RaceRunner::new(&root, &target, move || {
let touched = if change_output {
changed_target.join("artifact.bin")
} else {
changed_root.join("src/main.rs")
};
let now = SystemTime::now() - Duration::from_secs(60);
let file = fs::OpenOptions::new().write(true).open(touched).unwrap();
file.set_modified(now).unwrap();
});
let policy = CleanupPolicy {
min_inactive_seconds: Some(1800),
..Default::default()
};
let report = clean_with_roots_policy(
std::slice::from_ref(&root),
0,
&[],
mode,
&runner,
&NoopObserver,
&policy,
)
.unwrap();
assert_eq!(report.results.len(), 1, "{change_output} {mode:?}");
assert_eq!(
report.results[0].policy_disposition,
Some(PolicyDisposition::TooRecentForPolicy),
"{change_output} {mode:?}: {}",
report.results[0].detail
);
assert_eq!(
runner
.clean_calls
.load(std::sync::atomic::Ordering::Relaxed),
0,
"{change_output} {mode:?}"
);
}
}
}
#[test]
fn excluded_workspace_still_makes_nonexcluded_shared_output_non_cleanable() {
let temp = tempfile::tempdir().unwrap();
let sandbox = temp.path().join("scope");
let shared = sandbox.join("shared-target");
fs::create_dir_all(&shared).unwrap();
fs::write(
shared.join("CACHEDIR.TAG"),
b"Signature: 8a477f597d28d172789f06886806bc55\n",
)
.unwrap();
fs::write(shared.join("artifact.bin"), vec![0u8; 8192]).unwrap();
for name in ["included", "excluded"] {
let project = sandbox.join(name);
fs::create_dir_all(project.join("src")).unwrap();
fs::write(
project.join("Cargo.toml"),
format!("[package]\nname='{name}'\nversion='0.1.0'\nedition='2021'\n"),
)
.unwrap();
fs::write(project.join("Cargo.lock"), "version = 4\n").unwrap();
fs::write(project.join("src/main.rs"), "fn main() {}\n").unwrap();
fs::create_dir_all(project.join(".cargo")).unwrap();
fs::write(
project.join(".cargo/config.toml"),
format!("[build]\ntarget-dir = {:?}\n", shared),
)
.unwrap();
}
backdate(temp.path(), SystemTime::now() - Duration::from_secs(3600));
let policy = CleanupPolicy {
include: vec!["**".into()],
exclude: vec!["**/excluded".into()],
..Default::default()
};
let report = clean_with_roots_policy(
std::slice::from_ref(&sandbox),
0,
&[],
CleanMode::Simulate,
&SystemCleanupRunner,
&NoopObserver,
&policy,
)
.unwrap();
assert_eq!(
report.results.len(),
2,
"both workspaces must remain in the ownership universe"
);
assert!(
report
.results
.iter()
.all(|r| r.ownership == OutputOwnershipClass::Shared
&& r.outcome == CleanOutcome::Skipped)
);
assert!(
report
.results
.iter()
.any(|r| r.policy_disposition == Some(PolicyDisposition::Excluded)),
"{report:?}"
);
assert!(
report
.results
.iter()
.any(|r| r.policy_disposition.is_none()),
"included owner must still be blocked by excluded owner's shared output"
);
}
#[test]
fn race_marker_disappears_and_changes_skip() {
{
let (_d, root, target) = valid_fixture(1);
let target_clone = target.clone();
let runner = RaceRunner::new(&root, &target, move || {
let _ = fs::remove_file(target_clone.join("CACHEDIR.TAG"));
});
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
assert_eq!(report.results[0].outcome, CleanOutcome::Skipped);
assert!(report.results[0].detail.contains("CACHEDIR"));
}
{
let (_d, root, target) = valid_fixture(1);
let target_clone = target.clone();
let runner = RaceRunner::new(&root, &target, move || {
let _ = fs::write(target_clone.join("CACHEDIR.TAG"), b"corrupted\n");
let old = SystemTime::now() - Duration::from_secs(3600);
backdate(&target_clone, old);
});
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
assert_eq!(report.results[0].outcome, CleanOutcome::Skipped);
}
}
#[test]
fn race_covering_becomes_symlink_skips_and_changes_classification() {
let (_d, root, target) = valid_fixture(1);
let target_clone = target.clone();
let other = root.parent().unwrap().join("symlink-other");
std::fs::create_dir_all(&other).unwrap();
let runner = RaceRunner::new(&root, &target, move || {
let _ = fs::remove_dir_all(&target_clone);
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
let _ = symlink(&other, &target_clone);
}
#[cfg(not(unix))]
{
let _ = fs::create_dir_all(&target_clone);
}
});
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
for r in &report.results {
assert_ne!(r.outcome, CleanOutcome::Simulated);
}
}
#[test]
fn cleanup_progress_is_determinate_through_observer_path() {
use crate::progress::{ScanPhase, TestObserver};
for mode in [
CleanMode::CargoPreview,
CleanMode::Simulate,
CleanMode::Execute,
] {
let (_d, root, target) = valid_fixture(1);
let runner = FakeCleanupRunner::new(&root, &target, 1);
let observer = TestObserver::new();
let expected_phase = match mode {
CleanMode::CargoPreview => ScanPhase::CleanupPreview,
CleanMode::Simulate => ScanPhase::CleanupSimulate,
CleanMode::Execute => ScanPhase::CleanupExecute,
};
let report = clean_with(&root, 0, &[], mode, &runner, &observer).unwrap();
assert_eq!(report.results.len(), 1);
let total = observer.total_for(expected_phase);
assert!(
total.is_some(),
"{mode:?} must set determinate total through observer"
);
let total = total.unwrap();
assert_eq!(total, 1, "{mode:?} candidate count must be determinate");
assert_eq!(
observer.completed_count(expected_phase),
total as usize,
"{mode:?} done must equal total"
);
}
}
#[test]
fn scan_analysis_total_is_determinate_through_real_path() {
use crate::progress::{ScanPhase, TestObserver};
let (_d, root, target) = valid_fixture(1);
let runner = FakeCleanupRunner::new(&root, &target, 1);
let adapter = WorkspaceCleanupAdapter { runner: &runner };
let mut counters = ScanCounters::default();
let mut diags = Vec::new();
let observer = TestObserver::new();
let manifests = vec![root.join("Cargo.toml")];
let workspaces = workspace::resolve_workspaces(
&manifests,
&adapter,
&mut counters,
&mut diags,
&observer,
);
assert_eq!(workspaces.len(), 1);
let groups = workspace::build_groups(&workspaces);
assert_eq!(groups.len(), 1);
let start = SystemTime::now();
let cutoff = start.checked_sub(Duration::from_secs(0)).unwrap();
let physical = workspace::analyze_groups(
&workspaces,
groups.clone(),
start,
cutoff,
Duration::from_secs(0),
&mut counters,
&mut diags,
&observer,
);
assert_eq!(physical.len(), 1);
assert_eq!(observer.total_for(ScanPhase::Analysis), Some(1));
assert_eq!(observer.completed_count(ScanPhase::Analysis), 1);
}
#[derive(Clone)]
struct StagedOutput {
target: PathBuf,
build: Option<PathBuf>,
}
struct FakeWs {
root: PathBuf,
members: Vec<PathBuf>,
target: PathBuf,
build: Option<PathBuf>,
stage: Option<(usize, StagedOutput)>,
fail_metadata_from: Option<usize>,
}
struct StagedCargo {
ws: Vec<FakeWs>,
calls: Mutex<Vec<RecordedCall>>,
metadata_calls: Mutex<Vec<usize>>,
clean_removes: Mutex<Vec<PathBuf>>,
clean_hook: Mutex<Option<Box<dyn Fn() + Send + Sync>>>,
}
fn cargo_ok(json: serde_json::Value) -> ProcessOutput {
ProcessOutput {
success: true,
code: Some(0),
stdout: serde_json::to_vec(&json).unwrap(),
stderr: Vec::new(),
}
}
fn cargo_fail(stderr: &str) -> ProcessOutput {
ProcessOutput {
success: false,
code: Some(1),
stdout: Vec::new(),
stderr: stderr.as_bytes().to_vec(),
}
}
impl StagedCargo {
fn new() -> Self {
Self {
ws: Vec::new(),
calls: Mutex::new(Vec::new()),
metadata_calls: Mutex::new(Vec::new()),
clean_removes: Mutex::new(Vec::new()),
clean_hook: Mutex::new(None),
}
}
fn add(&mut self, root: &Path, target: PathBuf, build: Option<PathBuf>) -> &mut Self {
self.ws.push(FakeWs {
root: root.to_path_buf(),
members: vec![root.to_path_buf()],
target,
build,
stage: None,
fail_metadata_from: None,
});
self.metadata_calls.lock().unwrap().push(0);
self
}
fn stage(
&mut self,
index: usize,
from_call: usize,
target: PathBuf,
build: Option<PathBuf>,
) {
self.ws[index].stage = Some((from_call, StagedOutput { target, build }));
}
fn fail_metadata_from(&mut self, index: usize, from_call: usize) {
self.ws[index].fail_metadata_from = Some(from_call);
}
fn on_clean(&mut self, hook: impl Fn() + Send + Sync + 'static) {
*self.clean_hook.lock().unwrap() = Some(Box::new(hook));
}
fn removes_on_clean(&mut self, paths: Vec<PathBuf>) {
*self.clean_removes.lock().unwrap() = paths;
}
fn calls(&self) -> Vec<RecordedCall> {
self.calls.lock().unwrap().clone()
}
fn clean_calls(&self) -> Vec<RecordedCall> {
self.calls()
.into_iter()
.filter(|(_, args, _)| args.first().is_some_and(|a| a == "clean"))
.collect()
}
fn dry_run_calls(&self) -> Vec<RecordedCall> {
self.clean_calls()
.into_iter()
.filter(|(_, args, _)| args.iter().any(|a| a == "--dry-run"))
.collect()
}
fn find_ws(&self, manifest: &OsStr) -> Option<usize> {
let path = Path::new(manifest);
let key = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
self.ws.iter().position(|w| {
w.members.iter().any(|m| {
let member_manifest = m.join("Cargo.toml");
fs::canonicalize(&member_manifest).unwrap_or(member_manifest) == key
})
})
}
fn metadata_for(&self, index: usize) -> usize {
self.metadata_calls.lock().unwrap()[index]
}
}
impl CargoRunner for StagedCargo {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
self.calls
.lock()
.unwrap()
.push((cwd.to_path_buf(), args.to_vec(), Vec::new()));
self.dispatch(args)
}
}
impl StagedCargo {
fn dispatch(&self, args: &[OsString]) -> io::Result<ProcessOutput> {
if args.first().is_some_and(|a| a == "locate-project") {
let manifest = args.last().unwrap();
return Ok(match self.find_ws(manifest) {
Some(i) => cargo_ok(serde_json::json!({
"root": self.ws[i].root.join("Cargo.toml")
})),
None => cargo_fail("locate-project failed"),
});
}
if args.first().is_some_and(|a| a == "metadata") {
let manifest = args.last().unwrap();
let Some(i) = self.find_ws(manifest) else {
return Ok(cargo_fail("cargo metadata failed"));
};
let n = {
let mut counts = self.metadata_calls.lock().unwrap();
counts[i] += 1;
counts[i]
};
if self.ws[i].fail_metadata_from.is_some_and(|from| n >= from) {
return Ok(cargo_fail("cargo metadata failed"));
}
let staged = self.ws[i]
.stage
.as_ref()
.filter(|(from, _)| n >= *from)
.map(|(_, s)| s.clone());
let out = staged.unwrap_or(StagedOutput {
target: self.ws[i].target.clone(),
build: self.ws[i].build.clone(),
});
let members: Vec<String> = (0..self.ws[i].members.len())
.map(|k| format!("m{k}"))
.collect();
let packages: Vec<serde_json::Value> = self.ws[i]
.members
.iter()
.enumerate()
.map(|(k, m)| {
serde_json::json!({
"id": format!("m{k}"),
"name": format!("m{k}"),
"manifest_path": m.join("Cargo.toml"),
})
})
.collect();
let mut json = serde_json::json!({
"packages": packages,
"workspace_members": members,
"workspace_root": self.ws[i].root,
"target_directory": out.target,
});
if let Some(b) = &out.build {
json["build_directory"] = serde_json::json!(b);
}
return Ok(cargo_ok(json));
}
if !args.iter().any(|a| a == "--dry-run") {
for path in self.clean_removes.lock().unwrap().iter() {
let _ = fs::remove_file(path);
}
if let Some(hook) = self.clean_hook.lock().unwrap().as_ref() {
hook();
}
}
Ok(ProcessOutput {
success: true,
code: Some(0),
stdout: b"mock cargo clean success".to_vec(),
stderr: Vec::new(),
})
}
}
impl CleanupRunner for StagedCargo {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
CargoRunner::run(self, cwd, args)
}
fn run_with_env(
&self,
cwd: &Path,
args: &[OsString],
env: &[(OsString, OsString)],
) -> io::Result<ProcessOutput> {
self.calls
.lock()
.unwrap()
.push((cwd.to_path_buf(), args.to_vec(), env.to_vec()));
self.dispatch(args)
}
}
struct ParallelProbeRunner {
inner: StagedCargo,
active: std::sync::atomic::AtomicUsize,
peak: std::sync::atomic::AtomicUsize,
}
impl CargoRunner for ParallelProbeRunner {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
let metadata = args.first().is_some_and(|arg| arg == "metadata");
if metadata {
let active = self
.active
.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
+ 1;
self.peak
.fetch_max(active, std::sync::atomic::Ordering::SeqCst);
std::thread::sleep(Duration::from_millis(4));
}
let output = CargoRunner::run(&self.inner, cwd, args);
if metadata {
self.active
.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
}
output
}
}
impl CleanupRunner for ParallelProbeRunner {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
CargoRunner::run(self, cwd, args)
}
fn run_with_env(
&self,
cwd: &Path,
args: &[OsString],
env: &[(OsString, OsString)],
) -> io::Result<ProcessOutput> {
self.inner.run_with_env(cwd, args, env)
}
}
enum MetadataMutation {
WorkspaceRoot(PathBuf),
AddMember(PathBuf),
Malformed,
}
struct MetadataMutationRunner {
inner: StagedCargo,
metadata_calls: std::sync::atomic::AtomicUsize,
mutation: MetadataMutation,
}
impl CargoRunner for MetadataMutationRunner {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
let mut output = CargoRunner::run(&self.inner, cwd, args)?;
if args.first().is_some_and(|arg| arg == "metadata")
&& self
.metadata_calls
.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
>= 1
&& output.success
{
match &self.mutation {
MetadataMutation::WorkspaceRoot(root) => {
let mut json: serde_json::Value = serde_json::from_slice(&output.stdout)
.expect("staged metadata is valid JSON");
json["workspace_root"] = serde_json::json!(root);
output.stdout = serde_json::to_vec(&json).unwrap();
}
MetadataMutation::AddMember(manifest) => {
fs::create_dir_all(manifest.parent().unwrap()).unwrap();
fs::write(manifest, "").unwrap();
let mut json: serde_json::Value = serde_json::from_slice(&output.stdout)
.expect("staged metadata is valid JSON");
json["packages"]
.as_array_mut()
.unwrap()
.push(serde_json::json!({
"id": "raced-member",
"name": "raced-member",
"manifest_path": manifest,
}));
json["workspace_members"]
.as_array_mut()
.unwrap()
.push(serde_json::json!("raced-member"));
output.stdout = serde_json::to_vec(&json).unwrap();
}
MetadataMutation::Malformed => {
output.stdout = b"not json".to_vec();
}
}
}
Ok(output)
}
}
impl CleanupRunner for MetadataMutationRunner {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
CargoRunner::run(self, cwd, args)
}
fn run_with_env(
&self,
cwd: &Path,
args: &[OsString],
env: &[(OsString, OsString)],
) -> io::Result<ProcessOutput> {
self.inner.run_with_env(cwd, args, env)
}
}
fn ws_root(dir: &Path, name: &str) -> PathBuf {
let root = dir.join(name);
fs::create_dir_all(root.join("src")).unwrap();
fs::write(
root.join("Cargo.toml"),
format!("[package]\nname='{name}'\nversion='0.1.0'\nedition='2021'\n"),
)
.unwrap();
fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap();
root
}
fn cargo_output(path: &Path, bytes: usize) -> PathBuf {
fs::create_dir_all(path).unwrap();
fs::write(
path.join("CACHEDIR.TAG"),
b"Signature: 8a477f597d28d172789f06886806bc55\n",
)
.unwrap();
fs::write(path.join("artifact.bin"), vec![1u8; bytes]).unwrap();
path.to_path_buf()
}
fn canonical(path: &Path) -> PathBuf {
fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}
fn row_for<'a>(report: &'a CleanReport, root: &Path) -> &'a CleanResult {
let want = canonical(root);
report
.results
.iter()
.find(|r| r.display_path == want)
.unwrap_or_else(|| {
panic!(
"no cleanup result row for {}; rows: {:?}",
want.display(),
report
.results
.iter()
.map(|r| (r.display_path.display().to_string(), r.outcome))
.collect::<Vec<_>>()
)
})
}
fn sibling_ws_fixture(tag: &str) -> (TempDir, PathBuf, PathBuf, PathBuf) {
let d = tempfile::tempdir().unwrap();
let root = ws_root(d.path(), "ws");
let target = cargo_output(&root.join("target"), 4096);
let build = cargo_output(&root.join("build"), 4096);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let _ = tag;
(d, root, target, build)
}
fn staged_sibling_runner(root: &Path, target: &Path, build: &Path) -> StagedCargo {
let mut runner = StagedCargo::new();
runner.add(root, target.to_path_buf(), Some(build.to_path_buf()));
runner
}
#[test]
fn distinct_private_target_and_build_is_one_cleanable_unit() {
for mode in [
CleanMode::CargoPreview,
CleanMode::Simulate,
CleanMode::Execute,
] {
let (_d, root, target, build) = sibling_ws_fixture("siblings");
let mut runner = staged_sibling_runner(&root, &target, &build);
runner.removes_on_clean(vec![
target.join("artifact.bin"),
build.join("artifact.bin"),
]);
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], mode, &runner, &noop)
.unwrap_or_else(|e| panic!("{mode:?} {e}"));
assert_eq!(report.results.len(), 1, "{mode:?}: one result per unit");
let row = row_for(&report, &root);
let expected = match mode {
CleanMode::CargoPreview => CleanOutcome::Previewed,
CleanMode::Simulate => CleanOutcome::Simulated,
CleanMode::Execute => CleanOutcome::Cleaned,
};
assert_eq!(row.outcome, expected, "{mode:?}: {}", row.detail);
assert_eq!(row.output_roots.len(), 2, "{mode:?}: both roots");
assert_eq!(row.ownership, OutputOwnershipClass::PrivateBounded);
match mode {
CleanMode::CargoPreview => {
assert_eq!(runner.dry_run_calls().len(), 1, "{mode:?}");
assert!(target.join("artifact.bin").exists());
assert!(build.join("artifact.bin").exists());
}
CleanMode::Simulate => {
assert!(
runner.clean_calls().is_empty(),
"{mode:?}: simulation invokes no cargo clean"
);
assert!(target.join("artifact.bin").exists());
}
CleanMode::Execute => {
assert_eq!(runner.clean_calls().len(), 1, "{mode:?}");
assert!(!target.join("artifact.bin").exists());
assert!(!build.join("artifact.bin").exists());
}
}
}
}
#[test]
fn one_invocation_one_result_progress_total_and_no_sibling_row() {
use crate::progress::{ScanPhase, TestObserver};
for mode in [
CleanMode::CargoPreview,
CleanMode::Simulate,
CleanMode::Execute,
] {
let (_d, root, target, build) = sibling_ws_fixture("one-invocation");
let mut runner = staged_sibling_runner(&root, &target, &build);
runner.removes_on_clean(vec![
target.join("artifact.bin"),
build.join("artifact.bin"),
]);
let observer = TestObserver::new();
let phase = match mode {
CleanMode::CargoPreview => ScanPhase::CleanupPreview,
CleanMode::Simulate => ScanPhase::CleanupSimulate,
CleanMode::Execute => ScanPhase::CleanupExecute,
};
let report = clean_with(&root, 0, &[], mode, &runner, &observer).unwrap();
assert_eq!(report.results.len(), 1, "{mode:?}");
assert_eq!(observer.total_for(phase), Some(1), "{mode:?}");
assert_eq!(observer.completed_count(phase), 1, "{mode:?}");
let clean_calls = runner.clean_calls().len();
assert_eq!(
clean_calls,
usize::from(mode != CleanMode::Simulate),
"{mode:?}"
);
let text = report.render();
assert!(
!text.contains("vanished") && !text.contains("Skipped"),
"{mode:?}: no second vanished/skipped sibling row: {text}"
);
}
}
#[test]
fn private_target_with_external_unproven_build_skips_entire_unit() {
for mode in [
CleanMode::CargoPreview,
CleanMode::Simulate,
CleanMode::Execute,
] {
let d = tempfile::tempdir().unwrap();
let root = ws_root(d.path(), "ws");
let target = cargo_output(&root.join("target"), 4096);
let build = cargo_output(&d.path().join("shared-build"), 4096);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root, target, Some(build));
let noop = NoopObserver;
let report = clean_with(d.path(), 0, &[], mode, &runner, &noop).unwrap();
assert_eq!(report.results.len(), 1, "{mode:?}");
let row = row_for(&report, &root);
assert_eq!(row.outcome, CleanOutcome::Skipped, "{mode:?}");
assert_eq!(
row.ownership,
OutputOwnershipClass::ExternalUnproven,
"{mode:?}"
);
assert!(
row.detail.contains("build output"),
"{mode:?}: {}",
row.detail
);
assert!(
row.detail.contains("external-unproven"),
"{mode:?}: {}",
row.detail
);
assert!(runner.clean_calls().is_empty(), "{mode:?}");
}
}
#[test]
fn private_target_with_shared_build_skips_entire_unit() {
for mode in [
CleanMode::CargoPreview,
CleanMode::Simulate,
CleanMode::Execute,
] {
let d = tempfile::tempdir().unwrap();
let root_a = ws_root(d.path(), "a");
let root_b = ws_root(d.path(), "b");
let target_a = cargo_output(&root_a.join("target"), 4096);
let shared = cargo_output(&d.path().join("shared"), 4096);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root_a, target_a, Some(shared.clone()));
runner.add(&root_b, shared, None);
let noop = NoopObserver;
let report = clean_with(d.path(), 0, &[], mode, &runner, &noop).unwrap();
let row = row_for(&report, &root_a);
assert_eq!(row.outcome, CleanOutcome::Skipped, "{mode:?}");
assert_eq!(row.ownership, OutputOwnershipClass::Shared, "{mode:?}");
assert!(
row.detail.contains("build output"),
"{mode:?}: {}",
row.detail
);
assert!(row.detail.contains("shared"), "{mode:?}: {}", row.detail);
assert!(runner.clean_calls().is_empty(), "{mode:?}");
}
}
#[test]
fn external_unproven_target_with_private_build_skips_entire_unit() {
for mode in [
CleanMode::CargoPreview,
CleanMode::Simulate,
CleanMode::Execute,
] {
let d = tempfile::tempdir().unwrap();
let root = ws_root(d.path(), "ws");
let target = cargo_output(&d.path().join("external-target"), 4096);
let build = cargo_output(&root.join("build"), 4096);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root, target, Some(build));
let noop = NoopObserver;
let report = clean_with(d.path(), 0, &[], mode, &runner, &noop).unwrap();
let row = row_for(&report, &root);
assert_eq!(row.outcome, CleanOutcome::Skipped, "{mode:?}");
assert!(
row.detail.contains("target output"),
"{mode:?}: {}",
row.detail
);
assert!(runner.clean_calls().is_empty(), "{mode:?}");
}
}
#[test]
fn uncertain_build_identity_skips_entire_unit() {
for mode in [
CleanMode::CargoPreview,
CleanMode::Simulate,
CleanMode::Execute,
] {
let d = tempfile::tempdir().unwrap();
let root = ws_root(d.path(), "ws");
let target = cargo_output(&root.join("target"), 4096);
let build = root.join("build");
fs::write(&build, b"not a directory").unwrap();
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root, target, Some(build));
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], mode, &runner, &noop).unwrap();
assert!(
report.results.is_empty()
|| report
.results
.iter()
.all(|r| r.outcome == CleanOutcome::Skipped),
"{mode:?}: {report:?}"
);
for r in &report.results {
assert!(r.detail.contains("uncertain"), "{mode:?}: {}", r.detail);
}
assert!(runner.clean_calls().is_empty(), "{mode:?}");
}
}
#[cfg(unix)]
#[test]
fn symlink_build_identity_skips_entire_unit() {
use std::os::unix::fs::symlink;
let d = tempfile::tempdir().unwrap();
let root = ws_root(d.path(), "ws");
let target = cargo_output(&root.join("target"), 4096);
let real = cargo_output(&d.path().join("real-build"), 4096);
let link = root.join("build");
symlink(&real, &link).unwrap();
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root, target, Some(link));
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
assert!(
report.results.is_empty()
|| report
.results
.iter()
.all(|r| r.outcome == CleanOutcome::Skipped),
"{report:?}"
);
assert!(runner.clean_calls().is_empty());
}
fn synthetic_mixed_unit(
base: &Path,
target_class: OutputOwnershipClass,
build_class: OutputOwnershipClass,
) -> workspace::CleanupUnit {
let a = base.join("ws/target");
let b = base.join("ws/build");
let measured = |p: &Path, class| workspace::AffectedGroup {
display: p.to_path_buf(),
covering: vec![p.to_path_buf()],
ownership: class,
kinds: Vec::new(),
measured: Some(PhysicalOutputGroup {
covering_roots: vec![p.to_path_buf()],
physical_paths: vec![p.to_path_buf()],
display_path: p.to_path_buf(),
owners: Vec::new(),
ownership: class,
bytes: 1024,
metric: SizeMetric::Allocated,
newest_mtime: None,
artifact_entries: 1,
uncertain: false,
}),
skip: None,
};
let mut target_group = measured(&a, target_class);
target_group.kinds = vec![OutputRootKind::Target];
let mut build_group = measured(&b, build_class);
build_group.kinds = vec![OutputRootKind::Build];
let ws = base.join("ws");
workspace::CleanupUnit {
workspace_idx: 0,
id: WorkspaceId(ws.clone()),
root: ws.clone(),
root_manifest: ws.join("Cargo.toml"),
output: OutputSet {
target: OutputRoot {
kind: OutputRootKind::Target,
logical_path: a.clone(),
physical_path: Some(a.clone()),
exists: true,
is_symlink: false,
},
build: OutputRoot {
kind: OutputRootKind::Build,
logical_path: b.clone(),
physical_path: Some(b.clone()),
exists: true,
is_symlink: false,
},
},
capability: CargoCapabilities {
build_dir: CargoBuildDirCapability::Distinct,
metadata_had_build_directory: true,
env_build_dir_set: false,
},
groups: vec![target_group, build_group],
unmapped: Vec::new(),
covering: vec![a, b],
bytes: 2048,
}
}
#[test]
fn gate_blocks_mixed_class_units_in_every_combination() {
let d = tempfile::tempdir().unwrap();
let base = fs::canonicalize(d.path()).unwrap();
for build_class in [
OutputOwnershipClass::ExternalUnproven,
OutputOwnershipClass::Shared,
OutputOwnershipClass::Uncertain,
] {
let unit =
synthetic_mixed_unit(&base, OutputOwnershipClass::PrivateBounded, build_class);
let err = unit_block_reason(&unit, &base, &[]).unwrap_err();
assert!(err.contains("build output"), "{build_class:?}: {err}");
let unit =
synthetic_mixed_unit(&base, build_class, OutputOwnershipClass::PrivateBounded);
let err = unit_block_reason(&unit, &base, &[]).unwrap_err();
assert!(err.contains("target output"), "{build_class:?}: {err}");
}
let unit = synthetic_mixed_unit(
&base,
OutputOwnershipClass::PrivateBounded,
OutputOwnershipClass::PrivateBounded,
);
assert!(unit_block_reason(&unit, &base, &[]).is_ok());
}
#[test]
fn gate_blocks_unmeasured_and_unmapped_unit_members() {
let d = tempfile::tempdir().unwrap();
let base = fs::canonicalize(d.path()).unwrap();
let mut unit = synthetic_mixed_unit(
&base,
OutputOwnershipClass::PrivateBounded,
OutputOwnershipClass::PrivateBounded,
);
unit.groups[1].measured = None;
unit.groups[1].skip = Some(workspace::GroupSkipReason::ActiveOutput);
let err = unit_block_reason(&unit, &base, &[]).unwrap_err();
assert!(err.contains("build output"), "{err}");
assert!(err.contains("recent"), "{err}");
let mut unit = synthetic_mixed_unit(
&base,
OutputOwnershipClass::PrivateBounded,
OutputOwnershipClass::PrivateBounded,
);
unit.unmapped.push(unit.output.build.clone());
let err = unit_block_reason(&unit, &base, &[]).unwrap_err();
assert!(err.contains("unproven physical identity"), "{err}");
}
#[test]
fn equal_and_nested_target_build_are_one_unit_and_one_invocation() {
for shape in ["equal", "build_under_target", "target_under_build"] {
let d = tempfile::tempdir().unwrap();
let root = ws_root(d.path(), "ws");
let (target, build) = match shape {
"equal" => {
let t = cargo_output(&root.join("target"), 4096);
(t.clone(), t)
}
"build_under_target" => {
let t = cargo_output(&root.join("target"), 8192);
let b = cargo_output(&t.join("build"), 2048);
(t, b)
}
_ => {
let b = cargo_output(&root.join("build"), 8192);
let t = cargo_output(&b.join("target"), 2048);
(t, b)
}
};
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root, target, Some(build));
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::Execute, &runner, &noop).unwrap();
assert_eq!(report.results.len(), 1, "{shape}: one result");
let row = row_for(&report, &root);
assert_eq!(
row.outcome,
CleanOutcome::Cleaned,
"{shape}: {}",
row.detail
);
assert_eq!(row.output_roots.len(), 1, "{shape}: deduplicated union");
assert_eq!(runner.clean_calls().len(), 1, "{shape}: one invocation");
}
}
#[test]
fn cross_workspace_overlap_race_into_target_skips_candidate() {
for mode in [
CleanMode::Simulate,
CleanMode::CargoPreview,
CleanMode::Execute,
] {
let d = tempfile::tempdir().unwrap();
let root_a = ws_root(d.path(), "a");
let root_b = ws_root(d.path(), "b");
let target_a = cargo_output(&root_a.join("target"), 4096);
let target_b = cargo_output(&root_b.join("target"), 4096);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root_a, target_a.clone(), None);
runner.add(&root_b, target_b, None);
runner.stage(1, 2, target_a, None);
let noop = NoopObserver;
let report = clean_with(d.path(), 0, &[], mode, &runner, &noop).unwrap();
let row = row_for(&report, &root_a);
assert_eq!(
row.outcome,
CleanOutcome::Skipped,
"{mode:?}: {}",
row.detail
);
assert!(
row.detail.contains("shared") || row.detail.contains("overlaps"),
"{mode:?}: {}",
row.detail
);
assert!(runner.clean_calls().is_empty(), "{mode:?}: no clean at all");
assert!(
runner.metadata_for(1) >= 2,
"{mode:?}: B must actually be re-resolved by the fresh graph"
);
}
}
#[test]
fn cross_workspace_overlap_race_into_distinct_build_skips_candidate() {
for mode in [
CleanMode::Simulate,
CleanMode::CargoPreview,
CleanMode::Execute,
] {
let d = tempfile::tempdir().unwrap();
let root_a = ws_root(d.path(), "a");
let root_b = ws_root(d.path(), "b");
let target_a = cargo_output(&root_a.join("target"), 4096);
let build_a = cargo_output(&root_a.join("build"), 4096);
let target_b = cargo_output(&root_b.join("target"), 4096);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root_a, target_a, Some(build_a.clone()));
runner.add(&root_b, target_b, None);
runner.stage(1, 2, build_a, None);
let noop = NoopObserver;
let report = clean_with(d.path(), 0, &[], mode, &runner, &noop).unwrap();
let row = row_for(&report, &root_a);
assert_eq!(
row.outcome,
CleanOutcome::Skipped,
"{mode:?}: {}",
row.detail
);
assert!(
row.detail.contains("shared") || row.detail.contains("overlaps"),
"{mode:?}: {}",
row.detail
);
assert!(runner.clean_calls().is_empty(), "{mode:?}");
}
}
#[cfg(unix)]
#[test]
fn cross_workspace_symlink_into_candidate_output_fails_closed() {
use std::os::unix::fs::symlink;
let d = tempfile::tempdir().unwrap();
let root_a = ws_root(d.path(), "a");
let root_b = ws_root(d.path(), "b");
let target_a = cargo_output(&root_a.join("target"), 4096);
let target_b = cargo_output(&root_b.join("target"), 4096);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let link_b = root_b.join("link-target");
symlink(&target_a, &link_b).unwrap();
let _ = target_b;
let mut runner = StagedCargo::new();
runner.add(&root_a, target_a, None);
runner.add(&root_b, target_b, None);
runner.stage(1, 2, link_b, None);
let noop = NoopObserver;
let report = clean_with(d.path(), 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
let row = row_for(&report, &root_a);
assert_eq!(row.outcome, CleanOutcome::Skipped, "{}", row.detail);
assert!(
row.detail.contains("shared") || row.detail.contains("overlaps"),
"{}",
row.detail
);
assert!(runner.clean_calls().is_empty());
}
#[test]
fn cross_workspace_unresolvable_root_into_candidate_output_fails_closed() {
for mode in [
CleanMode::Simulate,
CleanMode::CargoPreview,
CleanMode::Execute,
] {
let d = tempfile::tempdir().unwrap();
let root_a = ws_root(d.path(), "a");
let root_b = ws_root(d.path(), "b");
let target_a = cargo_output(&root_a.join("target"), 4096);
let target_b = cargo_output(&root_b.join("target"), 4096);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root_a, target_a.clone(), None);
runner.add(&root_b, target_b, None);
runner.stage(1, 2, target_a.join("not-created-yet"), None);
let noop = NoopObserver;
let report = clean_with(d.path(), 0, &[], mode, &runner, &noop).unwrap();
let row = row_for(&report, &root_a);
assert_eq!(
row.outcome,
CleanOutcome::Skipped,
"{mode:?}: {}",
row.detail
);
assert!(row.detail.contains("overlaps"), "{mode:?}: {}", row.detail);
assert!(runner.clean_calls().is_empty(), "{mode:?}");
}
}
#[cfg(unix)]
#[test]
fn cross_workspace_symlinked_ancestor_into_candidate_output_fails_closed() {
use std::os::unix::fs::symlink;
let d = tempfile::tempdir().unwrap();
let root_a = ws_root(d.path(), "a");
let root_b = ws_root(d.path(), "b");
let target_a = cargo_output(&root_a.join("target"), 4096);
let target_b = cargo_output(&root_b.join("target"), 4096);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let alias = d.path().join("alias");
symlink(&target_a, &alias).unwrap();
let mut runner = StagedCargo::new();
runner.add(&root_a, target_a, None);
runner.add(&root_b, target_b, None);
runner.stage(1, 2, alias.join("not-created-yet"), None);
let noop = NoopObserver;
let report = clean_with(d.path(), 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
let row = row_for(&report, &root_a);
assert_eq!(row.outcome, CleanOutcome::Skipped, "{}", row.detail);
assert!(row.detail.contains("overlaps"), "{}", row.detail);
assert!(runner.clean_calls().is_empty());
}
#[test]
fn universe_workspace_that_cannot_reresolve_fails_closed() {
let d = tempfile::tempdir().unwrap();
let root_a = ws_root(d.path(), "a");
let root_b = ws_root(d.path(), "b");
let target_a = cargo_output(&root_a.join("target"), 4096);
let target_b = cargo_output(&root_b.join("target"), 4096);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root_a, target_a, None);
runner.add(&root_b, target_b, None);
runner.fail_metadata_from(1, 2);
let noop = NoopObserver;
let report = clean_with(d.path(), 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
assert!(
report.scope_blocked.is_some(),
"proof-time universe failure must scope-block: {report:?}"
);
assert_eq!(
report.scope_blocked.as_ref().map(|b| b.reason),
Some(ScopeBlockReason::OwnershipUnproven)
);
assert!(
report
.scope_blocked
.as_ref()
.is_some_and(|b| b.message.contains("could not be re-proven")
&& b.message.contains("no cleanup commands were run")),
"{:?}",
report.scope_blocked
);
assert!(
report.results.is_empty(),
"blocked scope reports no per-unit rows: {report:?}"
);
assert_eq!(report.counters.proof_cargo_locate_calls, 2);
assert!(runner.clean_calls().is_empty());
}
#[test]
fn initial_shared_overlap_is_decided_conservatively_without_proof() {
for mode in [
CleanMode::Simulate,
CleanMode::CargoPreview,
CleanMode::Execute,
] {
let d = tempfile::tempdir().unwrap();
let root_a = ws_root(d.path(), "a");
let root_b = ws_root(d.path(), "b");
let shared = cargo_output(&d.path().join("shared"), 4096);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root_a, shared.clone(), None);
runner.add(&root_b, shared, None);
runner.stage(1, 2, root_b.join("target"), None);
let noop = NoopObserver;
let report = clean_with(d.path(), 0, &[], mode, &runner, &noop).unwrap();
let row = row_for(&report, &root_a);
assert_eq!(
row.outcome,
CleanOutcome::Skipped,
"{mode:?}: {}",
row.detail
);
assert!(row.detail.contains("shared"), "{mode:?}: {}", row.detail);
assert_eq!(
report.counters.proof_workspaces_refreshed, 0,
"{mode:?}: gate blocked before any ownership proof"
);
assert!(runner.clean_calls().is_empty(), "{mode:?}");
}
}
#[test]
fn candidate_target_or_build_change_still_skips() {
let (_d, root, target, build) = sibling_ws_fixture("candidate-change");
let other = root.join("other-target");
let other_build = root.join("other-build");
cargo_output(&other, 1024);
cargo_output(&other_build, 1024);
backdate(&root, SystemTime::now() - Duration::from_secs(3600));
let mut runner = staged_sibling_runner(&root, &target, &build);
runner.stage(0, 2, other, None);
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
let row = row_for(&report, &root);
assert_eq!(row.outcome, CleanOutcome::Skipped, "{}", row.detail);
assert!(row.detail.contains("target changed"), "{}", row.detail);
assert!(runner.clean_calls().is_empty());
}
#[test]
fn union_accounting_counts_each_output_root_once() {
let d = tempfile::tempdir().unwrap();
let root = ws_root(d.path(), "ws");
let target = cargo_output(&root.join("target"), 4096);
let build = cargo_output(&root.join("build"), 1 << 20);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let expected_before = traverse::measure_single_target(&target).bytes
+ traverse::measure_single_target(&build).bytes;
let mut runner = staged_sibling_runner(&root, &target, &build);
runner.removes_on_clean(vec![
target.join("artifact.bin"),
build.join("artifact.bin"),
]);
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::Execute, &runner, &noop).unwrap();
let row = row_for(&report, &root);
assert_eq!(row.outcome, CleanOutcome::Cleaned, "{}", row.detail);
assert_eq!(
row.before_bytes,
Some(expected_before),
"pre-clean union counts both distinct roots once"
);
let after = row.after_bytes.expect("post-clean union measured");
assert!(after < expected_before);
assert_eq!(
row.observed_decrease,
Some(expected_before.saturating_sub(after))
);
assert!(row.output_roots.contains(&canonical(&target)));
assert!(row.output_roots.contains(&canonical(&build)));
}
#[test]
fn post_clean_disappearing_sibling_is_measured_normally() {
let (_d, root, target, build) = sibling_ws_fixture("disappearing-sibling");
let build_root = build.clone();
let mut runner = staged_sibling_runner(&root, &target, &build);
runner.removes_on_clean(vec![target.join("artifact.bin")]);
runner.on_clean(move || {
let _ = fs::remove_dir_all(&build_root);
});
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::Execute, &runner, &noop).unwrap();
let row = row_for(&report, &root);
assert_eq!(row.outcome, CleanOutcome::Cleaned, "{}", row.detail);
let before = row.before_bytes.unwrap();
let after = row.after_bytes.expect("surviving union measured");
assert!(after < before);
assert_eq!(row.observed_decrease, Some(before - after));
}
#[test]
fn post_clean_measurement_uncertainty_fabricates_no_decrease() {
let (_d, root, target, build) = sibling_ws_fixture("uncertain-measurement");
let build_root = build.clone();
let mut runner = staged_sibling_runner(&root, &target, &build);
runner.removes_on_clean(vec![target.join("artifact.bin")]);
runner.on_clean(move || {
let _ = fs::remove_dir_all(&build_root);
let _ = fs::write(&build_root, b"not a directory");
});
let noop = NoopObserver;
let report = clean_with(&root, 0, &[], CleanMode::Execute, &runner, &noop).unwrap();
let row = row_for(&report, &root);
assert_eq!(row.outcome, CleanOutcome::Cleaned, "{}", row.detail);
assert_eq!(row.after_bytes, None);
assert_eq!(row.observed_decrease, None, "no fabricated recovered bytes");
assert!(row.detail.contains("measurement failed"), "{}", row.detail);
assert!(report.diagnostics >= 1);
}
#[test]
fn another_workspaces_source_tree_inside_the_cleaned_region_is_never_cleaned() {
for mode in [
CleanMode::CargoPreview,
CleanMode::Simulate,
CleanMode::Execute,
] {
let d = tempfile::tempdir().unwrap();
let outer = ws_root(d.path(), "outer");
let out = cargo_output(&outer.join("out"), 4096);
let inner = ws_root(&out, "inner");
let inner_target = cargo_output(&d.path().join("inner-target"), 4096);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&outer, out.clone(), None);
runner.add(&inner, inner_target, None);
let report = clean_with(d.path(), 0, &[], mode, &runner, &NoopObserver).unwrap();
assert!(
report.resolved_workspaces >= 2,
"{mode:?}: both workspaces must resolve, got {}: {:?}",
report.resolved_workspaces,
report.render()
);
assert!(
runner.clean_calls().is_empty(),
"{mode:?}: no cargo clean may run with a neighbour's sources inside the region"
);
for path in [
inner.join("Cargo.toml"),
inner.join("src/main.rs"),
inner.join("src"),
] {
assert!(path.exists(), "{mode:?}: {} must survive", path.display());
}
}
}
#[test]
fn source_tree_as_output_root_is_never_cleaned() {
for declared in ["root", "src"] {
let d = tempfile::tempdir().unwrap();
let root = ws_root(d.path(), "proj");
let output = if declared == "root" {
root.clone()
} else {
root.join("src")
};
fs::write(
output.join("CACHEDIR.TAG"),
b"Signature: 8a477f597d28d172789f06886806bc55\n",
)
.unwrap();
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root, output, None);
for mode in [
CleanMode::Simulate,
CleanMode::CargoPreview,
CleanMode::Execute,
] {
let report = clean_with(d.path(), 0, &[], mode, &runner, &NoopObserver).unwrap();
if let Some(row) = report
.results
.iter()
.find(|r| r.display_path == canonical(&root))
{
assert_eq!(
row.outcome,
CleanOutcome::Skipped,
"{declared} {mode:?}: {}",
row.detail
);
}
assert!(
runner.clean_calls().is_empty(),
"{declared} {mode:?}: no cargo clean may run"
);
}
assert!(
root.join("src/main.rs").exists(),
"{declared}: sources must survive"
);
assert!(root.join("Cargo.toml").exists(), "{declared}");
}
}
#[test]
fn final_proof_cost_is_linear_in_the_number_of_workspaces() {
fn proof_spawns(workspaces: usize) -> u64 {
let d = tempfile::tempdir().unwrap();
let mut runner = StagedCargo::new();
for index in 0..workspaces {
let root = ws_root(d.path(), &format!("linear-{index}"));
let target = cargo_output(&root.join("target"), 512);
runner.add(&root, target, None);
}
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let report = clean_with(
d.path(),
0,
&[],
CleanMode::Simulate,
&runner,
&NoopObserver,
)
.unwrap();
assert_eq!(report.results.len(), workspaces);
report.counters.proof_cargo_metadata_calls + report.counters.proof_cargo_locate_calls
}
let four = proof_spawns(4);
let eight = proof_spawns(8);
assert_eq!(four, 16, "4 workspaces");
assert_eq!(eight, 32, "8 workspaces");
assert_eq!(eight, four * 2, "doubling workspaces doubles proof work");
}
#[test]
fn proof_failures_distinguish_a_change_from_an_unproven_ownership() {
assert_eq!(
proof_skip_code("ownership could not be re-proven: workspace /w did not re-resolve"),
CleanupReasonCode::SkippedOwnershipUnproven
);
assert_eq!(
proof_skip_code(
"ownership could not be re-proven: combined selected-root universe has 1 unresolved manifest(s)"
),
CleanupReasonCode::SkippedOwnershipUnproven
);
assert_eq!(
proof_skip_code("ownership could not be re-proven: workspace /w changed identity"),
CleanupReasonCode::SkippedChangedBeforeCleanup
);
assert_eq!(
proof_skip_code("workspace changed before cleanup; skipped: member set changed"),
CleanupReasonCode::SkippedChangedBeforeCleanup
);
assert_eq!(
CleanupReasonCode::SkippedOwnershipUnproven.as_str(),
"skipped_ownership_unproven"
);
}
#[test]
fn frozen_env_pins_the_build_directory_so_an_inherited_redirect_cannot_apply() {
let d = tempfile::tempdir().unwrap();
let root = ws_root(d.path(), "build-dir");
let target = cargo_output(&root.join("target"), 1024);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root, target, None);
let report = clean_with(
d.path(),
0,
&[],
CleanMode::Simulate,
&runner,
&NoopObserver,
)
.unwrap();
let row = row_for(&report, &root);
assert_eq!(row.outcome, CleanOutcome::Simulated, "{}", row.detail);
}
#[test]
fn stats_account_for_final_ownership_universe_proof_work() {
let d = tempfile::tempdir().unwrap();
let root_a = ws_root(d.path(), "a");
let root_b = ws_root(d.path(), "b");
let target_a = cargo_output(&root_a.join("target"), 4096);
let target_b = cargo_output(&root_b.join("target"), 2048);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root_a, target_a, None);
runner.add(&root_b, target_b, None);
let noop = NoopObserver;
let report = clean_with(d.path(), 0, &[], CleanMode::Simulate, &runner, &noop).unwrap();
let counters = &report.counters;
assert_eq!(counters.cargo_metadata_calls, 2, "initial analysis");
assert_eq!(counters.proof_workspaces_refreshed, 4);
assert_eq!(counters.proof_cargo_metadata_calls, 6);
assert_eq!(counters.proof_cargo_locate_calls, 2);
assert!(counters.proof_cargo_metadata_nanos > 0);
assert!(counters.proof_source_activity_nanos > 0);
let line = counters.proof_stats_line();
assert!(line.contains("proof_metadata=6"), "{line}");
assert!(line.contains("proof_locate=2"), "{line}");
assert!(line.contains("proof_workspaces_refreshed=4"), "{line}");
assert!(counters.proof_timings_line().contains("proof_metadata="));
assert!(counters.proof_metadata_peak_concurrency >= 1);
assert_eq!(counters.cargo_metadata_calls, 2);
assert!(counters.stats_line().contains("metadata=2"));
}
#[test]
fn combined_roots_share_one_ownership_proof_and_simulation_never_cleans() {
let d = tempfile::tempdir().unwrap();
let root_a = ws_root(d.path(), "combined-a");
let root_b = ws_root(d.path(), "combined-b");
let target_a = cargo_output(&root_a.join("target"), 4096);
let target_b = cargo_output(&root_b.join("target"), 2048);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root_a, target_a, None);
runner.add(&root_b, target_b, None);
let report = clean_with_roots(
&[root_b.clone(), root_a.clone()],
0,
&[],
CleanMode::Simulate,
&runner,
&NoopObserver,
)
.unwrap();
assert_eq!(report.results.len(), 2);
assert!(
report
.results
.iter()
.all(|r| r.outcome == CleanOutcome::Simulated)
);
assert!(runner.clean_calls().is_empty());
assert_eq!(report.counters.proof_cargo_metadata_calls, 6);
assert_eq!(report.counters.proof_cargo_locate_calls, 2);
}
#[test]
fn combined_private_roots_keep_preview_simulate_execute_parity() {
let d = tempfile::tempdir().unwrap();
let root_a = ws_root(d.path(), "parity-a");
let root_b = ws_root(d.path(), "parity-b");
let target_a = cargo_output(&root_a.join("target"), 4096);
let target_b = cargo_output(&root_b.join("target"), 2048);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let roots = [root_a.clone(), root_b.clone()];
for (mode, expected) in [
(CleanMode::CargoPreview, CleanOutcome::Previewed),
(CleanMode::Simulate, CleanOutcome::Simulated),
(CleanMode::Execute, CleanOutcome::Cleaned),
] {
let mut runner = StagedCargo::new();
runner.add(&root_a, target_a.clone(), None);
runner.add(&root_b, target_b.clone(), None);
let report = clean_with_roots(&roots, 0, &[], mode, &runner, &NoopObserver).unwrap();
assert_eq!(report.results.len(), 2, "{mode:?}");
assert!(
report.results.iter().all(|r| r.outcome == expected),
"{mode:?}: {:?}",
report.results
);
let calls = runner.clean_calls();
assert_eq!(
calls.len(),
if mode == CleanMode::Simulate { 0 } else { 2 },
"{mode:?}"
);
if mode == CleanMode::CargoPreview {
assert!(
calls
.iter()
.all(|(_, args, _)| args.iter().any(|a| a == "--dry-run"))
);
}
}
}
#[test]
fn combined_roots_classify_cross_root_output_as_shared_in_every_mode() {
let d = tempfile::tempdir().unwrap();
let root_a = ws_root(d.path(), "shared-a");
let root_b = ws_root(d.path(), "shared-b");
let target_a = cargo_output(&root_a.join("target"), 4096);
let _target_b = cargo_output(&root_b.join("target"), 2048);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
for mode in [
CleanMode::CargoPreview,
CleanMode::Simulate,
CleanMode::Execute,
] {
let mut runner = StagedCargo::new();
runner.add(&root_a, target_a.clone(), None);
runner.add(&root_b, target_a.clone(), None);
let report = clean_with_roots(
&[root_a.clone(), root_b.clone()],
0,
&[],
mode,
&runner,
&NoopObserver,
)
.unwrap();
assert!(
report
.results
.iter()
.all(|r| r.outcome == CleanOutcome::Skipped),
"{mode:?}: {:?}",
report.results
);
assert!(
report
.results
.iter()
.any(|r| r.ownership == OutputOwnershipClass::Shared)
);
assert!(runner.clean_calls().is_empty(), "{mode:?}");
}
}
#[test]
fn unresolved_manifest_in_second_root_blocks_first_root_for_all_modes() {
let d = tempfile::tempdir().unwrap();
let root_a = ws_root(d.path(), "coverage-a");
let root_b = ws_root(d.path(), "coverage-b");
let target_a = cargo_output(&root_a.join("target"), 4096);
let target_b = cargo_output(&root_b.join("target"), 2048);
let unresolved = root_b.join("unresolved/Cargo.toml");
fs::create_dir_all(unresolved.parent().unwrap()).unwrap();
fs::write(
&unresolved,
"[package]\nname='unresolved'\nversion='0.1.0'\n",
)
.unwrap();
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
for mode in [
CleanMode::CargoPreview,
CleanMode::Simulate,
CleanMode::Execute,
] {
let mut runner = StagedCargo::new();
runner.add(&root_a, target_a.clone(), None);
runner.add(&root_b, target_b.clone(), None);
let report = clean_with_roots(
&[root_a.clone(), root_b.clone()],
0,
&[],
mode,
&runner,
&NoopObserver,
)
.unwrap();
assert_eq!(report.unresolved_ownership.len(), 1, "{mode:?}");
assert!(report.results.is_empty(), "{mode:?}");
assert!(report.render().contains("2 root(s)"), "{mode:?}");
assert!(runner.clean_calls().is_empty(), "{mode:?}");
}
}
#[test]
fn proof_refresh_parallelism_is_bounded_and_results_stay_deterministic() {
let d = tempfile::tempdir().unwrap();
let mut runner = StagedCargo::new();
let mut roots = Vec::new();
for index in 0..8 {
let root = ws_root(d.path(), &format!("parallel-{index}"));
let target = cargo_output(&root.join("target"), 1024 + index * 128);
runner.add(&root, target, None);
roots.push(root);
}
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let runner = ParallelProbeRunner {
inner: runner,
active: std::sync::atomic::AtomicUsize::new(0),
peak: std::sync::atomic::AtomicUsize::new(0),
};
let report = clean_with(
d.path(),
0,
&[],
CleanMode::Simulate,
&runner,
&NoopObserver,
)
.unwrap();
let peak = runner.peak.load(std::sync::atomic::Ordering::SeqCst);
let available = std::thread::available_parallelism().map_or(1, usize::from);
assert!(peak >= available.clamp(1, 4).min(2), "peak={peak}");
assert!(peak <= PROOF_REFRESH_CONCURRENCY_CAP, "peak={peak}");
assert_eq!(
report.counters.proof_metadata_peak_concurrency as usize,
peak
);
assert_eq!(report.counters.proof_workspaces_refreshed, 16);
assert_eq!(report.counters.proof_cargo_metadata_calls, 24);
assert_eq!(report.counters.proof_cargo_locate_calls, 8);
assert_eq!(report.results.len(), 8);
assert!(report.results.windows(2).all(|pair| {
pair[0].before_bytes >= pair[1].before_bytes
|| pair[0].before_bytes == pair[1].before_bytes
}));
let roots_in_report: Vec<_> = report
.results
.iter()
.map(|row| row.display_path.clone())
.collect();
let mut expected: Vec<_> = roots
.into_iter()
.map(|root| {
(
traverse::measure_single_target(&root.join("target")).bytes,
canonical(&root),
)
})
.collect();
expected.sort_by(|(a_bytes, a_root), (b_bytes, b_root)| {
b_bytes.cmp(a_bytes).then_with(|| a_root.cmp(b_root))
});
assert_eq!(
roots_in_report,
expected
.into_iter()
.map(|(_, root)| root)
.collect::<Vec<_>>()
);
}
#[test]
fn sequential_and_parallel_refreshes_produce_the_same_workspace_graph_and_disposition() {
let d = tempfile::tempdir().unwrap();
let root_a = ws_root(d.path(), "parity-a");
let root_b = ws_root(d.path(), "parity-b");
let target_a = cargo_output(&root_a.join("target"), 4096);
let target_b = cargo_output(&root_b.join("target"), 2048);
backdate(d.path(), SystemTime::now() - Duration::from_secs(3600));
let mut runner = StagedCargo::new();
runner.add(&root_a, target_a, None);
runner.add(&root_b, target_b, None);
let manifests = [root_a.join("Cargo.toml"), root_b.join("Cargo.toml")];
let mut initial_counters = ScanCounters::default();
let mut initial_diagnostics = Vec::new();
let initial = workspace::resolve_workspaces(
&manifests,
&runner,
&mut initial_counters,
&mut initial_diagnostics,
&NoopObserver,
);
let mut sequential_counters = ScanCounters::default();
let sequential =
refresh_proof_universe_with_limit(&initial, &runner, &mut sequential_counters, 1)
.unwrap();
let mut parallel_counters = ScanCounters::default();
let parallel =
refresh_proof_universe_with_limit(&initial, &runner, &mut parallel_counters, 4)
.unwrap();
assert_eq!(sequential, parallel);
assert_eq!(
sequential_counters.proof_cargo_metadata_calls,
parallel_counters.proof_cargo_metadata_calls
);
let sequential_groups = workspace::build_groups(&sequential);
let parallel_groups = workspace::build_groups(¶llel);
let signature = |groups: &[workspace::RawGroup]| {
groups
.iter()
.map(|group| {
(
group.physicals.clone(),
group.covering.clone(),
group.display.clone(),
group.owners.clone(),
group.ownership,
)
})
.collect::<Vec<_>>()
};
assert_eq!(signature(&sequential_groups), signature(¶llel_groups));
let clock_start = SystemTime::now() + Duration::from_secs(1);
let cutoff = clock_start.checked_sub(Duration::from_secs(300)).unwrap();
let mut seq_counters = ScanCounters::default();
let mut seq_diagnostics = Vec::new();
let sequential_disposition = workspace::analyze_groups(
&sequential,
sequential_groups,
clock_start,
cutoff,
Duration::from_secs(300),
&mut seq_counters,
&mut seq_diagnostics,
&NoopObserver,
);
let mut par_counters = ScanCounters::default();
let mut par_diagnostics = Vec::new();
let parallel_disposition = workspace::analyze_groups(
¶llel,
parallel_groups,
clock_start,
cutoff,
Duration::from_secs(300),
&mut par_counters,
&mut par_diagnostics,
&NoopObserver,
);
assert_eq!(sequential_disposition, parallel_disposition);
}
#[test]
fn authorization_infrastructure_failure_scope_blocks_instead_of_per_unit_skip() {
assert!(is_authorization_infrastructure_error(
"cleanup authorization root must be absolute: relative/path"
));
assert!(is_authorization_infrastructure_error(
"cannot inspect cleanup authorization root /x: permission denied"
));
assert!(is_authorization_infrastructure_error(
"cleanup authorization root must not be a symlink: /x"
));
assert!(is_authorization_infrastructure_error(
"cannot resolve cleanup authorization root /x: foo"
));
assert!(is_authorization_infrastructure_error(
"cannot resolve cleanup root /x: foo"
));
assert!(!is_authorization_infrastructure_error(
"target output /x is private but outside the authorized cleanup boundary; add a `cleanup.allowed_output_roots` entry or use a clean ROOT that contains it"
));
let (_d, root, target) = valid_fixture(1);
let runner = FakeCleanupRunner::new(&root, &target, 1);
let report = clean_with(
&root,
0,
&[PathBuf::from("relative/allowed-root")],
CleanMode::Simulate,
&runner,
&NoopObserver,
)
.unwrap();
assert!(
report.scope_blocked.is_some(),
"infrastructure failure must scope-block: {report:?}"
);
assert_eq!(
report.scope_blocked.as_ref().map(|b| b.reason),
Some(ScopeBlockReason::OwnershipUnproven)
);
assert!(
report
.scope_blocked
.as_ref()
.is_some_and(|b| b.message.contains("authorization could not be proven")
&& b.message.contains("no cleanup commands were run")),
"{:?}",
report.scope_blocked
);
assert!(
report.results.is_empty(),
"blocked scope reports no per-unit rows: {report:?}"
);
assert!(runner.clean_calls().is_empty());
}
#[test]
fn covering_inspect_failure_maps_permission_denied_to_uncertain() {
let denied =
covering_inspect_failure(io::Error::new(io::ErrorKind::PermissionDenied, "denied"));
assert_eq!(denied.code, CleanupReasonCode::SkippedUncertain);
assert!(denied.detail.contains("uncertain"), "{}", denied.detail);
let other = covering_inspect_failure(io::Error::other("boom"));
assert_eq!(other.code, CleanupReasonCode::SkippedChangedBeforeCleanup);
let missing = PathBuf::from("/definitely/missing/cargo-cleanme-covering-root");
let failure = prove_covering_roots(std::slice::from_ref(&missing)).unwrap_err();
assert_eq!(failure.code, CleanupReasonCode::SkippedChangedBeforeCleanup);
}
#[test]
fn ownership_degraded_code_matches_scan_time_vocabulary() {
assert_eq!(
ownership_degraded_code(OutputOwnershipClass::Shared),
CleanupReasonCode::SkippedShared
);
assert_eq!(
ownership_degraded_code(OutputOwnershipClass::Uncertain),
CleanupReasonCode::SkippedUncertain
);
assert_eq!(
ownership_degraded_code(OutputOwnershipClass::ExternalUnproven),
CleanupReasonCode::SkippedOwnershipUnproven
);
let d = tempfile::tempdir().unwrap();
let base = fs::canonicalize(d.path()).unwrap();
for (class, expected) in [
(
OutputOwnershipClass::Shared,
CleanupReasonCode::SkippedShared,
),
(
OutputOwnershipClass::Uncertain,
CleanupReasonCode::SkippedUncertain,
),
(
OutputOwnershipClass::ExternalUnproven,
CleanupReasonCode::SkippedOwnershipUnproven,
),
] {
assert_eq!(ownership_degraded_code(class), expected);
let unit = synthetic_mixed_unit(&base, OutputOwnershipClass::PrivateBounded, class);
assert_eq!(unit_skip_code(&unit), expected, "{class:?}");
}
}
#[test]
fn package_selector_with_valid_workspace_index_evaluates_spec() {
let (_d, root, target) = valid_fixture(1);
let runner = FakeCleanupRunner::new(&root, &target, 1);
let report = clean_with_roots_policy_selector(
std::slice::from_ref(&root),
0,
&[],
CleanMode::Simulate,
&runner,
&NoopObserver,
&CleanupPolicy::default(),
Some(CleanupSelector::Package("missing-package".into())),
)
.unwrap();
assert_eq!(report.results.len(), 1);
assert_eq!(report.results[0].outcome, CleanOutcome::Skipped);
assert!(
matches!(
report.results[0].reason_code,
CleanupReasonCode::SelectorInvalid | CleanupReasonCode::SelectorUnsupported
),
"unexpected code: {:?}",
report.results[0].reason_code
);
assert!(runner.clean_calls().is_empty());
}
#[test]
fn new_manifest_after_proof_blocks_remaining_scope() {
struct PlantingRunner<'a> {
inner: FakeCleanupRunner,
planted: PathBuf,
metadata_calls: std::sync::atomic::AtomicUsize,
_marker: std::marker::PhantomData<&'a ()>,
}
impl CargoRunner for PlantingRunner<'_> {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
if args.first().is_some_and(|a| a == "metadata") {
let n = self
.metadata_calls
.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
+ 1;
if n == 4 {
fs::create_dir_all(self.planted.parent().unwrap()).unwrap();
fs::write(
&self.planted,
"[package]\nname='planted'\nversion='0.1.0'\n",
)
.unwrap();
}
}
CargoRunner::run(&self.inner, cwd, args)
}
}
impl CleanupRunner for PlantingRunner<'_> {
fn run(&self, cwd: &Path, args: &[OsString]) -> io::Result<ProcessOutput> {
CargoRunner::run(self, cwd, args)
}
fn run_with_env(
&self,
cwd: &Path,
args: &[OsString],
env: &[(OsString, OsString)],
) -> io::Result<ProcessOutput> {
self.inner.run_with_env(cwd, args, env)
}
}
for mode in [CleanMode::Simulate, CleanMode::Execute] {
let (_d, root, target) = valid_fixture(1);
let planted = root.join("planted/Cargo.toml");
let inner = FakeCleanupRunner::new(&root, &target, 1);
let runner = PlantingRunner {
inner,
planted,
metadata_calls: std::sync::atomic::AtomicUsize::new(0),
_marker: std::marker::PhantomData,
};
let report = clean_with(&root, 0, &[], mode, &runner, &NoopObserver).unwrap();
assert!(
report.scope_blocked.is_some(),
"{mode:?}: planted manifest must block: {report:?}"
);
assert_eq!(
report.scope_blocked.as_ref().map(|b| b.reason),
Some(ScopeBlockReason::IncompleteDiscovery),
"{mode:?}"
);
assert!(
report
.scope_blocked
.as_ref()
.is_some_and(|b| b.message.contains("manifest set differs")),
"{mode:?}: {:?}",
report.scope_blocked
);
assert!(runner.inner.clean_calls().is_empty(), "{mode:?}");
}
}
}