mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 10:18:18 +00:00
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:
@@ -18,7 +18,9 @@ it wrote.
|
||||
still exits 0 and records a degradation.
|
||||
4. Read the printed `scan_id=` and `run_dir=` lines; the run directory is `~/.cache/openultrasast/runs/<scan-id>/`
|
||||
(`$XDG_CACHE_HOME/openultrasast/runs/` when that variable is set to an absolute path; `OPENULTRASAST_RUNS_DIR`
|
||||
overrides it).
|
||||
overrides it). After a scan, with no `OPENULTRASAST_RUNS_DIR` set, the runs in that default location older than
|
||||
30 days are removed (`OPENULTRASAST_RUNS_RETENTION_DAYS` sets the number of days and `0` keeps every run), and
|
||||
nothing is removed from a location chosen with `OPENULTRASAST_RUNS_DIR`.
|
||||
5. Report the finding count, how many the verifier accepted, and **every** recorded degradation
|
||||
(`manifest.json`, key `degradations`). No findings plus a degradation is not a clean scan: the scan
|
||||
answered a smaller question than it was asked.
|
||||
|
||||
@@ -188,6 +188,10 @@ loads settings. Every run writes `manifest.json`, `findings.json`, `verification
|
||||
variable is set to an absolute path. The scan prints that path (`run_dir=<path>`).
|
||||
`OPENULTRASAST_RUNS_DIR` moves the run directory: an absolute path is used as given, and a relative
|
||||
one is resolved against the current working directory, never against the directory being scanned.
|
||||
After a scan writes its run to the default location, with no `OPENULTRASAST_RUNS_DIR` set, the runs
|
||||
there older than 30 days are removed, and `ousast` prints one `notice:` line when it removes any;
|
||||
`OPENULTRASAST_RUNS_RETENTION_DAYS` sets the number of days (`0` keeps every run), and nothing is
|
||||
ever removed from a location chosen with `OPENULTRASAST_RUNS_DIR`.
|
||||
|
||||
A scan that rejects or holds a finding writes one file into the scanned tree,
|
||||
`<target>/.openultrasast/calibration/false_positive_learnings.json`, and only when that file's
|
||||
|
||||
+5
-1
@@ -4,7 +4,11 @@ Each example stands on its own. A scan writes its run under
|
||||
`~/.cache/openultrasast/runs/<scan-id>/`, or under `$XDG_CACHE_HOME/openultrasast/runs/` when
|
||||
that variable is set to an absolute path, and prints that path. `OPENULTRASAST_RUNS_DIR`
|
||||
overrides the location: an absolute path is used as given, and a relative one is resolved against
|
||||
the current working directory, never against the target.
|
||||
the current working directory, never against the target. Once a scan has written its run to the
|
||||
default location, with no `OPENULTRASAST_RUNS_DIR` set, the runs there that are older than 30 days
|
||||
are removed, and `ousast` prints one `notice:` line when it removes any;
|
||||
`OPENULTRASAST_RUNS_RETENTION_DAYS` sets the number of days (`0` keeps every run), and nothing is
|
||||
ever removed from a location chosen with `OPENULTRASAST_RUNS_DIR`.
|
||||
|
||||
A scan that rejects or holds a finding writes one file into the scanned tree, and only when that
|
||||
file's content would change:
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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}",)
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
"""Narrow MCP server: tool listing, scan→status flow, and surface safety (Phase 12)."""
|
||||
|
||||
import errno
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from test_run_pruning import _default_cache, _earlier_run, _refuse_removal
|
||||
|
||||
from openultrasast.mcp import McpServer, serve
|
||||
|
||||
EXPECTED_TOOLS = {
|
||||
@@ -101,6 +105,7 @@ def test_scan_then_status_and_findings(tmp_path: Path, monkeypatch) -> None: #
|
||||
|
||||
scan = _call(server, "openultrasast.scan", {"path": str(_repo(tmp_path)), "mode": "quick"})
|
||||
assert not scan["isError"] and scan["scan_id"]
|
||||
assert scan["notices"] == [] # a run root of its own is never pruned, so the scan has nothing to say
|
||||
run_dir = scan["run_dir"]
|
||||
|
||||
status = _call(server, "openultrasast.status", {"run_dir": run_dir})
|
||||
@@ -137,6 +142,42 @@ def test_export_report_returns_markdown(tmp_path: Path, monkeypatch) -> None: #
|
||||
assert report["format"] == "markdown" and report["content"]
|
||||
|
||||
|
||||
def test_scan_result_carries_the_notice_of_the_runs_the_scan_removed(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
runs = _default_cache(tmp_path, monkeypatch)
|
||||
expired = _earlier_run(runs, 40)
|
||||
|
||||
result = _call(McpServer(), "openultrasast.scan", {"path": str(_repo(tmp_path)), "mode": "quick"})
|
||||
|
||||
assert not result["isError"]
|
||||
assert result["notices"] == [f"removed 1 run older than 30 days from {runs}"]
|
||||
assert not expired.exists()
|
||||
|
||||
|
||||
def test_scan_result_carries_the_notice_of_a_removal_that_was_refused(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
runs = _default_cache(tmp_path, monkeypatch)
|
||||
expired = _earlier_run(runs, 40)
|
||||
refusal = PermissionError(errno.EACCES, "Permission denied", str(expired))
|
||||
_refuse_removal(monkeypatch, expired, refusal)
|
||||
|
||||
result = _call(McpServer(), "openultrasast.scan", {"path": str(_repo(tmp_path)), "mode": "quick"})
|
||||
|
||||
assert result["exit_code"] == 0
|
||||
assert result["notices"] == [f"old runs could not be removed from {runs}: {refusal}"]
|
||||
|
||||
|
||||
def test_benchmark_result_carries_the_notice_of_the_runs_the_scan_removed(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
runs = _default_cache(tmp_path, monkeypatch)
|
||||
_repo(tmp_path)
|
||||
_earlier_run(runs, 40)
|
||||
manifest = tmp_path / "benchmark.toml"
|
||||
manifest.write_text('name = "py-smoke"\nlanguage = "python"\n\n[source]\npath = "repo"\n')
|
||||
|
||||
result = _call(McpServer(), "openultrasast.benchmark", {"manifest": str(manifest), "mode": "quick"})
|
||||
|
||||
assert not result["isError"]
|
||||
assert result["notices"] == [f"removed 1 run older than 30 days from {runs}"]
|
||||
|
||||
|
||||
# ---- stdio loop -------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
"""What a scan removes from its cache (contributor-scan Requirement 5.3, decision of 2026-11-24): once its run
|
||||
is written, the expired runs go from the default location, and nothing else does."""
|
||||
|
||||
import errno
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from test_scan_output_location import _scan, _target, _user_cache
|
||||
|
||||
from openultrasast import run
|
||||
from openultrasast.config import ResolvedConfig, load_config
|
||||
from openultrasast.run import prune_old_runs, prune_scan_runs
|
||||
|
||||
NOW = datetime(2026, 11, 24, 12, tzinfo=UTC)
|
||||
RETENTION = "OPENULTRASAST_RUNS_RETENTION_DAYS"
|
||||
OVER_THE_CALENDAR = (NOW - datetime(1, 1, 1, tzinfo=UTC)).days + 1
|
||||
|
||||
|
||||
def _run_id(started_at: datetime, suffix: str = "00000000") -> str:
|
||||
"""The id `create_scan_run` gives a run that started at `started_at`."""
|
||||
return f"{started_at:%Y%m%dT%H%M%SZ}-{suffix}"
|
||||
|
||||
|
||||
def _run(root: Path, name: str) -> Path:
|
||||
"""What an earlier scan left under `root`: a directory called `name` that holds a manifest."""
|
||||
path = root / name
|
||||
path.mkdir(parents=True)
|
||||
(path / "manifest.json").write_text("{}\n")
|
||||
return path
|
||||
|
||||
|
||||
def _earlier_run(runs: Path, age_days: int) -> Path:
|
||||
"""A run under `runs` that started `age_days` ago by the real clock."""
|
||||
return _run(runs, _run_id(datetime.now(UTC) - timedelta(days=age_days), uuid.uuid4().hex[:8]))
|
||||
|
||||
|
||||
def _default_cache(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
"""The default run root for this test, in a cache of its own, with the retention left at its default."""
|
||||
monkeypatch.delenv(RETENTION, raising=False)
|
||||
return _user_cache(tmp_path, monkeypatch)
|
||||
|
||||
|
||||
def _notices(out: str) -> list[str]:
|
||||
return re.findall(r"^notice: (.+)$", out, flags=re.MULTILINE)
|
||||
|
||||
|
||||
def _refuse_removal(monkeypatch: pytest.MonkeyPatch, run_dir: Path, error: Exception) -> None:
|
||||
"""Make the removal of `run_dir` raise `error`, as a cache that refuses deletion would; other removals go on."""
|
||||
remove = shutil.rmtree
|
||||
|
||||
def refuse(path, *args, **kwargs):
|
||||
# Permission bits cannot stand in for a cache that refuses deletion: root ignores them, and CI runs as root.
|
||||
if Path(path) == run_dir:
|
||||
raise error
|
||||
remove(path, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(run.shutil, "rmtree", refuse)
|
||||
|
||||
|
||||
def test_a_run_older_than_the_retention_is_removed_and_younger_ones_stay(tmp_path: Path) -> None:
|
||||
six_weeks_ago = _run(tmp_path, _run_id(NOW - timedelta(days=40)))
|
||||
a_month_ago = _run(tmp_path, _run_id(NOW - timedelta(days=31)))
|
||||
just_past_the_limit = _run(tmp_path, _run_id(NOW - timedelta(days=30, seconds=1)))
|
||||
at_the_limit = _run(tmp_path, _run_id(NOW - timedelta(days=30)))
|
||||
last_week = _run(tmp_path, _run_id(NOW - timedelta(days=5)))
|
||||
|
||||
removed = prune_old_runs(tmp_path, keep=None, retention_days=30, now=NOW)
|
||||
|
||||
assert sorted(removed) == [six_weeks_ago, a_month_ago, just_past_the_limit]
|
||||
assert sorted(tmp_path.iterdir()) == [at_the_limit, last_week]
|
||||
|
||||
|
||||
def test_the_current_run_stays_even_when_its_id_says_it_started_long_ago(tmp_path: Path) -> None:
|
||||
current = _run(tmp_path, _run_id(NOW - timedelta(days=40)))
|
||||
|
||||
assert prune_old_runs(tmp_path, keep=current, retention_days=30, now=NOW) == []
|
||||
assert (current / "manifest.json").is_file()
|
||||
|
||||
|
||||
def test_prune_scan_runs_keeps_the_run_it_is_told_to_keep(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
runs = _default_cache(tmp_path, monkeypatch)
|
||||
expired = _run(runs, _run_id(NOW - timedelta(days=40), "deadbeef"))
|
||||
current = _run(runs, _run_id(NOW - timedelta(days=40), "badc0de0"))
|
||||
|
||||
assert prune_scan_runs(ResolvedConfig(), keep=current) == (f"removed 1 run older than 30 days from {runs}",)
|
||||
assert (current / "manifest.json").is_file()
|
||||
assert not expired.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name",
|
||||
[
|
||||
"notes",
|
||||
"20261015T110527Z-b1dc097", # seven hex digits, not eight
|
||||
"20261015T110527Z-nothex00", # a suffix that is not hex
|
||||
"20261015T110527Z-DEADBEEF", # uppercase: create_scan_run writes lowercase hex
|
||||
"20261015T110527Z-deadbeef.bak", # a run's id with something after it
|
||||
"20261340T000000Z-deadbeef", # month 13: no run ever started then
|
||||
],
|
||||
)
|
||||
def test_a_directory_whose_name_is_not_the_id_of_a_run_stays(tmp_path: Path, name: str) -> None:
|
||||
directory = tmp_path / name
|
||||
directory.mkdir()
|
||||
(directory / "manifest.json").write_text("{}\n")
|
||||
|
||||
assert prune_old_runs(tmp_path, keep=None, retention_days=30, now=NOW) == []
|
||||
assert (directory / "manifest.json").is_file()
|
||||
|
||||
|
||||
def test_a_file_and_a_run_nested_under_another_directory_stay(tmp_path: Path) -> None:
|
||||
old_id = _run_id(NOW - timedelta(days=40))
|
||||
readme = tmp_path / "README"
|
||||
readme.write_text("kept\n")
|
||||
named_like_a_run = tmp_path / old_id
|
||||
named_like_a_run.write_text("a file, although it is named like an expired run\n")
|
||||
nested = _run(tmp_path / "archive", old_id)
|
||||
|
||||
assert prune_old_runs(tmp_path, keep=None, retention_days=30, now=NOW) == []
|
||||
assert sorted(tmp_path.iterdir()) == sorted([readme, tmp_path / "archive", named_like_a_run])
|
||||
assert (nested / "manifest.json").is_file()
|
||||
|
||||
|
||||
def test_a_symlink_to_an_expired_run_is_neither_removed_nor_followed(tmp_path: Path) -> None:
|
||||
runs = tmp_path / "runs"
|
||||
runs.mkdir()
|
||||
kept_elsewhere = _run(tmp_path, "kept-elsewhere")
|
||||
link = runs / _run_id(NOW - timedelta(days=40))
|
||||
link.symlink_to(kept_elsewhere, target_is_directory=True)
|
||||
|
||||
assert prune_old_runs(runs, keep=None, retention_days=30, now=NOW) == []
|
||||
assert link.is_symlink()
|
||||
assert (kept_elsewhere / "manifest.json").is_file()
|
||||
|
||||
|
||||
def test_a_retention_of_zero_removes_nothing(tmp_path: Path) -> None:
|
||||
expired = _run(tmp_path, _run_id(NOW - timedelta(days=400)))
|
||||
|
||||
assert prune_old_runs(tmp_path, keep=None, retention_days=0, now=NOW) == []
|
||||
assert (expired / "manifest.json").is_file()
|
||||
|
||||
|
||||
def test_the_retention_decides_which_runs_are_expired(tmp_path: Path) -> None:
|
||||
six_weeks_ago = _run(tmp_path, _run_id(NOW - timedelta(days=40)))
|
||||
last_week = _run(tmp_path, _run_id(NOW - timedelta(days=5)))
|
||||
|
||||
assert prune_old_runs(tmp_path, keep=None, retention_days=60, now=NOW) == []
|
||||
assert prune_old_runs(tmp_path, keep=None, retention_days=7, now=NOW) == [six_weeks_ago]
|
||||
assert (last_week / "manifest.json").is_file()
|
||||
|
||||
|
||||
def test_a_run_is_dated_by_its_id_not_by_the_filesystem(tmp_path: Path) -> None:
|
||||
copied_today = _run(tmp_path, _run_id(NOW - timedelta(days=40)))
|
||||
os.utime(copied_today, (NOW.timestamp(), NOW.timestamp()))
|
||||
restored_from_an_old_backup = _run(tmp_path, _run_id(NOW - timedelta(days=5)))
|
||||
os.utime(restored_from_an_old_backup, (0, 0))
|
||||
|
||||
assert prune_old_runs(tmp_path, keep=None, retention_days=30, now=NOW) == [copied_today]
|
||||
assert (restored_from_an_old_backup / "manifest.json").is_file()
|
||||
|
||||
|
||||
def test_the_retention_is_thirty_days_by_default(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.delenv(RETENTION, raising=False)
|
||||
|
||||
assert load_config(None).runs_retention_days == 30
|
||||
assert ResolvedConfig().runs_retention_days == 30
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["0", "7"])
|
||||
def test_the_environment_sets_the_retention(monkeypatch: pytest.MonkeyPatch, value: str) -> None:
|
||||
monkeypatch.setenv(RETENTION, value)
|
||||
|
||||
assert load_config(None).runs_retention_days == int(value)
|
||||
assert ResolvedConfig().runs_retention_days == int(value)
|
||||
|
||||
|
||||
def test_an_empty_retention_leaves_the_default_as_an_empty_runs_dir_does(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv(RETENTION, "")
|
||||
|
||||
assert load_config(None).runs_retention_days == 30
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["-1", "3.5", "soon"])
|
||||
def test_a_retention_that_is_negative_or_not_a_whole_number_is_rejected(monkeypatch: pytest.MonkeyPatch, value: str) -> None:
|
||||
monkeypatch.setenv(RETENTION, value)
|
||||
|
||||
with pytest.raises(ValueError, match=RETENTION):
|
||||
load_config(None)
|
||||
|
||||
|
||||
def test_a_scan_with_a_retention_of_zero_keeps_every_run_and_says_nothing(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
runs = _default_cache(tmp_path, monkeypatch)
|
||||
monkeypatch.setenv(RETENTION, "0")
|
||||
expired = _earlier_run(runs, 40)
|
||||
repo = _target(tmp_path)
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
assert (expired / "manifest.json").is_file()
|
||||
assert _notices(capsys.readouterr().out) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("expired_count", "runs_removed"), [(1, "run"), (2, "runs")])
|
||||
def test_a_scan_removes_the_expired_runs_from_the_default_location_and_says_how_many(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], expired_count: int, runs_removed: str
|
||||
) -> None:
|
||||
runs = _default_cache(tmp_path, monkeypatch)
|
||||
expired = [_earlier_run(runs, 40) for _ in range(expired_count)]
|
||||
last_week = _earlier_run(runs, 5)
|
||||
repo = _target(tmp_path)
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
out = capsys.readouterr().out
|
||||
(this_run,) = re.findall(r"^run_dir=(.+)$", out, flags=re.MULTILINE)
|
||||
assert sorted(runs.iterdir()) == sorted([last_week, Path(this_run)])
|
||||
assert _notices(out) == [f"removed {expired_count} {runs_removed} older than 30 days from {runs}"]
|
||||
assert not any(path.exists() for path in expired)
|
||||
|
||||
|
||||
def test_a_scan_with_a_runs_dir_of_its_own_removes_nothing_and_says_nothing_about_removal(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache"))
|
||||
elsewhere = tmp_path / "elsewhere" / "runs"
|
||||
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(elsewhere))
|
||||
monkeypatch.delenv(RETENTION, raising=False)
|
||||
kept_in_the_cache = _earlier_run(tmp_path / "cache" / "openultrasast" / "runs", 40)
|
||||
kept_elsewhere = _earlier_run(elsewhere, 40)
|
||||
repo = _target(tmp_path)
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
assert (kept_in_the_cache / "manifest.json").is_file()
|
||||
assert (kept_elsewhere / "manifest.json").is_file()
|
||||
assert _notices(capsys.readouterr().out) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("through_a_symlink", [False, True], ids=["literal-path", "through-a-symlink"])
|
||||
def test_a_scan_with_the_runs_dir_override_pointing_at_the_default_location_removes_nothing(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], through_a_symlink: bool
|
||||
) -> None:
|
||||
cache = tmp_path / "cache"
|
||||
monkeypatch.setenv("XDG_CACHE_HOME", str(cache))
|
||||
monkeypatch.delenv(RETENTION, raising=False)
|
||||
default = cache / "openultrasast" / "runs"
|
||||
expired = _earlier_run(default, 40)
|
||||
chosen = default
|
||||
if through_a_symlink:
|
||||
link = tmp_path / "link"
|
||||
link.symlink_to(cache, target_is_directory=True)
|
||||
chosen = link / "openultrasast" / "runs"
|
||||
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(chosen))
|
||||
repo = _target(tmp_path)
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
out = capsys.readouterr().out
|
||||
(this_run,) = re.findall(r"^run_dir=(.+)$", out, flags=re.MULTILINE)
|
||||
assert (default / Path(this_run).name / "manifest.json").is_file()
|
||||
assert (expired / "manifest.json").is_file()
|
||||
assert _notices(out) == []
|
||||
|
||||
|
||||
def test_a_scan_with_an_empty_runs_dir_override_removes_the_expired_runs_from_the_default_location(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
runs = _default_cache(tmp_path, monkeypatch)
|
||||
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", "")
|
||||
expired = _earlier_run(runs, 40)
|
||||
repo = _target(tmp_path)
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
assert not expired.exists()
|
||||
assert _notices(capsys.readouterr().out) == [f"removed 1 run older than 30 days from {runs}"]
|
||||
|
||||
|
||||
def test_a_scan_whose_removal_fails_still_succeeds_and_prints_one_notice(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
runs = _default_cache(tmp_path, monkeypatch)
|
||||
expired = _earlier_run(runs, 40)
|
||||
repo = _target(tmp_path)
|
||||
refusal = PermissionError(errno.EACCES, "Permission denied", str(expired))
|
||||
_refuse_removal(monkeypatch, expired, refusal)
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
assert (expired / "manifest.json").is_file()
|
||||
assert _notices(capsys.readouterr().out) == [f"old runs could not be removed from {runs}: {refusal}"]
|
||||
|
||||
|
||||
def test_a_scan_whose_removal_runs_out_of_recursion_still_succeeds_and_prints_one_notice(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
runs = _default_cache(tmp_path, monkeypatch)
|
||||
expired = _earlier_run(runs, 40)
|
||||
repo = _target(tmp_path)
|
||||
failure = RecursionError("maximum recursion depth exceeded")
|
||||
_refuse_removal(monkeypatch, expired, failure)
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
assert (expired / "manifest.json").is_file()
|
||||
assert _notices(capsys.readouterr().out) == [f"old runs could not be removed from {runs}: {failure}"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("retention_days", [OVER_THE_CALENDAR, 1_000_000, 10**9])
|
||||
def test_a_retention_longer_than_the_calendar_removes_nothing(tmp_path: Path, retention_days: int) -> None:
|
||||
expired = _run(tmp_path, _run_id(NOW - timedelta(days=40)))
|
||||
|
||||
assert prune_old_runs(tmp_path, keep=None, retention_days=retention_days, now=NOW) == []
|
||||
assert (expired / "manifest.json").is_file()
|
||||
|
||||
|
||||
def test_a_scan_with_a_retention_longer_than_the_calendar_succeeds_and_says_nothing(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
runs = _default_cache(tmp_path, monkeypatch)
|
||||
monkeypatch.setenv(RETENTION, "1000000")
|
||||
expired = _earlier_run(runs, 40)
|
||||
repo = _target(tmp_path)
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
assert (expired / "manifest.json").is_file()
|
||||
assert _notices(capsys.readouterr().out) == []
|
||||
Reference in New Issue
Block a user