diff --git a/src/inferrsi/harness/execution_service.py b/src/inferrsi/harness/execution_service.py index 66995746..0a85a809 100644 --- a/src/inferrsi/harness/execution_service.py +++ b/src/inferrsi/harness/execution_service.py @@ -689,23 +689,29 @@ def _run_steps(ctx: _Context, argvs: list[list[str]], deadline: float, cancellat continue timeout = step["timeout_seconds"] bound = deadline if timeout is None else min(deadline, time.monotonic() + float(timeout)) + step_limited = bound < deadline # A missing cwd is a recorded launch failure, not a directory H invents. logs = (ctx.captures / f"step-{index}.stdout", ctx.captures / f"step-{index}.stderr") run = local_process._supervise( argv, ctx.workspace / step["cwd"], os.environ.copy(), logs[0], logs[1], bound, - cancellation=cancellation, + cancellation=cancellation, step_limited=step_limited, ) runs.append((step, run)) - if run["pid"] is None and run["status"] == "timeout": - records.append(_not_started_step(step, "deadline_exhausted")) - stop = "deadline_exhausted" + if run["pid"] is None and run["status"] in ("timeout", "cancelled"): + if run["status"] == "cancelled": + reason = stop = "cancelled" + elif step_limited: + reason, stop = "step_timeout", "previous_step_failed" + else: + reason = stop = "deadline_exhausted" + records.append(_not_started_step(step, reason)) continue status = _STEP_STATUS[run["status"]] exited = status == "exited" if run["pid"] is None: reasons = ["launch_failed"] elif status == "timed_out": - reasons = ["deadline_exceeded" if bound >= deadline else "step_timeout"] + reasons = ["step_timeout" if step_limited else "deadline_exceeded"] elif status == "cancelled": reasons = [run["cancellation_source"]] elif status == "execution_error": diff --git a/src/inferrsi/harness/local_process.py b/src/inferrsi/harness/local_process.py index b14f0dec..7d98a621 100644 --- a/src/inferrsi/harness/local_process.py +++ b/src/inferrsi/harness/local_process.py @@ -256,11 +256,13 @@ def _supervise( deadline: float, *, cancellation=None, + step_limited: bool = False, ) -> dict: """Run one command inside its own process domain and return the observed facts. - ``deadline`` is a ``time.monotonic()`` value. ``cancellation`` is an optional handle - with ``is_set()``. ``status`` keeps the legacy vocabulary: completed, failed, timeout, + ``deadline`` is a ``time.monotonic()`` value. ``step_limited`` identifies a + per-step bound for the pre-launch timeout diagnostic. ``cancellation`` is an optional + handle with ``is_set()``. ``status`` keeps the legacy vocabulary: completed, failed, timeout, cancelled or error. ``domain_empty`` is True only when the Job or process group was confirmed to hold no live member after cleanup. """ @@ -280,10 +282,12 @@ def _supervise( "elapsed_seconds": None, } started, process, windows_job, attached, launched = time.monotonic(), None, None, False, None + timeout_before_launch = ("step timeout expired before command start" if step_limited + else "whole-run deadline exhausted before command start") try: remaining = deadline - started if remaining <= 0: - run.update(status="timeout", error="whole-run deadline exhausted before command start") + run.update(status="timeout", error=timeout_before_launch) else: options = ( {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} @@ -293,6 +297,13 @@ def _supervise( if os.name == "nt": windows_job = _WindowsJob() with stdout_path.open("wb") as stdout, stderr_path.open("wb") as stderr: + if cancellation is not None and cancellation.is_set(): + run.update(status="cancelled", error="cancellation requested", + cancellation_requested_at=_utc_now(), cancellation_source="caller") + return run + if time.monotonic() >= deadline: + run.update(status="timeout", error=timeout_before_launch) + return run process = subprocess.Popen( argv, cwd=cwd, diff --git a/tests/test_harness_execute.py b/tests/test_harness_execute.py index 0778e0d0..ac1f6eb3 100644 --- a/tests/test_harness_execute.py +++ b/tests/test_harness_execute.py @@ -7,7 +7,9 @@ import sys import threading import time +from datetime import datetime, timedelta, timezone from pathlib import Path +from types import SimpleNamespace import pytest @@ -220,6 +222,65 @@ def test_h02_2_timeout_cancel_and_cleanup_are_recorded_separately(h: Harness) -> assert late["steps"][0]["reasons"] == ["deadline_exhausted"] +@pytest.mark.parametrize("reason", ["cancelled", "deadline_exhausted", "step_timeout"]) +def test_prelaunch_limits_are_rechecked_after_opening_logs(h, monkeypatch, reason): + cancelled = reason == "cancelled" + step_limited = reason == "step_timeout" + cancellation = threading.Event() + open_path = Path.open + supervise = local_process._supervise + runs = [] + offset = 0 + + def open_log(path, *args, **kwargs): + nonlocal offset + stream = open_path(path, *args, **kwargs) + if path.name == "step-0.stderr": + if cancelled: + cancellation.set() + else: + offset = 7 if step_limited else 120 + return stream + + def observe_supervision(*args, **kwargs): + run = supervise(*args, **kwargs) + runs.append(run) + return run + + def unexpected_launch(*args, **kwargs): + pytest.fail("A worker started after the launch limit") + + monkeypatch.setattr(Path, "open", open_log) + monkeypatch.setattr(local_process, "time", SimpleNamespace( + monotonic=lambda: time.monotonic() + offset, sleep=time.sleep, + )) + monkeypatch.setattr(local_process, "_supervise", observe_supervision) + monkeypatch.setattr(local_process.subprocess, "Popen", unexpected_launch) + deadline = (datetime.now(timezone.utc) + timedelta(minutes=1)).strftime("%Y-%m-%dT%H:%M:%SZ") + spec = make_spec(h, [step("print('first')", timeout="5" if step_limited else None), + step("print('second')", step_id="second")], deadline=deadline) + record = h.execute(spec, cancellation=cancellation) + + schema_check(record) + assert record["started"] is False + assert record["phase"] == "finished" + assert record["process_outcome"] == ("cancelled" if cancelled else "not_started") + assert record["target_binding"]["runtime_bindings_by_step"] == [] + assert record["resource_leases"]["leases"] == [] + assert record["cleanup"]["status"] == "not_needed" + assert record["cancellation"]["requested"] is cancelled + assert record["cancellation"]["source"] == ("caller" if cancelled else None) + later_reason = "previous_step_failed" if step_limited else reason + assert [(s["status"], s["reasons"]) for s in record["steps"]] == [ + ("not_started", [reason]), ("not_started", [later_reason]), + ] + assert [run["error"] for run in runs] == [{ + "cancelled": "cancellation requested", + "deadline_exhausted": "whole-run deadline exhausted before command start", + "step_timeout": "step timeout expired before command start", + }[reason]] + + def test_h02_3_actual_input_mismatch_commits_a_fixed_not_started(h: Harness, tmp_path) -> None: source = tmp_path / "controller" / "candidate.txt" source.write_bytes("actual bytes 实际\n".encode("utf-8")) @@ -462,7 +523,8 @@ def test_steps_run_in_fixed_order_and_fail_fast(h: Harness, tmp_path) -> None: def _supervise_with_domain(domain_empty, calls: list[list[str]]): """Stub supervisor: first step uses the injected domain_empty fact; later steps are empty.""" - def fake(argv, cwd, environment, stdout_path, stderr_path, deadline, *, cancellation=None): + def fake(argv, cwd, environment, stdout_path, stderr_path, deadline, *, + cancellation=None, step_limited=False): calls.append(list(argv)) stdout_path.write_bytes(b"") stderr_path.write_bytes(b"")