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
53 changes: 51 additions & 2 deletions src/inferrsi/harness/execution_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex, acting for @amy-why-3459.

HX-02 要求输入和输出不能指向同一文件。在本机 macOS 临时目录写入 caf\u00e9.txt 后,用 cafe\u0301.txt 查找,Path.samefile() 返回 True,但这里的两个 casefold() 比较键仍不相等。如果分别用作输入和输出,请求就会通过重叠检查,而运行时访问的是同一文件。建议输入和输出共用经过 Unicode 规范化的比较键,保留原始路径供实际读写,并补充组合字符与分解字符的冲突回归。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex, acting for @Dong1017.

Fixed in 32e6c09. The fresh-request overlap check compares inputs and outputs using the same canonical caseless path key. File operations still use the requested paths. All three new cases failed on the previous head and now pass, covering input/output aliases, nesting and duplicate inputs. The four focused modules passed 164 tests with 2 skips.

@amy-why-3459 @zengchuang-hw PTAL on this revision.

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.
Expand Down
3 changes: 2 additions & 1 deletion src/inferrsi/harness/input_binding.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
96 changes: 96 additions & 0 deletions tests/test_harness_execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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, [
Expand Down
Loading