diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4723dbd6..2c380875 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,19 @@ 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. + # 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' }} 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" \ + --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 9d7ba598..9b2811bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2812,6 +2812,18 @@ 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 and an overall + 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 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). - 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..4df245c3 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -49,6 +49,27 @@ 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 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, and a timed-out host +process tree is stopped before the export. + ### Optional coverage Coverage is a diagnostic, not a quality gate. It is not part of the default 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..2d7e9afa 100644 --- a/scripts/openclaw_install_check.py +++ b/scripts/openclaw_install_check.py @@ -47,15 +47,19 @@ Usage: python scripts/openclaw_install_check.py --tarball \\ --out [--label ""] [--target-platform] \\ - [--timeout 300] -- + [--timeout 300] [--budget 1140] \\ + -- """ import argparse import hashlib import json +import math +import os import platform import re import shutil +import signal import socket import sqlite3 import subprocess @@ -179,6 +183,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", @@ -557,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, PermissionError): + 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, + encoding="utf-8", + errors="replace", + start_new_session=not windows, + creationflags=(getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) if windows else 0), ) - 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", - ) - 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]]] = { @@ -586,7 +637,15 @@ 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, + clock: Callable[[], float] = time.monotonic, +) -> 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 +669,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 - clock() + 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 +758,24 @@ def run_install_check( out: Path, *, 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, ) -> 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. + ``clock`` is the deadline clock; tests inject one to avoid wall-clock waits. + """ + 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) # must never stop the export from being written. @@ -722,7 +805,12 @@ 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, clock=clock + ) found = exchanges.pop("_leftovers", {}) runs = qualification.run_records(gateway, qualification._run_ids(gateway)) version = next( @@ -748,6 +836,8 @@ def run_install_check( }, "gateway_port": ctx.gateway_port, }, + "timeout_seconds": timeout, + "budget_seconds": budget, "token": NOT_RECORDED, "steps": steps, "exchanges": exchanges, @@ -771,11 +861,41 @@ 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 _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=float, default=300, help="seconds per host command") + parser.add_argument( + "--timeout", type=_positive_float, default=300, help="seconds per host command" + ) + parser.add_argument( + "--budget", + 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") parser.add_argument( "--target-platform", @@ -806,6 +926,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/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..e71197b1 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) @@ -398,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() @@ -461,6 +465,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..f155630a 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 @@ -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 321acf1b..fc067a41 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=( @@ -1628,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(): @@ -1706,8 +1714,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 +1772,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 +1816,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, @@ -1839,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 @@ -1978,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() @@ -1992,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() @@ -2099,6 +2126,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=( @@ -2219,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) @@ -2254,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) @@ -2279,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 @@ -2499,6 +2534,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_ac12_cancellation.py b/tests/test_ac12_cancellation.py index 4d1b45fc..8c7c55db 100644 --- a/tests/test_ac12_cancellation.py +++ b/tests/test_ac12_cancellation.py @@ -550,3 +550,217 @@ 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" + + +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" + assert run.workflow is None + + +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" diff --git a/tests/test_asset_operations.py b/tests/test_asset_operations.py index 2d6538e8..256872b2 100644 --- a/tests/test_asset_operations.py +++ b/tests/test_asset_operations.py @@ -692,12 +692,19 @@ 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={}) sample = await request_sample( @@ -705,10 +712,11 @@ async def get(self, *args, **kwargs): BODY, category="startup", ordinal=0, - deadline_at=time.monotonic() + 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 d212f87b..8e0b7e75 100644 --- a/tests/test_ci_workflows.py +++ b/tests/test_ci_workflows.py @@ -33,6 +33,29 @@ 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, 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 + + 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"] + assert "--budget 1140" in step["run"] + assert 1140 < step["timeout-minutes"] * 60 + + @pytest.mark.parametrize( "action, changes, reviews, edit_group", [ diff --git a/tests/test_gated_streaming.py b/tests/test_gated_streaming.py index 9b6c869c..9b4687ec 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,116 @@ 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("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", [ diff --git a/tests/test_openclaw_install_check.py b/tests/test_openclaw_install_check.py index 9cbd8f05..415c9184 100644 --- a/tests/test_openclaw_install_check.py +++ b/tests/test_openclaw_install_check.py @@ -17,15 +17,17 @@ 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") @@ -232,6 +234,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) @@ -585,6 +588,83 @@ 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 + + +@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() + + +@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 ): @@ -653,12 +733,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 ) @@ -667,6 +760,125 @@ def fake_run(command, **_): assert '/s /c ""C:\\x\\openclaw.cmd" "--version""' in seen[0] +@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 = [] + + 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="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 @@ -843,6 +1055,40 @@ 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: 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"]} + uninstall = next(s for s in export["steps"] if s["name"] == "uninstall") + assert status["inspect"] == "timed_out" + 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 + + def _message(role, content, tool_call_id=None): return SimpleNamespace( role=SimpleNamespace(value=role), content=content, tool_call_id=tool_call_id