Files
Open_Ultra_SAST/tests/test_task_images.py
T
Marius Ciepluch 55583b34c3 fix(images): the replay entry leaves benchmarks/unseen, so the replay stage builds (item 5b)
The maintainer's answer of 2026-11-27 to question 1 of the ninth session's menu, "Move the
file, fix now": the script leaves benchmarks/unseen for a path the build context keeps, and
the four references follow. .dockerignore:32 has excluded benchmarks/unseen since 9017038
(2026-11-24), so the COPY of the replay stage of plane/Dockerfile.engine-task stopped the
build. Measured again here from the root context, with scratch Dockerfiles: a COPY of the old
path fails with "not found", a COPY of a kept path succeeds, and after the change a COPY of
the new path succeeds.

What changed:
- benchmarks/unseen/replay_entry.py is benchmarks/replay/replay_entry.py (git mv, the
  content unchanged). The directory is the session's choice; no decision names it. The
  script's own line 18 looks for learn/ beside its own directory (parents[1] / "learn"), so a
  sibling of benchmarks/learn keeps that line as it is. Measured in a probe image: with the
  file directly under benchmarks/, the import of engine_task_entry fails at line 19.
- plane/Dockerfile.engine-task:47 copies the new path to ./benchmarks/replay/. The command
  of benchmarks/unseen/replay.py:46 names /app/benchmarks/replay/replay_entry.py. The two
  tests import benchmarks.replay.replay_entry.
- tests/test_task_images.py gains test_copy_sources_are_kept_by_the_build_context, over the
  four Dockerfiles that build from the root context: a COPY source that the root .dockerignore
  excludes stops the build.

Evidence:
- RED: the new test on a git archive of HEAD plus the new test file, 1 failed and 3 passed
  (the engine-task Dockerfile copies benchmarks/unseen/replay_entry.py); the first version of
  the helper gave the same on the working tree before the move.
- GREEN: 458 passed over tests/test_task_images.py, tests/test_unseen_*.py,
  tests/test_independent_population.py and tests/test_search_image.py after the move, and
  tests/test_task_images.py again, 27 passed, after the helper was hardened.
- ruff, mypy, the three gates and compileall pass, and the gates print what they printed
  before. `git diff --check` exits 0. No whole-suite run: that is step 9.
- An independent reviewer approved the change in one round. Its optional hardening of the
  helper is applied after the approval, as proposed: a line of .dockerignore is now matched
  against the path and each directory above it, where the first version took a line without a
  wildcard by prefix only. Two shapes stay as the reviewer found them: a line written with a
  leading ./ or /, and a `!` line with a wildcard are not read as Docker reads them.
- The scratch is under /tmp/opencode/s10_* and is not kept.

Side effect, by reading: the root Dockerfile copies the whole benchmarks directory
(Dockerfile:44), so the next scan image carries benchmarks/replay/replay_entry.py, where the
file was excluded with its directory. No image is rebuilt.

Found and not fixed, for the maintainer: after this commit the replay job of
engine-image.yml builds again, and the image it publishes cannot start its entry. In an
image built from plane/Dockerfile.engine-task the import at benchmarks/learn/
engine_task_entry.py:17 (from benchmarks.valid.artifact_contract, from 11059c4c of
2026-11-03) has nothing to resolve. By reading: the engine stage copies pyproject.toml,
README.md, LICENSE, src and three named files of benchmarks/learn, and the replay stage adds
one file, so neither image holds benchmarks/valid. Measured on the shipped scan image
openultrasast:dev 3f959b31f2f2 (built from 88ea171, before this change) with the network
off; the engine image and the replay image were not built or run here, and the runner's
environment was not read: `python3 /app/benchmarks/learn/engine_task_entry.py`, the way
benchmarks/learn/engine_trace_ax.py:38 launches the engine workload, stops at line 17 with
"No module named 'benchmarks'"; with /app on the path it stops with "No module named
'benchmarks.valid'", because 9017038 keeps benchmarks/valid out of every image; and the
replay actor's command in a probe image built from the scan image stops at
replay_entry.py:19 and then at that line. So a green replay job is not a working replay. The
fix is a decision: carry artifact_contract.py in the two stages, move
write_benchmark_artifact out of benchmarks/valid, or make the import lazy. It is not made
here; the fault is outside the answer.

Left as they are: .kiro/steering/roadmap.md:289 and
.kiro/specs/engine-change-scoped-analysis/brief.md:36 name the old path in the image
(steering is the maintainer's; both are reported); the contributor-scan record,
benchmarks/measurements/2026-10-04-unseen-06-scorer/record.json:8 and a PATHFINDER document
are dated records. No test reads the command path of replay.py:46 against the COPY's
destination; they agree by reading.
2026-11-27 16:00:32 +01:00

310 lines
15 KiB
Python

"""Offline image contracts; these do not claim a built image or measured size."""
import json
import re
from fnmatch import fnmatchcase
from pathlib import Path
import pytest
import yaml
ROOT = Path(__file__).resolve().parents[1]
def read(name):
return (ROOT / name).read_text()
def instructions(name):
text = re.sub(r"\\\n\s*", " ", read(name))
return [line for line in text.splitlines() if line and not line.startswith("#")]
def workflow(name):
# BaseLoader avoids YAML 1.1 interpreting GitHub's `on` as a boolean.
return yaml.load(read(f".github/workflows/{name}.yml"), Loader=yaml.BaseLoader)
@pytest.mark.parametrize(
"name,variant",
[
("plane/Dockerfile.engine-task", "BASE"),
("plane/Dockerfile.search-task", "BROWSER"),
("Dockerfile", "BASE"),
],
)
def test_digest_required_and_code_last(name, variant):
lines = instructions(name)
assert f"ARG TASK_{variant}_DIGEST" in lines
ref = f"ghcr.io/norandom/ousast-task-base:${{TASK_{variant}_TAG}}@${{TASK_{variant}_DIGEST}}"
assert any(line.startswith(f"FROM {ref}") for line in lines)
code = next(i for i, line in enumerate(lines) if line.startswith(("COPY src ", "COPY --chown=1000 src ")))
for i, line in enumerate(lines):
if "apt-get" in line or "--from=joern-build" in line or "frontend-retention-install.py" in line:
assert i < code
if "pip install" in line:
assert "--no-deps --no-cache-dir ." in line
assert i > code
assert not any("venv /venv" in line for line in lines)
def test_compose_builds_from_the_pinned_base():
"""`docker compose build` takes no arguments, so the base it resolves is whatever these defaults say."""
ref = json.loads(read("plane/task-base.digest"))["base"]
tag, digest = re.fullmatch(r"ghcr.io/norandom/ousast-task-base:(base-[a-z0-9-]+)@(sha256:[0-9a-f]{64})", ref).groups()
service = yaml.load(read("docker-compose.yml"), Loader=yaml.BaseLoader)["services"]["ousast"]
for name, default in (("TASK_BASE_TAG", tag), ("TASK_BASE_DIGEST", digest)):
default_ref = f"${{{name}:-{default}}}"
assert service["build"]["args"].get(name) == default_ref, f"{name} does not default to {default} (plane/task-base.digest)"
assert service["environment"]["OPENULTRASAST_RUNS_DIR"].startswith("/reports/")
def test_compose_leaves_the_reports_directory_to_the_user():
"""Docker creates a missing bind source as root, and the image runs as uid 1000: the run could not write."""
service = yaml.safe_load(read("docker-compose.yml"))["services"]["ousast"]
mounts = {v["target"]: v for v in service["volumes"] if isinstance(v, dict)}
assert "/reports" in mounts, "the /reports volume is short syntax, so Docker creates a missing source as root"
assert mounts["/reports"]["source"] == "${OUSAST_REPORTS:-./reports}"
assert mounts["/reports"].get("bind", {}).get("create_host_path") is False
def test_compose_refuses_a_target_that_does_not_exist():
"""Docker creates a missing bind source as an empty directory, and an empty target scans clean: a typo reads as clean."""
service = yaml.safe_load(read("docker-compose.yml"))["services"]["ousast"]
mounts = {v["target"]: v for v in service["volumes"] if isinstance(v, dict)}
assert "/target" in mounts, "the /target volume is short syntax, so Docker creates a missing source as an empty directory"
assert mounts["/target"]["source"] == "${TARGET:-.}"
assert mounts["/target"]["read_only"] is True
assert mounts["/target"].get("bind", {}).get("create_host_path") is False
def test_shared_ancestry_and_replay_exact_engine():
base = read("plane/Dockerfile.base")
assert "FROM ghcr.io/norandom/ax-task-runner:v0.3.1 AS base" in base
assert "FROM ${TASK_BASE_REF} AS base-browser" in base
common, browser = base.split("FROM ${TASK_BASE_REF} AS base-browser")
assert "chromium" not in common and "chromium" in browser
assert "21-jdk-jammy" in common
assert "COPY src" not in base and 'p["dependencies"]' in base
assert "pip install --no-cache-dir -r /tmp/requirements.txt" in base
engine = read("plane/Dockerfile.engine-task")
assert "ARG ENGINE_REF=engine" in engine and "FROM ${ENGINE_REF} AS replay" in engine
wf = workflow("engine-image")
assert wf["jobs"]["replay"]["needs"] == ["pins", "engine"]
builds = [s["with"] for s in wf["jobs"]["replay"]["steps"] if s.get("uses") == "docker/build-push-action@v6"]
assert "ENGINE_REF=${{ needs.engine.outputs.image }}@${{ needs.engine.outputs.digest }}" in builds[0]["build-args"]
base_wf = workflow("task-base-image")
browser_build = next(s["with"] for s in base_wf["jobs"]["base"]["steps"] if s.get("id") == "browser")
assert "@${{ steps.base.outputs.digest }}" in browser_build["build-args"]
# Remote ancestry and anonymous existence are checked before downstream builds.
assert 'manifests["base-browser"][:len(base)] != base' in read(".github/workflows/engine-image.yml")
@pytest.mark.parametrize("name", ["engine-image", "task-base-image"])
def test_triggers_caches_and_digest_outputs(name):
wf = workflow(name)
assert "workflow_dispatch" in wf["on"]
assert "src/**" not in wf["on"]["push"]["paths"]
if name == "engine-image":
assert wf["on"]["push"]["tags"] == ["v*"]
assert "plane/task-base.digest" in wf["on"]["push"]["paths"]
else:
assert set(wf["on"]["push"]["paths"]) == {"plane/Dockerfile.base", "pyproject.toml", "uv.lock"}
builds = [s["with"] for job in wf["jobs"].values() for s in job["steps"] if s.get("uses") == "docker/build-push-action@v6"]
assert builds
for build in builds:
assert "type=gha" in build["cache-from"] and "type=gha" in build["cache-to"]
assert build["push"] == "true"
assert "outputs.digest" in read(f".github/workflows/{name}.yml")
def test_pin_bootstrap_fails_closed():
pins = json.loads(read("plane/task-base.digest"))
assert set(pins) >= {"base", "base-browser"}
for key in ("base", "base-browser"):
if pins[key] is None:
assert "UNPUBLISHED" in pins["note"]
else:
assert re.fullmatch(r"ghcr.io/norandom/ousast-task-base:base-[a-z0-9-]+@sha256:[0-9a-f]{64}", pins[key])
wf = read(".github/workflows/engine-image.yml")
assert "raise SystemExit" in wf and '"inspect", "--raw", ref' in wf
assert "needs: pins" in wf
@pytest.mark.parametrize("case", ["unpublished", "missing", "wrong-ancestry", "valid"])
def test_ci_pin_gate_offline(case, tmp_path, monkeypatch):
"""Exercise the actual workflow Python, with only registry reads replaced."""
import subprocess
pin_step = next(s for s in workflow("engine-image")["jobs"]["pins"]["steps"] if s.get("id") == "pins")
script = pin_step["run"].split("<<'PYTHON'\n", 1)[1].rsplit("PYTHON", 1)[0]
base = "ghcr.io/norandom/ousast-task-base:base-1234567@sha256:" + "a" * 64
browser = "ghcr.io/norandom/ousast-task-base:base-1234567-browser@sha256:" + "b" * 64
(tmp_path / "plane").mkdir()
(tmp_path / "plane/task-base.digest").write_text(
json.dumps(
{
"base": None if case == "unpublished" else base,
"base-browser": browser,
}
)
)
output = tmp_path / "output"
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("GITHUB_OUTPUT", str(output))
calls = []
def inspect(argv):
calls.append(argv)
assert argv[:5] == ["docker", "buildx", "imagetools", "inspect", "--raw"]
if case == "missing":
raise subprocess.CalledProcessError(1, argv)
layers = [{"digest": "sha256:shared"}]
if argv[-1] == browser:
if case == "wrong-ancestry":
layers = [{"digest": "sha256:different"}]
layers.append({"digest": "sha256:chromium"})
return json.dumps({"layers": layers}).encode()
monkeypatch.setattr(subprocess, "check_output", inspect)
if case == "valid":
exec(compile(script, "workflow-pin-gate", "exec"), {})
assert "base_digest=sha256:" in output.read_text()
assert "browser_digest=sha256:" in output.read_text()
assert len(calls) == 2
else:
expected = subprocess.CalledProcessError if case == "missing" else SystemExit
with pytest.raises(expected):
exec(compile(script, "workflow-pin-gate", "exec"), {})
if case == "unpublished":
assert not calls
@pytest.mark.parametrize("case", ["unpublished", "bare-tag", "short-digest", "wrong-repo", "valid"])
def test_release_pins_the_base_of_its_scan_image(case, tmp_path, monkeypatch):
"""`Dockerfile`'s own default base is `base-unpublished`: built without the pin, the release image cannot exist."""
steps = workflow("release")["jobs"]["images"]["steps"]
pin_steps = [s for s in steps if s.get("id") == "pins"]
assert pin_steps, "the images job reads no pin, so its build takes Dockerfile's default base"
build = next(s for s in steps if s.get("uses") == "docker/build-push-action@v6")
assert steps.index(pin_steps[0]) < steps.index(build), "the pin is read after the build that needs it"
assert "TASK_BASE_TAG=${{ steps.pins.outputs.base_tag }}" in build["with"]["build-args"]
assert "TASK_BASE_DIGEST=${{ steps.pins.outputs.base_digest }}" in build["with"]["build-args"]
script = pin_steps[0]["run"].split("<<'PYTHON'\n", 1)[1].rsplit("PYTHON", 1)[0]
pinned = "ghcr.io/norandom/ousast-task-base:base-1234567@sha256:" + "a" * 64
ref = {
"unpublished": None,
"bare-tag": pinned.split("@")[0],
"short-digest": pinned[:-40],
"wrong-repo": pinned.replace("norandom/ousast-task-base", "other/base"),
"valid": pinned,
}[case]
(tmp_path / "plane").mkdir()
(tmp_path / "plane/task-base.digest").write_text(json.dumps({"base": ref}))
output = tmp_path / "output"
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("GITHUB_OUTPUT", str(output))
if case == "valid":
exec(compile(script, "release-pin-gate", "exec"), {})
assert output.read_text() == "base_tag=base-1234567\nbase_digest=sha256:" + "a" * 64 + "\n"
else:
with pytest.raises(SystemExit) as stopped:
exec(compile(script, "release-pin-gate", "exec"), {})
assert stopped.value.code == "base: unpublished/invalid pin; run task-base-image and update plane/task-base.digest"
assert not output.exists()
def test_base_preserves_executor_build_toolchains():
common = read("plane/Dockerfile.base").split("FROM ${TASK_BASE_REF} AS base-browser")[0]
commands = " ".join(instructions("plane/Dockerfile.base")).split("FROM ${TASK_BASE_REF} AS base-browser")[0]
install = re.search(r"apt-get install -y --no-install-recommends\s+(.*?)\s+&&", commands).group(1)
packages = set(install.split())
assert packages == {
"nodejs",
"npm",
"node-typescript",
"php-cli",
"composer",
"maven",
"sqlite3",
"bubblewrap",
"util-linux",
"git",
"ca-certificates",
"libstdc++6",
"zlib1g",
}
assert "gradle" not in packages
assert "FROM eclipse-temurin:21-jdk-jammy AS jdk" in common
assert "COPY --from=jdk /opt/java/openjdk /opt/java/openjdk" in common
for command in (
"javac -version",
"npm --version",
"composer --version",
"mvn --version",
"python3 -m venv /venv",
"/venv/bin/pip install",
):
assert command in common
assert "joern" not in common.lower()
assert "apt-get clean" in common
for directory in ("doc", "man", "info"):
assert f"path-exclude=/usr/share/{directory}/*" in common
assert f" /usr/share/{directory}/*" in common
def test_reserved_populations_stay_out_of_the_image():
patterns = [line.strip() for line in read(".dockerignore").splitlines()]
patterns = [line for line in patterns if line and not line.startswith("#")]
for population in ("benchmarks/valid", "benchmarks/unseen"):
assert population in patterns, f"{population} is not excluded from the build context"
assert not any(line.startswith(f"!{population}") for line in patterns), f"{population} is let back in"
def test_search_pilot_files_stay_out_of_the_image():
"""The search pilot's working files are git-ignored, so a checkout never has them; a local build context does."""
patterns = [line.strip() for line in read(".dockerignore").splitlines()]
patterns = [line for line in patterns if line and not line.startswith("#")]
private = "benchmarks/search/private/"
assert private in patterns, f"{private} is not excluded from the build context"
# Docker cleans each line, so `!benchmarks/search/private` lets the directory back in as well.
assert not any(line.startswith(f"!{private}".rstrip("/")) for line in patterns), f"{private} is let back in"
def _kept_by_build_context(path, patterns):
"""Docker keeps a path unless a line of .dockerignore names it or a directory above it; the last matching line wins."""
kept = True
ancestors = [path[:cut] for cut in (match.start() for match in re.finditer("/", path))]
for pattern in patterns:
negated = pattern.startswith("!")
pattern = pattern[1:] if negated else pattern
if any(fnmatchcase(candidate, pattern.rstrip("/")) for candidate in (path, *ancestors)):
kept = negated
return kept
@pytest.mark.parametrize(
"name",
["Dockerfile", "plane/Dockerfile.base", "plane/Dockerfile.engine-task", "plane/Dockerfile.search-task"],
)
def test_copy_sources_are_kept_by_the_build_context(name):
"""A COPY whose source the root .dockerignore excludes stops the build: the replay stage copied from benchmarks/unseen."""
patterns = [line.strip() for line in read(".dockerignore").splitlines()]
patterns = [line for line in patterns if line and not line.startswith("#")]
copies = [line.split()[1:] for line in instructions(name) if line.startswith("COPY ") and "--from=" not in line]
sources = [word for words in copies for word in words[:-1] if not word.startswith("--")]
assert sources
for source in sources:
assert _kept_by_build_context(source, patterns), f"{name} copies {source}, which the root .dockerignore excludes"
def test_app_layers_carry_their_owner():
"""`COPY --chown` on every layer under /app: a final `chown -R` would store each of its files twice."""
lines = instructions("Dockerfile")
final_stage = lines[max(i for i, line in enumerate(lines) if line.startswith("FROM ")) :]
assert not any(line.startswith("RUN chown") for line in final_stage), "a chown over /app stores its files twice"
copies = [line for line in final_stage if line.startswith("COPY ") and "--from=" not in line]
assert copies
for line in copies:
assert line.startswith("COPY --chown=1000 "), f"{line} does not name the runtime user"