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
68 changes: 40 additions & 28 deletions benchmark/runtime/sforge_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,31 @@ def _minimum_free_bytes(*paths: Path) -> int:
return min(shutil.disk_usage(path).free for path in paths)


def _require_research_headroom(paths: tuple[Path, Path], pending_bytes: int = 0) -> None:
free = _minimum_free_bytes(*paths)
available = free - _RESEARCH_DISK_HEADROOM_FLOOR_BYTES
if available <= 0 or pending_bytes > available:
raise InsufficientDiskHeadroomError(errno.ENOSPC, "insufficient host disk headroom for research collection")


class _ResearchExtractionReader:
"""Check uncompressed bytes before tarfile copies the next block to disk."""

def __init__(self, archive: tarfile.TarFile, paths: tuple[Path, Path]) -> None:
source = archive.fileobj
self._read = source.read
self._paths = paths
self.seek = source.seek
self.tell = source.tell
self.close = source.close
self.write = source.write

def read(self, size: int = -1) -> bytes:
data = self._read(size)
_require_research_headroom(self._paths, len(data))
return data


def _filter_research_members(
archive: tarfile.TarFile,
members: list[tarfile.TarInfo],
Expand Down Expand Up @@ -243,31 +268,20 @@ def _extract_artifact_archive(
research_cleanup: bool = False,
):
"""Collect one native archive without materializing it as Python bytes."""
free_before: int | None = None
paths = (Path(tempfile.gettempdir()), target.parent)
if research_cleanup:
target.parent.mkdir(parents=True, exist_ok=True)
free_before = _minimum_free_bytes(Path(tempfile.gettempdir()), target.parent)
if free_before <= _RESEARCH_DISK_HEADROOM_FLOOR_BYTES:
raise InsufficientDiskHeadroomError(
errno.ENOSPC,
"host temp/log disk headroom below 10 GiB floor before research collection",
)
_require_research_headroom(paths)
chunks, _ = self._raw(handle).get_archive(str(remote))
try:
# A seekable spool preserves the existing tar extraction/filter
# behavior. Its lifetime is independent of TarFile reference cycles.
written = 0
with tempfile.TemporaryFile() as archive_file:
# Unbuffered research writes make the previous chunk visible to the next free-space check.
spool = tempfile.TemporaryFile(buffering=0) if research_cleanup else tempfile.TemporaryFile()
with spool as archive_file:
for chunk in chunks:
written += len(chunk)
if (
free_before is not None
and free_before - written < _RESEARCH_DISK_HEADROOM_FLOOR_BYTES
):
raise InsufficientDiskHeadroomError(
errno.ENOSPC,
"research archive spool aborted before breaching 10 GiB free-disk floor",
)
if research_cleanup:
_require_research_headroom(paths, len(chunk))
archive_file.write(chunk)
archive_file.seek(0)
target.mkdir(exist_ok=True)
Expand All @@ -277,16 +291,14 @@ def _extract_artifact_archive(
else:
members = _filter_research_members(archive, archive.getmembers())
extract_bytes = sum(m.size for m in members if m.isfile())
if (
free_before is not None
and free_before - written - extract_bytes
< _RESEARCH_DISK_HEADROOM_FLOOR_BYTES
):
raise InsufficientDiskHeadroomError(
errno.ENOSPC,
"research archive extraction aborted before breaching 10 GiB free-disk floor",
)
archive.extractall(target, members=members, filter="data")
_require_research_headroom(paths, extract_bytes)
source = archive.fileobj
archive.fileobj = _ResearchExtractionReader(archive, paths)
try:
archive.extractall(target, members=members, filter="data")
_require_research_headroom(paths)
finally:
archive.fileobj = source
finally:
close = getattr(chunks, "close", None)
if close is not None:
Expand Down
48 changes: 48 additions & 0 deletions benchmark/tests/test_sforge_artifact_spooling.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,54 @@ def get_archive(remote):
assert not (root / ".cargo-target").exists()


@pytest.mark.parametrize("pressure", ["spooling", "before-extraction", "during-extraction"])
def test_research_collection_observes_disk_pressure_midstream(tmp_path, monkeypatch, pressure):
from benchmark.runtime.research_artifacts import RESEARCH_DIRECTORY

backend = collector(tmp_path)
backend.research_sidecar = True
buf = io.BytesIO()
data = bytes(3 * 1024**2)
with tarfile.open(fileobj=buf, mode="w") as archive:
entry = tarfile.TarInfo("research/evidence")
entry.size = len(data)
archive.addfile(entry, io.BytesIO(data))

low_disk = False
closed = []
target = backend.log_dir / "research/research/evidence"

def research_stream():
nonlocal low_disk
try:
yield buf.getvalue()[:4096]
low_disk = pressure == "spooling"
yield buf.getvalue()[4096:]
low_disk = pressure == "before-extraction"
finally:
closed.append(True)

def free_bytes(*paths):
in_file = pressure == "during-extraction" and target.exists() and target.stat().st_size > 0
return 0 if low_disk or in_file else 20 * 1024**3

def get_archive(remote):
return (research_stream() if remote == RESEARCH_DIRECTORY else iter([archive_bytes()])), {}

monkeypatch.setattr(backend, "_raw", lambda _: SimpleNamespace(get_archive=get_archive))
monkeypatch.setattr(transport, "_minimum_free_bytes", free_bytes)
monkeypatch.setattr(transport.DockerBackend, "cleanup_container", lambda *args: None)
backend.cleanup_container("owned-container")
rows = json.loads((backend.log_dir / "artifact-collection.json").read_text())
assert closed == [True]
assert [row for row in rows if row["artifact"] == "research"] == [{
"artifact": "research", "collected": False, "error_kind": "InsufficientDiskHeadroomError",
"reason": "insufficient_host_disk_headroom",
}]
assert all(row["collected"] for row in rows if row["artifact"] != "research")
assert not target.exists() or target.stat().st_size < len(data)


@pytest.mark.parametrize("data_name", ["core", "evidence.bin"])
def test_research_hardlinks_keep_the_same_evidence_in_terminal_receipt(tmp_path, monkeypatch, data_name):
from benchmark.runtime.research_artifacts import RESEARCH_DIRECTORY
Expand Down
1 change: 1 addition & 0 deletions benchmark/tests/test_sforge_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,7 @@ def test_artifact_collection_preserves_both_session_homes_without_auth(tmp_path,
pytest.importorskip("sforge")
pytest.importorskip("harbor")
from benchmark.runtime.sforge_backend import RecordingDockerBackend, DockerBackend
monkeypatch.setattr("benchmark.runtime.sforge_backend._minimum_free_bytes", lambda *_: 20 * 1024**3)
backend = object.__new__(RecordingDockerBackend)
backend.research_sidecar = research_sidecar
backend.checkpoint = None
Expand Down
Loading