From d401907ac81ceb997ecb888c199acb90169bfda8 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:20:33 +0800 Subject: [PATCH 1/3] Validate execution paths and arguments before registration Reject overlapping materialized paths and embedded NUL arguments before claiming fresh requests. Keep existing files when exclusive opening fails. Agent-assisted-by: Codex / unknown effort=unknown (implementer) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- src/inferrsi/harness/execution_service.py | 39 +++++++++- src/inferrsi/harness/input_binding.py | 3 +- tests/test_harness_execute.py | 87 +++++++++++++++++++++++ 3 files changed, 126 insertions(+), 3 deletions(-) diff --git a/src/inferrsi/harness/execution_service.py b/src/inferrsi/harness/execution_service.py index 478d36853..fb7816410 100644 --- a/src/inferrsi/harness/execution_service.py +++ b/src/inferrsi/harness/execution_service.py @@ -9,7 +9,7 @@ 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 +411,43 @@ def _validate_fields(spec: object) -> bool: return bool(evaluation) +def _ordinary_path_errors(spec: Mapping) -> list[str]: + """Keep materialized inputs distinct from other inputs and from declared outputs.""" + if not spec["inputs"]: + return [] + + # The workspace can reside on a case-insensitive filesystem. + inputs = [PurePosixPath(item["materialized_path"].casefold()) for item in spec["inputs"]] + input_paths = set(inputs) + input_parents = {parent for path in inputs for parent in path.parents} + errors = [] + 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 = PurePosixPath(output["path"].casefold()) + if (path in input_paths or path in input_parents + or not input_paths.isdisjoint(path.parents)): + field = f"steps[{step_index}].outputs[{output_index}].path" + 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..17bc3a632 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,92 @@ 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"), + (["x/y"], "x", "steps[1].outputs[0].path"), + (["x"], "x/y", "steps[1].outputs[0].path"), + (["data.txt", "DATA.txt"], None, "inputs"), + (["x/y", "x"], None, "inputs"), +]) +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() + + +def test_registered_ordinary_request_can_replay_legacy_path_overlap( + h: Harness, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> 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", "data.txt")])], + 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, [ From b5de94b4b831287fd9bfa1de391a90340b8e672f Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:43:23 +0800 Subject: [PATCH 2/3] Reject ambiguous path components in ordinary runs Agent-assisted-by: Codex / unknown effort=unknown (implementer) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- src/inferrsi/harness/execution_service.py | 22 +++++++++++++++------- tests/test_harness_execute.py | 12 +++++++++--- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/inferrsi/harness/execution_service.py b/src/inferrsi/harness/execution_service.py index fb7816410..ea6319b9b 100644 --- a/src/inferrsi/harness/execution_service.py +++ b/src/inferrsi/harness/execution_service.py @@ -411,24 +411,32 @@ 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_errors(spec: Mapping) -> list[str]: """Keep materialized inputs distinct from other inputs and from declared outputs.""" - if not spec["inputs"]: - return [] - - # The workspace can reside on a case-insensitive filesystem. + # The workspace may use Windows name normalization or case-insensitive comparisons. + alias_error = "path components cannot end in a space or period" inputs = [PurePosixPath(item["materialized_path"].casefold()) for item in spec["inputs"]] input_paths = set(inputs) input_parents = {parent for path in inputs for parent in path.parents} - errors = [] + 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 = PurePosixPath(output["path"].casefold()) - if (path in input_paths or path in input_parents + 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)): - field = f"steps[{step_index}].outputs[{output_index}].path" errors.append(f"{field}: overlaps an input") return errors diff --git a/tests/test_harness_execute.py b/tests/test_harness_execute.py index 17bc3a632..56aec7265 100644 --- a/tests/test_harness_execute.py +++ b/tests/test_harness_execute.py @@ -516,6 +516,11 @@ def test_spec_time_refusals_register_nothing(h: Harness) -> None: (["x"], "x/y", "steps[1].outputs[0].path"), (["data.txt", "DATA.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, @@ -541,15 +546,16 @@ def test_ordinary_paths_refused_before_claim( assert not h._target.work_root.exists() -def test_registered_ordinary_request_can_replay_legacy_path_overlap( - h: Harness, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +@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", "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: []) From 32e6c097d961438dd465ffd9839f8a5777b1f96c Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:15:45 +0800 Subject: [PATCH 3/3] Compare Unicode-equivalent Harness workspace paths Compare materialized inputs and declared outputs by canonical caseless keys before registration. Agent-assisted-by: Codex / unknown effort=unknown (implementer) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- src/inferrsi/harness/execution_service.py | 12 +++++++++--- tests/test_harness_execute.py | 3 +++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/inferrsi/harness/execution_service.py b/src/inferrsi/harness/execution_service.py index ea6319b9b..73c9c4a03 100644 --- a/src/inferrsi/harness/execution_service.py +++ b/src/inferrsi/harness/execution_service.py @@ -6,6 +6,7 @@ import shutil import sys import time +import unicodedata from collections.abc import Mapping from dataclasses import dataclass from datetime import datetime, timezone @@ -415,11 +416,16 @@ 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.""" - # The workspace may use Windows name normalization or case-insensitive comparisons. alias_error = "path components cannot end in a space or period" - inputs = [PurePosixPath(item["materialized_path"].casefold()) for item in spec["inputs"]] + 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 = [ @@ -431,7 +437,7 @@ def _ordinary_path_errors(spec: Mapping) -> list[str]: 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 = PurePosixPath(output["path"].casefold()) + 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}") diff --git a/tests/test_harness_execute.py b/tests/test_harness_execute.py index 56aec7265..94b26d45c 100644 --- a/tests/test_harness_execute.py +++ b/tests/test_harness_execute.py @@ -512,9 +512,12 @@ def test_spec_time_refusals_register_nothing(h: Harness) -> None: @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"),