mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 10:18:18 +00:00
The decision of the maintainer on the ninth session's menu, answer 9 (.kiro/handover.md,
untracked, 1340-1343 as it stood on 2026-11-27; the option as offered, 1451-1452):
> 9. The ledger in the image. Answer: "Decide the key now": a digest of the tree's files
> (the `fingerprint` of the `provenance` stage is no digest), one ledger per digest under
> the runs directory; a design note is shown to the maintainer before any code.
The design note (/tmp/opencode/s10_c10_design_note.md, 299 lines) was reviewed in five
rounds before it was shown, and shown to the maintainer whole on 2026-11-27 with its three
questions. The maintainer's answers came on 2026-11-28, through the question tool, each the
recommended option as offered: "Stand as written (Recommended)" on the note's rule of reading
and writing (its section 3.3), "With the runs, by last use (Recommended)" on how long a ledger
stays (section 3.5), and "Build it now (Recommended)". The dated note on task 3.1 of
.kiro/specs/contributor-scan/tasks.md (lines 459-502) carries the rule as approved.
The fault: the image mounts the target read-only, so the ledger a scan writes into the tree
(<target>/.openultrasast/calibration/false_positive_learnings.json) cannot be written there,
the scan records ledger_not_written, and the next scan in the image starts without the
learnings of the one before.
What changed
- src/openultrasast/tree_digest.py: tree_digest(target, runs_directory) (line 48), a sha256
over one entry per file in path order (the length of the path, a colon, the path, a tab,
the sha256 of the bytes), after a version line. Left out: links, the directories a scan
ignores (IGNORED_DIRS, so that the tree's ledger does not change its own key) and the runs
directory, whichever way it is reached (by device and inode). A file that cannot be read
and a directory that cannot be listed are named "unreadable"; a directory that can be
listed but not searched raises, as the scan's own reading of the tree does.
- src/openultrasast/digest_ledger.py: the ledger of a digest, calibration/<digest>.json under
the runs directory, in the JSON of the tree's ledger. read_digest_ledger (line 47) reads it
and marks it as used; settle_digest_ledger (line 65) applies the rule.
The tree took the write: the ledger is removed. The tree refused: the ledger is written
with its own entries and this scan's new ones, never one whose finding id the tree's
ledger has, only when that differs from its content, and removed when that would leave it
empty. No write: a ledger whose every entry the tree's ledger also has is removed. One that
could not be read (a file that is not a ledger, whatever its top level or its depth) is
taken for empty and goes, unless the tree refused and this scan wrote it. It is written
through a temporary file of the writer's own and a rename (line 112).
- src/openultrasast/cli.py: the stage tree_digest, before any stage reads the tree
(cli.py:603-605); _read_ledgers (cli.py:1085-1099), the tree's ledger and then the
digest's, the tree's entry winning by finding id; _persist_calibration_feedback
(cli.py:1101-1136), which writes the tree's ledger when its content would differ from what
it held, also when only the digest's entries are new to it; the manifest's ledger block
(cli.py:731-735); a notice when the digest's ledger could not be written or removed
(cli.py:755).
- src/openultrasast/run.py: prune_expired_ledgers (run.py:112), called by prune_scan_runs
(run.py:71-99). Under calibration/ of the same two locations as the runs, a ledger, or the
temporary file it was written through, last used OPENULTRASAST_RUNS_RETENTION_DAYS days
ago is removed; 0 keeps all. Files called something else, links and directories stay. A
removal that fails is said once and costs the scan nothing.
- src/openultrasast/reports.py: write_manifest takes ledger (reports.py:212, 254-255). The
ledger_not_written sentence names the digest's ledger when it holds the learnings
(reports.py:461-467, chosen at 479-483).
- README.md, docs/examples.md, docs/architecture.md and
.agents/skills/openultrasast-scan/SKILL.md say where the learnings of a read-only tree go,
and what removes them.
Two departures from recorded decisions, both put to the maintainer in the note and accepted
with it:
- The tree's ledger is written when a scan learns nothing new, because the digest's entries
are new to it. The decision of 2026-11-24 says it "is written only when a scan learns
something" (spec.json:68).
- A ledger of a digest is removed when it expires, and its time is changed when a scan reads
it. The decision of 2026-11-24 says "the scan's own run and anything not named like a run
are never touched" (spec.json:73), and dates a run by its id, where a ledger is dated by
its use.
Measured
- The built function gives the note's prototype's digest for the four-file subject
(915506a8...) and for libpng's copy (1dcd664f...): s10_c10_port.out.
- In the image, on the final code. A probe image of openultrasast:dev (3f959b31f2f2) with
the tree's package copied over it, built at 09:06:36Z and holding the tree's 297 .py files
(s10_c10_image_probe/03_probe_sources.out, s10_c10_sources_still_equal4.out). Standard
mode, no key, network none. The four C files of contrib/examples of libpng and their
README, copied fresh and mounted read-only at /target; a scratch runs directory mounted at
/reports with the wrapper's OPENULTRASAST_RUNS_DIR=/reports (s10_c10_image_probe.sh,
stamps 09:06:36Z to 09:09:14Z, 2026-11-28).
- The first scan learns four entries and keeps them in /reports/calibration/<digest>.json:
calibrations_applied=0, project_score 26, the manifest's ledger {digest_ledger: written,
learnings_read: {digest: 0, tree: 0}} (10_, 11_). The report names the file.
- The second scan of the same bytes reads them: calibrations_applied=2 on two files,
project_score 59, penalty_total 32.0, learnings_read 4 from the digest's ledger,
digest_ledger "left as it was" (20_, 21_). The file's time is that of the second scan's
read, 09:07:19Z (22_).
- The digest the scan took in the image equals the one taken on the host for the same
files (s10_c10_image_digest_host4.out). The target is unchanged
(s10_c10_image_target_same4.out).
- Three earlier runs of this probe and of the native run below, each on the code as it
stood before a later correction of the same rule (the value for a ledger that could not
be read; a ledger whose top level is not an object; one nested too deep), gave the same
numbers. Their stamps: 08:12:50Z to 08:17:31Z, 08:23:38Z to 08:27:42Z and 08:50:15Z to
08:54:17Z. They are kept as s10_c10_image_probe_run1, _run2, s10_c10_native_run1,
_run2 and _run3; of the third image run s10_c10_image_probe_run3.out and the host,
target and sources checks numbered 3 remain, since s10_c10_image_probe_run3 is empty.
Its files were read by the reviewer in round two.
- The shipped image, the control, on the same files: calibrations_applied=0 and
project_score 26 on both scans, no ledger block and no ledger (30_ to 42_).
- Natively, on a fresh copy of the same five files, the network off (s10_c10_native.sh,
09:09:14Z to 09:10:38Z): the first scan writes the tree's ledger (calibrations_applied=0,
project_score 26, digest_ledger none), the second reads it (calibrations_applied=2,
project_score 59, learnings_read 4 from the tree's ledger), and no ledger of a digest is
made (s10_c10_native/10_ to 22_).
- The probe left no container (2 before, 2 after: 00_, 91_) and its image is removed (90_,
92_).
Tests
- tests/test_tree_digest.py (7) and tests/test_digest_ledger.py (11, one over nine contents
a file may hold); seven tests in tests/test_scan_output_location.py, six through the scan
(three over two cases) and one on _read_ledgers; six in tests/test_run_pruning.py; one
sentence in tests/test_reports.py. The scan test of a refused write selects its run by
name now, since the runs directory holds calibration/ as well.
- RED on an archive of e231b78 with the final test files: the two unit files do not import
(s10_c10_red14.out); the scan, pruning and report files give 15 failed, 101 passed
(s10_c10_red13.out; the tree's tree_digest.py and digest_ledger.py were copied into that
archive, since the test file imports both, and cli.py, run.py and reports.py were HEAD's).
On the tree before each fix: the test of a ledger that is not a JSON object failed
(s10_c10_red8.out), and so did the content nested too deep and its scan test
(s10_c10_red12.out).
- GREEN on the final tree: 134 passed over the five files (s10_c10_green9.out); 873 passed
over the 60 files of the scan path (s10_c10_wide4_full.out; the list is
s10_c10_testfiles.txt); the docs and skills tests, with the strict site build, 11 passed
(s10_c10_docs_tests4.out; no page changed after it).
- Gates on the final tree: ten zeros (s10_c10e_exits.txt), the three gate outputs equal to
the baseline.
- Review: three rounds against e231b78, by one reviewer subagent, read-only; no
docker and no wrapper run, the probes read from their files. Round one blocked
on one finding and measured it end to end on a scratch tree: a ledger of a
digest whose top level is not a JSON object raised AttributeError in the tree's
loader and stopped the scan (exit 1), against the note's "a cache must not stop
a scan". Round two approved with remarks, which the code and the tests took:
RecursionError joined the tuple (digest_ledger.py:57), with a ninth content in
the unit test and a scan test of a ledger that is not a ledger, red before the
fix (s10_c10_red12.out). Round three approved the code, the tests and the dated
note, and blocked on one sentence of this message, which named
s10_c10_image_probe_run3 as kept: that directory is empty. On the final tree the
reviewer measured the scan past a digest's ledger nested 5000 deep (exit 0,
"unreadable", the file removed) and passed 30000 contents through
read_digest_ledger, with none let through; it re-ran the five files (134
passed), the docs and skills files with two scan files outside the sixty (20
passed), ruff, mypy (297 files) and the comparison of the three gate outputs
with the baseline, the gates themselves not run; it recomputed the three
digests, matched the tree's 297 .py files to the fourth probe image's list, and
read the fourth image and native runs. The third image run's files were read in
round two, before they were lost. The sentence was reworded as the reviewer
wrote it.
By reading, not measured
- A pre-push run does not go through _run_scan, and src/openultrasast/push names no ledger:
nothing changes there.
- ousast benchmark and the MCP server call _run_scan and get the rule as a scan does.
- mark_all of the hunt tooling lists the children of a runs root it is given; it has no
caller under src.
Found and not fixed, for the maintainer
- The note says the digest stage's seconds are in the manifest. No stage's are: a stage's
time is in trace/events.jsonl (stage_start and stage_end), and so is this one's. The pages
and the dated note do not repeat the sentence.
- The report's sentence (reports.py:461-467) says this scan's learnings are kept in the
ledger of the digest whenever that file holds some of them (cli.py:1131-1133). A new
learning whose finding id the tree's ledger already holds is left out by the rule; the
tree's version stands, and the new evidence text is in the run directory alone. The
sentence is the note's as approved.
- The tree's own ledger stops the scan when its top level is not a JSON object, or when it
is nested too deep (calibration.py:157-159, read at cli.py:610 outside any stage). That
is older than this commit; the ledger of a digest does not.
- read_digest_ledger raises when calibration/ cannot be searched, as the tree's ledger does
when .openultrasast/calibration cannot (digest_ledger.py:53).
- By reading: a tree whose runs directory is the target itself gets another digest at every
scan, since its run directory is made inside the target before the stage. Such a tree can
be written, so its own ledger takes the learnings and no ledger of a digest is made.
- docs/architecture.md draws no provenance stage, which cli.py runs between
entry_point_mapping and rank.
- The wrapper builds its image only when the image is missing: until a rebuild, a scan
through it runs the shipped code, which has none of this.
- The notice of a removed ledger names the runs directory as the scan sees it (/reports in
the image), not the host's path.
Not checked
- the whole test suite; Windows; ops/shell/ousast.ps1 (not read for this commit); two scans
of one tree at once; the wrapper and the compose route (the probe used docker run with the
wrapper's mount and override); a removal that fails on a real cache; Docker Desktop, where
a directory mounted twice may not keep one inode.
476 lines
20 KiB
Python
476 lines
20 KiB
Python
"""What a scan removes from its cache (contributor-scan Requirement 5.3, decisions of 2026-11-24 and 2026-11-27):
|
|
once its run is written, the expired runs go from the default location and from the shell wrapper's mount of it,
|
|
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 WRAPPER_RUNS_MOUNT, 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_through_the_wrapper_removes_the_expired_runs_from_the_mounted_runs_directory(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
"""What a scan in the image sees through the shell wrapper. The runs directory is a stand-in for `/reports`,
|
|
which only root can make on the host."""
|
|
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", "/reports")
|
|
monkeypatch.delenv(RETENTION, raising=False)
|
|
mounted = tmp_path / "reports"
|
|
_earlier_run(mounted, 40)
|
|
last_week = _earlier_run(mounted, 5)
|
|
current = _run(mounted, _run_id(datetime.now(UTC), "badc0de0"))
|
|
|
|
notices = prune_scan_runs(ResolvedConfig(runs_dir=str(mounted)), keep=current)
|
|
|
|
assert notices == (f"removed 1 run older than 30 days from {mounted}",)
|
|
assert sorted(mounted.iterdir()) == [last_week, current]
|
|
|
|
|
|
def test_a_scan_that_compose_runs_without_the_wrapper_removes_nothing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""The compose file's own `OPENULTRASAST_RUNS_DIR`, `/reports/runs`: a location chosen, where nothing is removed."""
|
|
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", "/reports/runs")
|
|
monkeypatch.delenv(RETENTION, raising=False)
|
|
runs = tmp_path / "reports" / "runs"
|
|
expired = _earlier_run(runs, 40)
|
|
current = _run(runs, _run_id(datetime.now(UTC), "badc0de0"))
|
|
|
|
assert prune_scan_runs(ResolvedConfig(runs_dir=str(runs)), keep=current) == ()
|
|
assert sorted(runs.iterdir()) == [expired, current]
|
|
|
|
|
|
def test_the_wrapper_passes_the_override_that_a_scan_prunes() -> None:
|
|
"""The wrapper's word and the scan's mount point must not drift apart: the scan prunes `/reports` by that name."""
|
|
wrapper = Path(__file__).resolve().parents[1] / "ops" / "shell" / "ousast.sh"
|
|
assert f"OPENULTRASAST_RUNS_DIR={WRAPPER_RUNS_MOUNT}" in wrapper.read_text().split()
|
|
|
|
|
|
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) == []
|
|
|
|
|
|
def _ledger_file(runs: Path, age_days: int, name: str) -> Path:
|
|
"""A file under the directory of the ledgers of tree digests, last used `age_days` ago by the real clock."""
|
|
path = runs / "calibration" / name
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text('{"learnings": []}\n')
|
|
last_used = (datetime.now(UTC) - timedelta(days=age_days)).timestamp()
|
|
os.utime(path, (last_used, last_used))
|
|
return path
|
|
|
|
|
|
def _digest(suffix: str = ".json") -> str:
|
|
return f"{uuid.uuid4().hex}{uuid.uuid4().hex[:32]}{suffix}"
|
|
|
|
|
|
def test_a_ledger_of_a_tree_digest_unused_for_longer_than_the_retention_is_removed_with_the_runs(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
"""By the decision of 2026-11-28: a ledger is dated by its last use, a run by its id."""
|
|
monkeypatch.delenv("OPENULTRASAST_RUNS_DIR", raising=False)
|
|
monkeypatch.delenv(RETENTION, raising=False)
|
|
runs = tmp_path / "runs"
|
|
_ledger_file(runs, 40, _digest())
|
|
last_week = _ledger_file(runs, 5, _digest())
|
|
current = _run(runs, _run_id(datetime.now(UTC), "badc0de0"))
|
|
|
|
notices = prune_scan_runs(ResolvedConfig(runs_dir=str(runs)), keep=current)
|
|
|
|
assert notices == (f"removed 1 ledger of a tree digest unused for 30 days from {runs / 'calibration'}",)
|
|
assert list((runs / "calibration").iterdir()) == [last_week]
|
|
assert sorted(runs.iterdir()) == sorted([runs / "calibration", current])
|
|
|
|
|
|
def test_a_scan_removes_the_expired_ledgers_and_says_so(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
|
) -> None:
|
|
runs = _default_cache(tmp_path, monkeypatch)
|
|
_ledger_file(runs, 40, _digest(".json." + uuid.uuid4().hex + ".tmp"))
|
|
_ledger_file(runs, 40, _digest())
|
|
last_week = _ledger_file(runs, 5, _digest())
|
|
repo = _target(tmp_path)
|
|
|
|
assert _scan(repo) == 0
|
|
|
|
assert list((runs / "calibration").iterdir()) == [last_week]
|
|
assert _notices(capsys.readouterr().out) == [f"removed 2 ledgers of a tree digest unused for 30 days from {runs / 'calibration'}"]
|
|
|
|
|
|
def test_nothing_under_the_ledgers_directory_that_is_not_a_ledger_is_touched(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.delenv("OPENULTRASAST_RUNS_DIR", raising=False)
|
|
runs = tmp_path / "runs"
|
|
notes = _ledger_file(runs, 40, "notes.txt")
|
|
elsewhere = _ledger_file(tmp_path, 40, _digest())
|
|
link = runs / "calibration" / _digest()
|
|
link.symlink_to(elsewhere)
|
|
directory = runs / "calibration" / _digest()
|
|
directory.mkdir()
|
|
|
|
assert prune_scan_runs(ResolvedConfig(runs_dir=str(runs)), keep=runs / _run_id(datetime.now(UTC), "badc0de0")) == ()
|
|
assert sorted(path.name for path in (runs / "calibration").iterdir()) == sorted([notes.name, link.name, directory.name])
|
|
assert elsewhere.is_file()
|
|
|
|
|
|
def test_a_retention_of_zero_keeps_every_ledger(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.delenv("OPENULTRASAST_RUNS_DIR", raising=False)
|
|
monkeypatch.setenv(RETENTION, "0")
|
|
runs = tmp_path / "runs"
|
|
expired = _ledger_file(runs, 40, _digest())
|
|
|
|
assert prune_scan_runs(ResolvedConfig(runs_dir=str(runs), runs_retention_days=0), keep=None) == ()
|
|
assert expired.is_file()
|
|
|
|
|
|
def test_a_ledger_is_kept_through_compose_without_the_wrapper(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", "/reports/runs")
|
|
monkeypatch.delenv(RETENTION, raising=False)
|
|
runs = tmp_path / "reports" / "runs"
|
|
expired = _ledger_file(runs, 40, _digest())
|
|
|
|
assert prune_scan_runs(ResolvedConfig(runs_dir=str(runs)), keep=None) == ()
|
|
assert expired.is_file()
|
|
|
|
|
|
def test_a_ledger_that_cannot_be_removed_is_said_once_and_costs_the_scan_nothing(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
|
) -> None:
|
|
runs = _default_cache(tmp_path, monkeypatch)
|
|
expired = _ledger_file(runs, 40, _digest())
|
|
refusal = PermissionError(errno.EACCES, "Permission denied", str(expired))
|
|
unlink = Path.unlink
|
|
|
|
def refuse(path, *args, **kwargs):
|
|
if path == expired:
|
|
raise refusal
|
|
unlink(path, *args, **kwargs)
|
|
|
|
monkeypatch.setattr(Path, "unlink", refuse)
|
|
repo = _target(tmp_path)
|
|
|
|
assert _scan(repo) == 0
|
|
|
|
assert expired.is_file()
|
|
assert _notices(capsys.readouterr().out) == [f"a ledger of a tree digest could not be removed from {runs / 'calibration'}: {refusal}"]
|