diff --git a/src/inferrsi/harness/execution_service.py b/src/inferrsi/harness/execution_service.py index 478d36853..73c9c4a03 100644 --- a/src/inferrsi/harness/execution_service.py +++ b/src/inferrsi/harness/execution_service.py @@ -6,10 +6,11 @@ import shutil import sys import time +import unicodedata from collections.abc import Mapping from dataclasses import dataclass from datetime import datetime, timezone -from pathlib import Path +from pathlib import Path, PurePosixPath from inferrsi.contracts import json_v1 from inferrsi.harness import ( @@ -411,8 +412,56 @@ def _validate_fields(spec: object) -> bool: return bool(evaluation) +def _has_windows_path_alias(path: PurePosixPath) -> bool: + return any(part.endswith((" ", ".")) for part in path.parts) + + +def _ordinary_path_key(value: str) -> PurePosixPath: + # Compare paths using canonical caseless matching. + decomposed = unicodedata.normalize("NFD", value) + return PurePosixPath(unicodedata.normalize("NFD", decomposed.casefold())) + + +def _ordinary_path_errors(spec: Mapping) -> list[str]: + """Keep materialized inputs distinct from other inputs and from declared outputs.""" + alias_error = "path components cannot end in a space or period" + inputs = [_ordinary_path_key(item["materialized_path"]) for item in spec["inputs"]] + input_paths = set(inputs) + input_parents = {parent for path in inputs for parent in path.parents} + errors = [ + f"inputs[{index}].materialized_path: {alias_error}" + for index, path in enumerate(inputs) + if _has_windows_path_alias(path) + ] + if len(input_paths) != len(inputs) or not input_paths.isdisjoint(input_parents): + errors.append("inputs: materialized paths must not overlap") + for step_index, step in enumerate(spec["steps"]): + for output_index, output in enumerate(step["outputs"]): + path = _ordinary_path_key(output["path"]) + field = f"steps[{step_index}].outputs[{output_index}].path" + if _has_windows_path_alias(path): + errors.append(f"{field}: {alias_error}") + elif (path in input_paths or path in input_parents + or not input_paths.isdisjoint(path.parents)): + errors.append(f"{field}: overlaps an input") + return errors + + def _validate_fresh(spec, target, artifact_reader, evaluation): - """Validate fixed bytes and target support only for a request not yet registered.""" + """Validate workspace, command, fixed bytes and target support for a fresh request.""" + errors = [ + f"steps[{step_index}].args[{arg_index}]: contains a NUL character" + for step_index, step in enumerate(spec["steps"]) + for arg_index, arg in enumerate(step["args"]) + if "\0" in arg + ] + if not evaluation: + errors.extend(_ordinary_path_errors(spec)) + if errors: + raise PublicError( + "InvalidExecutionSpec", stage="validate", message="illegal ExecutionSpec", + field_errors=errors, + ) if evaluation: # Malformed or inconsistent bindings are refused here, before the RunStore sees the # request. The reader is the read-only port; H does not write or register anything. diff --git a/src/inferrsi/harness/input_binding.py b/src/inferrsi/harness/input_binding.py index 9ea05c85e..7d63cea4c 100644 --- a/src/inferrsi/harness/input_binding.py +++ b/src/inferrsi/harness/input_binding.py @@ -42,8 +42,9 @@ def copy_stream(stream: BinaryIO, target: Path) -> tuple[str, int]: hasher = hashlib.sha256() size = 0 target.parent.mkdir(parents=True, exist_ok=True) + out = open(target, "xb") try: - with open(target, "xb") as out: + with out: for chunk in iter(lambda: stream.read(_CHUNK), b""): out.write(chunk) hasher.update(chunk) diff --git a/tests/test_harness_execute.py b/tests/test_harness_execute.py index 012fee3d0..94b26d45c 100644 --- a/tests/test_harness_execute.py +++ b/tests/test_harness_execute.py @@ -8,6 +8,7 @@ import threading import time from datetime import datetime, timedelta, timezone +from io import BytesIO from pathlib import Path from types import SimpleNamespace @@ -508,6 +509,101 @@ def test_spec_time_refusals_register_nothing(h: Harness) -> None: assert attempt_rows(h) == [] +@pytest.mark.parametrize(("input_paths", "output_path", "field"), [ + (["data.txt"], "data.txt", "steps[1].outputs[0].path"), + (["data.txt"], "DATA.txt", "steps[1].outputs[0].path"), + (["caf\u00e9.txt"], "CAFE\u0301.txt", "steps[1].outputs[0].path"), + (["caf\u00e9"], "cafe\u0301/result.txt", "steps[1].outputs[0].path"), + (["x/y"], "x", "steps[1].outputs[0].path"), + (["x"], "x/y", "steps[1].outputs[0].path"), + (["data.txt", "DATA.txt"], None, "inputs"), + (["caf\u00e9.txt", "cafe\u0301.txt"], None, "inputs"), + (["x/y", "x"], None, "inputs"), + (["data.txt"], "data.txt.", "steps[1].outputs[0].path"), + (["data.txt "], "data.txt", "inputs[0].materialized_path"), + (["weights./data.txt"], "weights/data.txt", "inputs[0].materialized_path"), + (["weights/data.txt"], "weights /data.txt", "steps[1].outputs[0].path"), + ([], "data.txt ", "steps[1].outputs[0].path"), +]) +def test_ordinary_paths_refused_before_claim( + h: Harness, tmp_path: Path, input_paths: list[str], output_path: str | None, field: str, +) -> None: + (tmp_path / "controller" / "data.txt").write_bytes(b"input bytes") + marker = tmp_path / "starts.txt" + inputs = [ + {"role": f"input-{index}", "source": "data.txt", "source_namespace": "controller", + "source_ref": None, "snapshot_format": "file-v1", "expected_sha256": None, + "materialized_path": path} + for index, path in enumerate(input_paths) + ] + outputs = [output("result", output_path)] if output_path else [] + spec = make_spec(h, [ + step(counter_code(marker), step_id="first"), + step("pass", step_id="second", outputs=outputs), + ], inputs=inputs) + + for error in (error_of(h.execute, spec), error_of(execution_service.validate, spec, h._target)): + assert (error.code, error.stage) == ("InvalidExecutionSpec", "validate") + assert any(detail.startswith(f"{field}:") for detail in error.field_errors) + assert attempt_rows(h) == [] and starts(marker) == 0 + assert not h._target.work_root.exists() + + +@pytest.mark.parametrize("output_path", ["data.txt", "data.txt."]) +def test_registered_ordinary_request_can_replay_legacy_paths( + h: Harness, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, output_path: str, +) -> None: + (tmp_path / "controller" / "data.txt").write_bytes(b"input bytes") + marker = tmp_path / "starts.txt" + item = {"role": "input", "source": "data.txt", "source_namespace": "controller", + "source_ref": None, "snapshot_format": "file-v1", "expected_sha256": None, + "materialized_path": "data.txt"} + spec = make_spec(h, [step(counter_code(marker), outputs=[output("result", output_path)])], + inputs=[item]) + with monkeypatch.context() as patch: + patch.setattr(execution_service, "_ordinary_path_errors", lambda spec: []) + legacy = h.execute(spec) + + assert h.execute(spec)["record_ref"] == legacy["record_ref"] + assert starts(marker) == 1 + + +def test_nul_argument_refused_before_claim(h: Harness, tmp_path: Path) -> None: + marker = tmp_path / "starts.txt" + command = step(counter_code(marker)) + command["args"].append("before\0after") + spec = make_spec(h, [command]) + + error = error_of(h.execute, spec) + assert (error.code, error.stage) == ("InvalidExecutionSpec", "validate") + assert any(detail.startswith("steps[0].args[2]:") for detail in error.field_errors) + assert attempt_rows(h) == [] and starts(marker) == 0 + + +def test_copy_stream_failed_exclusive_open_preserves_existing_file(tmp_path: Path) -> None: + target = tmp_path / "existing.txt" + target.write_bytes(b"original bytes") + + with pytest.raises(FileExistsError): + input_binding.copy_stream(BytesIO(b"replacement bytes"), target) + + assert target.read_bytes() == b"original bytes" + + +def test_copy_stream_read_failure_removes_its_new_file(tmp_path: Path) -> None: + class BrokenStream(BytesIO): + def read(self, size=-1): + if self.tell(): + raise OSError("stream read failed") + return super().read(size) + + target = tmp_path / "partial.txt" + with pytest.raises(OSError, match="stream read failed"): + input_binding.copy_stream(BrokenStream(b"partial bytes"), target) + + assert not target.exists() + + def test_steps_run_in_fixed_order_and_fail_fast(h: Harness, tmp_path) -> None: marker = tmp_path / "starts.txt" record = h.execute(make_spec(h, [