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
+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}",)