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
75 changes: 59 additions & 16 deletions src/inferrsi/harness/executor/serving/_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,9 +206,58 @@ def git(*args):
return commit


_TREE_INCLUDE_BATCH_BYTES = 8 * 1024
_BLOB_BATCH_BYTES = 8 * 1024 * 1024


def _tree_include_batches(includes):
batch = []
size = 0
for name in includes or ["."]:
relative = Path(name)
if relative.is_absolute() or ".." in relative.parts:
raise ValueError("Candidate includes must be relative paths inside the project")
path = relative.as_posix()
# Git interprets colon-prefixed pathspecs. Let it resolve those individually.
magic = path.startswith(":")
cost = len(os.fsencode(path)) + 3 # Separators and possible argument quotes.
if batch and (magic or size + cost > _TREE_INCLUDE_BATCH_BYTES):
yield batch
batch, size = [], 0
if magic:
yield [path]
else:
batch.append(path)
size += cost
if batch:
yield batch


def _tree_entries_by_include(listing, includes):
records = []
for entry in listing.rstrip(b"\0").split(b"\0") if listing else ():
metadata, path = entry.split(b"\t", 1)
records.append((os.fsdecode(path), metadata))
if len(includes) == 1:
yield records
return

# Git lists the union in tree order. Restore in declared include order so
# an existing path retains the same first file on case-insensitive volumes.
groups = {name: [] for name in includes}
root_group = groups.get(".")
for record in records:
path, _ = record
if root_group is not None:
root_group.append(record)
while path:
group = groups.get(path)
if group is not None:
group.append(record)
path = path.rpartition("/")[0]
yield from groups.values()


def _blob_batches(entries):
batch = []
size = 0
Expand Down Expand Up @@ -260,22 +309,16 @@ def git(*args, input_bytes=b"", stdout=subprocess.PIPE):
raise TimeoutError("Profiling timeout while restoring the recorded revision") from error

entries = {}
for name in includes or ["."]:
relative = Path(name)
if relative.is_absolute() or ".." in relative.parts:
raise ValueError("Candidate includes must be relative paths inside the project")
listing = git(
"ls-tree", "-rlz", "--full-tree",
commit, "--", relative.as_posix(),
)
if not listing:
raise ValueError("Declared candidate files are missing from the retained commit")
for entry in listing.rstrip(b"\0").split(b"\0"):
metadata, path = entry.split(b"\t", 1)
mode, kind, oid, length = metadata.split()
if kind != b"blob" or mode not in (b"100644", b"100755"):
raise ValueError("Candidate tree contains symbolic or special files")
entries[os.fsdecode(path)] = int(mode, 8) & 0o555, oid, int(length)
for batch in _tree_include_batches(includes):
listing = git("ls-tree", "-rlz", "--full-tree", commit, "--", *batch)
for matches in _tree_entries_by_include(listing, batch):
if not matches:
raise ValueError("Declared candidate files are missing from the retained commit")
for path, metadata in matches:
mode, kind, oid, length = metadata.split()
if kind != b"blob" or mode not in (b"100644", b"100755"):
raise ValueError("Candidate tree contains symbolic or special files")
entries[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.
Expand Down
93 changes: 86 additions & 7 deletions tests/apps/test_project_service_reuse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1816,6 +1816,79 @@ 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(
("suffix", "listings"), [("", 1), ("x" * 80, 2)], ids=["single-batch", "bounded-arguments"],
)
def test_snapshot_batches_tree_lookups_for_explicit_includes(
campaign, monkeypatch, suffix, listings,
):
repo = campaign["repo"]
payloads = {f"inputs/part {i:03}{suffix}.bin": bytes([i]) * 4096 for i in range(126)}
explicit_files = list(reversed(payloads))
empty = "inputs/group/empty"
executable = "inputs/group/executable-é.bin"
payloads.update({empty: b"", executable: b"\0\r\n"})
for name, content in {**payloads, "inputs/group-other/undeclared": b"excluded"}.items():
path = repo / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(content)
(repo / executable).chmod(0o755)
subprocess.run(["git", "-C", str(repo), "add", "inputs"], check=True)
subprocess.run(["git", "-C", str(repo), "update-index", "--chmod=+x", "--",
executable], check=True)
commit(repo)
includes = [empty, "inputs/group", *explicit_files, executable, empty]
revision = executor.service_revision(repo, includes)
(repo / executable).write_bytes(b"uncommitted worktree bytes")

destination = repo.parent / "snapshot"
run = subprocess.run
open_path = Path.open
commands = []
written_paths = []

def count_restore(argv, **options):
commands.append(argv[4])
assert "--no-replace-objects" in argv
assert options["env"]["GIT_CONFIG_NOSYSTEM"] == "1"
assert 0 < options["timeout"] <= 60
return run(argv, **options)

def record_writes(path, mode="r", *args, **kwargs):
if mode == "xb" and path.is_relative_to(destination):
written_paths.append(path.relative_to(destination).as_posix())
return open_path(path, mode, *args, **kwargs)

monkeypatch.setattr(subprocess, "run", count_restore)
monkeypatch.setattr(Path, "open", record_writes)
executor.retain_service_revision(
repo, destination, includes, revision,
private_snapshot=True, deadline=time.monotonic() + 60,
)
assert written_paths == [empty, executable, *explicit_files]
assert {p.relative_to(destination).as_posix(): p.read_bytes()
for p in destination.rglob("*") if p.is_file()} == payloads
if os.name == "posix":
expected_modes = {name: 0o555 if name == executable else 0o444 for name in payloads}
assert {name: stat.S_IMODE((destination / name).stat().st_mode)
for name in payloads} == expected_modes
assert commands == ["ls-tree"] * listings + ["cat-file"]


def test_snapshot_preserves_git_literal_pathspecs(campaign):
repo = campaign["repo"]
(repo / "other.txt").write_bytes(b"selected")
subprocess.run(["git", "-C", str(repo), "add", "other.txt"], check=True)
commit(repo)
revision = executor.service_revision(repo, ["engine.py", "other.txt"])
destination = repo.parent / "snapshot"
executor.retain_service_revision(
repo, destination, ["engine.py", ":(literal)other.txt"], revision,
)
assert {p.name for p in destination.iterdir()} == {"engine.py", "other.txt"}
assert (destination / "other.txt").read_bytes() == b"selected"


@pytest.mark.parametrize(
("block_count", "source_mode", "restored_mode"),
[(16, 0o755, 0o555), (64, 0o644, 0o444)],
Expand Down Expand Up @@ -1865,9 +1938,11 @@ def test_large_blob_restore_uses_bounded_python_memory(
assert stat.S_IMODE((restored / "c tail").stat().st_mode) == 0o444


@pytest.mark.parametrize("includes", [None, ["model.bin", "Model.bin"]],
ids=["tree-order", "include-order"])
@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):
def test_snapshot_case_variant_blobs(campaign, monkeypatch, fold_names, large_first, includes):
repo = campaign["repo"]
destination = repo.parent / "snapshot"
large = b"b" * (8 * 1024 * 1024 + 1)
Expand Down Expand Up @@ -1895,11 +1970,11 @@ def git(*args, data=None):
marker.touch()
if fold_names or marker.with_name("caseprobe").exists():
with pytest.raises(FileExistsError):
executor.retain_service_revision(repo, destination, None, revision)
executor.retain_service_revision(repo, destination, includes, revision)
retained, = destination.iterdir()
assert retained.read_bytes() == first
assert retained.read_bytes() == (first if includes is None else second)
else:
executor.retain_service_revision(repo, destination, None, revision)
executor.retain_service_revision(repo, destination, includes, revision)
assert (destination / "Model.bin").read_bytes() == first
assert (destination / "model.bin").read_bytes() == second

Expand Down Expand Up @@ -1971,18 +2046,22 @@ def test_execution_preserves_tree_inputs_despite_export_attributes(campaign, att


@pytest.mark.parametrize("invalid", ["missing", "symlink"])
def test_tree_snapshot_rejects_missing_or_special_declared_input(campaign, invalid):
@pytest.mark.parametrize("valid", ["engine.py", "included", "."])
def test_tree_snapshot_rejects_missing_or_special_declared_input(campaign, invalid, valid):
repo = campaign["repo"]
(repo / "included").mkdir()
(repo / "included/keep").write_bytes(b"included")
subprocess.run(["git", "-C", str(repo), "add", "included"], check=True)
if invalid == "symlink":
(repo / invalid).symlink_to("engine.py")
subprocess.run(["git", "-C", str(repo), "add", invalid], check=True)
commit(repo)
commit(repo)
revision = subprocess.check_output(
["git", "-C", str(repo), "rev-parse", "HEAD"], text=True
).strip()
destination = repo.parent / "snapshot"
with pytest.raises(ValueError, match="missing|symbolic"):
executor.retain_service_revision(repo, destination, ["engine.py", invalid], revision)
executor.retain_service_revision(repo, destination, [valid, invalid], revision)
assert not destination.exists()


Expand Down
Loading