Skip to content

Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.

fix(tier3): stop running and queued Harbor jobs on Ctrl+C (#291)

Narendran Raghavan53329d6036a8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bd12b384..2b51d087 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -717,6 +717,16 @@ All notable changes to SkillEvaluator are documented in this file.
edited skill whose name, description, or (with `--full-body`) `SKILL.md`
changed is still compared with its old entry; build the catalog from the tree
you screen.
+- Ctrl+C during `tier3 evaluate` now stops the run. The interrupt reached only
+ the coordinating thread, so running Harbor jobs kept going in their own
+ process groups, agents waiting for a `--max-agents` slot still started, and
+ the command appeared to hang until every job finished. Queued agents,
+ conditions, and `--stop-on-pass` attempts now never start. Each running
+ Harbor job receives SIGTERM and up to 30 seconds to stop its trial
+ environments, such as Docker containers, before its process group is
+ killed; a second Ctrl+C skips that wait, and on Windows the task tree is
+ stopped immediately. Progress shows the agents that are stopping and reports
+ the run as interrupted instead of failed unexpectedly.
### Security
diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx
index 4a5b8438..3973d573 100644
--- a/docs/tier3-live-evaluation.mdx
+++ b/docs/tier3-live-evaluation.mdx
@@ -106,6 +106,18 @@ using Harbor 0.24:
a new session can escape process-group cleanup, so the host-side Harbor CLI,
configuration, and local-mode skills must be trusted. Run untrusted evaluated
workloads in Docker or another isolated Harbor backend instead of local mode.
+- Ctrl+C stops the whole run. Agents still waiting for a `--max-agents` slot,
+ queued conditions, and remaining `--stop-on-pass` attempts never start. Each
+ running Harbor job receives SIGTERM, which Harbor handles by stopping its
+ trial environments, and has up to 30 seconds to exit before its POSIX process
+ group is killed and reaped. The progress view shows the agents that are
+ stopping; a second Ctrl+C skips the wait. On Windows the Harbor task tree is
+ stopped immediately. A skipped or exceeded wait, or a Windows run, can leave
+ trial containers or in-container agent processes running. Harbor's Docker
+ backends name each Compose project after its trial, so
+ `docker ps --filter label=com.docker.compose.project` lists the candidates;
+ check their project names before removing them with `docker rm -f`. The
+ progress view marks unfinished stages as interrupted.
- Docker accepts Harbor stdin payloads and isolates main-container execution
from sidecar operations without placing environment values on Compose argv.
For NVIDIA Build, the credential reaches the trusted parent over stdin; each
diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.py
index cf4b3a64..d1c5e46a 100644
--- a/src/skillevaluator/tier3/harbor/runner.py
+++ b/src/skillevaluator/tier3/harbor/runner.py
@@ -26,7 +26,7 @@ import time
import tomllib
import unicodedata
from collections.abc import Iterable, Iterator, Mapping, Sequence
-from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, as_completed, wait
+from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, as_completed, wait
from contextlib import ExitStack, contextmanager, suppress
from dataclasses import dataclass, field, replace
from datetime import UTC, datetime
@@ -791,6 +791,11 @@ _HARBOR_RUN_DIAGNOSTIC_TAIL_CHARS = 16 * 1024
_HARBOR_RUN_OUTPUT_READ_BYTES = 64 * 1024
_HARBOR_RUN_POLL_SECONDS = 0.01
_HARBOR_RUN_TERMINATE_SECONDS = 0.1
+# Harbor turns SIGTERM into KeyboardInterrupt and then stops its trial
+# environments (for example removing Docker containers). An interrupted run
+# waits this long for that cleanup before it kills the process group.
+_HARBOR_RUN_CANCEL_GRACE_SECONDS = 30.0
+_HARBOR_RUN_CANCEL_POLL_SECONDS = 0.1
_HARBOR_RUN_REAP_SECONDS = 5.0
@@ -805,6 +810,32 @@ class _HarborRunTimeoutError(RuntimeError):
"""Raised after timed-out Harbor orchestration cleanup completes."""
+class _HarborRunCancelledError(BaseException):
+ """Raised on a worker thread once an interrupted run's Harbor job is contained.
+
+ Like ``KeyboardInterrupt``, it bypasses ``except Exception`` handlers that
+ record ordinary job failures, so a cancelled run stops instead of moving on
+ to its next attempt or condition.
+ """
+
+
+@dataclass(frozen=True, eq=False)
+class _HarborRunCancellation:
+ """Cross-thread stop request for the Harbor jobs of an interrupted run.
+
+ Ctrl+C reaches only the coordinating thread. Setting ``requested`` stops new
+ Harbor launches and sends running jobs SIGTERM with a cleanup grace period;
+ setting ``forced`` (a second Ctrl+C) ends that grace period early.
+ """
+
+ requested: threading.Event = field(default_factory=threading.Event)
+ forced: threading.Event = field(default_factory=threading.Event)
+
+ def raise_if_requested(self) -> None:
+ if self.requested.is_set():
+ raise _HarborRunCancelledError("Tier 3 evaluation was interrupted before this Harbor job started")
+
+
def _redact_harbor_diagnostic(detail: object, *, secret_values: set[str]) -> str:
"""Normalize a complete diagnostic, then remove synthesized exact secrets."""
normalized = redact_progress_detail(detail, secret_values=secret_values)
@@ -3608,16 +3639,44 @@ def _verified_windows_taskkill_path() -> Path:
return resolved_candidate
-def _terminate_harbor_process_tree(process: subprocess.Popen[bytes]) -> None:
- """Terminate the POSIX process group or Windows task tree and reap Harbor."""
+def _wait_for_harbor_leader(
+ process: subprocess.Popen[bytes],
+ timeout_seconds: float,
+ *,
+ end_grace: threading.Event | None,
+) -> None:
+ """Wait up to ``timeout_seconds`` for Harbor to exit, or until ``end_grace`` is set."""
+ deadline = time.monotonic() + timeout_seconds
+ while (remaining := deadline - time.monotonic()) > 0:
+ if end_grace is not None and end_grace.is_set():
+ return
+ try:
+ process.wait(timeout=min(remaining, _HARBOR_RUN_CANCEL_POLL_SECONDS))
+ except subprocess.TimeoutExpired:
+ continue
+ return
+
+
+def _terminate_harbor_process_tree(
+ process: subprocess.Popen[bytes],
+ *,
+ grace_seconds: float = _HARBOR_RUN_TERMINATE_SECONDS,
+ end_grace: threading.Event | None = None,
+) -> None:
+ """Terminate the POSIX process group or Windows task tree and reap Harbor.
+
+ On POSIX the group receives SIGTERM, then SIGKILL once the leader exits or
+ ``grace_seconds`` pass, whichever is first; a set ``end_grace`` skips the
+ rest of the grace period. Windows has no SIGTERM that Harbor handles, so
+ its task tree is always stopped with ``taskkill /T /F``.
+ """
if os.name == "posix":
# POSIX process groups do not own a descendant that deliberately calls
# setsid(2). The host-side Harbor CLI/configuration is therefore a
# trusted boundary; untrusted task execution belongs in an isolated
# backend rather than SkillEvaluator's experimental local mode.
_signal_harbor_process_group(process, signal.SIGTERM)
- with suppress(subprocess.TimeoutExpired):
- process.wait(timeout=_HARBOR_RUN_TERMINATE_SECONDS)
+ _wait_for_harbor_leader(process, grace_seconds, end_grace=end_grace)
# Always signal the original group after the grace period. The leader
# may already have exited while a descendant retained the output pipe.
_signal_harbor_process_group(process, signal.SIGKILL)
@@ -3669,14 +3728,23 @@ def _run_bounded_harbor_process(
max_output_bytes: int,
diagnostic_tail_chars: int,
secret_values: set[str],
+ cancellation: _HarborRunCancellation | None = None,
) -> _BoundedHarborProcessResult:
- """Run Harbor with bounded merged output and optional cleanup deadline."""
+ """Run Harbor with bounded merged output and optional cleanup deadline.
+
+ A requested ``cancellation`` prevents the launch, or stops a running
+ process tree, and then raises :class:`_HarborRunCancelledError`. A running
+ job gets SIGTERM and up to ``_HARBOR_RUN_CANCEL_GRACE_SECONDS`` to stop its
+ environments before the group is killed, unless the cancellation is forced.
+ """
if timeout_seconds is not None and timeout_seconds <= 0:
raise ValueError("Harbor run timeout must be positive")
if max_output_bytes <= 0:
raise ValueError("Harbor output byte limit must be positive")
if diagnostic_tail_chars <= 0:
raise ValueError("Harbor diagnostic tail limit must be positive")
+ if cancellation is not None:
+ cancellation.raise_if_requested()
creation_flags = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) if os.name == "nt" else 0
process = subprocess.Popen(
@@ -3777,6 +3845,9 @@ def _run_bounded_harbor_process(
break
if reader_done.is_set() and process.poll() is not None:
break
+ if cancellation is not None and cancellation.requested.is_set():
+ # The BaseException handler below stops the process tree.
+ raise _HarborRunCancelledError("Tier 3 evaluation was interrupted; Harbor job stopped")
if deadline is None:
reader_done.wait(_HARBOR_RUN_POLL_SECONDS)
continue
@@ -3816,7 +3887,16 @@ def _run_bounded_harbor_process(
cleanup_error: BaseException | None = None
if process.poll() is None or not reader_done.is_set():
try:
- _terminate_harbor_process_tree(process)
+ if cancellation is not None and isinstance(primary_error, _HarborRunCancelledError):
+ # Let Harbor's SIGTERM handling stop its trial environments
+ # instead of leaving containers or agent processes behind.
+ _terminate_harbor_process_tree(
+ process,
+ grace_seconds=_HARBOR_RUN_CANCEL_GRACE_SECONDS,
+ end_grace=cancellation.forced,
+ )
+ else:
+ _terminate_harbor_process_tree(process)
except BaseException as exc:
cleanup_error = exc
if not reader_started:
@@ -3856,7 +3936,12 @@ def _run_harbor(
expected_trials: int | None = None,
expected_total_trials: int | None = None,
include_task_names: list[str] | None = None,
+ cancellation: _HarborRunCancellation | None = None,
) -> tuple[bool, str]:
+ if cancellation is not None:
+ # Check before the credential refresh as well as at launch, so a queued
+ # condition or attempt makes no token request after an interrupt.
+ cancellation.raise_if_requested()
base_url = (
(verifier_env or {}).get("OPENAI_BASE_URL")
or run_env.get("OPENAI_BASE_URL")
@@ -3932,6 +4017,7 @@ def _run_harbor(
max_output_bytes=_HARBOR_RUN_OUTPUT_MAX_BYTES,
diagnostic_tail_chars=_HARBOR_RUN_DIAGNOSTIC_TAIL_CHARS,
secret_values=secret_values,
+ cancellation=cancellation,
)
except _HarborRunTimeoutError as exc:
if adc_timeout is not None:
@@ -4497,6 +4583,7 @@ def _run_stop_on_pass_variant(
agent_import_path: str | None = None,
verifier_env: Mapping[str, str] | None = None,
environment_kwargs: Mapping[str, Any] | None = None,
+ cancellation: _HarborRunCancellation | None = None,
) -> list[str]:
"""Run each case one attempt at a time, stopping its attempts on first pass."""
errors: list[tuple[Path, str]] = []
@@ -4523,6 +4610,7 @@ def _run_stop_on_pass_variant(
environment_kwargs=environment_kwargs,
expected_trials=1,
include_task_names=[task_name],
+ cancellation=cancellation,
)
job_dir = jobs_dir / job_name
attempt_job_dirs.append(job_dir)
@@ -4618,6 +4706,7 @@ def _run_agent_pair(
verifier_env: Mapping[str, str] | None = None,
environment_kwargs: Mapping[str, Any] | None = None,
with_agent_import_path: str | None = None,
+ cancellation: _HarborRunCancellation | None = None,
additional_arms: Sequence[tuple[str, Path, str | None]] = (),
additional_arm_errors: dict[str, str] | None = None,
) -> list[str]:
@@ -4664,6 +4753,7 @@ def _run_agent_pair(
agent_import_path=job_import_path,
verifier_env=verifier_env,
environment_kwargs=environment_kwargs,
+ cancellation=cancellation,
)
except Exception as exc:
if variant not in extra_variants:
@@ -4701,6 +4791,7 @@ def _run_agent_pair(
verifier_env=verifier_env,
environment_kwargs=environment_kwargs,
expected_trials=expected_trials,
+ cancellation=cancellation,
): variant
for (variant, dataset, job_import_path), condition_concurrency in zip(jobs, job_concurrency, strict=True)
}
@@ -4783,21 +4874,25 @@ class _RunProgressLifecycle:
def close(self) -> None:
self._reporter.close()
- def fail_unfinished(self) -> None:
- """Fail every open stage and finish the run without masking its error."""
+ def fail_unfinished(self, *, interrupted: bool = False) -> None:
+ """Fail every open stage and finish the run without masking its error.
+
+ ``interrupted`` reports Ctrl+C or cancellation rather than an unexpected failure.
+ """
+ stage_detail = "interrupted before completion" if interrupted else "unexpected failure interrupted this stage"
for stage in tuple(self._active_stages):
self.emit(
ProgressEvent(
stage=stage,
state="failed",
- detail="unexpected failure interrupted this stage",
+ detail=stage_detail,
)
)
self.emit(
ProgressEvent(
stage="run-finished",
state="failed",
- detail="Tier 3 evaluation failed unexpectedly",
+ detail="Tier 3 evaluation interrupted" if interrupted else "Tier 3 evaluation failed unexpectedly",
output_dir=self._output_dir,
result_path=self._existing_file(self._result_path),
report_path=self._existing_file(self._report_path),
@@ -5888,6 +5983,8 @@ def _run_harbor_eval_impl(
)
errors: list[str] = []
started_agents: SimpleQueue[str] = SimpleQueue()
+ # Ctrl+C reaches only this thread; workers observe it through this object.
+ cancellation = _HarborRunCancellation()
def _execute_agent(agent: str) -> list[str]:
started_agents.put(agent)
@@ -5914,6 +6011,7 @@ def _run_harbor_eval_impl(
task_names=task_selectors,
verifier_env=job_judge_verifier_env,
environment_kwargs=effective_environment_kwargs,
+ cancellation=cancellation,
**(
{
"additional_arms": additional_arms[agent],
@@ -5940,39 +6038,80 @@ def _run_harbor_eval_impl(
variants = "with-skill" if skip_baseline else "with-skill + baseline"
reporter.emit(ProgressEvent(stage=f"agent:{agent}", state="running", detail=variants))
+ futures: dict[Future[list[str]], str] = {}
+
+ def _join_interrupted_agents() -> None:
+ """Wait while running agents stop their Harbor jobs after an interrupt.
+
+ A second Ctrl+C ends the cleanup grace period; a third one propagates.
+ """
+ stopping_reported = False
+ while True:
+ try:
+ running = [future for future in futures if not future.done()]
+ if not running:
+ return
+ if not stopping_reported:
+ stopping_reported = True
+ for agent in sorted(futures[future] for future in running):
+ reporter.emit(
+ ProgressEvent(
+ stage=f"agent:{agent}",
+ state="running",
+ detail=(
+ "stopping Harbor jobs; press Ctrl+C again to skip up to "
+ f"{_HARBOR_RUN_CANCEL_GRACE_SECONDS:g}s of environment cleanup"
+ ),
+ )
+ )
+ wait(running, timeout=_HARBOR_RUN_CANCEL_POLL_SECONDS)
+ except KeyboardInterrupt:
+ if cancellation.forced.is_set():
+ raise
+ cancellation.forced.set()
+
with ThreadPoolExecutor(max_workers=min(max_agents, len(agents))) as executor:
- futures = {executor.submit(_execute_agent, agent): agent for agent in agents}
- pending = set(futures)
- while pending:
- _emit_started_agents()
- done, pending = wait(pending, timeout=0.1, return_when=FIRST_COMPLETED)
- _emit_started_agents()
- for future in done:
- agent = futures[future]
- active_agents.discard(agent)
- try:
- agent_errors = future.result()
- except Exception as exc:
- reporter.emit(
- ProgressEvent(
- stage=f"agent:{agent}",
- state="failed",
- detail="agent worker failed unexpectedly",
+ try:
+ futures = {executor.submit(_execute_agent, agent): agent for agent in agents}
+ pending = set(futures)
+ while pending:
+ _emit_started_agents()
+ done, pending = wait(pending, timeout=0.1, return_when=FIRST_COMPLETED)
+ _emit_started_agents()
+ for future in done:
+ agent = futures[future]
+ active_agents.discard(agent)
+ try:
+ agent_errors = future.result()
+ except Exception as exc:
+ reporter.emit(
+ ProgressEvent(
+ stage=f"agent:{agent}",
+ state="failed",
+ detail="agent worker failed unexpectedly",
+ )
)
- )
- unexpected_worker_error = unexpected_worker_error or exc
- continue
- errors.extend(agent_errors)
- if agent_errors:
- reporter.emit(
- ProgressEvent(
- stage=f"agent:{agent}",
- state="failed",
- detail="one or more Harbor jobs failed; inspect retained artifacts",
+ unexpected_worker_error = unexpected_worker_error or exc
+ continue
+ errors.extend(agent_errors)
+ if agent_errors:
+ reporter.emit(
+ ProgressEvent(
+ stage=f"agent:{agent}",
+ state="failed",
+ detail="one or more Harbor jobs failed; inspect retained artifacts",
+ )
)
- )
- else:
- reporter.emit(ProgressEvent(stage=f"agent:{agent}", state="complete"))
+ else:
+ reporter.emit(ProgressEvent(stage=f"agent:{agent}", state="complete"))
+ except BaseException:
+ # Without this, the executor exit would wait for every running
+ # Harbor job to finish and would still start queued agents. Cancel
+ # the queue first so a worker that stops never picks up another agent.
+ executor.shutdown(wait=False, cancel_futures=True)
+ cancellation.requested.set()
+ _join_interrupted_agents()
+ raise
if unexpected_worker_error is not None:
for agent in sorted(active_agents):
@@ -6220,14 +6359,14 @@ def run_harbor_eval(*args: Any, **kwargs: Any) -> dict[str, Any]:
)
lifecycle.finish_result(result)
return result
- except BaseException:
+ except BaseException as exc:
_finalize_harbor_artifacts(
run_dir_value=lifecycle.output_dir,
keep_requested=bool(kwargs.get("keep_harbor_jobs", False)),
result=None,
)
try:
- lifecycle.fail_unfinished()
+ lifecycle.fail_unfinished(interrupted=isinstance(exc, (KeyboardInterrupt, _HarborRunCancelledError)))
except BaseException:
logger.debug("Tier 3 progress terminalization failed", exc_info=True)
raise
diff --git a/tests/test_harbor_runner_status.py b/tests/test_harbor_runner_status.py
index 7a6e094d..c64b2890 100644
--- a/tests/test_harbor_runner_status.py
+++ b/tests/test_harbor_runner_status.py
@@ -386,6 +386,230 @@ def test_bounded_harbor_process_failure_reaps_descendants(
assert not child_marker.exists()
[email protected](os.name != "posix", reason="requires POSIX process-group verification")
+def test_bounded_harbor_process_cancellation_reaps_descendants(tmp_path: Path) -> None:
+ child_pid_path = tmp_path / "cancelled-child-pid"
+ child_marker = tmp_path / "cancelled-child-survived"
+ child_script = (
+ "import pathlib,signal,time;"
+ "signal.signal(signal.SIGTERM, signal.SIG_IGN);"
+ "time.sleep(1);"
+ f"pathlib.Path({str(child_marker)!r}).write_text('survived')"
+ )
+ parent_script = (
+ "import pathlib,subprocess,sys,time;"
+ f"child=subprocess.Popen([{sys.executable!r},'-c',{child_script!r}]);"
+ f"pathlib.Path({str(child_pid_path)!r}).write_text(str(child.pid));"
+ "time.sleep(30)"
+ )
+ cancellation = runner._HarborRunCancellation()
+
+ def cancel_once_child_started() -> None:
+ deadline = time.monotonic() + 10
+ while not child_pid_path.exists() and time.monotonic() < deadline:
+ time.sleep(0.01)
+ cancellation.requested.set()
+
+ canceller = threading.Thread(target=cancel_once_child_started, daemon=True)
+ canceller.start()
+ with pytest.raises(runner._HarborRunCancelledError):
+ runner._run_bounded_harbor_process(
+ [sys.executable, "-c", parent_script],
+ env=dict(os.environ),
+ cwd=Path.cwd(),
+ stdin_text=None,
+ timeout_seconds=None,
+ max_output_bytes=4096,
+ diagnostic_tail_chars=128,
+ secret_values=set(),
+ cancellation=cancellation,
+ )
+ canceller.join(timeout=5)
+
+ child_pid = int(child_pid_path.read_text(encoding="ascii"))
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline:
+ try:
+ os.kill(child_pid, 0)
+ except ProcessLookupError:
+ break
+ time.sleep(0.01)
+ else:
+ with contextlib.suppress(ProcessLookupError):
+ os.kill(child_pid, signal.SIGKILL)
+ pytest.fail("Harbor descendant survived cancellation")
+ time.sleep(1.05)
+ assert not child_marker.exists()
+
+
+def _sigterm_handling_harbor_script(ready_path: Path, *, on_sigterm: list[str]) -> str:
+ """Stand-in Harbor CLI that reports readiness and handles SIGTERM itself."""
+ handler = "".join(f" {line}\n" for line in on_sigterm)
+ return (
+ "import pathlib,signal,sys,time\n"
+ "def stop(*_):\n"
+ f"{handler}"
+ "signal.signal(signal.SIGTERM, stop)\n"
+ f"pathlib.Path({str(ready_path)!r}).write_text('ready')\n"
+ "time.sleep(120)\n"
+ )
+
+
+def _cancel_when_ready(
+ ready_path: Path,
+ cancellation: runner._HarborRunCancellation,
+ *,
+ force_after_seconds: float | None = None,
+) -> threading.Thread:
+ def cancel() -> None:
+ deadline = time.monotonic() + 30
+ while not ready_path.exists() and time.monotonic() < deadline:
+ time.sleep(0.01)
+ cancellation.requested.set()
+ if force_after_seconds is not None:
+ time.sleep(force_after_seconds)
+ cancellation.forced.set()
+
+ canceller = threading.Thread(target=cancel, daemon=True)
+ canceller.start()
+ return canceller
+
+
[email protected](os.name != "posix", reason="requires POSIX SIGTERM delivery")
+def test_bounded_harbor_process_cancellation_lets_harbor_finish_cleanup(tmp_path: Path) -> None:
+ # Harbor maps SIGTERM to KeyboardInterrupt and then stops its trial
+ # environments. Cancellation must wait for that instead of killing the
+ # group after the short timeout grace.
+ ready_path = tmp_path / "ready"
+ cleanup_marker = tmp_path / "cleanup-finished"
+ script = _sigterm_handling_harbor_script(
+ ready_path,
+ on_sigterm=[
+ "time.sleep(0.5)",
+ f"pathlib.Path({str(cleanup_marker)!r}).write_text('done')",
+ "sys.exit(0)",
+ ],
+ )
+ cancellation = runner._HarborRunCancellation()
+ canceller = _cancel_when_ready(ready_path, cancellation)
+
+ with pytest.raises(runner._HarborRunCancelledError) as exc_info:
+ runner._run_bounded_harbor_process(
+ [sys.executable, "-c", script],
+ env=dict(os.environ),
+ cwd=tmp_path,
+ stdin_text=None,
+ timeout_seconds=None,
+ max_output_bytes=4096,
+ diagnostic_tail_chars=128,
+ secret_values=set(),
+ cancellation=cancellation,
+ )
+ canceller.join(timeout=5)
+
+ assert cleanup_marker.read_text(encoding="utf-8") == "done"
+ assert not getattr(exc_info.value, "__notes__", [])
+
+
[email protected](os.name != "posix", reason="requires POSIX SIGTERM delivery")
[email protected]("ending", ["forced", "grace-expired"])
+def test_bounded_harbor_process_cancellation_kills_harbor_that_ignores_sigterm(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ ending: str,
+) -> None:
+ ready_path = tmp_path / "ready"
+ script = _sigterm_handling_harbor_script(ready_path, on_sigterm=["pass"])
+ if ending == "forced":
+ # A second Ctrl+C must not wait out the cleanup grace period.
+ monkeypatch.setattr(runner, "_HARBOR_RUN_CANCEL_GRACE_SECONDS", 300.0)
+ force_after_seconds: float | None = 0.2
+ else:
+ monkeypatch.setattr(runner, "_HARBOR_RUN_CANCEL_GRACE_SECONDS", 0.3)
+ force_after_seconds = None
+ cancellation = runner._HarborRunCancellation()
+ canceller = _cancel_when_ready(ready_path, cancellation, force_after_seconds=force_after_seconds)
+ started = time.monotonic()
+
+ with pytest.raises(runner._HarborRunCancelledError) as exc_info:
+ runner._run_bounded_harbor_process(
+ [sys.executable, "-c", script],
+ env=dict(os.environ),
+ cwd=tmp_path,
+ stdin_text=None,
+ timeout_seconds=None,
+ max_output_bytes=4096,
+ diagnostic_tail_chars=128,
+ secret_values=set(),
+ cancellation=cancellation,
+ )
+ canceller.join(timeout=5)
+
+ # The stand-in sleeps for 120 s, so returning sooner proves SIGKILL.
+ assert time.monotonic() - started < 60
+ assert not getattr(exc_info.value, "__notes__", [])
+
+
+def test_bounded_harbor_process_never_launches_after_cancellation(monkeypatch: pytest.MonkeyPatch) -> None:
+ launched: list[object] = []
+ monkeypatch.setattr(runner.subprocess, "Popen", lambda *args, **_kwargs: launched.append(args))
+ cancellation = runner._HarborRunCancellation()
+ cancellation.requested.set()
+
+ with pytest.raises(runner._HarborRunCancelledError):
+ runner._run_bounded_harbor_process(
+ [sys.executable, "-c", "pass"],
+ env=dict(os.environ),
+ cwd=Path.cwd(),
+ stdin_text=None,
+ timeout_seconds=None,
+ max_output_bytes=4096,
+ diagnostic_tail_chars=128,
+ secret_values=set(),
+ cancellation=cancellation,
+ )
+
+ assert launched == []
+
+
+def test_run_harbor_checks_cancellation_before_refreshing_credentials(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ refreshed: list[object] = []
+
+ def refresh(*args: object, **kwargs: object) -> None:
+ refreshed.append((args, kwargs))
+
+ def launch(*_args: object, **_kwargs: object) -> None:
+ pytest.fail("Harbor launched after cancellation")
+
+ monkeypatch.setattr(runner, "refresh_host_vertex_adc_environment", refresh)
+ monkeypatch.setattr(runner, "_run_bounded_harbor_process", launch)
+ cancellation = runner._HarborRunCancellation()
+ cancellation.requested.set()
+
+ with pytest.raises(runner._HarborRunCancelledError):
+ runner._run_harbor(
+ dataset=tmp_path / "dataset",
+ agent="opencode",
+ job_name="demo-opencode-with",
+ env_mode="docker",
+ model="nvidia/openai/gpt-oss-120b",
+ jobs_dir=tmp_path / "jobs",
+ run_env={},
+ n_attempts=1,
+ n_concurrent=1,
+ timeout_multiplier=1.0,
+ override_cpus=None,
+ override_memory_mb=None,
+ override_storage_mb=None,
+ cancellation=cancellation,
+ )
+
+ assert refreshed == []
+
+
@pytest.mark.skipif(os.name != "nt", reason="requires Windows taskkill tree verification")
@pytest.mark.parametrize("failure_mode", ["output", "timeout"])
def test_bounded_harbor_process_failure_reaps_windows_descendants(
@@ -753,6 +977,54 @@ def test_stop_on_pass_preserves_nvidia_build_agent_import_path(
}
[email protected]("stop_on_pass", [False, True])
+def test_agent_pair_launches_nothing_after_cancellation(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ stop_on_pass: bool,
+) -> None:
+ cancellation = runner._HarborRunCancellation()
+ launched: list[str] = []
+
+ def _run_harbor(**kwargs: object) -> tuple[bool, str]:
+ assert kwargs["cancellation"] is cancellation
+ # Mirrors the gate at the top of the real _run_harbor.
+ cancellation.raise_if_requested()
+ launched.append(str(kwargs["job_name"]))
+ # Ctrl+C arrives while the first Harbor job runs.
+ cancellation.requested.set()
+ raise runner._HarborRunCancelledError("interrupted")
+
+ monkeypatch.setattr(runner, "_run_harbor", _run_harbor)
+ monkeypatch.setattr(runner, "_job_passed", lambda *_args, **_kwargs: False)
+ monkeypatch.setattr(runner, "_merge_attempt_jobs", lambda *_args, **_kwargs: None)
+
+ with pytest.raises(runner._HarborRunCancelledError):
+ runner._run_agent_pair(
+ skill_name="demo",
+ agent="opencode",
+ model="nvidia/openai/gpt-oss-120b",
+ env_mode="docker",
+ with_skill=tmp_path / "with",
+ baseline=tmp_path / "without",
+ jobs_dir=tmp_path / "jobs",
+ run_env={},
+ n_attempts=2,
+ n_concurrent=1,
+ timeout_multiplier=1.0,
+ override_cpus=None,
+ override_memory_mb=None,
+ override_storage_mb=None,
+ expected_trials=2,
+ stop_on_pass=stop_on_pass,
+ task_names=["case-001"],
+ cancellation=cancellation,
+ )
+
+ assert len(launched) == 1
+ assert "-with" in launched[0]
+
+
_UNSAFE_LINK = r"symlink|reparse"
diff --git a/tests/test_tier3_progress.py b/tests/test_tier3_progress.py
index b772b8c0..bb8b4873 100644
--- a/tests/test_tier3_progress.py
+++ b/tests/test_tier3_progress.py
@@ -2767,6 +2767,100 @@ def test_default_collection_exception_cleans_transient_artifacts(
assert not (run_dirs[0] / "_harbor-tasks").exists()
+class _InterruptingReporter(_RecordingReporter):
+ """Deliver Ctrl+C on the coordinator thread once the first agent is running."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.interrupted = False
+
+ def emit(self, event: Any) -> None:
+ super().emit(event)
+ if not self.interrupted and event.stage.startswith("agent:") and event.state == "running":
+ self.interrupted = True
+ raise KeyboardInterrupt
+
+
+def test_interrupt_cancels_running_agent_and_never_starts_queued_agents(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ launched: list[str] = []
+ observed_cancellation: list[bool] = []
+
+ def run_agent(**kwargs: Any) -> list[str]:
+ launched.append(kwargs["agent"])
+ cancellation = kwargs.get("cancellation")
+ # Harbor jobs poll this event; the bounded wait keeps a regression from hanging.
+ observed_cancellation.append(cancellation is not None and cancellation.requested.wait(10))
+ return []
+
+ # The stub configures max_agents=1, so the second agent waits in the queue.
+ runner, skill = _stub_runner(monkeypatch, tmp_path, run_agent=run_agent)
+ reporter = _InterruptingReporter()
+
+ with pytest.raises(KeyboardInterrupt):
+ runner.run_harbor_eval(
+ skill,
+ ["codex", "opencode"],
+ output_dir=tmp_path / "results",
+ progress_reporter=reporter,
+ )
+
+ assert launched == ["codex"]
+ assert observed_cancellation == [True]
+ events = [(event.stage, event.state, event.detail) for event in reporter.events]
+ assert ("agent:codex", "failed", "interrupted before completion") in events
+ assert ("agent:opencode", "running", "with-skill + baseline") not in events
+ assert events[-1] == ("run-finished", "failed", "Tier 3 evaluation interrupted")
+
+
+class _RepeatedInterruptReporter(_RecordingReporter):
+ """Deliver Ctrl+C when the first agent starts and again when it reports stopping."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.interrupts = 0
+
+ def emit(self, event: Any) -> None:
+ super().emit(event)
+ if self.interrupts < 2 and event.stage.startswith("agent:") and event.state == "running":
+ self.interrupts += 1
+ raise KeyboardInterrupt
+
+
+def test_second_interrupt_forces_running_agents_to_stop(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ observed: list[tuple[bool, bool]] = []
+
+ def run_agent(**kwargs: Any) -> list[str]:
+ cancellation = kwargs["cancellation"]
+ # A running Harbor job stays in its cleanup grace until it is forced.
+ observed.append((cancellation.requested.wait(10), cancellation.forced.wait(10)))
+ return []
+
+ runner, skill = _stub_runner(monkeypatch, tmp_path, run_agent=run_agent)
+ reporter = _RepeatedInterruptReporter()
+
+ with pytest.raises(KeyboardInterrupt):
+ runner.run_harbor_eval(
+ skill,
+ ["codex"],
+ output_dir=tmp_path / "results",
+ progress_reporter=reporter,
+ )
+
+ assert observed == [(True, True)]
+ assert reporter.interrupts == 2
+ events = [(event.stage, event.state, event.detail) for event in reporter.events]
+ stopping = [detail for stage, state, detail in events if stage == "agent:codex" and state == "running"]
+ assert stopping[-1].startswith("stopping Harbor jobs; press Ctrl+C again")
+ assert ("agent:codex", "failed", "interrupted before completion") in events
+ assert events[-1] == ("run-finished", "failed", "Tier 3 evaluation interrupted")
+
+
def test_runtime_preflight_running_event_precedes_slow_preflight_call(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,