|
4 | 4 | import json |
5 | 5 | import os |
6 | 6 | from pathlib import Path |
| 7 | +import signal |
7 | 8 | import subprocess |
8 | 9 | import sys |
9 | 10 | import time |
@@ -183,6 +184,160 @@ def test_timeout_is_failure(tmp_path): |
183 | 184 | assert result["status"] == "FAIL" and "exceeded" in result["error"] |
184 | 185 |
|
185 | 186 |
|
| 187 | +@pytest.mark.parametrize("failure", [KeyboardInterrupt("cancelled"), SystemExit(143)]) |
| 188 | +def test_cancellation_reclaims_live_gate_and_preserves_exception(tmp_path, monkeypatch, failure): |
| 189 | + real_popen = subprocess.Popen |
| 190 | + children = [] |
| 191 | + |
| 192 | + def launch(*args, **kwargs): |
| 193 | + process = real_popen(*args, **kwargs) |
| 194 | + if args[0][0] != sys.executable: |
| 195 | + return process |
| 196 | + children.append(process) |
| 197 | + original_wait = process.wait |
| 198 | + |
| 199 | + def interrupt(*args, **kwargs): |
| 200 | + process.wait = original_wait |
| 201 | + raise failure |
| 202 | + |
| 203 | + process.wait = interrupt |
| 204 | + return process |
| 205 | + |
| 206 | + monkeypatch.setattr(runner.subprocess, "Popen", launch) |
| 207 | + try: |
| 208 | + with pytest.raises(type(failure)) as caught: |
| 209 | + runner.run_gate(runner.Gate("frontend", (sys.executable, "-c", "import time;time.sleep(60)"), |
| 210 | + tmp_path / "frontend"), {}, timeout=90) |
| 211 | + assert caught.value is failure |
| 212 | + row = caught.value.w2_gate_result |
| 213 | + assert row["status"] == "FAIL" and row["interrupted"] is True |
| 214 | + assert row["seconds"] >= 0 |
| 215 | + assert type(failure).__name__ in row["error"] |
| 216 | + assert children[0].poll() is not None |
| 217 | + finally: |
| 218 | + for process in children: |
| 219 | + if process.poll() is None: |
| 220 | + process.kill() |
| 221 | + process.wait(timeout=5) |
| 222 | + |
| 223 | + |
| 224 | +def test_cancellation_cleanup_and_log_errors_preserve_original(tmp_path, monkeypatch): |
| 225 | + failure = KeyboardInterrupt("primary interruption") |
| 226 | + |
| 227 | + class Process: |
| 228 | + returncode = None |
| 229 | + |
| 230 | + def poll(self): |
| 231 | + return None |
| 232 | + |
| 233 | + def wait(self, **kwargs): |
| 234 | + raise failure |
| 235 | + |
| 236 | + class Log: |
| 237 | + def close(self): |
| 238 | + raise OSError("secondary close error") |
| 239 | + |
| 240 | + monkeypatch.setattr(Path, "open", lambda *args, **kwargs: Log()) |
| 241 | + monkeypatch.setattr(runner.subprocess, "Popen", lambda *args, **kwargs: Process()) |
| 242 | + monkeypatch.setattr(runner, "terminate_process_tree", lambda process: (_ for _ in ()).throw(OSError("cleanup failed"))) |
| 243 | + with pytest.raises(KeyboardInterrupt) as caught: |
| 244 | + runner.run_gate(runner.Gate("frontend", ("unused",), tmp_path / "frontend"), {}, timeout=10) |
| 245 | + assert caught.value is failure |
| 246 | + row = failure.w2_gate_result |
| 247 | + assert "primary interruption" in row["error"] |
| 248 | + assert "cleanup failed" in row["cleanup_error"] |
| 249 | + assert "secondary close error" in row["log_error"] |
| 250 | + assert row["status"] == "FAIL" and row["passed"] is False |
| 251 | + |
| 252 | + |
| 253 | +@pytest.mark.parametrize("failure, code", [(KeyboardInterrupt(), 130), (SystemExit(143), 143)]) |
| 254 | +def test_cancelled_main_saves_failure_report_without_running_next_gate(tmp_path, monkeypatch, failure, code): |
| 255 | + monkeypatch.setattr(runner, "checkout_evidence", lambda: {"head": None}) |
| 256 | + monkeypatch.setattr(runner, "source_fingerprints", lambda: {}) |
| 257 | + launched = [] |
| 258 | + |
| 259 | + def cancel(gate, *args, **kwargs): |
| 260 | + launched.append(gate.name) |
| 261 | + failure.w2_gate_result = {"name": gate.name, "status": "FAIL", "passed": False, |
| 262 | + "interrupted": True, "error": "original cancellation"} |
| 263 | + raise failure |
| 264 | + |
| 265 | + monkeypatch.setattr(runner, "run_gate", cancel) |
| 266 | + previous_term = signal.getsignal(signal.SIGTERM) |
| 267 | + out = tmp_path / "cancelled" |
| 268 | + assert runner.main(["--output-dir", str(out)]) == code |
| 269 | + assert signal.getsignal(signal.SIGTERM) == previous_term |
| 270 | + report = json.loads((out / "report.json").read_text()) |
| 271 | + assert report["status"] == "FAIL" and report["interrupted"] is True |
| 272 | + assert launched == ["frontend"] |
| 273 | + assert report["gates"][0]["error"] == "original cancellation" |
| 274 | + assert all(row["status"] == "NOT_RUN" for row in report["gates"][1:]) |
| 275 | + assert (out / "report.md").is_file() and (out / "report.html").is_file() |
| 276 | + |
| 277 | + |
| 278 | +@pytest.mark.skipif(sys.platform != "linux", reason="Linux supervisor signal and nested-session integration") |
| 279 | +@pytest.mark.parametrize("cancel_signal", [signal.SIGINT, signal.SIGTERM]) |
| 280 | +def test_real_acceptance_supervisor_cancellation_cleans_nested_worker(tmp_path, cancel_signal): |
| 281 | + pidfile = tmp_path / "worker.json" |
| 282 | + out = tmp_path / "acceptance" |
| 283 | + worker = ("import os,time,json;from pathlib import Path;" |
| 284 | + "pid=os.getpid();stat=Path(f'/proc/{pid}/stat').read_text();" |
| 285 | + f"Path({str(pidfile)!r}).write_text(json.dumps([pid,stat.rsplit(')',1)[1].split()[19]]));" |
| 286 | + "time.sleep(60)") |
| 287 | + probe = ("import sys;from scratchv.runtime.riscv_tensor import _run_process;" |
| 288 | + f"_run_process([sys.executable,'-B','-c',{worker!r}],cwd=None,timeout=50)") |
| 289 | + supervisor = ( |
| 290 | + "import sys;from scripts import run_w2_acceptance as r;" |
| 291 | + "r.source_fingerprints=lambda:{};r.checkout_evidence=lambda:{'head':None};" |
| 292 | + f"r.build_plan=lambda a:[r.Gate('frontend',(sys.executable,'-B','-c',{probe!r}),a.output_dir/'frontend')];" |
| 293 | + f"raise SystemExit(r.main(['--output-dir',{str(out)!r},'--gates','frontend']))") |
| 294 | + unrelated = subprocess.Popen([sys.executable, "-c", "import time;time.sleep(60)"], start_new_session=True) |
| 295 | + process = subprocess.Popen([sys.executable, "-B", "-c", supervisor], cwd=runner.ROOT, |
| 296 | + stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True) |
| 297 | + pid = None |
| 298 | + try: |
| 299 | + deadline = time.monotonic() + 15 |
| 300 | + while True: |
| 301 | + assert process.poll() is None, "Supervisor exited before worker readiness" |
| 302 | + assert time.monotonic() < deadline, "Worker did not become ready" |
| 303 | + try: |
| 304 | + pid, started = json.loads(pidfile.read_text()) |
| 305 | + break |
| 306 | + except (FileNotFoundError, ValueError): |
| 307 | + time.sleep(0.01) |
| 308 | + process.send_signal(cancel_signal) |
| 309 | + stdout, stderr = process.communicate(timeout=25) |
| 310 | + assert process.returncode == 128 + cancel_signal, (stdout, stderr) |
| 311 | + report = json.loads((out / "report.json").read_text()) |
| 312 | + assert report["status"] == "FAIL" and report["interrupted"] is True |
| 313 | + assert report["gates"][0]["interrupted"] is True |
| 314 | + assert report["gates"][0]["status"] == "FAIL" |
| 315 | + assert all(row["status"] == "NOT_RUN" for row in report["gates"][1:]) |
| 316 | + assert unrelated.poll() is None |
| 317 | + deadline = time.monotonic() + 5 |
| 318 | + while True: |
| 319 | + try: |
| 320 | + fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split() |
| 321 | + except FileNotFoundError: |
| 322 | + break |
| 323 | + if fields[0] in {"Z", "X"} or fields[19] != started: |
| 324 | + break |
| 325 | + assert time.monotonic() < deadline, "Detached worker survived supervisor cancellation" |
| 326 | + time.sleep(0.01) |
| 327 | + finally: |
| 328 | + for child in (process, unrelated): |
| 329 | + if child.poll() is None: |
| 330 | + os.killpg(child.pid, signal.SIGKILL) |
| 331 | + child.wait(timeout=5) |
| 332 | + if pid is not None: |
| 333 | + try: |
| 334 | + fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split() |
| 335 | + if fields[19] == started and fields[0] not in {"Z", "X"}: |
| 336 | + os.kill(pid, signal.SIGKILL) |
| 337 | + except FileNotFoundError: |
| 338 | + pass |
| 339 | + |
| 340 | + |
186 | 341 | @pytest.mark.skipif(sys.platform != "linux", reason="Linux nested-session SIGTERM integration") |
187 | 342 | def test_supervisor_cancels_nested_worker_session(tmp_path): |
188 | 343 | """Real probe -> _run_process -> different session, not a mocked killpg.""" |
|
0 commit comments