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
98 changes: 98 additions & 0 deletions src/inferrsi/harness/executor/_service_snapshot_git.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
"""Seal one retained service candidate through a supervised Git import."""

import hashlib
import stat
import subprocess
import sys
from contextlib import suppress
from os import fstat
from pathlib import Path

from ..records.artifact_primitives import digest
from ._snapshot_git import SnapshotChanged, _quoted
from .candidates import members, private_git_environment

_CANDIDATE_REF = "refs/heads/candidate"


def _write_candidate_blob(stream, name, path):
with path.open("rb") as data:
info = fstat(data.fileno())
if not stat.S_ISREG(info.st_mode):
raise ValueError("Snapshot inputs must be regular files")
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()
remaining = info.st_size
buffer = memoryview(bytearray(min(remaining, 1024 * 1024)))
# Git expects exactly the declared byte count before the next command.
while remaining:
length = data.readinto(buffer[:remaining])
if not length:
break
chunk = buffer[:length]
stream.write(chunk)
hasher.update(chunk)
remaining -= length
if remaining or data.read(1):
raise SnapshotChanged("Snapshot length changed during import")
stream.write(b"\n")
return {"mode": stat.S_IMODE(info.st_mode), "sha256": hasher.hexdigest()}


def seal_candidate(repo: Path, source: Path, expected_id: str) -> str:
"""Write the existing candidate commit format to Git without an input spool."""
env = private_git_environment()
git = ["git", "-C", str(repo)]
subprocess.run(["git", "init", "--quiet", "--bare", "--template=", str(repo)],
env=env, check=True, capture_output=True)
paths = members(source)
single_file = source.is_file()
if single_file:
paths = {"candidate.py": source}

# Keep the finished pack as the private repository's object store.
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
stream = child.stdin
try:
header = (
f"commit {_CANDIDATE_REF}\nmark :1\n"
"committer InferRSI <snapshot@example.invalid> 1 +0000\ndata 0\n"
)
stream.write(header.encode("ascii"))
entries = {
name: _write_candidate_blob(stream, name, path) for name, path in paths.items()
}
received = entries["candidate.py"]["sha256"] if single_file else digest(entries)
if received != expected_id:
raise SnapshotChanged("Streamed bytes differ from the retained snapshot")
stream.write(b"\nget-mark :1\ndone\n")
stream.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 main():
from ._git_worker import await_launch

repo, source, snapshot_id, deadline = sys.argv[1:]
repo = Path(repo)
if await_launch(repo.parent, float(deadline)):
print(seal_candidate(repo, Path(source), snapshot_id))


if __name__ == "__main__":
main()
5 changes: 2 additions & 3 deletions src/inferrsi/harness/manager/_round_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import time
from pathlib import Path

from ..executor import TaskProtocolError, _git_worker, candidates
from ..executor import TaskProtocolError, _git_worker, _service_snapshot_git, candidates
from ..executor._ordinary import validate_frozen_files
from ..records import service_io
from ..records.artifact_primitives import file_lock
Expand Down Expand Up @@ -91,8 +91,7 @@ def _seal_service_candidate(directory, plan, pending, deadline):
with _git_worker.scratch(directory, _git_worker.SEAL_PREFIX) as scratch:
staging = scratch / "inputs"
run = _git_worker.run(
child_command("inferrsi.harness.executor._snapshot_git", staging, source,
snapshot_id, deadline),
child_command(_service_snapshot_git.__name__, staging, source, snapshot_id, deadline),
child_directory(), scratch, deadline,
)
if run["status"] == "timeout" or time.time() >= deadline:
Expand Down
1 change: 1 addition & 0 deletions tests/apps/test_optimization_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -1840,6 +1840,7 @@ def test_runtime_identity_covers_migrated_process_domain_and_not_removed_executo
identity = session_runtime_identity()
root = Path(str(files("inferrsi")))
assert "harness/executor/local_process.py" in identity
assert "harness/executor/_service_snapshot_git.py" in identity
# #412 R2: the Harness-owned primitives replace infra.artifacts in six modules.
assert "harness/records/artifact_primitives.py" in identity
# #412 R3: the protocol child entry runs every task protocol operation.
Expand Down
12 changes: 8 additions & 4 deletions tests/apps/test_service_static_round.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,10 +207,12 @@ def test_static_service_sealing_preserves_retained_attempt(campaign, capsys, mon
'#!/bin/sh\n'
'case "$2" in\n'
' */.runtime-seal-*/inputs)\n'
' if [ "$3" = fast-import ] && [ ! -f "$STATIC_TEST_SEAL" ]; then\n'
' : > "$STATIC_TEST_SEAL"\n'
f' {"exec sleep 120" if fault == "deadline" else "exit 75"}\n'
' fi;;\n'
' for arg; do\n'
' if [ "$arg" = fast-import ] && [ ! -f "$STATIC_TEST_SEAL" ]; then\n'
' : > "$STATIC_TEST_SEAL"\n'
f' {"exec sleep 120" if fault == "deadline" else "exit 75"}\n'
' fi\n'
' done;;\n'
'esac\n'
'exec "$STATIC_TEST_GIT" "$@"\n', encoding="utf-8",
)
Expand Down Expand Up @@ -246,6 +248,7 @@ def expire_worker_during_seal(root, pending, deadline):
assert result["completed_rounds"] == result["allocated_rounds"] == 0
assert result["pending"] is None and result["best"]["kind"] == "baseline"
assert not (attempt / _round_worker.ACCEPTED).exists()
assert not (attempt / "source-git").exists()
assert not (attempt / "execution").exists()
assert not list(attempt.glob(".runtime-seal-*"))
assert call(campaign, "recover")["latest_observation"] == row
Expand All @@ -262,6 +265,7 @@ def expire_worker_during_seal(root, pending, deadline):
assert pending["revision"] is None
assert json.loads(check)["status"] == "timeout"
assert not (attempt / _round_worker.ACCEPTED).exists()
assert not (attempt / "source-git").exists()
assert not (attempt / "service").exists()
assert not list(attempt.glob(".runtime-seal-*"))

Expand Down
90 changes: 90 additions & 0 deletions tests/harness/test_service_candidate_seal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""Git object parity and rejected input for the single-candidate seal."""

import shutil
import subprocess
import tempfile
from io import BytesIO

import pytest

from inferrsi.harness.executor import _service_snapshot_git
from inferrsi.harness.executor._service_snapshot_git import seal_candidate
from inferrsi.harness.executor._snapshot_git import SnapshotChanged, import_snapshots
from inferrsi.harness.executor.candidates import identity, private_git_environment

pytestmark = pytest.mark.skipif(shutil.which("git") is None, reason="service sealing uses Git")


@pytest.mark.parametrize("single_file", [False, True], ids=["tree", "file"])
def test_streamed_candidate_has_the_same_git_objects(tmp_path, monkeypatch, single_file):
binary = b"snapshot\0\n" * (256 * 1024)
if single_file:
source = tmp_path / "source.py"
payload = source
git_name = "candidate.py"
else:
source = tmp_path / "source"
source.mkdir()
git_name = "参数.bin"
payload = source / git_name
(source / "empty").touch()
payload.write_bytes(binary)
payload.chmod(0o755)
snapshot_id = identity(source)
previous = import_snapshots(tmp_path / "spooled.git", (("candidate", source, snapshot_id),))
repo = tmp_path / "streamed.git"

def verify_no_spool(*args, **kwargs):
pytest.fail("The streaming Git import staged its input in a temporary file")

monkeypatch.setattr(tempfile, "TemporaryFile", verify_no_spool)
assert seal_candidate(repo, source, snapshot_id) == previous
assert len(list((repo / "objects" / "pack").glob("*.pack"))) == 1
git = ["git", "-C", str(repo)]
env = private_git_environment()
published = subprocess.check_output(
[*git, "rev-parse", "refs/heads/candidate"], env=env, text=True,
).strip()
assert published == previous
content = subprocess.check_output(
[*git, "cat-file", "blob", f"{published}:{git_name}"], env=env,
)
assert content == binary


def test_streamed_blob_rejects_growth_before_sending_extra_bytes(tmp_path, monkeypatch):
payload = tmp_path / "candidate.py"
payload.write_bytes(b"before")
fstat = _service_snapshot_git.fstat

def grow_after_stat(fd):
info = fstat(fd)
with payload.open("ab") as candidate:
candidate.write(b"after")
return info

monkeypatch.setattr(_service_snapshot_git, "fstat", grow_after_stat)
stream = BytesIO()
with pytest.raises(SnapshotChanged, match="length changed"):
_service_snapshot_git._write_candidate_blob(stream, "candidate.py", payload)
assert stream.getvalue() == b'M 100644 inline "candidate.py"\ndata 6\nbefore'


def test_changed_candidate_cannot_publish_a_git_ref(tmp_path):
source = tmp_path / "source"
source.mkdir()
payload = source / "candidate.py"
payload.write_bytes(b"original\n")
snapshot_id = identity(source)
payload.write_bytes(b"modified\n")
repo = tmp_path / "snapshot.git"

with pytest.raises(SnapshotChanged, match="retained snapshot"):
seal_candidate(repo, source, snapshot_id)

result = subprocess.run(
["git", "-C", str(repo), "show-ref", "--verify", "--quiet", "refs/heads/candidate"],
env=private_git_environment(),
check=False,
)
assert result.returncode == 1
Loading