diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fd2e164..fca97b55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,12 @@ Python callers passing `runner=` to `run_search` / `run_confirmation`:** the runner now receives a `launch_guard` keyword and must create its process inside it. See [Model recipes](docs/MODEL_RECIPES.md). +- `recipe search` / `recipe confirm` wait at most 60 seconds for the shared + `.process-cleanup.lock` (printing a progress line naming the holder every + 10 seconds) and then refuse the launch or fail the marker write with exit 4, + instead of waiting indefinitely. Their stderr diagnostics are best effort: a + closed or missing stderr drops them (never redirects them to stdout) and no + longer turns exit 4 into exit 1 with a traceback. - Refusal rates exclude invalid completions by default (#332). This applies to `refusal_rate`, `refusal_rate_with_ci`, `arditi_refusal_rate`, verification, and community comparison reports. **Refusal rates from earlier versions are diff --git a/docs/MODEL_RECIPES.md b/docs/MODEL_RECIPES.md index 5b180fff..54187468 100644 --- a/docs/MODEL_RECIPES.md +++ b/docs/MODEL_RECIPES.md @@ -328,7 +328,9 @@ cleanup failure. Any error closing the evaluator's pipes or selector during a cleanup failure, including an interrupt (KeyboardInterrupt or SystemExit), is attached to it as a note and never replaces it, so verify-edit still exits 4. On exit 4 the CLI also prints the failure's notes and any interrupting signal on -stderr. Check that no evaluator or vLLM process from the recorded run is still +stderr. These stderr lines (CRITICAL, refusal, progress and notes) are best +effort: if stderr is closed or missing they are dropped (never sent to stdout), +and the exit code stays 4. Check that no evaluator or vLLM process from the recorded run is still running (it may hold GPU memory and the port), then delete the file to continue. The leader is left unreaped and its process object stays held by diff --git a/obliteratus/recipes/search.py b/obliteratus/recipes/search.py index f7474e7c..bf9e3233 100644 --- a/obliteratus/recipes/search.py +++ b/obliteratus/recipes/search.py @@ -74,28 +74,40 @@ def _cleanup_lock(marker: Path) -> FileLock: def _diagnostic(message: str) -> None: - """Print `message` to stderr, best effort: it never raises. + """Write `message` as one line to stderr, best effort: it never raises an Exception. The callers are fail-closed paths whose handlers expect only OSError; a closed stderr (ValueError) or a path the stream cannot encode (UnicodeEncodeError) must not abort a lock wait or replace exit 4. An - unencodable message is retried with non-ASCII characters escaped. + unencodable line is retried once with non-ASCII characters escaped; any + other write failure drops it. With no stderr at all (sys.stderr is None, + for example under pythonw) the line is dropped, never sent to stdout. A + failed flush is ignored and never writes the line again. A BaseException + raised by the stream (KeyboardInterrupt, SystemExit) still propagates. """ - try: - print(message, file=sys.stderr, flush=True) + stream = sys.stderr + if stream is None: return - except Exception: # any failure: a diagnostic must never change the control flow - pass + line = message + "\n" try: - print(message.encode("ascii", "backslashreplace").decode("ascii"), file=sys.stderr, flush=True) - except Exception: # still unwritable (for example closed): drop the line + stream.write(line) + except UnicodeEncodeError: + try: + stream.write(line.encode("ascii", "backslashreplace").decode("ascii")) + except Exception: # still unwritable: drop the line + return + except Exception: # for example closed: drop the line + return + try: + stream.flush() + except Exception: # the line was already handed to the stream; never write it twice pass def _lock_holder(path: Path) -> str: """Best-effort hint of who holds `path` (Linux /proc/locks), for progress lines. - Diagnostic only, so it never raises: it runs on the fail-closed lock paths, + Diagnostic only, so it never raises an Exception: it runs on the fail-closed lock paths, where any exception other than OSError would escape their handling (on Windows, for example, os.major does not exist). """ @@ -122,7 +134,8 @@ def _lock_holder(path: Path) -> str: def _acquire_cleanup_lock(lock: FileLock, path: Path) -> None: """Wait at most _MARKER_LOCK_TIMEOUT for the cleanup lock; raise filelock.Timeout after. - Print a progress line to stderr every _CLEANUP_LOCK_PROGRESS seconds of waiting. + Print a progress line to stderr (best effort, see _diagnostic) every + _CLEANUP_LOCK_PROGRESS seconds of waiting. """ limit = _MARKER_LOCK_TIMEOUT deadline = time.monotonic() + limit @@ -161,8 +174,9 @@ def _write_durably(path: Path, document: dict) -> None: def record_process_cleanup_failure(marker: Path, subject: str, log: Path) -> None: """Durably record a cleanup failure before anything else can be launched. - If the marker cannot be written and synced, report it loudly on stderr and - raise ProcessCleanupFailed, so the run still stops with exit 4. + If the marker cannot be written and synced, print a CRITICAL line on stderr + (best effort: dropped if stderr is closed or missing) and raise + ProcessCleanupFailed, so the run still stops with exit 4. """ written = False try: diff --git a/obliteratus/recipes/search_cli.py b/obliteratus/recipes/search_cli.py index 512cec5b..4ce785a0 100644 --- a/obliteratus/recipes/search_cli.py +++ b/obliteratus/recipes/search_cli.py @@ -3,7 +3,6 @@ from __future__ import annotations import argparse -import sys from pathlib import Path from rich.markup import escape @@ -84,7 +83,7 @@ def _cleanup_details(error: BaseException) -> list[str]: def run_cli(args: argparse.Namespace, console) -> int: from obliteratus.process_groups import ProcessGroupCleanupError - from obliteratus.recipes.search import run_search + from obliteratus.recipes.search import _diagnostic, run_search from obliteratus.verify_edit.verdicts import EXIT_CLEANUP try: @@ -121,8 +120,9 @@ def run_cli(args: argparse.Namespace, console) -> int: # Distinct from input errors: a process group may still be running. # (ProcessCleanupFailed is a ProcessGroupCleanupError.) console.print(f"[red]recipe {args.recipe_command}[/] {escape(str(exc))}") + # Best effort: a closed or missing stderr must not turn exit 4 into a traceback. for line in _cleanup_details(exc): - print(line, file=sys.stderr, flush=True) + _diagnostic(line) return EXIT_CLEANUP except (OSError, ValueError) as exc: console.print(f"[red]recipe {args.recipe_command}[/] {escape(str(exc))}") diff --git a/tests/test_recipe_search.py b/tests/test_recipe_search.py index 3d4ef3c8..f2f82d31 100644 --- a/tests/test_recipe_search.py +++ b/tests/test_recipe_search.py @@ -1377,6 +1377,8 @@ def test_broken_stderr_never_changes_the_fail_closed_lock_paths(tmp_path, monkey if kind == "unencodable-path": output = _ascii_output(stream) assert "waiting for" in output and "\\xfc" in output, output # escaped, not lost + assert "refusing to launch" in output, output + assert "CRITICAL: could not record" in output, output @pytest.mark.parametrize("kind", ["closed", "unencodable-path"]) @@ -1385,24 +1387,64 @@ def test_broken_stderr_during_a_contended_marker_write_still_records_it(tmp_path from obliteratus.recipes import search - directory, _ = _broken_stderr(monkeypatch, tmp_path, kind) + directory, stream = _broken_stderr(monkeypatch, tmp_path, kind) monkeypatch.setattr(search, "_MARKER_LOCK_TIMEOUT", 30.0) monkeypatch.setattr(search, "_CLEANUP_LOCK_PROGRESS", 0.1) marker = directory / search.CLEANUP_MARKER - held, done = threading.Event(), threading.Event() + held, printed = threading.Event(), threading.Event() + real_diagnostic = search._diagnostic - def hold_briefly(): + def diagnostic(message): + real_diagnostic(message) # its print fails: closed, or unencodable then escaped + if message.startswith("waiting for"): + printed.set() + + monkeypatch.setattr(search, "_diagnostic", diagnostic) + + def hold_until_a_progress_print(): holder = FileLock(str(directory / ".process-cleanup.lock")) with holder: held.set() - done.wait(timeout=0.6) # several progress prints fail meanwhile + printed.wait(timeout=20) # released only after a failing progress print - worker = threading.Thread(target=hold_briefly, daemon=True) + worker = threading.Thread(target=hold_until_a_progress_print, daemon=True) worker.start() assert held.wait(timeout=10) search.record_process_cleanup_failure(marker, "candidate alpha", directory / "a.log") worker.join(timeout=10) + assert printed.is_set(), "the marker write never waited behind the held lock" assert _read(marker)["subject"] == "candidate alpha" + if kind == "unencodable-path": + output = _ascii_output(stream) + assert "waiting for" in output and "\\xfc" in output, output + + +def test_diagnostic_with_no_stderr_is_dropped_not_sent_to_stdout(monkeypatch, capsys): + from obliteratus.recipes import search + + monkeypatch.setattr(sys, "stderr", None) # for example pythonw, or a detached service + search._diagnostic("CRITICAL: could not record the marker") + assert capsys.readouterr().out == "" + + +def test_diagnostic_flush_failure_never_prints_the_line_twice(monkeypatch): + from obliteratus.recipes import search + + class FlushFails: + def __init__(self): + self.written = [] + + def write(self, text): + self.written.append(text) + return len(text) + + def flush(self): + raise OSError(5, "simulated flush failure") + + stream = FlushFails() + monkeypatch.setattr(sys, "stderr", stream) + search._diagnostic("CRITICAL: could not record the marker") + assert "".join(stream.written).count("could not record the marker") == 1, stream.written def test_marker_release_failure_after_a_durable_write_says_it_was_recorded(tmp_path, monkeypatch, capsys): @@ -1590,6 +1632,43 @@ def test_recipe_cli_prints_cleanup_notes_and_interrupt_to_stderr(setup_grid, mon assert "interrupted by SIGTERM" in err +@pytest.mark.parametrize("kind", ["closed", "none"]) +def test_recipe_cli_exits_four_when_stderr_is_closed_or_missing(setup_grid, monkeypatch, capsys, kind): + """The notes are best effort: a broken stderr never turns exit 4 into a traceback.""" + import io + + from obliteratus.cli import main + from obliteratus.process_groups import ProcessInterrupted + from obliteratus.recipes import search + + _, path, _, _, _ = setup_grid + + def cleanup_failed(grid): + try: + raise ProcessInterrupted(signal.SIGTERM) + except ProcessInterrupted as interrupt: + failure = search.ProcessCleanupFailed("candidate alpha: a process group may still be running") + failure.add_note("could not write candidates/alpha.json: OSError(28)") + raise failure from interrupt + + monkeypatch.setattr(search, "run_search", cleanup_failed) + stream = None + if kind == "closed": + stream = io.StringIO() + stream.close() + monkeypatch.setattr(sys, "stderr", stream) + try: + main(["recipe", "search", str(path)]) + except SystemExit as error: + code = error.code + except BaseException as error: # pragma: no cover - reported as the failure + pytest.fail(f"recipe search crashed with {error!r} instead of exiting 4") + assert code == 4 + out = capsys.readouterr().out + assert "a process group may still be running" in out + assert "could not write candidates/alpha.json" not in out # stderr-only, never stdout + + def test_recipe_cli_exits_four_on_process_cleanup_failure(setup_grid, monkeypatch, capsys): from obliteratus.cli import main from obliteratus.recipes import search