From eb399eeb858ab0b66667782fd2c80ff97284e4ba Mon Sep 17 00:00:00 2001 From: "seiko.iwasawa" Date: Tue, 1 Dec 2026 08:51:41 +0300 Subject: [PATCH 01/12] fix(orchestrator): keep a requested cancel ahead of later failures (RM14; AC12; AC19) --- src/relaymind/orchestrator/_run_types.py | 2 + src/relaymind/orchestrator/client_loop.py | 2 + src/relaymind/orchestrator/generation.py | 6 +- src/relaymind/orchestrator/local_loop.py | 48 ++++++++++++---- src/relaymind/orchestrator/publish.py | 2 +- tests/test_gated_streaming.py | 67 ++++++++++++++++++++++- 6 files changed, 110 insertions(+), 17 deletions(-) diff --git a/src/relaymind/orchestrator/_run_types.py b/src/relaymind/orchestrator/_run_types.py index 7c06242e..7e9dcbcf 100644 --- a/src/relaymind/orchestrator/_run_types.py +++ b/src/relaymind/orchestrator/_run_types.py @@ -580,6 +580,7 @@ class _RunHost(Protocol): model_calls: list[dict[str, str]] generating: dict[str, ModelAdapter] cancel_asked: set[str] + cancel_requested: bool workflow: _Workflow | None tool_branch: str | None decision: RouteDecision | None @@ -622,6 +623,7 @@ def _answer_options( self, defaults: GenerationOptions, *, tools_offered: bool = False ) -> GenerationOptions: ... def _local_unavailable(self, detail: str) -> Escalation: ... + def _cancel(self) -> RunOutcome: ... def _fail(self, error_code: str, *, detail: str, **extra: Any) -> RunOutcome: ... async def _protected(self, work: Callable[[], Awaitable[RunOutcome]]) -> RunOutcome: ... async def _run_local( diff --git a/src/relaymind/orchestrator/client_loop.py b/src/relaymind/orchestrator/client_loop.py index 9cedb73c..9e4b5db1 100644 --- a/src/relaymind/orchestrator/client_loop.py +++ b/src/relaymind/orchestrator/client_loop.py @@ -461,6 +461,8 @@ async def _escalate_client(self, stop: Escalation) -> RunOutcome: def _complete(self, reply: _Reply) -> RunOutcome: """End the run with the reply: an answer, or the calls the caller executes.""" + if self.cancel_requested: + return self._cancel() model = self.active_model answer: str | None = None if reply.calls: diff --git a/src/relaymind/orchestrator/generation.py b/src/relaymind/orchestrator/generation.py index 156b9116..b0697da0 100644 --- a/src/relaymind/orchestrator/generation.py +++ b/src/relaymind/orchestrator/generation.py @@ -201,7 +201,7 @@ async def _generate( def check_live() -> None: task = asyncio.current_task() - if task is not None and task.cancelling(): + if self.cancel_requested or (task is not None and task.cancelling()): raise asyncio.CancelledError if self.o.clock.monotonic() - started >= limit: raise TimeoutError @@ -278,7 +278,7 @@ def check_live() -> None: self._cancel_call(call_id) break task = asyncio.current_task() - if task is not None and task.cancelling(): + if self.cancel_requested or (task is not None and task.cancelling()): # A provider that ignored the cancel answered late. Its # result is dropped: it proposes, runs, and publishes # nothing (spec 0.19 section 7.4). @@ -316,7 +316,7 @@ def check_live() -> None: # The trace names the limit that bounded this generation, local # or external, not always local time (RM03, RM16). task = asyncio.current_task() - if task is not None and task.cancelling(): + if self.cancel_requested or (task is not None and task.cancelling()): failure = GenerationFailed(code="cancelled", message="model generation interrupted") raise asyncio.CancelledError from None deadline_missed = placement.deadline_seconds is not None diff --git a/src/relaymind/orchestrator/local_loop.py b/src/relaymind/orchestrator/local_loop.py index 321acf1b..8987d0fe 100644 --- a/src/relaymind/orchestrator/local_loop.py +++ b/src/relaymind/orchestrator/local_loop.py @@ -1279,6 +1279,10 @@ def __init__( # (RM14). The parallel workflow has two at once (spec 0.25). self.generating: dict[str, ModelAdapter] = {} self.cancel_asked: set[str] = set() + # A user cancel outranks a failure the provider or a late budget + # check reports after it, even when the provider consumes the task + # cancellation (RM14, AC12, spec 0.19 section 7.4). + self.cancel_requested = False # The parallel workflow of this run, once it started (spec 0.25), and # the branch the tool events of the local branch are traced under. self.workflow: _Workflow | None = None @@ -1608,6 +1612,8 @@ async def _run_local(self, loop: _Loop, confirmed: _Confirmation | None = None) return await self._escalate( Escalation(exceeded.reason_code, str(exceeded), budget=exceeded.budget) ) + if self.cancel_requested: + return self._cancel() self.move( RunState.COMPLETED, event=( @@ -1706,8 +1712,27 @@ async def route() -> Routing: return await self._guarded(route) + def _cancel(self) -> RunOutcome: + """End the run as cancelled; a requested cancel outranks a later failure.""" + self.record = self.o.machine.get(self.run_id) + if RunState(self.record.state) in TERMINAL_STATES: + return RunOutcome(self.run_id, RunState(self.record.state), decision=self.decision) + payload = self._selector_payload( + EventType.RUN_CANCELLED, {"reason": CANCEL_REQUESTED, **self._summary()} + ) + self.record = self.o.machine.cancel( + self.run_id, + self.record.version, + reason=CANCEL_REQUESTED, + event=(EventType.RUN_CANCELLED, GATEWAY_ACTOR, payload), + ) + self._selector_persisted(EventType.RUN_CANCELLED) + return RunOutcome(self.run_id, RunState.CANCELLED, decision=self.decision) + def _fail(self, error_code: str, *, detail: str, **extra: Any) -> RunOutcome: """End the run as failed with error_code and its run.failed event.""" + if self.cancel_requested: + return self._cancel() self.move( RunState.FAILED, error_code=error_code, @@ -1745,6 +1770,8 @@ def _workflow_unavailable(self, detail: str) -> RunOutcome: return self._fail(WORKFLOW_UNAVAILABLE, detail=detail, reason_code=PARALLEL_WORKFLOW) def _needs_external(self, stop: Escalation) -> RunOutcome: + if self.cancel_requested: + return self._cancel() self.move( RunState.FAILED, error_code=NEEDS_EXTERNAL, @@ -1787,20 +1814,12 @@ def _abort(self, exc: BaseException) -> None: self.record = self.o.machine.get(self.run_id) if RunState(self.record.state) in TERMINAL_STATES: return - if isinstance(exc, asyncio.CancelledError): + if isinstance(exc, asyncio.CancelledError) or self.cancel_requested: # A cancel that reaches the task, from the native cancel, # a chat disconnect, or the event loop, is a cancel - # request (spec 0.17 sections 7.4 and 8). - payload = self._selector_payload( - EventType.RUN_CANCELLED, {"reason": CANCEL_REQUESTED, **self._summary()} - ) - self.record = self.o.machine.cancel( - self.run_id, - self.record.version, - reason=CANCEL_REQUESTED, - event=(EventType.RUN_CANCELLED, GATEWAY_ACTOR, payload), - ) - self._selector_persisted(EventType.RUN_CANCELLED) + # request (spec 0.17 sections 7.4 and 8). A request cancel + # also outranks a failure the provider reports after it. + self._cancel() return self.move( RunState.FAILED, @@ -2099,6 +2118,8 @@ async def _run_external( reason_code=stop.reason_code, budget=exceeded.budget, ) + if self.cancel_requested: + return self._cancel() self.move( RunState.COMPLETED, event=( @@ -2499,6 +2520,9 @@ def _stop(run: _Run, task: "asyncio.Task[Any]") -> None: first, and the adapter is asked while it still knows the generation (task.cancel() tears its stream down). """ + # Record the request before the provider sees it: a provider that + # consumes the task cancellation must not turn this run into a failure. + run.cancel_requested = True run.cancel_generation() task.cancel() diff --git a/src/relaymind/orchestrator/publish.py b/src/relaymind/orchestrator/publish.py index 317cc3b5..22ce1b48 100644 --- a/src/relaymind/orchestrator/publish.py +++ b/src/relaymind/orchestrator/publish.py @@ -93,7 +93,7 @@ def _draft_publishable(self, draft: str) -> bool: def _publication_ready(self, external: bool) -> None: task = asyncio.current_task() - if task is not None and task.cancelling(): + if self.cancel_requested or (task is not None and task.cancelling()): raise asyncio.CancelledError record = self.o.machine.get(self.run_id) if record.state in TERMINAL_STATES or record.version != self.record.version: diff --git a/tests/test_gated_streaming.py b/tests/test_gated_streaming.py index 9b6c869c..ca9a6038 100644 --- a/tests/test_gated_streaming.py +++ b/tests/test_gated_streaming.py @@ -4,7 +4,15 @@ import pytest -from gateway_helpers import STAGING_OK, build_gateway, health_tail, route_turn, run, text_turn +from gateway_helpers import ( # noqa: F401 - close_gateway_stores is an autouse fixture + STAGING_OK, + build_gateway, + close_gateway_stores, + health_tail, + route_turn, + run, + text_turn, +) from helpers import of_type from relaymind.adapters import Completed, TextDelta from relaymind.orchestrator.performance import PerformanceSettings @@ -345,6 +353,63 @@ async def generate(request): asyncio.run(scenario()) +def test_disconnect_cancel_wins_when_provider_consumes_cancellation(tmp_path): + """RM14/AC12/AC19: a provider that swallows the task cancel still ends cancelled. + + The request records its own cancel before asking the provider, so late + cleanup that consumes the task cancellation and spends the remaining + budget can never turn the run into a failed run or publish its text. + """ + from api_helpers import make_app + from relaymind.api.native import NativeSettings + from test_chat_disconnect_cancel import chat_client, until + + async def scenario(): + gateway = build_gateway( + tmp_path, + [route_turn("check-service-health"), *health_tail()[:-1]], + performance=PerformanceSettings(answer_stream="live", early_headers=True), + ) + original = gateway.adapter.generate + entered = asyncio.Event() + + async def generate(request): + if not request.generation_id.endswith("_final"): + async for event in original(request): + yield event + return + yield TextDelta(STAGING_OK + " ") + entered.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + # A resistant provider acknowledges and consumes the task + # cancellation, then returns text after spending the budget. + task = asyncio.current_task() + assert task is not None + task.uncancel() + gateway.clock.advance(1000) + yield TextDelta("staging-api is unavailable. ") + yield Completed("stop") + + gateway.adapter.generate = generate + client = chat_client( + make_app(gateway, native=NativeSettings(heartbeat_seconds=0.01)), stream=True + ).start() + await asyncio.wait_for(entered.wait(), 1) + await until(lambda: any(STAGING_OK.encode() in m.get("body", b"") for m in client.sent)) + await client.leave() + run_id = gateway.adapter.requests[0].generation_id.split("_gen")[0] + record = gateway.store.get_run(run_id) + events = gateway.store.events(record.run_id) + assert record.state == "cancelled", (record.state, record.error_code) + assert not of_type(events, "run.failed") + assert not any("unavailable" in e.payload["text"] for e in of_type(events, "answer.delta")) + assert len(gateway.adapter.cancelled) == 1 + + asyncio.run(scenario()) + + @pytest.mark.parametrize( "bounds, expected_budget, expected_reason", [ From 840960d48380edbe70ad2e8a7baf53ff3d2cb32d Mon Sep 17 00:00:00 2001 From: "seiko.iwasawa" Date: Tue, 1 Dec 2026 08:51:47 +0300 Subject: [PATCH 02/12] test(asset-operations): time the evidence deadline with the injected clock (RM38; AC29) --- tests/test_asset_operations.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_asset_operations.py b/tests/test_asset_operations.py index 2d6538e8..c7fa68b2 100644 --- a/tests/test_asset_operations.py +++ b/tests/test_asset_operations.py @@ -700,12 +700,14 @@ async def get(self, *args, **kwargs): await asyncio.sleep(0.05) return httpx.Response(200, json={}) + clock = FakeClock() sample = await request_sample( SlowEvidence(), BODY, category="startup", ordinal=0, - deadline_at=time.monotonic() + 0.01, + deadline_at=clock.mono + 0.01, + clock=clock.monotonic, ) assert sample.error == "evidence_timeout" assert sample.client_elapsed_ms < 10 From 6b2be6005f558884be80503095c0670de9da521b Mon Sep 17 00:00:00 2001 From: "seiko.iwasawa" Date: Tue, 1 Dec 2026 08:51:54 +0300 Subject: [PATCH 03/12] ci(openclaw): widen the Windows install bound and slow-step limits (RM33; AC24) --- .github/workflows/ci.yml | 13 ++++++++++++- integrations/openclaw/vitest.config.ts | 4 ++++ scripts/openclaw_install_check.py | 1 + tests/test_ci_workflows.py | 20 ++++++++++++++++++++ tests/test_openclaw_install_check.py | 1 + 5 files changed, 38 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4723dbd6..cbc6b17a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -115,7 +115,9 @@ jobs: - name: Test # Parallel workers, one test file per worker at a time; on Windows the - # single-process run took about 29 minutes. + # single-process run took about 29 minutes. The bound turns a hung + # test into a fast failure instead of the 60-minute job timeout. + timeout-minutes: 45 run: pytest -n auto --dist loadfile --durations=30 --junitxml=ci-evidence/core-tests.xml - uses: actions/upload-artifact@v4 @@ -179,6 +181,7 @@ jobs: - name: Plugin tests working-directory: integrations/openclaw + timeout-minutes: 15 run: npm test - name: Release artifact @@ -225,6 +228,7 @@ jobs: # blocked capture (exit 0); harness/fixture errors must fail the job. # Typical 50–100 s; tier deadline 180 s, plus 60 s for cleanup/export. - name: Transport, plugin, and artifact tiers + timeout-minutes: 25 run: > pytest tests/test_asset_whole_task_host_config.py tests/test_asset_whole_task_inputs.py tests/test_openclaw_host_transport.py tests/test_openclaw_plugin.py @@ -254,10 +258,17 @@ jobs: --durations=30 --junitxml=ci-evidence/openclaw-tests.xml - name: Pinned host lifecycle (install, inspect, round trips, removal) + # The Windows runner spends 200-220 s in the host's npm install alone + # (about 30 s on Linux and macOS), so its per-command bound is wider. + # A real hang still fails here instead of at the 60-minute job limit. + timeout-minutes: 20 + env: + HOST_TIMEOUT: ${{ matrix.os == 'windows-latest' && '600' || '300' }} run: | tarball="release/openclaw/$(node -p "require('./release/openclaw/release.json').filename")" python scripts/openclaw_install_check.py --tarball "$tarball" \ --out "ci-evidence/openclaw-install-check-${{ matrix.os }}.json" \ + --timeout "$HOST_TIMEOUT" \ --label "GitHub Actions ${{ matrix.os }} runner, Node $(node --version)" \ -- node integrations/openclaw/node_modules/openclaw/openclaw.mjs diff --git a/integrations/openclaw/vitest.config.ts b/integrations/openclaw/vitest.config.ts index 8b5840ac..26765869 100644 --- a/integrations/openclaw/vitest.config.ts +++ b/integrations/openclaw/vitest.config.ts @@ -3,5 +3,9 @@ import { defineConfig } from "vitest/config"; export default defineConfig({ test: { include: ["test/**/*.test.ts"], + // The lock/ledger tests drive real file-system interleavings; a busy + // Windows runner can exceed Vitest's 5 s default without a test bug. + testTimeout: 30_000, + hookTimeout: 30_000, }, }); diff --git a/scripts/openclaw_install_check.py b/scripts/openclaw_install_check.py index 453b3842..e45f2ec3 100644 --- a/scripts/openclaw_install_check.py +++ b/scripts/openclaw_install_check.py @@ -748,6 +748,7 @@ def run_install_check( }, "gateway_port": ctx.gateway_port, }, + "timeout_seconds": timeout, "token": NOT_RECORDED, "steps": steps, "exchanges": exchanges, diff --git a/tests/test_ci_workflows.py b/tests/test_ci_workflows.py index d212f87b..cb751d84 100644 --- a/tests/test_ci_workflows.py +++ b/tests/test_ci_workflows.py @@ -33,6 +33,26 @@ def one(match): return re.sub(r"\$\{\{(.*?)\}\}", one, template) +def test_openclaw_lifecycle_has_a_wider_windows_command_timeout(): + """RM33/AC24: the Windows host install gets room without relaxing every platform. + + The Windows runner spends roughly 200-220 s in the host's npm install, + against about 30 s on Linux and macOS, so the shared 300 s default is + too tight there. The step also has its own bound, so a real hang ends + before the job timeout. + """ + import yaml + + workflow = yaml.safe_load((WORKFLOWS / "ci.yml").read_text("utf-8")) + steps = workflow["jobs"]["openclaw-plugin"]["steps"] + step = next(s for s in steps if s.get("name", "").startswith("Pinned host lifecycle")) + windows = _interpolate(step["env"]["HOST_TIMEOUT"], {"matrix": {"os": "windows-latest"}}) + linux = _interpolate(step["env"]["HOST_TIMEOUT"], {"matrix": {"os": "ubuntu-latest"}}) + assert (windows, linux) == ("600", "300") + assert step["timeout-minutes"] == 20 + assert '--timeout "$HOST_TIMEOUT"' in step["run"] + + @pytest.mark.parametrize( "action, changes, reviews, edit_group", [ diff --git a/tests/test_openclaw_install_check.py b/tests/test_openclaw_install_check.py index 9cbd8f05..184575b7 100644 --- a/tests/test_openclaw_install_check.py +++ b/tests/test_openclaw_install_check.py @@ -232,6 +232,7 @@ def test_every_step_runs_in_order_against_an_isolated_host_home(stub_host, tarba home = tmp_path / "host" export = run(stub_host, tarball, tmp_path, host_home=home) assert export["status"] == "completed" + assert export["timeout_seconds"] == 300 assert [s["name"] for s in export["steps"]] == list(install_check.STEPS) assert all(s["status"] == "passed" for s in export["steps"]), export["steps"] recorded = calls(home) From 6252c927f8f44a3601c361f2f9622a98283800d6 Mon Sep 17 00:00:00 2001 From: "seiko.iwasawa" Date: Tue, 1 Dec 2026 08:52:01 +0300 Subject: [PATCH 04/12] docs: record timing-test and master-rerun rules --- CHANGELOG.md | 7 +++++++ docs/TESTING.md | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d7ba598..317ea06a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2812,6 +2812,13 @@ pre-release development. ### Fixed +- CI stability (RM14; RM33; RM38; AC12; AC19; AC24; AC29): a requested cancel now + outranks a later failure even when a provider consumes the task cancellation, the + Windows OpenClaw lifecycle gets a wider per-command timeout, the OpenClaw lock + tests no longer inherit Vitest's 5 s default, and the timing test reads an injected + clock instead of the wall clock. The cancel precedence follows the existing + section 7.4 rule; the other changes are test and CI only. + - Hardened automated-host control polling and provider-response failures. Future executions require explicit v2 control budgets and fresh preregistration; historical inputs and outcomes remain unchanged. Timeout paths retain the last recommendation state, and functional transport tests allow cold worker startup (RM03, RM05, RM16, RM44). - Addressed #277/#280 review findings: portable transport tests, clear blind-CLI input errors, consistent stored row evidence, fenced JSON proposals, private-file read bounds, and redacted public home paths with retained original bindings. Historical benchmark results and qualification claims are unchanged. diff --git a/docs/TESTING.md b/docs/TESTING.md index 7e00957a..f8cde80f 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -49,6 +49,25 @@ marker when the test drops below 10 seconds; the gap keeps a run near the line from churning the marker. The Windows job runs the same tests slower, so the Ubuntu job is the reference. The fast local subset leaves those tests out. +### Timing-sensitive tests + +A loaded runner, a parallel worker, or a slow file system must never change a +test's verdict. Inject `FakeClock` (or the production clock parameter) and +assert the recorded duration, not the wall-clock duration of the test process; +do not use `asyncio.sleep` as synchronization. A real sleep may remain where +the test proves an external timeout, but the assertion reads the injected +clock. File-system stress tests that need real operations keep a generous +per-test timeout instead of a tight one. + +### A failed master run + +Read the failed job and its annotations before rerunning. A cancelled job with +`The job was not acquired by Runner of type hosted` is GitHub capacity, not a +test failure: rerun that job. A failed step is a real failure until its test or +harness is fixed; do not add a retry that hides it. The OpenClaw host lifecycle +keeps its per-command timeout in the JSON export, so a `timed_out` step names +the bound that was hit. + ### Optional coverage Coverage is a diagnostic, not a quality gate. It is not part of the default From 0f6aec677663aab3189f01e410ee9992e125d84c Mon Sep 17 00:00:00 2001 From: "seiko.iwasawa" Date: Tue, 1 Dec 2026 16:43:18 +0300 Subject: [PATCH 05/12] fix(ci): keep OpenClaw timeout evidence and strengthen timing test Add a lifecycle budget to the OpenClaw install check and pass 1140 s from the CI step, so a stalled cleanup cannot let the 20-minute step deadline kill the process before the JSON export is written. Record the budget and the effective per-step timeout in the export. Make the asset timing test advance FakeClock at the POST completion and at the evidence timeout, then assert the POST duration, so it fails when a timeout is recorded as the response completion. RM33; RM38; AC24; AC29. --- .github/workflows/ci.yml | 4 ++- CHANGELOG.md | 9 ++--- docs/TESTING.md | 5 +-- scripts/openclaw_install_check.py | 49 +++++++++++++++++++++++++--- tests/test_asset_operations.py | 14 +++++--- tests/test_ci_workflows.py | 7 ++-- tests/test_openclaw_install_check.py | 37 ++++++++++++++++++++- 7 files changed, 106 insertions(+), 19 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cbc6b17a..2c380875 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -260,7 +260,8 @@ jobs: - name: Pinned host lifecycle (install, inspect, round trips, removal) # The Windows runner spends 200-220 s in the host's npm install alone # (about 30 s on Linux and macOS), so its per-command bound is wider. - # A real hang still fails here instead of at the 60-minute job limit. + # The 19-minute lifecycle budget keeps a minute under this 20-minute + # step for Python startup and the export, even if cleanup stalls. timeout-minutes: 20 env: HOST_TIMEOUT: ${{ matrix.os == 'windows-latest' && '600' || '300' }} @@ -269,6 +270,7 @@ jobs: python scripts/openclaw_install_check.py --tarball "$tarball" \ --out "ci-evidence/openclaw-install-check-${{ matrix.os }}.json" \ --timeout "$HOST_TIMEOUT" \ + --budget 1140 \ --label "GitHub Actions ${{ matrix.os }} runner, Node $(node --version)" \ -- node integrations/openclaw/node_modules/openclaw/openclaw.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 317ea06a..16278342 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2814,10 +2814,11 @@ pre-release development. - CI stability (RM14; RM33; RM38; AC12; AC19; AC24; AC29): a requested cancel now outranks a later failure even when a provider consumes the task cancellation, the - Windows OpenClaw lifecycle gets a wider per-command timeout, the OpenClaw lock - tests no longer inherit Vitest's 5 s default, and the timing test reads an injected - clock instead of the wall clock. The cancel precedence follows the existing - section 7.4 rule; the other changes are test and CI only. + Windows OpenClaw lifecycle gets a wider per-command timeout and an overall + lifecycle budget that keeps the export inside the CI step deadline, the OpenClaw + lock tests no longer inherit Vitest's 5 s default, and the timing test advances an + injected clock and asserts the POST duration. The cancel precedence follows the + existing section 7.4 rule; the other changes are test and CI only. - Hardened automated-host control polling and provider-response failures. Future executions require explicit v2 control budgets and fresh preregistration; historical inputs and outcomes remain unchanged. Timeout paths retain the last recommendation state, and functional transport tests allow cold worker startup (RM03, RM05, RM16, RM44). diff --git a/docs/TESTING.md b/docs/TESTING.md index f8cde80f..04842477 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -65,8 +65,9 @@ Read the failed job and its annotations before rerunning. A cancelled job with `The job was not acquired by Runner of type hosted` is GitHub capacity, not a test failure: rerun that job. A failed step is a real failure until its test or harness is fixed; do not add a retry that hides it. The OpenClaw host lifecycle -keeps its per-command timeout in the JSON export, so a `timed_out` step names -the bound that was hit. +keeps its per-command timeout and the overall lifecycle budget in the JSON +export, so a `timed_out` step names the bound that was hit; the budget also +keeps time to write the export before the step deadline. ### Optional coverage diff --git a/scripts/openclaw_install_check.py b/scripts/openclaw_install_check.py index e45f2ec3..a7519ad1 100644 --- a/scripts/openclaw_install_check.py +++ b/scripts/openclaw_install_check.py @@ -47,7 +47,8 @@ Usage: python scripts/openclaw_install_check.py --tarball \\ --out [--label ""] [--target-platform] \\ - [--timeout 300] -- + [--timeout 300] [--budget 1140] \\ + -- """ import argparse @@ -179,6 +180,9 @@ def _redact_default_model(text: str) -> str: TOOL_CALL_ID = "call_read_1" TOOL_ANSWER = "The note says the lantern is on the second shelf." OUTPUT_TAIL = 4000 +# Kept free at the end of the lifecycle budget for the JSON export, so a +# stalled cleanup step cannot let the step deadline kill the process first. +EXPORT_RESERVE_SECONDS = 30.0 STEPS = ( "version", @@ -586,7 +590,14 @@ def _run(command: Sequence[str], args: list[str], stdin: str | None, env, timeou } -def run_steps(command: Sequence[str], ctx: Context, timeout: float) -> tuple[list, dict, str]: +def run_steps( + command: Sequence[str], + ctx: Context, + timeout: float, + *, + deadline: float | None = None, +) -> tuple[list, dict, str]: + """Run the host steps; ``deadline`` caps each command and leaves export time.""" steps: list[dict] = [] exchanges: dict[str, dict] = {} found: dict[str, dict] = {} @@ -610,10 +621,21 @@ def run_steps(command: Sequence[str], ctx: Context, timeout: float) -> tuple[lis continue if name in ("text-exchange", "tool-exchange"): exec_state_dir(ctx, name).mkdir(parents=True, exist_ok=True) + step_timeout = timeout + if deadline is not None: + remaining = deadline - time.monotonic() + if remaining <= 0: + step["reason"] = "lifecycle_budget_exhausted" + stopped = True + continue + step_timeout = min(timeout, remaining) + step["timeout_seconds"] = round(step_timeout, 3) before = set(qualification._run_ids(ctx.gateway)) requests_before = len(ctx.gateway.adapter.requests) try: - code, stdout, stderr, timed_out, seconds = _run(command, args, stdin, ctx.env, timeout) + code, stdout, stderr, timed_out, seconds = _run( + command, args, stdin, ctx.env, step_timeout + ) except OSError as error: # The host command cannot start: this step did not run. The rest # stays listed as not_run, and the cleanup still runs if installed. @@ -688,11 +710,18 @@ def run_install_check( out: Path, *, timeout: float = 300, + budget: float | None = None, label: str | None = None, target_platform: bool = False, host_home: Path | None = None, ) -> dict: - """Run the lifecycle against one doubles gateway; write and return the export.""" + """Run the lifecycle against one doubles gateway; write and return the export. + + ``budget`` bounds the whole check, including the export. The command + deadline keeps ``EXPORT_RESERVE_SECONDS`` free, so a stalled cleanup step + cannot let the CI step deadline kill the process before the export exists. + """ + started = time.monotonic() tarball = Path(tarball).resolve() # Removed by hand at the end: a file a host child still holds (Windows) # must never stop the export from being written. @@ -722,7 +751,10 @@ def run_install_check( gateway=gateway, gateway_port=_closed_port(), ) - steps, exchanges, status = run_steps(command, ctx, timeout) + deadline = None + if budget is not None: + deadline = started + budget - EXPORT_RESERVE_SECONDS + steps, exchanges, status = run_steps(command, ctx, timeout, deadline=deadline) found = exchanges.pop("_leftovers", {}) runs = qualification.run_records(gateway, qualification._run_ids(gateway)) version = next( @@ -749,6 +781,7 @@ def run_install_check( "gateway_port": ctx.gateway_port, }, "timeout_seconds": timeout, + "budget_seconds": budget, "token": NOT_RECORDED, "steps": steps, "exchanges": exchanges, @@ -777,6 +810,11 @@ def main(argv: Sequence[str] | None = None) -> int: parser.add_argument("--tarball", type=Path, required=True, help="the release artifact") parser.add_argument("--out", type=Path, required=True) parser.add_argument("--timeout", type=float, default=300, help="seconds per host command") + parser.add_argument( + "--budget", + type=float, + help="seconds for the whole check, including the export (default: no overall bound)", + ) parser.add_argument("--label", help="the machine and runtime, recorded in the export") parser.add_argument( "--target-platform", @@ -807,6 +845,7 @@ def main(argv: Sequence[str] | None = None) -> int: args.tarball, args.out, timeout=args.timeout, + budget=args.budget, label=args.label, target_platform=args.target_platform, ) diff --git a/tests/test_asset_operations.py b/tests/test_asset_operations.py index c7fa68b2..256872b2 100644 --- a/tests/test_asset_operations.py +++ b/tests/test_asset_operations.py @@ -692,25 +692,31 @@ async def go(): async with await client_for(app) as production: view = (await production.post("/relay/v1/recommendations", json=BODY)).json() + post_seconds = 0.01 + clock = FakeClock() + class SlowEvidence: async def post(self, *args, **kwargs): + clock.advance(post_seconds) return httpx.Response(200, json=view) async def get(self, *args, **kwargs): - await asyncio.sleep(0.05) + try: + await asyncio.sleep(0.2) + finally: + clock.advance(5.0) return httpx.Response(200, json={}) - clock = FakeClock() sample = await request_sample( SlowEvidence(), BODY, category="startup", ordinal=0, - deadline_at=clock.mono + 0.01, + deadline_at=clock.mono + 0.05, clock=clock.monotonic, ) assert sample.error == "evidence_timeout" - assert sample.client_elapsed_ms < 10 + assert sample.client_elapsed_ms == pytest.approx(post_seconds * 1000) finally: await service.stop() runs.close() diff --git a/tests/test_ci_workflows.py b/tests/test_ci_workflows.py index cb751d84..8e0b7e75 100644 --- a/tests/test_ci_workflows.py +++ b/tests/test_ci_workflows.py @@ -38,8 +38,9 @@ def test_openclaw_lifecycle_has_a_wider_windows_command_timeout(): The Windows runner spends roughly 200-220 s in the host's npm install, against about 30 s on Linux and macOS, so the shared 300 s default is - too tight there. The step also has its own bound, so a real hang ends - before the job timeout. + too tight there. The step also has its own bound, and the lifecycle + budget keeps time for the export inside that bound, so a real hang ends + before the job timeout and still leaves the timeout evidence. """ import yaml @@ -51,6 +52,8 @@ def test_openclaw_lifecycle_has_a_wider_windows_command_timeout(): assert (windows, linux) == ("600", "300") assert step["timeout-minutes"] == 20 assert '--timeout "$HOST_TIMEOUT"' in step["run"] + assert "--budget 1140" in step["run"] + assert 1140 < step["timeout-minutes"] * 60 @pytest.mark.parametrize( diff --git a/tests/test_openclaw_install_check.py b/tests/test_openclaw_install_check.py index 184575b7..6632da95 100644 --- a/tests/test_openclaw_install_check.py +++ b/tests/test_openclaw_install_check.py @@ -32,7 +32,7 @@ # The host stand-in. It keeps its config in OPENCLAW_CONFIG_PATH, its stored # credentials in a SQLite file under OPENCLAW_STATE_DIR, and logs each call. STUB_HOST = r""" -import json, os, sqlite3, sys, urllib.request +import json, os, sqlite3, sys, time, urllib.request from pathlib import Path args = sys.argv[1:] @@ -50,6 +50,9 @@ if fail and " ".join(args).startswith(fail): print("stub: refused " + fail, file=sys.stderr) raise SystemExit(1) +stall = [part for part in os.environ.get("STUB_STALL", "").split(",") if part] +if any(" ".join(args).startswith(part) for part in stall): + time.sleep(float(os.environ.get("STUB_STALL_SECONDS", "60"))) def load(): if not config_path.exists(): @@ -586,6 +589,21 @@ def test_the_main_entry_exits_by_the_result(stub_host, tarball, tmp_path, monkey install_check.main(["--tarball", str(tarball), "--out", str(out)]) +def test_the_main_entry_passes_the_lifecycle_budget(tarball, tmp_path, monkeypatch): + seen = {} + + def record(*args, **kwargs): + seen.update(kwargs) + return {"status": "completed", "passed": True, "steps": []} + + monkeypatch.setattr(install_check, "run_install_check", record) + monkeypatch.setattr(install_check.shutil, "which", lambda name: name) + out = tmp_path / "budget.json" + argv = ["--tarball", str(tarball), "--out", str(out), "--budget", "1140", "--", "openclaw"] + assert install_check.main(argv) == 0 + assert seen["budget"] == 1140 + + def test_the_main_entry_lists_only_the_steps_that_ran_and_failed( stub_host, tarball, tmp_path, monkeypatch, capsys ): @@ -844,6 +862,23 @@ def locked(path, *args, **kwargs): assert json.loads((tmp_path / "export.json").read_text("utf-8"))["passed"] is True +def test_a_lifecycle_budget_stops_a_stalled_cleanup_before_the_export( + stub_host, tarball, tmp_path, monkeypatch +): + """RM33/AC24: the overall budget keeps time for the export, not just one command.""" + monkeypatch.setenv("STUB_STALL", "plugins inspect,plugins uninstall") + monkeypatch.setenv("STUB_STALL_SECONDS", "10") + monkeypatch.setattr(install_check, "EXPORT_RESERVE_SECONDS", 0.1) + export = run(stub_host, tarball, tmp_path, timeout=10, budget=3) + status = {s["name"]: s["status"] for s in export["steps"]} + inspect = next(s for s in export["steps"] if s["name"] == "inspect") + assert status["inspect"] == "timed_out" + assert inspect["timeout_seconds"] < 10 + assert export["budget_seconds"] == 3 + assert (tmp_path / "export.json").is_file() + assert export["passed"] is False + + def _message(role, content, tool_call_id=None): return SimpleNamespace( role=SimpleNamespace(value=role), content=content, tool_call_id=tool_call_id From fac711a05e6dbda35f08ccc6f0ffe43d48370b60 Mon Sep 17 00:00:00 2001 From: "seiko.iwasawa" Date: Tue, 1 Dec 2026 18:03:02 +0300 Subject: [PATCH 06/12] fix(openclaw): stop the host tree on timeout and validate budgets (RM33; AC24) Run host commands in their own process group, stop the whole tree on timeout, and read stdout/stderr from temporary files so a Windows respawn cannot hold inherited pipes past the budget. Make the cleanup-deadline test inject the lifecycle clock, time out inspect promptly, stall uninstall, and assert the remaining budget and the export. Reject non-finite timeout and budget values before the lifecycle starts. --- CHANGELOG.md | 3 +- docs/TESTING.md | 3 +- scripts/openclaw_install_check.py | 103 +++++++++++++++---- tests/test_openclaw_install_check.py | 147 ++++++++++++++++++++++++--- 4 files changed, 219 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16278342..894af05f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2815,7 +2815,8 @@ pre-release development. - CI stability (RM14; RM33; RM38; AC12; AC19; AC24; AC29): a requested cancel now outranks a later failure even when a provider consumes the task cancellation, the Windows OpenClaw lifecycle gets a wider per-command timeout and an overall - lifecycle budget that keeps the export inside the CI step deadline, the OpenClaw + lifecycle budget that keeps the export inside the CI step deadline and stops the + host process tree on timeout, non-finite budget values are rejected, the OpenClaw lock tests no longer inherit Vitest's 5 s default, and the timing test advances an injected clock and asserts the POST duration. The cancel precedence follows the existing section 7.4 rule; the other changes are test and CI only. diff --git a/docs/TESTING.md b/docs/TESTING.md index 04842477..4df245c3 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -67,7 +67,8 @@ test failure: rerun that job. A failed step is a real failure until its test or harness is fixed; do not add a retry that hides it. The OpenClaw host lifecycle keeps its per-command timeout and the overall lifecycle budget in the JSON export, so a `timed_out` step names the bound that was hit; the budget also -keeps time to write the export before the step deadline. +keeps time to write the export before the step deadline, and a timed-out host +process tree is stopped before the export. ### Optional coverage diff --git a/scripts/openclaw_install_check.py b/scripts/openclaw_install_check.py index a7519ad1..5d9a746d 100644 --- a/scripts/openclaw_install_check.py +++ b/scripts/openclaw_install_check.py @@ -54,9 +54,12 @@ import argparse import hashlib import json +import math +import os import platform import re import shutil +import signal import socket import sqlite3 import subprocess @@ -561,27 +564,71 @@ def _path_forms(candidate: PurePath, home: PurePath) -> set[str]: return forms +def _stop_tree(process: subprocess.Popen) -> None: + """Stop the host and its children; Windows can respawn with inherited stdio.""" + if sys.platform == "win32": + if process.poll() is None: + try: + subprocess.run( + ["taskkill", "/T", "/F", "/PID", str(process.pid)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=10, + check=False, + ) + except (OSError, subprocess.TimeoutExpired): + pass + if process.poll() is None: + process.kill() + else: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + + def _run(command: Sequence[str], args: list[str], stdin: str | None, env, timeout: float): invocation = host_invocation(command, args) started = time.monotonic() - try: - completed = subprocess.run( + windows = sys.platform == "win32" + with ( + tempfile.TemporaryFile("w+", encoding="utf-8", errors="replace") as out, + tempfile.TemporaryFile("w+", encoding="utf-8", errors="replace") as err, + ): + process = subprocess.Popen( invocation, env=env, - input=stdin, - capture_output=True, + stdin=subprocess.PIPE if stdin is not None else subprocess.DEVNULL, + stdout=out, + stderr=err, text=True, - timeout=timeout, - ) - result = (completed.returncode, completed.stdout, completed.stderr, None) - except subprocess.TimeoutExpired as error: - result = ( - None, - qualification._text(error.stdout), - qualification._text(error.stderr), - "timed_out", + encoding="utf-8", + errors="replace", + start_new_session=not windows, + creationflags=(getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) if windows else 0), ) - return (*result, round(time.monotonic() - started, 3)) + if stdin is not None: + try: + process.stdin.write(stdin) + process.stdin.close() + except (BrokenPipeError, OSError): + pass + timed_out = None + try: + code = process.wait(timeout=timeout) + except subprocess.TimeoutExpired: + timed_out = "timed_out" + _stop_tree(process) + code = None + out.seek(0) + err.seek(0) + stdout, stderr = out.read(), err.read() + return code, stdout, stderr, timed_out, round(time.monotonic() - started, 3) CHECKS: dict[str, Callable[[str, Context], tuple[bool, dict]]] = { @@ -596,6 +643,7 @@ def run_steps( timeout: float, *, deadline: float | None = None, + clock: Callable[[], float] = time.monotonic, ) -> tuple[list, dict, str]: """Run the host steps; ``deadline`` caps each command and leaves export time.""" steps: list[dict] = [] @@ -623,7 +671,7 @@ def run_steps( exec_state_dir(ctx, name).mkdir(parents=True, exist_ok=True) step_timeout = timeout if deadline is not None: - remaining = deadline - time.monotonic() + remaining = deadline - clock() if remaining <= 0: step["reason"] = "lifecycle_budget_exhausted" stopped = True @@ -711,6 +759,7 @@ def run_install_check( *, timeout: float = 300, budget: float | None = None, + clock: Callable[[], float] = time.monotonic, label: str | None = None, target_platform: bool = False, host_home: Path | None = None, @@ -720,8 +769,13 @@ def run_install_check( ``budget`` bounds the whole check, including the export. The command deadline keeps ``EXPORT_RESERVE_SECONDS`` free, so a stalled cleanup step cannot let the CI step deadline kill the process before the export exists. + ``clock`` is the deadline clock; tests inject one to avoid wall-clock waits. """ - started = time.monotonic() + if not math.isfinite(timeout): + raise ValueError("timeout must be finite") + if budget is not None and not math.isfinite(budget): + raise ValueError("budget must be finite") + started = clock() tarball = Path(tarball).resolve() # Removed by hand at the end: a file a host child still holds (Windows) # must never stop the export from being written. @@ -754,7 +808,9 @@ def run_install_check( deadline = None if budget is not None: deadline = started + budget - EXPORT_RESERVE_SECONDS - steps, exchanges, status = run_steps(command, ctx, timeout, deadline=deadline) + steps, exchanges, status = run_steps( + command, ctx, timeout, deadline=deadline, clock=clock + ) found = exchanges.pop("_leftovers", {}) runs = qualification.run_records(gateway, qualification._run_ids(gateway)) version = next( @@ -805,14 +861,23 @@ def run_install_check( return json.loads(text) +def _finite_float(value: str) -> float: + number = float(value) + if not math.isfinite(number): + raise argparse.ArgumentTypeError("must be a finite number") + return number + + def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--tarball", type=Path, required=True, help="the release artifact") parser.add_argument("--out", type=Path, required=True) - parser.add_argument("--timeout", type=float, default=300, help="seconds per host command") + parser.add_argument( + "--timeout", type=_finite_float, default=300, help="seconds per host command" + ) parser.add_argument( "--budget", - type=float, + type=_finite_float, help="seconds for the whole check, including the export (default: no overall bound)", ) parser.add_argument("--label", help="the machine and runtime, recorded in the export") diff --git a/tests/test_openclaw_install_check.py b/tests/test_openclaw_install_check.py index 6632da95..1ece3ce2 100644 --- a/tests/test_openclaw_install_check.py +++ b/tests/test_openclaw_install_check.py @@ -17,22 +17,24 @@ import json import os import shutil +import signal import socket import sqlite3 +import subprocess import sys from pathlib import Path, PureWindowsPath from types import SimpleNamespace import pytest -from helpers import load_script_module +from helpers import FakeClock, load_script_module install_check = load_script_module("openclaw_install_check") # The host stand-in. It keeps its config in OPENCLAW_CONFIG_PATH, its stored # credentials in a SQLite file under OPENCLAW_STATE_DIR, and logs each call. STUB_HOST = r""" -import json, os, sqlite3, sys, time, urllib.request +import json, os, sqlite3, sys, urllib.request from pathlib import Path args = sys.argv[1:] @@ -50,9 +52,6 @@ if fail and " ".join(args).startswith(fail): print("stub: refused " + fail, file=sys.stderr) raise SystemExit(1) -stall = [part for part in os.environ.get("STUB_STALL", "").split(",") if part] -if any(" ".join(args).startswith(part) for part in stall): - time.sleep(float(os.environ.get("STUB_STALL_SECONDS", "60"))) def load(): if not config_path.exists(): @@ -604,6 +603,30 @@ def record(*args, **kwargs): assert seen["budget"] == 1140 +@pytest.mark.parametrize("value", ["nan", "inf", "-inf"]) +def test_a_non_finite_lifecycle_budget_is_refused(value, tarball, tmp_path, monkeypatch, capsys): + def no_run(*args, **kwargs): + raise AssertionError("the install check must not start") + + monkeypatch.setattr(install_check, "run_install_check", no_run) + out = tmp_path / "x.json" + with pytest.raises(SystemExit) as raised: + install_check.main( + ["--tarball", str(tarball), "--out", str(out), f"--budget={value}", "--", "openclaw"] + ) + assert raised.value.code == 2 + assert "finite" in capsys.readouterr().err + assert not out.exists() + + +def test_a_non_finite_budget_is_refused_before_the_lifecycle(tarball, tmp_path): + with pytest.raises(ValueError, match="finite"): + install_check.run_install_check( + ["openclaw"], tarball, tmp_path / "x.json", budget=float("nan") + ) + assert not (tmp_path / "x.json").exists() + + def test_the_main_entry_lists_only_the_steps_that_ran_and_failed( stub_host, tarball, tmp_path, monkeypatch, capsys ): @@ -672,12 +695,25 @@ def test_a_batch_host_command_is_run_through_cmd_on_windows(monkeypatch): """``_run`` passes the cmd.exe command line for a batch file on Windows.""" seen = [] - def fake_run(command, **_): + class FakeProcess: + returncode = 0 + + def wait(self, timeout=None): + return 0 + + def poll(self): + return 0 + + def kill(self): + pass + + def fake_popen(command, **kwargs): seen.append(command) - return SimpleNamespace(returncode=0, stdout="ok", stderr="") + kwargs["stdout"].write("ok") + return FakeProcess() monkeypatch.setattr(install_check.sys, "platform", "win32") - monkeypatch.setattr(install_check.subprocess, "run", fake_run) + monkeypatch.setattr(install_check.subprocess, "Popen", fake_popen) code, stdout, _, timed_out, _ = install_check._run( [r"C:\x\openclaw.cmd"], ["--version"], None, {}, 5 ) @@ -686,6 +722,68 @@ def fake_run(command, **_): assert '/s /c ""C:\\x\\openclaw.cmd" "--version""' in seen[0] +@pytest.mark.parametrize("platform", ["win32", "linux"]) +def test_a_timed_out_host_command_stops_the_process_tree(monkeypatch, platform): + """A host that respawns children must not outlive the timeout on either platform.""" + calls = [] + + class FakeProcess: + pid = 4321 + + def __init__(self): + self.returncode = None + self.timed_out = False + + def wait(self, timeout=None): + if self.returncode is None and not self.timed_out: + self.timed_out = True + raise subprocess.TimeoutExpired("host", timeout or 0) + self.returncode = -9 + return self.returncode + + def poll(self): + return self.returncode + + def kill(self): + self.returncode = -9 + + fake_process = FakeProcess() + + def fake_popen(command, **kwargs): + calls.append(("popen", command, kwargs)) + return fake_process + + monkeypatch.setattr(install_check.sys, "platform", platform) + monkeypatch.setattr(install_check.subprocess, "Popen", fake_popen) + if platform == "win32": + + def fake_run(command, **kwargs): + calls.append(("taskkill", command, kwargs)) + return SimpleNamespace(returncode=0) + + monkeypatch.setattr(install_check.subprocess, "run", fake_run) + else: + + def fake_killpg(pid, sig): + calls.append(("killpg", pid, sig)) + + monkeypatch.setattr(install_check.os, "killpg", fake_killpg) + + code, stdout, stderr, timed_out, _ = install_check._run( + ["openclaw"], ["plugins", "uninstall", "relaymind", "--force"], None, {}, 5 + ) + assert (code, stdout, stderr, timed_out) == (None, "", "", "timed_out") + popen = next(call for call in calls if call[0] == "popen") + if platform == "win32": + assert popen[2]["start_new_session"] is False + taskkill = next(call for call in calls if call[0] == "taskkill") + assert taskkill[1] == ["taskkill", "/T", "/F", "/PID", "4321"] + else: + assert popen[2]["start_new_session"] is True + killpg = next(call for call in calls if call[0] == "killpg") + assert killpg[1:] == (4321, signal.SIGKILL) + + @pytest.mark.skipif(sys.platform != "win32", reason="a batch file runs only on Windows") def test_the_whole_lifecycle_passes_through_a_cmd_shim_on_windows(stub_host, tarball, tmp_path): """The host behind an npm-style ``.cmd`` shim, as ``openclaw`` is on Windows @@ -865,16 +963,33 @@ def locked(path, *args, **kwargs): def test_a_lifecycle_budget_stops_a_stalled_cleanup_before_the_export( stub_host, tarball, tmp_path, monkeypatch ): - """RM33/AC24: the overall budget keeps time for the export, not just one command.""" - monkeypatch.setenv("STUB_STALL", "plugins inspect,plugins uninstall") - monkeypatch.setenv("STUB_STALL_SECONDS", "10") - monkeypatch.setattr(install_check, "EXPORT_RESERVE_SECONDS", 0.1) - export = run(stub_host, tarball, tmp_path, timeout=10, budget=3) + """RM33/AC24: cleanup gets only the remaining budget and the export is written.""" + clock = FakeClock() + seen = {} + + def fake_run(command, args, stdin, env, timeout): + if args[:2] == ["plugins", "inspect"]: + clock.advance(1.0) + return (None, "", "", "timed_out", 1.0) + if args[:2] == ["plugins", "uninstall"]: + seen["uninstall_timeout"] = timeout + clock.advance(timeout) + return (None, "", "", "timed_out", timeout) + clock.advance(0.1) + return (0, "", "", None, 0.1) + + monkeypatch.setattr(install_check, "EXPORT_RESERVE_SECONDS", 0.5) + monkeypatch.setattr(install_check, "_run", fake_run) + export = run(stub_host, tarball, tmp_path, timeout=10, budget=10, clock=clock.monotonic) status = {s["name"]: s["status"] for s in export["steps"]} - inspect = next(s for s in export["steps"] if s["name"] == "inspect") + uninstall = next(s for s in export["steps"] if s["name"] == "uninstall") assert status["inspect"] == "timed_out" - assert inspect["timeout_seconds"] < 10 - assert export["budget_seconds"] == 3 + assert status["uninstall"] == "timed_out" + assert 0 < uninstall["timeout_seconds"] < 10 + assert seen["uninstall_timeout"] == pytest.approx(uninstall["timeout_seconds"]) + assert status["remove-config"] == "not_run" + assert status["remove-credential"] == "not_run" + assert export["budget_seconds"] == 10 assert (tmp_path / "export.json").is_file() assert export["passed"] is False From 103812e2b50a3f359c2fb2aabcd16876c2ace8f0 Mon Sep 17 00:00:00 2001 From: "seiko.iwasawa" Date: Tue, 1 Dec 2026 21:11:13 +0300 Subject: [PATCH 07/12] test(openclaw): skip the POSIX process-tree case on Windows (RM33; AC24) The linux parameter patches os.killpg and asserts signal.SIGKILL, both POSIX-only, so it cannot run on Windows. The win32 parameter still covers the Windows branch, and the POSIX branch remains covered on Linux and macOS. --- tests/test_openclaw_install_check.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/test_openclaw_install_check.py b/tests/test_openclaw_install_check.py index 1ece3ce2..baea29b6 100644 --- a/tests/test_openclaw_install_check.py +++ b/tests/test_openclaw_install_check.py @@ -722,7 +722,19 @@ def fake_popen(command, **kwargs): assert '/s /c ""C:\\x\\openclaw.cmd" "--version""' in seen[0] -@pytest.mark.parametrize("platform", ["win32", "linux"]) +@pytest.mark.parametrize( + "platform", + [ + "win32", + pytest.param( + "linux", + marks=pytest.mark.skipif( + sys.platform == "win32", + reason="os.killpg and signal.SIGKILL are POSIX-only", + ), + ), + ], +) def test_a_timed_out_host_command_stops_the_process_tree(monkeypatch, platform): """A host that respawns children must not outlive the timeout on either platform.""" calls = [] From 188af77966aa0591e3393dd3c1394a102251dc9a Mon Sep 17 00:00:00 2001 From: "seiko.iwasawa" Date: Tue, 1 Dec 2026 21:13:25 +0300 Subject: [PATCH 08/12] fix(openclaw): keep timeout evidence when killpg raises PermissionError (RM33; AC24) Treat a PermissionError from os.killpg like a missing process. The timeout path still reaps the child, reads the captured stdout/stderr, and reports timed_out instead of falling through to run_steps' OSError path, which recorded the step as not_run. --- CHANGELOG.md | 7 +++-- scripts/openclaw_install_check.py | 2 +- tests/test_openclaw_install_check.py | 45 ++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 894af05f..9b2811bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2818,8 +2818,11 @@ pre-release development. lifecycle budget that keeps the export inside the CI step deadline and stops the host process tree on timeout, non-finite budget values are rejected, the OpenClaw lock tests no longer inherit Vitest's 5 s default, and the timing test advances an - injected clock and asserts the POST duration. The cancel precedence follows the - existing section 7.4 rule; the other changes are test and CI only. + injected clock and asserts the POST duration, the POSIX process-tree test is + skipped on Windows, and a `PermissionError` from `os.killpg` is treated as an + already-gone process so a timed-out macOS step keeps its timeout status and + captured output. The cancel precedence follows the existing section 7.4 rule; the + other changes harden the OpenClaw lifecycle and its CI coverage. - Hardened automated-host control polling and provider-response failures. Future executions require explicit v2 control budgets and fresh preregistration; historical inputs and outcomes remain unchanged. Timeout paths retain the last recommendation state, and functional transport tests allow cold worker startup (RM03, RM05, RM16, RM44). diff --git a/scripts/openclaw_install_check.py b/scripts/openclaw_install_check.py index 5d9a746d..49ce2e6c 100644 --- a/scripts/openclaw_install_check.py +++ b/scripts/openclaw_install_check.py @@ -583,7 +583,7 @@ def _stop_tree(process: subprocess.Popen) -> None: else: try: os.killpg(process.pid, signal.SIGKILL) - except ProcessLookupError: + except (ProcessLookupError, PermissionError): pass try: process.wait(timeout=10) diff --git a/tests/test_openclaw_install_check.py b/tests/test_openclaw_install_check.py index baea29b6..571773e4 100644 --- a/tests/test_openclaw_install_check.py +++ b/tests/test_openclaw_install_check.py @@ -796,6 +796,51 @@ def fake_killpg(pid, sig): assert killpg[1:] == (4321, signal.SIGKILL) +@pytest.mark.skipif(sys.platform == "win32", reason="os.killpg is POSIX-only") +def test_a_permission_error_from_killpg_keeps_the_timeout_evidence(monkeypatch): + """A macOS EPERM from killpg must not escape _run and lose the timeout evidence.""" + + class FakeProcess: + pid = 4321 + + def __init__(self): + self.returncode = None + self.timed_out = False + + def wait(self, timeout=None): + if not self.timed_out: + self.timed_out = True + raise subprocess.TimeoutExpired("host", timeout or 0) + self.returncode = -9 + return self.returncode + + def poll(self): + return self.returncode + + def kill(self): + self.returncode = -9 + + process = FakeProcess() + + def fake_popen(command, **kwargs): + kwargs["stdout"].write("host stdout") + kwargs["stderr"].write("host stderr") + return process + + def fake_killpg(pid, sig): + raise PermissionError("process group is gone") + + monkeypatch.setattr(install_check.sys, "platform", "linux") + monkeypatch.setattr(install_check.subprocess, "Popen", fake_popen) + monkeypatch.setattr(install_check.os, "killpg", fake_killpg) + + code, stdout, stderr, timed_out, _ = install_check._run( + ["openclaw"], ["plugins", "uninstall", "relaymind", "--force"], None, {}, 5 + ) + assert (code, timed_out) == (None, "timed_out") + assert (stdout, stderr) == ("host stdout", "host stderr") + + @pytest.mark.skipif(sys.platform != "win32", reason="a batch file runs only on Windows") def test_the_whole_lifecycle_passes_through_a_cmd_shim_on_windows(stub_host, tarball, tmp_path): """The host behind an npm-style ``.cmd`` shim, as ``openclaw`` is on Windows From 540225a5d0f99da8b453fb7cc7ddea77be22e119 Mon Sep 17 00:00:00 2001 From: "seiko.iwasawa" Date: Tue, 1 Dec 2026 21:55:33 +0300 Subject: [PATCH 09/12] fix(orchestrator): keep cancel precedence across escalations and late failures (RM14; AC12) --- src/relaymind/orchestrator/client_loop.py | 2 + src/relaymind/orchestrator/generation.py | 11 ++++ src/relaymind/orchestrator/local_loop.py | 4 ++ tests/test_ac12_cancellation.py | 73 +++++++++++++++++++++++ tests/test_gated_streaming.py | 53 ++++++++++++++++ 5 files changed, 143 insertions(+) diff --git a/src/relaymind/orchestrator/client_loop.py b/src/relaymind/orchestrator/client_loop.py index 9e4b5db1..95c3052f 100644 --- a/src/relaymind/orchestrator/client_loop.py +++ b/src/relaymind/orchestrator/client_loop.py @@ -378,6 +378,8 @@ def _unique(self, call: ToolCall) -> ToolCall: async def _escalate_client(self, stop: Escalation) -> RunOutcome: """Fall back to the external model before anything is exposed, or stop (RM04).""" + if self.cancel_requested: + return self._cancel() external = self.o.external if external is None or self.mode is ExecutionMode.LOCAL_ONLY or not stop.hand_off: return self._needs_external(stop) diff --git a/src/relaymind/orchestrator/generation.py b/src/relaymind/orchestrator/generation.py index b0697da0..f155630a 100644 --- a/src/relaymind/orchestrator/generation.py +++ b/src/relaymind/orchestrator/generation.py @@ -334,10 +334,18 @@ def check_live() -> None: failure = GenerationFailed(code="time_budget", message=f"{exhausted.budget} spent") self._cancel_call(call_id) except BudgetExceededError as exc: + task = asyncio.current_task() + if self.cancel_requested or (task is not None and task.cancelling()): + failure = GenerationFailed(code="cancelled", message="model generation interrupted") + raise asyncio.CancelledError from None exhausted = exc failure = GenerationFailed(code="time_budget", message=f"{exc.budget} spent") self._cancel_call(call_id) except Exception as exc: + task = asyncio.current_task() + if self.cancel_requested or (task is not None and task.cancelling()): + failure = GenerationFailed(code="cancelled", message="model generation interrupted") + raise asyncio.CancelledError from None failure = GenerationFailed(code="interrupted", message="model generation interrupted") if gate is None or gating or isinstance(exc, _PublicationFailure): raise @@ -390,6 +398,9 @@ def check_live() -> None: else {"code": failure.code, "message": self.scrub(failure.message)}, }, ) + task = asyncio.current_task() + if self.cancel_requested or (task is not None and task.cancelling()): + raise asyncio.CancelledError if exhausted is not None: raise exhausted if deadline_missed: diff --git a/src/relaymind/orchestrator/local_loop.py b/src/relaymind/orchestrator/local_loop.py index 8987d0fe..2f8762c0 100644 --- a/src/relaymind/orchestrator/local_loop.py +++ b/src/relaymind/orchestrator/local_loop.py @@ -1634,6 +1634,8 @@ async def _run_local(self, loop: _Loop, confirmed: _Confirmation | None = None) def _clarify(self, routing: Routing) -> RunOutcome: """Suspend in waiting_input, or fail once the clarification rounds are spent.""" + if self.cancel_requested: + return self._cancel() decision = routing.decision assert decision.clarification is not None if not routing.missing or not routing.missing.strip(): @@ -1858,6 +1860,8 @@ async def _escalate(self, stop: Escalation) -> RunOutcome: anything is sent (RM13). A stop the external stage could not resolve either does not hand off (section 4.4). """ + if self.cancel_requested: + return self._cancel() if self.authority.answer_owner is not None: return self._fail( EXTERNAL_FAILED, detail=stop.detail, reason_code=stop.reason_code, **stop.extra diff --git a/tests/test_ac12_cancellation.py b/tests/test_ac12_cancellation.py index 4d1b45fc..0319d13e 100644 --- a/tests/test_ac12_cancellation.py +++ b/tests/test_ac12_cancellation.py @@ -550,3 +550,76 @@ async def go(): finished = delete_finished(events) assert finished.payload["result"]["status"] == "unknown_outcome" assert len(handler.calls) == 1 + + +def test_escalation_after_a_cancel_returns_cancelled(tmp_path, monkeypatch): + """RM14, AC12: a requested cancel beats a local failure that would hand off.""" + from relaymind.orchestrator.local_loop import Escalation, _Run + + gateway = build_gateway(tmp_path, [], external_turns=[]) + run = _Run(gateway.orchestrator, user("hello"), None, None) + run.open() + run.cancel_requested = True + + async def no_handoff(*args, **kwargs): + raise AssertionError("handoff after cancel") + + def no_needs_external(stop): + raise AssertionError("needs_external after cancel") + + monkeypatch.setattr(run, "_hand_off", no_handoff) + monkeypatch.setattr(run, "_needs_external", no_needs_external) + outcome = asyncio.run(run._escalate(Escalation("capability_missing", "test", hand_off=True))) + assert outcome.state is RunState.CANCELLED + assert gateway.store.get_run(run.run_id).state == "cancelled" + + +def test_client_escalation_after_a_cancel_returns_cancelled(tmp_path, monkeypatch): + """RM14, AC12: a client-owned escalation does not measure or move after cancel.""" + from relaymind.orchestrator.client_loop import ToolOffer, _ClientRun + from relaymind.orchestrator.local_loop import Escalation + + gateway = build_gateway(tmp_path, [], external_turns=[]) + run = _ClientRun( + gateway.orchestrator, + user("hello"), + ToolOffer(), + None, + "relaymind-client-tools", + None, + ) + run.open() + run.cancel_requested = True + monkeypatch.setattr(run.meter, "external_room", lambda: None) + + async def no_measure(*args, **kwargs): + raise AssertionError("external measure after cancel") + + monkeypatch.setattr(run, "_measure", no_measure) + outcome = asyncio.run( + run._escalate_client(Escalation("capability_missing", "test", hand_off=True)) + ) + assert outcome.state is RunState.CANCELLED + assert gateway.store.get_run(run.run_id).state == "cancelled" + + +def test_clarification_after_a_cancel_returns_cancelled(tmp_path): + """RM14, AC12: a cancel beats a clarification wait.""" + from relaymind.orchestrator.local_loop import _Run + from relaymind.orchestrator.route_decision import Language, Route, RouteDecision + from relaymind.orchestrator.router import Routing + + gateway = build_gateway(tmp_path, []) + run = _Run(gateway.orchestrator, user("hello"), None, None) + run.open() + run.cancel_requested = True + decision = RouteDecision( + route=Route.CLARIFY, + skill_id=None, + language=Language.EN, + reason_code="missing_input", + clarification="Which service?", + ) + outcome = run._clarify(Routing(decision, missing="service")) + assert outcome.state is RunState.CANCELLED + assert gateway.store.get_run(run.run_id).state == "cancelled" diff --git a/tests/test_gated_streaming.py b/tests/test_gated_streaming.py index ca9a6038..9b4687ec 100644 --- a/tests/test_gated_streaming.py +++ b/tests/test_gated_streaming.py @@ -410,6 +410,59 @@ async def generate(request): asyncio.run(scenario()) +@pytest.mark.parametrize("failure", ["budget", "runtime"]) +def test_disconnect_cancel_wins_when_provider_raises_after_cancel(tmp_path, failure): + """RM14/AC12/AC19: a cancel wins over a late provider budget or generic failure.""" + from api_helpers import make_app + from relaymind.api.native import NativeSettings + from relaymind.orchestrator.budgets import BudgetExceededError + from test_chat_disconnect_cancel import chat_client, until + + async def scenario(): + gateway = build_gateway( + tmp_path, + [route_turn("check-service-health"), *health_tail()[:-1]], + performance=PerformanceSettings(answer_stream="live", early_headers=True), + ) + original = gateway.adapter.generate + entered = asyncio.Event() + + async def generate(request): + if not request.generation_id.endswith("_final"): + async for event in original(request): + yield event + return + yield TextDelta(STAGING_OK + " ") + entered.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + task = asyncio.current_task() + assert task is not None + task.uncancel() + gateway.clock.advance(1000) + if failure == "budget": + raise BudgetExceededError("active_seconds", 1) from None + raise RuntimeError("provider failed after cancel") from None + + gateway.adapter.generate = generate + client = chat_client( + make_app(gateway, native=NativeSettings(heartbeat_seconds=0.01)), stream=True + ).start() + await asyncio.wait_for(entered.wait(), 1) + await until(lambda: any(STAGING_OK.encode() in m.get("body", b"") for m in client.sent)) + await client.leave() + run_id = gateway.adapter.requests[0].generation_id.split("_gen")[0] + record = gateway.store.get_run(run_id) + events = gateway.store.events(record.run_id) + assert record.state == "cancelled", (record.state, record.error_code) + assert not of_type(events, "run.failed") + assert of_type(events, "model.finished")[-1].payload["error"]["code"] == "cancelled" + assert len(gateway.adapter.cancelled) == 1 + + asyncio.run(scenario()) + + @pytest.mark.parametrize( "bounds, expected_budget, expected_reason", [ From e67749747cdbea12173c5ebf4d7b19ab617c5cd6 Mon Sep 17 00:00:00 2001 From: "seiko.iwasawa" Date: Tue, 1 Dec 2026 21:55:39 +0300 Subject: [PATCH 10/12] fix(openclaw): reject non-positive lifecycle bounds (RM33; AC24) --- scripts/openclaw_install_check.py | 28 +++++++++++++++----- tests/test_openclaw_install_check.py | 38 ++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 6 deletions(-) diff --git a/scripts/openclaw_install_check.py b/scripts/openclaw_install_check.py index 49ce2e6c..2d7e9afa 100644 --- a/scripts/openclaw_install_check.py +++ b/scripts/openclaw_install_check.py @@ -771,10 +771,10 @@ def run_install_check( cannot let the CI step deadline kill the process before the export exists. ``clock`` is the deadline clock; tests inject one to avoid wall-clock waits. """ - if not math.isfinite(timeout): - raise ValueError("timeout must be finite") - if budget is not None and not math.isfinite(budget): - raise ValueError("budget must be finite") + if not math.isfinite(timeout) or timeout <= 0: + raise ValueError("timeout must be positive and finite") + if budget is not None and (not math.isfinite(budget) or budget <= EXPORT_RESERVE_SECONDS): + raise ValueError("budget must be finite and greater than the export reserve") started = clock() tarball = Path(tarball).resolve() # Removed by hand at the end: a file a host child still holds (Windows) @@ -868,16 +868,32 @@ def _finite_float(value: str) -> float: return number +def _positive_float(value: str) -> float: + number = _finite_float(value) + if number <= 0: + raise argparse.ArgumentTypeError("must be positive") + return number + + +def _lifecycle_budget(value: str) -> float: + number = _finite_float(value) + if number <= EXPORT_RESERVE_SECONDS: + raise argparse.ArgumentTypeError( + f"must be greater than the export reserve ({EXPORT_RESERVE_SECONDS:g} s)" + ) + return number + + def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--tarball", type=Path, required=True, help="the release artifact") parser.add_argument("--out", type=Path, required=True) parser.add_argument( - "--timeout", type=_finite_float, default=300, help="seconds per host command" + "--timeout", type=_positive_float, default=300, help="seconds per host command" ) parser.add_argument( "--budget", - type=_finite_float, + type=_lifecycle_budget, help="seconds for the whole check, including the export (default: no overall bound)", ) parser.add_argument("--label", help="the machine and runtime, recorded in the export") diff --git a/tests/test_openclaw_install_check.py b/tests/test_openclaw_install_check.py index 571773e4..415c9184 100644 --- a/tests/test_openclaw_install_check.py +++ b/tests/test_openclaw_install_check.py @@ -627,6 +627,44 @@ def test_a_non_finite_budget_is_refused_before_the_lifecycle(tarball, tmp_path): assert not (tmp_path / "x.json").exists() +@pytest.mark.parametrize( + ("flag", "value", "message"), + [ + ("--timeout", "0", "positive"), + ("--timeout", "-1", "positive"), + ("--budget", "0", "export reserve"), + ("--budget", "30", "export reserve"), + ], +) +def test_a_non_positive_lifecycle_bound_is_refused( + flag, value, message, tarball, tmp_path, monkeypatch, capsys +): + def no_run(*args, **kwargs): + raise AssertionError("the install check must not start") + + monkeypatch.setattr(install_check, "run_install_check", no_run) + out = tmp_path / "x.json" + with pytest.raises(SystemExit) as raised: + install_check.main( + ["--tarball", str(tarball), "--out", str(out), f"{flag}={value}", "--", "openclaw"] + ) + assert raised.value.code == 2 + assert message in capsys.readouterr().err + assert not out.exists() + + +@pytest.mark.parametrize( + ("timeout", "budget"), + [(0, None), (-1, None), (300, 0), (300, 30)], +) +def test_a_non_positive_bound_is_refused_before_the_lifecycle(timeout, budget, tarball, tmp_path): + with pytest.raises(ValueError, match="positive|export reserve"): + install_check.run_install_check( + ["openclaw"], tarball, tmp_path / "x.json", timeout=timeout, budget=budget + ) + assert not (tmp_path / "x.json").exists() + + def test_the_main_entry_lists_only_the_steps_that_ran_and_failed( stub_host, tarball, tmp_path, monkeypatch, capsys ): From 95743426b085c9fd90786887f69418fada10cd12 Mon Sep 17 00:00:00 2001 From: "seiko.iwasawa" Date: Tue, 1 Dec 2026 22:18:35 +0300 Subject: [PATCH 11/12] fix(orchestrator): recheck cancel after external measurement and parallel join (RM14; AC12) --- src/relaymind/orchestrator/client_loop.py | 2 + src/relaymind/orchestrator/local_loop.py | 10 ++ tests/test_ac12_cancellation.py | 140 ++++++++++++++++++++++ 3 files changed, 152 insertions(+) diff --git a/src/relaymind/orchestrator/client_loop.py b/src/relaymind/orchestrator/client_loop.py index 95c3052f..e71197b1 100644 --- a/src/relaymind/orchestrator/client_loop.py +++ b/src/relaymind/orchestrator/client_loop.py @@ -400,6 +400,8 @@ async def _escalate_client(self, stop: Escalation) -> RunOutcome: detail=f"the external request could not be prepared: {exc}", reason_code=stop.reason_code, ) + if self.cancel_requested: + return self._cancel() if not size.fits: return self._fail_context(size) local_boundary = self.o.clock.monotonic() diff --git a/src/relaymind/orchestrator/local_loop.py b/src/relaymind/orchestrator/local_loop.py index 2f8762c0..fc067a41 100644 --- a/src/relaymind/orchestrator/local_loop.py +++ b/src/relaymind/orchestrator/local_loop.py @@ -2001,6 +2001,8 @@ async def _hand_off( anything is sent. extra adds payload fields to handoff.started. prefetch runs the skill's declared calls first (RM29). """ + if self.cancel_requested: + return self._cancel() try: if capabilities is None: capabilities = await external.adapter.capabilities() @@ -2015,6 +2017,8 @@ async def _hand_off( detail=f"the external request could not be prepared: {exc}", reason_code=stop.reason_code, ) + if self.cancel_requested: + return self._cancel() if not size.fits: return self._fail_context(size) local_boundary = self.o.clock.monotonic() @@ -2244,6 +2248,8 @@ async def _run_parallel(self, decision: RouteDecision) -> RunOutcome: one branch cancels the other, and the calls of both stay in the inventory of the terminal event (section 12.1). """ + if self.cancel_requested: + return self._cancel() external = self.o.external if external is None: raise Escalation(PARALLEL_WORKFLOW, "no external model is configured", hand_off=False) @@ -2279,6 +2285,8 @@ async def _run_parallel(self, decision: RouteDecision) -> RunOutcome: detail=f"the draft request could not be measured: {exc}", reason_code=PARALLEL_WORKFLOW, ) + if self.cancel_requested: + return self._cancel() if not size.fits: return self._fail_context(size) self.move(RunState.PARALLEL_RUNNING) @@ -2304,6 +2312,8 @@ async def _run_parallel(self, decision: RouteDecision) -> RunOutcome: for task in unfinished: task.cancel() await asyncio.gather(*unfinished, return_exceptions=True) + if self.cancel_requested: + return self._cancel() failed = self._failed_branch(local, draft) if failed is not None: return failed diff --git a/tests/test_ac12_cancellation.py b/tests/test_ac12_cancellation.py index 0319d13e..5bac4f3b 100644 --- a/tests/test_ac12_cancellation.py +++ b/tests/test_ac12_cancellation.py @@ -623,3 +623,143 @@ def test_clarification_after_a_cancel_returns_cancelled(tmp_path): outcome = run._clarify(Routing(decision, missing="service")) assert outcome.state is RunState.CANCELLED assert gateway.store.get_run(run.run_id).state == "cancelled" + + +def test_client_escalation_cancel_during_measure_returns_cancelled(tmp_path, monkeypatch): + """RM14, AC12: a cancel during the external measurement stops the handoff.""" + from relaymind.orchestrator.client_loop import ToolOffer, _ClientRun + from relaymind.orchestrator.handoff import RequestSize + from relaymind.orchestrator.local_loop import Escalation + + gateway = build_gateway(tmp_path, [], external_turns=[]) + run = _ClientRun( + gateway.orchestrator, + user("hello"), + ToolOffer(), + None, + "relaymind-client-tools", + None, + ) + run.open() + monkeypatch.setattr(run.meter, "external_room", lambda: None) + + async def measure(adapter): + run.cancel_requested = True + return RequestSize(1, 100, "utf8_bytes") + + async def no_converse(*args, **kwargs): + raise AssertionError("external stage after cancel") + + monkeypatch.setattr(run, "_measure", measure) + monkeypatch.setattr(run, "_converse", no_converse) + outcome = asyncio.run( + run._escalate_client(Escalation("capability_missing", "test", hand_off=True)) + ) + assert outcome.state is RunState.CANCELLED + assert gateway.store.get_run(run.run_id).state == "cancelled" + + +def test_handoff_cancel_during_measure_returns_cancelled(tmp_path, monkeypatch): + """RM14, AC12: a cancel during the external measurement stops the handoff.""" + from types import SimpleNamespace + + from relaymind.orchestrator import local_loop + from relaymind.orchestrator.handoff import RequestSize + from relaymind.orchestrator.local_loop import Escalation, _Run + + gateway = build_gateway(tmp_path, []) + run = _Run(gateway.orchestrator, user("hello"), None, None) + run.open() + + async def measure(*args): + run.cancel_requested = True + return RequestSize(1, 100, "utf8_bytes") + + async def no_external(*args, **kwargs): + raise AssertionError("external stage after cancel") + + monkeypatch.setattr(local_loop, "measure_request", measure) + monkeypatch.setattr(run, "_run_external", no_external) + envelope = SimpleNamespace(skill=None, operation_ids=(), allowed_tools=()) + loop = SimpleNamespace(schemas=(), conversation=()) + external = SimpleNamespace(adapter=object(), model_id="external") + outcome = asyncio.run( + run._hand_off( + external, + envelope, + loop, + Escalation("capability_missing", "test", hand_off=True), + {}, + capabilities=object(), + ) + ) + assert outcome.state is RunState.CANCELLED + assert gateway.store.get_run(run.run_id).state == "cancelled" + + +def _parallel_run(tmp_path, monkeypatch): + from types import SimpleNamespace + + from relaymind.orchestrator import local_loop + from relaymind.orchestrator.local_loop import _Run + from relaymind.orchestrator.route_decision import Language + + gateway = build_gateway(tmp_path, [], external_turns=[]) + run = _Run(gateway.orchestrator, user("hello"), None, None) + run.open() + run.language = Language.EN + skill = SimpleNamespace(parallel_workflow="workflow") + loop = SimpleNamespace(skill=skill, schemas=()) + monkeypatch.setattr(run, "_local_setup", lambda decision, read_only=False: loop) + monkeypatch.setattr(run.meter, "external_room", lambda **kwargs: None) + + async def no_synthesize(*args, **kwargs): + raise AssertionError("synthesis after cancel") + + monkeypatch.setattr(run, "_synthesize", no_synthesize) + return gateway, run, local_loop + + +def test_parallel_cancel_during_measure_returns_cancelled(tmp_path, monkeypatch): + """RM14, AC12: a cancel during the draft measurement stops the workflow.""" + from relaymind.orchestrator.handoff import RequestSize + + gateway, run, local_loop = _parallel_run(tmp_path, monkeypatch) + + async def measure(*args): + run.cancel_requested = True + return RequestSize(1, 100, "utf8_bytes") + + async def branch(*args, **kwargs): + return None + + monkeypatch.setattr(local_loop, "measure_request", measure) + monkeypatch.setattr(run, "_local_health_branch", branch) + monkeypatch.setattr(run, "_checklist_branch", branch) + outcome = asyncio.run(run._run_parallel(None)) + assert outcome.state is RunState.CANCELLED + assert gateway.store.get_run(run.run_id).state == "cancelled" + + +def test_parallel_cancel_after_branches_returns_cancelled(tmp_path, monkeypatch): + """RM14, AC12: a cancel after both branches finish does not start the synthesis.""" + from relaymind.orchestrator.handoff import RequestSize + + gateway, run, local_loop = _parallel_run(tmp_path, monkeypatch) + + async def measure(*args): + return RequestSize(1, 100, "utf8_bytes") + + async def local_branch(*args, **kwargs): + run.cancel_requested = True + raise asyncio.CancelledError + + async def draft_branch(*args, **kwargs): + return None + + monkeypatch.setattr(local_loop, "measure_request", measure) + monkeypatch.setattr(run, "_local_health_branch", local_branch) + monkeypatch.setattr(run, "_checklist_branch", draft_branch) + outcome = asyncio.run(run._run_parallel(None)) + assert outcome.state is RunState.CANCELLED + assert gateway.store.get_run(run.run_id).state == "cancelled" From b26e45ad010694a35fba95b8535fad1f2eb2ea33 Mon Sep 17 00:00:00 2001 From: "seiko.iwasawa" Date: Tue, 1 Dec 2026 22:35:22 +0300 Subject: [PATCH 12/12] test(orchestrator): assert the parallel workflow does not start after cancel (RM14; AC12) --- tests/test_ac12_cancellation.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_ac12_cancellation.py b/tests/test_ac12_cancellation.py index 5bac4f3b..8c7c55db 100644 --- a/tests/test_ac12_cancellation.py +++ b/tests/test_ac12_cancellation.py @@ -739,6 +739,7 @@ async def branch(*args, **kwargs): outcome = asyncio.run(run._run_parallel(None)) assert outcome.state is RunState.CANCELLED assert gateway.store.get_run(run.run_id).state == "cancelled" + assert run.workflow is None def test_parallel_cancel_after_branches_returns_cancelled(tmp_path, monkeypatch):