feat(contributor-scan): remove scan runs older than 30 days from the default cache (3.1, run retention)

By maintainer decision. Since 6edae3a a native scan leaves a run directory
under ~/.cache/openultrasast/runs/ and nothing removed them. After a scan's
manifest is written, with no OPENULTRASAST_RUNS_DIR set, the runs in that
default location that are older than 30 days are now removed. The age comes
from the UTC timestamp in the run id, never from file times, so a copied or
touched directory is not misjudged, and a run exactly 30 days old is kept.

Never touched: the scan's own run; anything not named exactly like a run
(only direct children of the runs root whose name is a run id); symlinks,
which are neither followed nor removed; and any location chosen with
OPENULTRASAST_RUNS_DIR, even when it resolves to the default.

OPENULTRASAST_RUNS_RETENTION_DAYS sets the number of days and 0 keeps every
run. A failed prune never fails the scan: it is one notice on the command
line, and the MCP scan and benchmark results now carry a notices key. A
retention longer than the calendar and a directory tree too deep to remove
are both turned into that same behaviour.

Known limits, on record: a removal that fails part-way leaves the run half
deleted and it is retried on every later scan; the prune stops at the first
failure; a clock set far ahead removes earlier runs; a filesystem mounted at
or under an expired run is emptied before the removal fails.

Tests: tests/test_run_pruning.py drives the function and the real command
line (34 tests); tests/test_mcp.py pins the notices. The reviewer attacked
the deletion path with about sixty hostile inputs and twenty-three mutations;
all are killed or kept safe.
This commit is contained in:
Marius Ciepluch
2026-11-24 17:51:37 +01:00
parent efa2b62bff
commit 17d46c0f93
9 changed files with 478 additions and 7 deletions
+4 -2
View File
@@ -71,7 +71,7 @@ from .repos import resolve as resolve_repo
from .repos import select as select_repo
from .repos import verify as verify_repo
from .ruleset import DEFAULT_RULESET_DIR, load_ruleset
from .run import ScanRun, create_scan_run
from .run import ScanRun, create_scan_run, prune_scan_runs
from .scoring import build_score_artifact
from .semantic import (
OverlayRecord,
@@ -816,6 +816,7 @@ def _run_scan(path: Path, config_path: Path, mode: str, fail_on: str) -> ScanOut
),
)
runtime.finish(status="succeeded")
prune_notices = prune_scan_runs(config, keep=run.root)
return ScanOutcome(
scan_id=run.scan_id,
run_dir=run.root,
@@ -828,7 +829,8 @@ def _run_scan(path: Path, config_path: Path, mode: str, fail_on: str) -> ScanOut
f"language not covered: {item['language']} ({item['count']} files)"
for item in runtime.state["degradations"]
if item.get("reason") == "language_not_covered"
),
)
+ prune_notices,
)
+22 -1
View File
@@ -203,19 +203,39 @@ def _user_cache_dir() -> Path:
return Path.home() / ".cache"
def _runs_dir_override() -> str:
"""The `OPENULTRASAST_RUNS_DIR` set in the environment; empty when runs go to the default location."""
return os.environ.get("OPENULTRASAST_RUNS_DIR", "")
def runs_dir_is_overridden() -> bool:
"""Whether `OPENULTRASAST_RUNS_DIR` names where runs go. Wherever it points, that location is never pruned."""
return bool(_runs_dir_override())
def _runs_dir() -> str:
"""Where a scan creates its run: the user's cache, unless `OPENULTRASAST_RUNS_DIR` says otherwise.
Always absolute, and taken from the working directory when the override is relative, never from the
target: a run inside the analysed tree is what this default exists to prevent.
"""
override = os.environ.get("OPENULTRASAST_RUNS_DIR")
override = _runs_dir_override()
if not override:
return str(_user_cache_dir() / "openultrasast" / "runs")
path = Path(override)
return str(path if path.is_absolute() else Path.cwd() / path)
def _runs_retention_days() -> int:
"""How long a run stays in the default cache before a later scan removes it; 0 keeps every run."""
value = os.environ.get("OPENULTRASAST_RUNS_RETENTION_DAYS", "").strip()
if not value:
return 30
if not value.isdecimal():
raise ValueError(f"OPENULTRASAST_RUNS_RETENTION_DAYS must be a whole number of days, 0 or more, not {value!r}")
return int(value)
@dataclass(frozen=True)
class ResolvedConfig:
models: ModelConfig = ModelConfig()
@@ -232,6 +252,7 @@ class ResolvedConfig:
# Read from the environment each time a config is built, so one made without `load_config` lands in the
# same place.
runs_dir: str = field(default_factory=_runs_dir)
runs_retention_days: int = field(default_factory=_runs_retention_days)
def load_config(config_path: Path | None = None, *, dotenv: bool = True) -> ResolvedConfig:
+2
View File
@@ -75,6 +75,7 @@ def _scan(args: dict[str, Any]) -> dict[str, Any]:
"mode": mode,
"finding_count": outcome.finding_count,
"exit_code": outcome.exit_code,
"notices": list(outcome.notices),
}
@@ -182,6 +183,7 @@ def _benchmark(args: dict[str, Any]) -> dict[str, Any]:
"missed": metrics.missed_findings_total,
"false_positives": metrics.false_positive_findings_total,
"recall": metrics.recall,
"notices": list(outcome.notices),
}
+63 -2
View File
@@ -1,11 +1,15 @@
from __future__ import annotations
import re
import shutil
from dataclasses import dataclass
from datetime import UTC, datetime
from datetime import UTC, datetime, timedelta
from pathlib import Path
from uuid import uuid4
from .config import ResolvedConfig, write_resolved_config
from .config import ResolvedConfig, runs_dir_is_overridden, write_resolved_config
_RUN_ID = re.compile(r"(\d{8}T\d{6}Z)-[0-9a-f]{8}")
@dataclass(frozen=True)
@@ -24,3 +28,60 @@ def create_scan_run(target: Path, config: ResolvedConfig) -> ScanRun:
(root / "preprocess").mkdir()
write_resolved_config(config, root / "resolved_config.json")
return ScanRun(scan_id=scan_id, root=root, target=resolved_target)
def _run_started_at(name: str) -> datetime | None:
"""When the run called `name` started, or None when `name` is not the id of a run."""
match = _RUN_ID.fullmatch(name)
if match is None:
return None
try:
return datetime.strptime(match[1], "%Y%m%dT%H%M%SZ").replace(tzinfo=UTC)
except ValueError:
return None
def _is_expired_run(entry: Path, cutoff: datetime) -> bool:
"""A run directory, not a link to one, that started before `cutoff`."""
started_at = _run_started_at(entry.name)
return started_at is not None and started_at < cutoff and entry.is_dir() and not entry.is_symlink()
def prune_old_runs(runs_root: Path, *, keep: Path | None = None, retention_days: int, now: datetime | None = None) -> list[Path]:
"""Remove the runs directly under `runs_root` that are older than `retention_days`, and return them.
A run is as old as the timestamp in its id says, whatever its file times say. Everything else stays: files,
directories called something else, symbolic links, and `keep`, the run just written.
"""
if retention_days <= 0:
return []
try:
cutoff = (now or datetime.now(UTC)) - timedelta(days=retention_days)
except OverflowError:
return [] # a retention longer than the calendar: no run is that old
removed = []
for entry in runs_root.iterdir():
if entry != keep and _is_expired_run(entry, cutoff):
shutil.rmtree(entry)
removed.append(entry)
return removed
def prune_scan_runs(config: ResolvedConfig, *, keep: Path) -> tuple[str, ...]:
"""Remove the expired runs once a scan has written its own; returns what the scan is to say about it.
Only the default location is pruned: while `OPENULTRASAST_RUNS_DIR` is set, wherever it points, every run
stays. Nothing is said when nothing was removed, and a removal that fails is said once and costs the scan
nothing.
"""
if runs_dir_is_overridden():
return ()
root = Path(config.runs_dir)
try:
removed = prune_old_runs(root, keep=keep, retention_days=config.runs_retention_days)
except (OSError, RecursionError) as exc:
return (f"old runs could not be removed from {root}: {exc}",)
if not removed:
return ()
runs = "run" if len(removed) == 1 else "runs"
return (f"removed {len(removed)} {runs} older than {config.runs_retention_days} days from {root}",)