diff --git a/src/inferrsi/benchmark/preparation.py b/src/inferrsi/benchmark/preparation.py index ddcd5ec0..d67b7365 100644 --- a/src/inferrsi/benchmark/preparation.py +++ b/src/inferrsi/benchmark/preparation.py @@ -338,22 +338,33 @@ def validate_prepared(prepared: dict, protocol_bytes: bytes) -> None: "Prepared object disagrees with its frozen protocol.", "IdentityMismatch") -def _measure(source) -> tuple[int, str]: +def _verify_resource(source, ref: dict) -> None: if source is None: raise FileNotFoundError("A required resource is unavailable.") + expected_size = ref["size_bytes"] if isinstance(source, bytes): - return len(source), sha256(source).hexdigest() - size, digest = 0, sha256() - with closing(source): - while True: - chunk = source.read(1024 * 1024) - if not isinstance(chunk, bytes): - raise TypeError("A host resource capability must return binary bytes.") - if not chunk: - break - size += len(chunk) - digest.update(chunk) - return size, digest.hexdigest() + matches = len(source) == expected_size and sha256(source).hexdigest() == ref["sha256"] + else: + digest = sha256() + size = 0 + matches = None + try: + with closing(source): + while True: + chunk = source.read(min(1024 * 1024, expected_size - size + 1)) + if not isinstance(chunk, bytes): + raise TypeError("A host resource capability must return binary bytes.") + size += len(chunk) + if not chunk or size > expected_size: + break + digest.update(chunk) + matches = size == expected_size and digest.hexdigest() == ref["sha256"] + except Exception: + # Keep the established mismatch if closing the stream also fails. + if matches is not False: + raise + _require(matches, + "Resource bytes disagree with their fixed metadata.", "ArtifactIntegrityError") class PreparationService: @@ -422,12 +433,9 @@ def _prepare(self, request: dict) -> tuple: closure = _closure(protocol) for resource in closure: try: - size, digest = _measure(self._resources(resource["role"])) + _verify_resource(self._resources(resource["role"]), resource["artifact"]) except (KeyError, OSError): raise PreparationError("ArtifactUnavailable", "A required resource is unavailable.") - ref = resource["artifact"] - _require((size, digest) == (ref["size_bytes"], ref["sha256"]), - "Resource bytes disagree with their fixed metadata.", "ArtifactIntegrityError") data = canonical_encode(protocol) prepared = { "schema_version": 1, "prepared_id": "", **{key: deepcopy(protocol[key]) diff --git a/tests/test_benchmark_preparation.py b/tests/test_benchmark_preparation.py index 39a8ebab..0e85c271 100644 --- a/tests/test_benchmark_preparation.py +++ b/tests/test_benchmark_preparation.py @@ -6,7 +6,7 @@ import sys from copy import deepcopy from hashlib import sha256 -from io import StringIO +from io import BytesIO, StringIO from pathlib import Path import pytest @@ -193,6 +193,43 @@ def test_wrong_resource_bytes_are_not_frozen_as_a_different_pin(preparation): assert service.prepare(request)["code"] == "ArtifactIntegrityError" +@pytest.mark.parametrize("close_fails", [False, True], ids=["closes", "close-error"]) +def test_t36_oversized_resource_stops_at_the_first_extra_byte(preparation, tmp_path, close_fails): + _, request, sources, protocol, _, config, archive = preparation + fixed_bytes = sources["input-data"].read_bytes() + read_sizes = [] + + class OversizedResource(BytesIO): + def read(self, size=-1): + read_sizes.append(size) + if len(read_sizes) > 1: + raise OSError("resource read failed") + return super().read(size) + + def close(self): + super().close() + if close_fails: + raise OSError("resource close failed") + + stream = OversizedResource(fixed_bytes + b"x") + service = benchmark.PreparationService( + protocol, + resources=lambda role: stream if role == "input-data" else sources[role].read_bytes(), + worker_role="worker-code", + ) + result = apps_prepare( + {"schema_version": 1, "request": request}, workspace=tmp_path, + storage_config=config, prepare_benchmark=service.prepare, + encode_prepared=benchmark.encode, validate_prepared=benchmark.validate_prepared, + ) + assert result.result["reason_code"] == "ArtifactIntegrityError" + assert result.result["error"]["stage"] == "prepare" + assert result.result["prepared_ref"] is None + assert list(archive.iterdir()) == [] + assert read_sizes == [len(fixed_bytes) + 1] + assert stream.closed + + @pytest.mark.parametrize("change", [ lambda value: value["candidate_contract"].update(unknown=True), lambda value: value["recipe"].update(unrecognized=True),