Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 74 additions & 45 deletions src/inferrsi/harness/executor/_snapshot_git.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import stat
import subprocess
import sys
import tempfile
from contextlib import suppress
from pathlib import Path, PurePosixPath

from ..records.artifact_primitives import digest
Expand Down Expand Up @@ -48,58 +48,87 @@ def import_snapshots(repo: Path, snapshots, *, single_file_name: str = "candidat
git = ["git", "-C", str(repo)]
subprocess.run(["git", "init", "--quiet", "--bare", "--template=", str(repo)],
env=env, check=True, capture_output=True)
with tempfile.TemporaryFile(dir=repo) as stream:
previous = {}
for index, (role, source, expected_id) in enumerate(snapshots, 1):
ref = f"refs/heads/{role}".encode("ascii")
stream.write(b"commit " + ref + b"\nmark :%d\n" % index)
stream.write(b"committer InferRSI <snapshot@example.invalid> 1 +0000\ndata 0\n")
if index > 1:
stream.write(b"from :%d\n" % (index - 1))
paths = members(source)
single_file = source.is_file()
if single_file:
paths = {logical_name: source} # Both packaged arms share a logical name.
for removed in sorted(previous.keys() - paths.keys()):
stream.write(b"D " + _quoted(removed) + b"\n")
entries = {}
for name, path in paths.items():
start = stream.tell()
entries[name] = _write_blob(stream, name, path)
if entries[name] == previous.get(name):
stream.seek(start) # Reuse the verified blob inherited from the first tree.
received = entries[logical_name]["sha256"] if single_file else digest(entries)
if received != expected_id:
raise SnapshotChanged("Streamed bytes differ from the retained snapshot")
stream.write(b"\n")
previous = entries
stream.write(b"done\n")
stream.truncate()
stream.seek(0)
subprocess.run([*git, "fast-import", "--quiet"], env=env, stdin=stream,
capture_output=True, check=True)
return subprocess.check_output(
[*git, "rev-parse", ref.decode("ascii")], env=env, text=True
).strip()


def _write_blob(stream, name, path):
# The private repository can serve its objects directly from the import pack.
command = [*git, "-c", "fastimport.unpackLimit=0", "fast-import", "--quiet", "--done"]
with subprocess.Popen(command, env=env, stdin=subprocess.PIPE,
stdout=subprocess.PIPE) as child:
assert child.stdin is not None and child.stdout is not None
try:
_write_snapshots(child.stdin, snapshots, logical_name)
child.stdin.close()
revision = child.stdout.read()
except BaseException:
child.kill()
with suppress(OSError):
child.stdin.close()
raise
if returncode := child.wait():
raise subprocess.CalledProcessError(returncode, command)
return revision.decode("ascii").strip()


def _write_snapshots(stream, snapshots, logical_name):
previous = {}
index = 0
for index, (role, source, expected_id) in enumerate(snapshots, 1):
ref = f"refs/heads/{role}".encode("ascii")
stream.write(b"commit " + ref + b"\nmark :%d\n" % index)
stream.write(b"committer InferRSI <snapshot@example.invalid> 1 +0000\ndata 0\n")
if index > 1:
stream.write(b"from :%d\n" % (index - 1))
paths = members(source)
single_file = source.is_file()
if single_file:
paths = {logical_name: source} # Both packaged arms share a logical name.
for removed in sorted(previous.keys() - paths.keys()):
stream.write(b"D " + _quoted(removed) + b"\n")
entries = {
name: _write_blob(stream, name, path, previous.get(name))
for name, path in paths.items()
}
received = entries[logical_name]["sha256"] if single_file else digest(entries)
if received != expected_id:
raise SnapshotChanged("Streamed bytes differ from the retained snapshot")
stream.write(b"\n")
previous = entries
if not index:
raise ValueError("At least one snapshot is required")
stream.write(b"get-mark :%d\ndone\n" % index)


def _write_blob(stream, name, path, inherited):
with path.open("rb") as data:
info = os.fstat(data.fileno())
if not stat.S_ISREG(info.st_mode):
raise ValueError("Snapshot inputs must be regular files")
permissions = stat.S_IMODE(info.st_mode)
buffer = memoryview(bytearray(min(info.st_size, 1024 * 1024)))
if inherited is not None and inherited["mode"] == permissions:
if _blob_digest(data, info.st_size, buffer) == inherited["sha256"]:
return inherited
data.seek(0)
mode = b"100755" if info.st_mode & stat.S_IXUSR else b"100644"
stream.write(b"M " + mode + b" inline " + _quoted(name) + b"\n")
stream.write(b"data %d\n" % info.st_size)
hasher = hashlib.sha256()
start = stream.tell()
for chunk in iter(lambda: data.read(1024 * 1024), b""):
stream.write(chunk)
hasher.update(chunk)
if stream.tell() - start != info.st_size:
raise SnapshotChanged("Snapshot length changed during import")
checksum = _blob_digest(data, info.st_size, buffer, stream)
stream.write(b"\n")
return {"mode": stat.S_IMODE(info.st_mode), "sha256": hasher.hexdigest()}
return {"mode": permissions, "sha256": checksum}


def _blob_digest(data, remaining, buffer, stream=None):
hasher = hashlib.sha256()
while remaining:
size = data.readinto(buffer[:remaining])
if not size:
break
chunk = buffer[:size]
if stream is not None:
stream.write(chunk)
hasher.update(chunk)
remaining -= size
if remaining or data.read(1):
raise SnapshotChanged("Snapshot length changed during import")
return hasher.hexdigest()


def main():
Expand Down
110 changes: 102 additions & 8 deletions tests/harness/test_candidate_static_rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@
import json
import os
import shutil
import stat
import subprocess
import sys
import tempfile
import time
from io import BytesIO
from pathlib import Path

import pytest
Expand All @@ -15,7 +18,7 @@
from inferrsi.harness.evaluator._act_base import l0_gatekeeper as gate
from inferrsi.harness.executor import _snapshot_git
from inferrsi.harness.executor._snapshot_git import import_snapshots
from inferrsi.harness.executor.candidates import identity
from inferrsi.harness.executor.candidates import identity, private_git_environment
from inferrsi.harness.manager import _static_round

PAIR = """def forward(x, side):
Expand Down Expand Up @@ -94,6 +97,52 @@ def test_bridge_preserves_protected_paths_and_incomplete_priority(tmp_path):
assert inspect(baseline, candidate) == static.summarize(report)


def test_paired_bridge_streams_the_same_git_history(tmp_path, monkeypatch):
baseline, candidate = tmp_path / "baseline", tmp_path / "candidate"
binary = b"unchanged\x00chunk\n" * (128 * 1024)
shared_name = "参数.bin"
for source in (baseline, candidate):
source.mkdir()
(source / shared_name).write_bytes(binary)
(baseline / "removed").touch()
(baseline / "run.py").write_bytes(b"VALUE = 1\n")
(candidate / "run.py").write_bytes(b"VALUE = 2\n")
(candidate / "run.py").chmod(0o755)
(candidate / "empty").touch()
snapshots = (("baseline", baseline, identity(baseline)),
("candidate", candidate, identity(candidate)))

commands = BytesIO()
_snapshot_git._write_snapshots(commands, snapshots, "candidate.py")
assert commands.getvalue().count(binary) == 1

def reject_spool(*args, **kwargs):
pytest.fail("Paired import opened a temporary input file")

repo = tmp_path / "inputs.git"
with monkeypatch.context() as patch:
patch.setattr(tempfile, "TemporaryFile", reject_spool)
revision = import_snapshots(repo, snapshots)

git = ["git", "-C", str(repo)]
env = private_git_environment()
base_sha, candidate_sha, parent_sha = subprocess.check_output(
[*git, "rev-parse", "baseline", "candidate", "candidate^"], env=env, text=True,
).splitlines()
assert revision == candidate_sha
assert base_sha == parent_sha
assert subprocess.check_output([*git, "show", f"{revision}:{shared_name}"], env=env) == binary
assert subprocess.check_output([*git, "show", f"{revision}:empty"], env=env) == b""
assert subprocess.check_output([*git, "show", f"{revision}:run.py"], env=env) == b"VALUE = 2\n"
diff = subprocess.check_output(
[*git, "diff", "--no-renames", "--name-status", base_sha, revision], env=env,
)
assert diff.splitlines() == [b"A\tempty", b"D\tremoved", b"M\trun.py"]
tree_entry = subprocess.check_output([*git, "ls-tree", revision, "run.py"], env=env)
executable = (candidate / "run.py").stat().st_mode & stat.S_IXUSR
assert tree_entry.split()[0] == (b"100755" if executable else b"100644")


def test_single_file_uses_same_logical_name(tmp_path):
baseline, candidate = tmp_path / "baseline.py", tmp_path / "candidate.py"
for path in (baseline, candidate):
Expand Down Expand Up @@ -158,13 +207,19 @@ def test_bridge_compares_only_the_sealed_bytes(tmp_path):
candidate.write_text("answer = 1\n")
retained = identity(candidate)
candidate.write_text("answer = 2\n")
repo = tmp_path / "scan.git"
assert static.inspect_snapshot(baseline, candidate, identity(baseline), retained,
repo=tmp_path / "scan.git") == {
repo=repo) == {
"status": "input_changed",
}
assert subprocess.check_output(
["git", "-C", str(repo), "for-each-ref"], env=private_git_environment(),
) == b""
assert static.inspect_snapshot(baseline, candidate, identity(baseline), identity(candidate),
repo=repo)["status"] == "clear"


def slow_git_diff(tmp_path, monkeypatch):
def git_wrapper(tmp_path, monkeypatch, script):
tools = tmp_path / "bin"
tools.mkdir()
marker = tmp_path / "refs"
Expand All @@ -173,16 +228,55 @@ def slow_git_diff(tmp_path, monkeypatch):
monkeypatch.setenv("PATH", str(tools) + os.pathsep + os.environ["PATH"])
wrapper = tools / "git"
wrapper.write_text(
'#!/bin/sh\n'
'#!/bin/sh\n' + script + 'exec "$STATIC_TEST_GIT" "$@"\n', encoding="utf-8",
)
wrapper.chmod(0o755)
return marker


def slow_git_diff(tmp_path, monkeypatch):
return git_wrapper(
tmp_path, monkeypatch,
'if [ "$5" = diff ]; then\n'
' "$STATIC_TEST_GIT" -C "$4" rev-parse refs/heads/baseline refs/heads/candidate'
' > "$STATIC_TEST_REFS" || exit\n'
' exec sleep 30\n'
'fi\n'
'exec "$STATIC_TEST_GIT" "$@"\n', encoding="utf-8",
'fi\n',
)
wrapper.chmod(0o755)
return marker


@pytest.mark.skipif(os.name != "posix", reason="uses a POSIX Git wrapper and timeout")
@pytest.mark.parametrize("action", [
pytest.param("exit 17", id="git-error"),
pytest.param("exec sleep 30", id="timeout"),
pytest.param('touch "$STATIC_TEST_CANCEL"\n exec sleep 30', id="cancelled"),
])
def test_static_scan_reaps_failed_stream_and_allows_retry(tmp_path, monkeypatch, action):
baseline, candidate, attempt = (tmp_path / name for name in ("base", "candidate", "attempt"))
attempt.mkdir()
for root, value in ((baseline, 1), (candidate, 2)):
root.mkdir()
(root / "entry.py").write_text(f"VALUE = {value}\n", encoding="utf-8")
(root / "payload.bin").write_bytes(b"\x00" * (2 * 1024 * 1024))
inputs = (baseline, candidate, identity(baseline), identity(candidate), static.rules_version())
cancellation = attempt / "cancel"

with monkeypatch.context() as patch:
patch.setenv("STATIC_TEST_CANCEL", str(cancellation))
marker = git_wrapper(
tmp_path, patch,
'if [ "$5" = fast-import ]; then\n'
' printf started > "$STATIC_TEST_REFS"\n'
f' {action}\n'
'fi\n',
)
assert _static_round.scan(inputs, time.time() + 3, cancellation)["status"] == "waiting"
assert marker.read_text(encoding="utf-8") == "started"

cancellation.unlink(missing_ok=True)
assert not list(attempt.iterdir())
assert _static_round.scan(inputs, time.time() + 10, cancellation)["status"] == "clear"
assert not list(attempt.iterdir())


@pytest.mark.skipif(os.name != "posix", reason="uses a POSIX Git wrapper and timeout")
Expand Down
Loading