feat(contributor-scan): benchmark runs go beside the scan runs (3.1, follow-up)

`ousast benchmark` and its MCP twin wrote a run to
`<target>/.openultrasast/benchmarks/<id>/`, into the scanned tree, and no user
document said so. By the maintainer decision of 2026-11-24 a benchmark run now
goes to `<runs_dir>/<benchmark-run-id>/`, beside the scan runs, where run
retention removes it like a scan run.

`create_benchmark_run` in src/openultrasast/benchmark.py takes the runs
directory instead of the target. The two `_benchmark` functions, in cli.py and
in mcp.py, load the configuration the way `_run_scan` does and pass
`config.runs_dir`, so a benchmark run follows `OPENULTRASAST_RUNS_DIR` like the
scan it runs.

Both create the run once the scan has returned. Created first, as it was, the
run was under the scan's own retention while the scan ran, and a scan that
outlasted the retention window took it for an old one: the scoreboard could not
be written and the scan outcome was never printed. A failed scan now also
leaves no empty run behind.

README.md and docs/examples.md name where a benchmark run goes.

Tests: the three location assertions failed before the change and pass after
it. A new test pins that retention removes a benchmark run like a scan run, and
another that a benchmark keeps its run when its scan outlasts the retention
window. The nine test files around the change pass (120 passed); ruff, mypy,
the three gates and compileall pass. A run of the real CLI printed `run_dir=`
and `benchmark_run_dir=` as siblings under the runs directory and left only the
calibration ledger in the scanned tree. An independent reviewer approved the
change in two rounds; its first round found the retention window, which this
cut closes.
This commit is contained in:
Marius Ciepluch
2026-11-25 10:40:01 +01:00
parent 78434a6e9f
commit 9e4983f465
7 changed files with 83 additions and 13 deletions
+5
View File
@@ -193,6 +193,11 @@ there older than 30 days are removed, and `ousast` prints one `notice:` line whe
`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`.
`ousast benchmark` writes its run to the same runs directory, as
`<runs_dir>/<benchmark-run-id>/` beside the scan runs, and prints that path
(`benchmark_run_dir=<path>`); run retention removes it like a scan run. The MCP tool
`openultrasast.benchmark` uses the same directory.
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
content would change; on a read-only tree the scan records `ledger_not_written` instead and keeps
+3 -1
View File
@@ -8,7 +8,9 @@ the current working directory, never against the target. Once a scan has written
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`.
ever removed from a location chosen with `OPENULTRASAST_RUNS_DIR`. `ousast benchmark` writes its
run to the same directory, as `<runs_dir>/<benchmark-run-id>/` beside the scan runs, and prints
that path (`benchmark_run_dir=<path>`); run retention removes it like a scan run.
A scan that rejects or holds a finding writes one file into the scanned tree, and only when that
file's content would change:
+7 -2
View File
@@ -182,10 +182,15 @@ def resolve_benchmark_source(manifest_path: Path, manifest: BenchmarkManifest) -
return source.resolve()
def create_benchmark_run(target: Path, manifest: BenchmarkManifest) -> BenchmarkRun:
def create_benchmark_run(runs_dir: Path, manifest: BenchmarkManifest) -> BenchmarkRun:
"""A run beside the scan runs, named like one so that run retention removes it.
Create it once its scan has returned: a run that exists while a scan prunes can be taken for an old
one when the scan outlasts the retention window.
"""
timestamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
benchmark_run_id = f"{timestamp}-{uuid4().hex[:8]}"
root = target.resolve() / ".openultrasast" / "benchmarks" / benchmark_run_id
root = runs_dir / benchmark_run_id
root.mkdir(parents=True, exist_ok=False)
return BenchmarkRun(benchmark_run_id=benchmark_run_id, root=root, manifest=manifest)
+2 -1
View File
@@ -1100,10 +1100,11 @@ def _benchmark(manifest_path: Path, config_path: Path, mode: str) -> int:
raise SystemExit(f"benchmark manifest is not a file: {manifest_path}")
manifest = load_benchmark_manifest(manifest_path)
target = resolve_benchmark_source(manifest_path, manifest)
run = create_benchmark_run(target, manifest)
config = load_config(config_path if config_path.exists() else None)
started_at = perf_counter()
outcome = _run_scan(target, config_path, mode, "never")
runtime_seconds = perf_counter() - started_at
run = create_benchmark_run(Path(config.runs_dir), manifest)
findings = _load_scan_findings(outcome.run_dir)
baseline_findings = load_baseline_findings(manifest_path, manifest)
result = evaluate_benchmark(
+5 -2
View File
@@ -163,6 +163,7 @@ def _artifacts(args: dict[str, Any]) -> dict[str, Any]:
def _benchmark(args: dict[str, Any]) -> dict[str, Any]:
from .benchmark import create_benchmark_run, evaluate_benchmark, load_benchmark_manifest, load_findings, resolve_benchmark_source
from .cli import _run_scan
from .config import load_config
manifest_path = Path(_require(args, "manifest"))
if not manifest_path.is_file():
@@ -170,8 +171,10 @@ def _benchmark(args: dict[str, Any]) -> dict[str, Any]:
mode = str(args.get("mode", "quick"))
manifest = load_benchmark_manifest(manifest_path)
target = resolve_benchmark_source(manifest_path, manifest)
run = create_benchmark_run(target, manifest)
outcome = _run_scan(target, Path(str(args.get("config", "openultrasast.toml"))), mode, "never")
config_path = Path(str(args.get("config", "openultrasast.toml")))
config = load_config(config_path if config_path.exists() else None)
outcome = _run_scan(target, config_path, mode, "never")
run = create_benchmark_run(Path(config.runs_dir), manifest)
result = evaluate_benchmark(
run=run, mode=mode, findings=load_findings(outcome.run_dir / "findings.json"), scan_id=outcome.scan_id, scan_run_dir=outcome.run_dir
)
+46 -7
View File
@@ -1,6 +1,9 @@
import json
from datetime import UTC, datetime, timedelta, tzinfo
from pathlib import Path
from test_run_pruning import _default_cache
from openultrasast.benchmark import (
create_benchmark_run,
evaluate_benchmark,
@@ -10,6 +13,7 @@ from openultrasast.benchmark import (
)
from openultrasast.cli import main
from openultrasast.findings import StaticFinding
from openultrasast.run import prune_old_runs
def test_benchmark_manifest_loads_expected_findings(tmp_path: Path) -> None:
@@ -103,7 +107,7 @@ evidence = "memcpy copies attacker-controlled input"
+ "\n"
)
manifest = load_benchmark_manifest(manifest_path)
run = create_benchmark_run(repo, manifest)
run = create_benchmark_run(repo / ".runs", manifest)
result = evaluate_benchmark(run=run, mode="quick", findings=[], scan_id="scan-1", scan_run_dir=repo / ".runs" / "scan-1")
write_benchmark_artifacts(run, manifest_path, result)
@@ -146,8 +150,9 @@ evidence = "memcpy copies attacker-controlled input"
assert main(["benchmark", str(manifest_path), "--mode", "quick"]) == 0
benchmark_dir = sorted((repo / ".openultrasast" / "benchmarks").iterdir())[-1]
payload = json.loads((benchmark_dir / "benchmark_result.json").read_text())
[scoreboard] = sorted((repo / ".runs").glob("*/benchmark_result.json"))
assert not (repo / ".openultrasast" / "benchmarks").exists()
payload = json.loads(scoreboard.read_text())
assert payload["benchmark_name"] == "cpp-smoke"
assert payload["metrics"]["expected_findings_total"] == 1
@@ -157,6 +162,40 @@ evidence = "memcpy copies attacker-controlled input"
assert payload["metrics"]["artifact_links"]["findings"].endswith("findings.json")
def test_run_retention_removes_a_benchmark_run_like_a_scan_run(tmp_path: Path) -> None:
manifest_path = tmp_path / "benchmark.toml"
manifest_path.write_text('name = "cpp-smoke"\nlanguage = "c_cpp"\n\n[source]\npath = "repo"\n')
runs = tmp_path / "runs"
run = create_benchmark_run(runs, load_benchmark_manifest(manifest_path))
assert run.root.parent == runs
assert prune_old_runs(runs, retention_days=30, now=datetime.now(UTC) + timedelta(days=31)) == [run.root]
class _FortyDaysAgo(datetime):
"""Stands in for the clock that names a benchmark run: that run then started forty days ago."""
@classmethod
def now(cls, tz: tzinfo | None = None) -> datetime:
return datetime.now(UTC) - timedelta(days=40)
def test_benchmark_keeps_its_run_when_its_scan_outlasts_the_retention(tmp_path: Path, monkeypatch) -> None: # type: ignore[no-untyped-def]
repo = tmp_path / "repo"
repo.mkdir()
(repo / "app.py").write_text("@app.route('/admin')\ndef admin():\n return eval(request.data)\n")
manifest = tmp_path / "benchmark.toml"
manifest.write_text('name = "py-smoke"\nlanguage = "python"\n\n[source]\npath = "repo"\n')
runs = _default_cache(tmp_path, monkeypatch)
monkeypatch.setattr("openultrasast.benchmark.datetime", _FortyDaysAgo)
assert main(["benchmark", str(manifest), "--mode", "quick"]) == 0
[scoreboard] = runs.glob("*/benchmark_result.json")
assert json.loads(scoreboard.read_text())["benchmark_name"] == "py-smoke"
def test_benchmark_matching_uses_function_sink_and_evidence_text(tmp_path: Path) -> None:
manifest_path = tmp_path / "benchmark.toml"
repo = tmp_path / "repo"
@@ -182,7 +221,7 @@ evidence = "attacker-controlled memcpy"
+ "\n"
)
manifest = load_benchmark_manifest(manifest_path)
run = create_benchmark_run(repo, manifest)
run = create_benchmark_run(repo / ".runs", manifest)
findings = [
_finding(
finding_id="c-unsafe-memory-copy:src/vuln.cpp:9",
@@ -226,7 +265,7 @@ evidence = "memcpy"
+ "\n"
)
manifest = load_benchmark_manifest(manifest_path)
run = create_benchmark_run(repo, manifest)
run = create_benchmark_run(repo / ".runs", manifest)
findings = [
_finding(
finding_id="c-shell-exec:src/other.cpp:12",
@@ -299,7 +338,7 @@ evidence = "memcpy copies attacker-controlled input"
+ "\n"
)
manifest = load_benchmark_manifest(manifest_path)
run = create_benchmark_run(repo, manifest)
run = create_benchmark_run(repo / ".runs", manifest)
baseline_findings = load_baseline_findings(manifest_path, manifest)
unrelated_finding = _finding(
finding_id="c-shell-exec:src/other.cpp:12",
@@ -372,7 +411,7 @@ evidence = "system runs attacker input"
+ "\n"
)
manifest = load_benchmark_manifest(manifest_path)
run = create_benchmark_run(repo, manifest)
run = create_benchmark_run(repo / ".runs", manifest)
findings = [
_finding(
finding_id="c-unsafe-memory-copy:src/vuln.cpp:9",
+15
View File
@@ -178,6 +178,21 @@ def test_benchmark_result_carries_the_notice_of_the_runs_the_scan_removed(tmp_pa
assert result["notices"] == [f"removed 1 run older than 30 days from {runs}"]
def test_a_benchmark_run_sits_beside_the_scan_runs_not_in_the_scanned_tree(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
runs = _default_cache(tmp_path, monkeypatch)
repo = _repo(tmp_path)
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"]
benchmark_run = runs / result["benchmark_run_id"]
assert benchmark_run.is_dir()
assert any((path / "manifest.json").is_file() for path in runs.iterdir() if path != benchmark_run)
assert not (repo / ".openultrasast" / "benchmarks").exists()
# ---- stdio loop -------------------------------------------------------------