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
39 changes: 33 additions & 6 deletions src/inferrsi/harness/executor/serving/_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import subprocess
import time
from pathlib import Path
from tempfile import TemporaryDirectory

from ...evaluator.reference_guard import validate_reference_guard
from ...records import service_io
Expand Down Expand Up @@ -205,11 +206,14 @@ def git(*args):
return commit


_BLOB_BATCH_BYTES = 8 * 1024 * 1024


def _blob_batches(entries):
batch = []
size = 0
for path, (mode, oid, length) in entries.items():
if batch and (size + length > 8 * 1024 * 1024 or len(batch) >= 1024):
if batch and (size + length > _BLOB_BATCH_BYTES or len(batch) >= 1024):
yield batch
batch, size = [], 0
batch.append((path, mode, oid, length))
Expand All @@ -218,22 +222,40 @@ def _blob_batches(entries):
yield batch


def _restore_large_blob(git, destination, name, mode, oid, length):
"""Let Git write the raw blob to disk before publishing the checked file."""
target = service_io.safe_path(destination, name)
target.parent.mkdir(parents=True, exist_ok=True)
with TemporaryDirectory(dir=target.parent) as staging:
pending = Path(staging) / "blob"
with pending.open("wb") as output:
git("cat-file", "blob", oid.decode("ascii"), stdout=output)
if pending.stat().st_size != length:
raise ValueError("Unexpected Git blob size while restoring the recorded revision")
pending.chmod(mode)
# Publish only if no earlier Git path resolved to this filesystem name.
if os.name == "nt":
pending.rename(target) # Windows rename fails if the destination exists.
else:
os.link(pending, target)


def retain_service_revision(source, destination, includes, commit, *, deadline=None,
private_snapshot=False):
if not isinstance(commit, str) or not re.fullmatch(r"[a-f0-9]{40,64}", commit):
raise ValueError("Candidate requires an existing Git commit")

options = {"env": private_git_environment()} if private_snapshot else {}

def git(*args, input_bytes=None):
def git(*args, input_bytes=b"", stdout=subprocess.PIPE):
timeout = None if deadline is None else deadline - time.monotonic()
if timeout is not None and timeout <= 0:
raise TimeoutError("Profiling timeout while restoring the recorded revision")
try:
return subprocess.check_output(
return subprocess.run(
["git", "--no-replace-objects", "-C", str(source), *args],
input=input_bytes, timeout=timeout, **options,
)
input=input_bytes, stdout=stdout, check=True, timeout=timeout, **options,
).stdout
except subprocess.TimeoutExpired as error:
raise TimeoutError("Profiling timeout while restoring the recorded revision") from error

Expand All @@ -256,6 +278,10 @@ def git(*args, input_bytes=None):
entries[os.fsdecode(path)] = int(mode, 8) & 0o555, oid, int(length)
destination.mkdir()
for batch in _blob_batches(entries):
# The batcher gives each oversized blob its own batch.
if batch[0][3] > _BLOB_BATCH_BYTES:
_restore_large_blob(git, destination, *batch[0])
continue
# Query object IDs so filenames and archive export attributes do not affect the bytes.
query = b"".join(oid + b"\n" for _, _, oid, _ in batch)
blobs = io.BytesIO(git("cat-file", "--batch", input_bytes=query))
Expand All @@ -267,7 +293,8 @@ def git(*args, input_bytes=None):
raise ValueError("Incomplete Git blob while restoring the recorded revision")
target = service_io.safe_path(destination, name)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(content)
with target.open("xb") as output:
output.write(content)
target.chmod(mode)


Expand Down
133 changes: 133 additions & 0 deletions tests/apps/test_project_service_reuse.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
import copy
import errno
import json
import os
import shutil
import stat
import subprocess
import sys
import time
import tracemalloc
from pathlib import Path
from types import SimpleNamespace
from zipfile import ZipFile
Expand Down Expand Up @@ -1814,6 +1816,137 @@ def test_snapshot_batches_binary_and_empty_git_blobs(campaign):
assert {p.name: p.read_bytes() for p in (destination / "inputs").iterdir()} == blobs


@pytest.mark.parametrize(
("block_count", "source_mode", "restored_mode"),
[(16, 0o755, 0o555), (64, 0o644, 0o444)],
ids=["executable-16mib", "regular-64mib"],
)
def test_large_blob_restore_uses_bounded_python_memory(
campaign, block_count, source_mode, restored_mode,
):
repo = campaign["repo"]
inputs = repo / "inputs"
inputs.mkdir()
large = inputs / "b binary"
block = bytes(range(256)) * 4096
with large.open("wb") as stream:
for _ in range(block_count):
stream.write(block)
large.chmod(source_mode)
(inputs / "a empty").touch()
(inputs / "c tail").write_bytes(b"\0\r\n")
subprocess.run(["git", "-C", str(repo), "add", "inputs"], check=True)
commit(repo)
revision = executor.service_revision(repo, ["inputs"])
size = large.stat().st_size
large.write_bytes(b"uncommitted worktree contents")

destination = repo.parent / "snapshot"
tracemalloc.start()
try:
executor.retain_service_revision(
repo, destination, ["inputs", "inputs/b binary"], revision, private_snapshot=True,
)
_, peak = tracemalloc.get_traced_memory()
finally:
tracemalloc.stop()

assert peak <= 1024 * 1024, f"Restoring {size} bytes allocated {peak} bytes on the Python heap"
restored = destination / "inputs"
assert sorted(path.name for path in restored.iterdir()) == ["a empty", "b binary", "c tail"]
assert (restored / "a empty").read_bytes() == b""
assert (restored / "c tail").read_bytes() == b"\0\r\n"
with (restored / "b binary").open("rb") as stream:
for _ in range(block_count):
assert stream.read(len(block)) == block
assert stream.read(1) == b""
if os.name == "posix":
assert stat.S_IMODE((restored / "b binary").stat().st_mode) == restored_mode
assert stat.S_IMODE((restored / "c tail").stat().st_mode) == 0o444


@pytest.mark.parametrize("fold_names", [False, True], ids=["host-filesystem", "aliased-paths"])
@pytest.mark.parametrize("large_first", [False, True], ids=["small-first", "large-first"])
def test_snapshot_case_variant_blobs(campaign, monkeypatch, fold_names, large_first):
repo = campaign["repo"]
destination = repo.parent / "snapshot"
large = b"b" * (8 * 1024 * 1024 + 1)
first, second = (large, b"small") if large_first else (b"small", large)

# Construct a commit without checking out either name, including on case-insensitive hosts.
def git(*args, data=None):
return subprocess.check_output(
["git", "-C", str(repo), "-c", "user.name=Fixture", "-c",
"user.email=fixture@example.invalid", *args], input=data,
).strip()

tree = git("mktree", data=b"".join(
b"100644 blob " + git("hash-object", "-w", "--stdin", data=payload) + b"\t" + name + b"\n"
for name, payload in [(b"Model.bin", first), (b"model.bin", second)]
))
revision = git("commit-tree", tree.decode("ascii"), "-m", "Case variants").decode("ascii")
if fold_names:
# Exercise no-clobber on case-sensitive CI as well as the native volume above.
safe_path = service_io.safe_path
monkeypatch.setattr(
service_io, "safe_path", lambda root, name: safe_path(root, name.lower())
)
marker = repo.parent / "CaseProbe"
marker.touch()
if fold_names or marker.with_name("caseprobe").exists():
with pytest.raises(FileExistsError):
executor.retain_service_revision(repo, destination, None, revision)
retained, = destination.iterdir()
assert retained.read_bytes() == first
else:
executor.retain_service_revision(repo, destination, None, revision)
assert (destination / "Model.bin").read_bytes() == first
assert (destination / "model.bin").read_bytes() == second


@pytest.mark.parametrize(("failure", "error"), [
("git", subprocess.CalledProcessError),
("timeout", TimeoutError),
("short", ValueError),
("long", ValueError),
])
def test_large_blob_restore_discards_failed_output(campaign, monkeypatch, failure, error):
repo = campaign["repo"]
member = repo / "large.bin"
size = 8 * 1024 * 1024 + 1
with member.open("wb") as stream:
stream.truncate(size)
subprocess.run(["git", "-C", str(repo), "add", "large.bin"], check=True)
commit(repo)
revision = executor.service_revision(repo, ["large.bin"])
destination = repo.parent / "snapshot"
run = subprocess.run

def fail_after_write(argv, **options):
if "cat-file" not in argv:
return run(argv, **options)
assert "--no-replace-objects" in argv
assert options["env"]["GIT_CONFIG_NOSYSTEM"] == "1"
assert 0 < options["timeout"] <= 60
output = options["stdout"]
output.write(b"partial")
assert not (destination / "large.bin").exists()
if failure == "git":
raise subprocess.CalledProcessError(1, argv)
if failure == "timeout":
raise subprocess.TimeoutExpired(argv, options["timeout"])
output.truncate(size + 1 if failure == "long" else size - 1)
return subprocess.CompletedProcess(argv, 0)

monkeypatch.setattr(subprocess, "run", fail_after_write)
with pytest.raises(error):
executor.retain_service_revision(
repo, destination, ["large.bin"], revision, private_snapshot=True,
deadline=time.monotonic() + 60,
)
assert list(destination.iterdir()) == []


@pytest.mark.parametrize("attribute", ["export-ignore", "export-subst"])
def test_execution_preserves_tree_inputs_despite_export_attributes(campaign, attribute):
repo = campaign["repo"]
Expand Down
Loading