Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Do not let the signal handler's own logging stop it dying (#9083)
Daniel Han68815aa8884d
diff --git a/.github/scripts/kaggle_t4_ci/launch.py b/.github/scripts/kaggle_t4_ci/launch.pyindex afa5f2f9e21..0e0dea23177 100644--- a/.github/scripts/kaggle_t4_ci/launch.py+++ b/.github/scripts/kaggle_t4_ci/launch.py@@ -55,6 +55,7 @@ import argparseimport jsonimport osimport re+import selectimport atexitimport shutilimport signal@@ -215,8 +216,84 @@ def worst_case_seconds(max_wait: int, kernels: int) -> int:)+_STDOUT_FD = 1++# Set once, on entry to the signal handler, and never cleared: the process is dying.+# Below it, NO line written to stdout may either block or raise, and both have to be+# handled here rather than at the handler's own call sites. release() reports a refused+# delete and warns about a kernel it could not delete through the ordinary path, so those+# lines are reached transitively, and either failure strands the cleanup: a block never+# reaches the retry or the `finally`, and a raise propagates out of delete_kernel() and+# abandons the remaining delete attempts for a kernel that is still billing.+_IN_SIGNAL_HANDLER = False+++def _writable(fd: int) -> bool:+ """Whether a write to ``fd`` can proceed without blocking, asked without writing.++ A regular file or a terminal always answers yes; a pipe answers no exactly when it+ has backed up, which is the case worth avoiding. Any error answers no: a closed or+ unselectable descriptor is not somewhere to risk a stall from a signal handler.+ """+ try:+ return bool(select.select([], [fd], [], 0)[1])+ except BaseException: # noqa: BLE001+ return False+++def _line_from_signal(line: str) -> None:+ """One line out, from a context where the ordinary path can raise OR block.++ It can RAISE: a handler runs on the main thread wherever that thread happened to be,+ and if it was inside a write to stdout the interpreter refuses the second one+ outright, ``RuntimeError: reentrant call inside <_io.BufferedWriter name='<stdout>'>``.+ That is not hypothetical; it was captured on a loaded CI runner, where it escaped the+ handler and left a cancelled launcher exiting 1 instead of dying of its signal.+ ``os.write`` goes straight to the descriptor and takes no lock the interrupted frame+ could already hold, which is what makes it usable as the fallback.++ It can also BLOCK, which raising does not cover and no ``except`` or ``finally``+ catches. stdout in CI is a pipe, and if the collector stops draining it both the+ buffered flush and the raw write sleep in the kernel. That backpressure is also what+ leaves the main thread parked mid-write, so the two arrive together. Asking first+ turns the stall into a dropped line: POSIX reports a pipe writable only when at least+ PIPE_BUF bytes fit, and these lines are far shorter than that.+ """+ if not _writable(_STDOUT_FD):+ return+ try:+ _emit(line)+ except BaseException: # noqa: BLE001 -- a log line may never decide whether we die+ try:+ os.write(_STDOUT_FD, (line + "\n").encode("utf-8", "replace"))+ except BaseException: # noqa: BLE001+ pass+++def _emit(line: str) -> None:+ print(line, flush = True)+++def _write_line(line: str) -> None:+ """Every line this script puts on stdout goes through here.++ Unconditional on the ordinary path, which is everything before something kills us:+ nothing dropped, nothing swallowed, no syscall added.+ """+ if not _IN_SIGNAL_HANDLER:+ _emit(line)+ return+ _line_from_signal(line)++def _log(msg: str) -> None:- print(f"[launch] {msg}", flush = True)+ _write_line(f"[launch] {msg}")+++def _log_from_signal(msg: str) -> None:+ """``_log`` for the handler's own lines. Kept as its own name because the handler+ runs before the flag it sets can matter to anything else reading this."""+ _line_from_signal(f"[launch] {msg}")def _out(key: str, value: str) -> None:@@ -935,8 +1012,17 @@ def _install_release_handlers(release: Callable[[], None]) -> None:atexit.register(release)def _release_and_die(signum, _frame):- _log(f"received signal {signum}; deleting kernels before exiting")+ # First, and outside the try: from here on every _log in this process drops a+ # line rather than stalling on a stdout nobody is draining. release() logs+ # through the ordinary path -- delete_kernel() reports a refused delete that way+ # -- and a stall there is a stall before the retry and before the `finally`.+ global _IN_SIGNAL_HANDLER+ _IN_SIGNAL_HANDLER = True+ # Everything before the `finally` is best effort. The death is not: a handler+ # that returns normally leaves the process exiting on whatever code main()+ # computes, and a cancelled job then reads as a completed one.try:+ _log_from_signal(f"received signal {signum}; deleting kernels before exiting")release()except BaseException as exc: # noqa: BLE001# A raise here used to propagate into the main thread, where main()'s@@ -946,21 +1032,23 @@ def _install_release_handlers(release: Callable[[], None]) -> None:# RETURNING 0, and the cancelled job read as completed. Deleting is# best effort, the exit status is not. Retried once, since the kernel# is billing meanwhile.- _log(f"release() failed under signal {signum}: {type(exc).__name__}: {exc}")+ _log_from_signal(f"release() failed under signal {signum}: {type(exc).__name__}: {exc}")try:release()except BaseException as retry_exc: # noqa: BLE001# Nothing more to try in-process: the slug stays in the registry# for the next launch's orphan sweep, as after a kill -9.- _log(+ _log_from_signal(f"release() failed again: {type(retry_exc).__name__}: {retry_exc}. "f"The kernels stay in the registry for the next launcher's sweep")- # Die of the original signal rather than exiting 0, so the status- # still reads "killed by signal N". A CI system treats a 0 from a- # cancelled job as a completed one.- signal.signal(signum, signal.SIG_DFL)- os.kill(os.getpid(), signum)+ finally:+ # Die of the original signal rather than exiting 0, so the status+ # still reads "killed by signal N". A CI system treats a 0 from a+ # cancelled job as a completed one. In a `finally` because anything+ # above can raise -- including the logging, which is how this was found.+ signal.signal(signum, signal.SIG_DFL)+ os.kill(os.getpid(), signum)for _sig in (signal.SIGINT, signal.SIGTERM, getattr(signal, "SIGHUP", None)):if _sig is None:@@ -1066,12 +1154,16 @@ def main() -> int:entry["released"] = all(s in done for s in _slugs_filed(entry))result["unreleased"] = leakedif leaked:- print(+ # _write_line, not _log: the [launch] prefix would stop GitHub parsing+ # this as an annotation. Not print: release() runs from the signal handler+ # too, and this line is emitted on exactly the path where a kernel is still+ # billing, so a raw write here blocks or raises before the handler can+ # re-raise its signal.+ _write_line("::warning title=Kaggle kernels may still be running::"+ ", ".join(leaked)+ " could not be deleted, so they may keep billing accelerator "- "quota until they hit their own ceiling. Delete them by hand.",- flush = True,+ "quota until they hit their own ceiling. Delete them by hand.")# From here on release() is reachable from a signal and from atexit too,diff --git a/tests/kaggle/test_launch_cleanup.py b/tests/kaggle/test_launch_cleanup.pyindex baece94dafa..5c379e7aab0 100644--- a/tests/kaggle/test_launch_cleanup.py+++ b/tests/kaggle/test_launch_cleanup.py@@ -418,6 +418,45 @@ def _waiting_launcher(outdir: Path) -> str:)+def _flooding_launcher(outdir: Path) -> str:+ """A launcher parked inside a write to a stdout nobody is draining.++ Two things differ from `_waiting_launcher`. It writes until the pipe is full instead+ of sleeping, so when the signal lands the main thread is asleep in the kernel holding+ the buffer lock rather than merely idle. And its delete logs on the way through, so+ the handler meets a blocking `_log` it did not call itself: `delete_kernel` reports a+ refused delete through the ordinary path, and a stall there is a stall before the+ retry and before the `finally` that re-raises the signal. A fake deletion that+ succeeds silently never reaches that.+ """+ return (+ _waiting_launcher(outdir)+ .replace(+ " time.sleep(%d)" % _STALL_SEC,+ "\n".join(+ [+ " while True:",+ " sys.stdout.write('x' * 65536)",+ " sys.stdout.flush()",+ ]+ ),+ )+ .replace(+ " launch.main()",+ "\n".join(+ [+ " _real_delete = launch.delete_kernel",+ " def _noisy_delete(slug):",+ " launch._log(f'deleting {slug}')",+ " return _real_delete(slug)",+ " launch.delete_kernel = _noisy_delete",+ " launch.main()",+ ]+ ),+ )+ )++@pytest.mark.parametrize("signame", ["SIGINT", "SIGTERM"])def test_a_signalled_launcher_deletes_its_kernels(tmp_path, signame):"""SIGTERM is what `kill` and an Actions cancel send; SIGINT is Ctrl-C.@@ -521,6 +560,273 @@ def test_the_stall_outlasts_the_death_budget():)+def test_the_handler_survives_its_own_logging_failing(tmp_path):+ """The reentrancy that a contended runner produced, made deterministic.++ A signal handler runs on the main thread wherever it was, and if that was inside a+ write to stdout the interpreter refuses the second one: ``RuntimeError: reentrant+ call inside <_io.BufferedWriter name='<stdout>'>``. Captured on a staging runner,+ where it escaped the handler before it could re-raise the signal and the launcher+ exited 1. Nothing about the timing is reproduced here; the failure it causes is,+ by making the handler's own log call raise.+ """+ proc = _runner(+ tmp_path,+ _waiting_launcher(tmp_path / "out").replace(+ " launch.main()",+ "\n".join(+ [+ " _real_emit = launch._emit",+ " def _reentrant(line):",+ " if 'received signal' in line:",+ " raise RuntimeError(",+ ' "reentrant call inside <_io.BufferedWriter "',+ " \"name='<stdout>'>\")",+ " _real_emit(line)",+ " launch._emit = _reentrant",+ " launch.main()",+ ]+ ),+ ),+ )+ try:+ _await_ready(proc)+ proc.send_signal(signal.SIGTERM)+ _wait_for_death(proc)+ finally:+ if proc.poll() is None:+ proc.kill()+ assert proc.returncode == -signal.SIGTERM, (+ f"a log call that raised inside the handler turned SIGTERM into returncode "+ f"{proc.returncode}. Launcher said: {_tail(proc)}"+ )+ # And the kernel is still deleted: the logging is what failed, not the cleanup.+ assert any("me/k-1" in c for c in _deletions(tmp_path))+++def test_the_handler_survives_a_stdout_nobody_is_draining(tmp_path):+ """Raising is not the only way a log line stops the handler; blocking is the other.++ stdout in CI is a pipe. If whatever collects it stops reading, the pipe fills and a+ write goes to sleep in the kernel instead of failing, so no ``except`` and no+ ``finally`` runs. The handler announces itself BEFORE calling ``release()``, so the+ kernels would keep billing until something killed the launcher from outside, which is+ the one outcome this file exists to prevent. The same backpressure is what makes the+ reentrancy above likely, so the two arrive together.++ Reproduced exactly: the launcher writes until the pipe is full and this test never+ reads a byte of it, so the main thread is asleep inside a write, holding the buffer+ lock, when the signal lands. Both the buffered path and the raw descriptor are then+ unavailable, and the line has to be dropped rather than waited on.+ """+ proc = _runner(tmp_path, _flooding_launcher(tmp_path / "out"))+ try:+ _await_ready(proc)+ time.sleep(2) # long enough for the pipe to fill and the write to park+ proc.send_signal(signal.SIGTERM)+ _wait_for_death(proc)+ finally:+ if proc.poll() is None:+ proc.kill()+ assert any("me/k-1" in c for c in _deletions(tmp_path)), (+ "a full stdout pipe stopped the handler before release(), so the kernel stayed up "+ "and billed. The diagnostic must be dropped rather than blocked on."+ )+ assert json.loads((tmp_path / "inflight.json").read_text()) == []+ assert proc.returncode == -signal.SIGTERM, (+ f"the launcher exited {proc.returncode} rather than dying of SIGTERM after its "+ f"logging blocked"+ )+++def test_a_reentrant_log_inside_the_delete_retries_does_not_abandon_them(tmp_path):+ """The transitive path, where a dropped line costs a whole retry budget.++ ``delete_kernel`` reports a refused delete through the ordinary ``_log``. If that+ raises the reentrancy above, the exception propagates out of ``delete_kernel`` and+ out of ``release()``, so a kernel Kaggle would have accepted on the third attempt is+ never asked a third time. Distinct from the handler's own lines, which were already+ wrapped, and from a full pipe, which drops rather than raises.++ Here the shim refuses twice and accepts on the third, and every ``_emit`` raises+ while the handler is running, so the retries only complete if the failure is+ swallowed where it happens.+ """+ record = tmp_path / "kaggle_calls.txt"+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir(parents = True, exist_ok = True)+ shim = bin_dir / "kaggle"+ shim.write_text(+ textwrap.dedent(f"""\+ #!{sys.executable}+ import sys, pathlib+ record = pathlib.Path({str(record)!r})+ record.open("a").write(" ".join(sys.argv[1:]) + "\\n")+ seen = sum(1 for l in record.read_text().splitlines() if l.startswith("kernels delete"))+ if seen < 3: # refuse the first two, accept the third+ sys.stderr.write("500 Server Error\\n")+ sys.exit(1)+ """),+ encoding = "utf-8",+ )+ shim.chmod(0o755)++ script = tmp_path / "runner.py"+ script.write_text(+ textwrap.dedent(f"""\+ import sys, time+ sys.path.insert(0, {str(CI_DIR)!r})+ import launch+ launch.INFLIGHT = __import__("pathlib").Path({str(tmp_path / "inflight.json")!r})+ launch.DELETE_BACKOFF_SEC = 0+ _real_emit = launch._emit+ def _reentrant(line):+ if launch._IN_SIGNAL_HANDLER:+ raise RuntimeError(+ "reentrant call inside <_io.BufferedWriter name='<stdout>'>")+ _real_emit(line)+ launch._emit = _reentrant+ def release():+ if launch.delete_kernel("me/k-1"):+ launch._inflight_drop("me/k-1")+ launch._inflight_add("me/k-1")+ launch._install_release_handlers(release)+ print("READY", flush=True)+ time.sleep({_STALL_SEC})+ """),+ encoding = "utf-8",+ )+ env = {**os.environ, "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}"}+ proc = subprocess.Popen(+ [sys.executable, str(script)],+ env = env,+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ text = True,+ )+ try:+ _await_ready(proc)+ proc.send_signal(signal.SIGTERM)+ _wait_for_death(proc)+ finally:+ if proc.poll() is None:+ proc.kill()++ attempts = _deletions(tmp_path)+ assert len(attempts) >= 3, (+ f"only {len(attempts)} delete attempts were made. A log line raising inside "+ f"delete_kernel abandoned the retries, so a kernel Kaggle would have released "+ f"on the third attempt keeps billing. Launcher said: {_tail(proc)}"+ )+ assert json.loads((tmp_path / "inflight.json").read_text()) == []+++def test_the_leaked_kernel_warning_does_not_strand_the_handler(tmp_path):+ """The branch that only opens when cleanup has already failed.++ ``release()`` ends by warning about kernels it could not delete. That line is+ emitted on exactly the path where a kernel is still billing, so a raw write there+ blocks on a full pipe before the ``finally`` can re-raise the signal: the launcher+ neither dies nor reports, and the kernel runs on. Every other test in this file has+ a deletion that eventually succeeds, which leaves the warning unreached.+ """+ record = tmp_path / "kaggle_calls.txt"+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir(parents = True, exist_ok = True)+ shim = bin_dir / "kaggle"+ shim.write_text(+ textwrap.dedent(f"""\+ #!{sys.executable}+ import sys, pathlib+ pathlib.Path({str(record)!r}).open("a").write(" ".join(sys.argv[1:]) + "\\n")+ sys.stderr.write("500 Server Error\\n")+ sys.exit(1)+ """),+ encoding = "utf-8",+ )+ shim.chmod(0o755)++ body = _flooding_launcher(tmp_path / "out").replace(+ " launch.main()", " launch.DELETE_BACKOFF_SEC = 0\n launch.main()"+ )+ script = tmp_path / "runner.py"+ script.write_text(+ textwrap.dedent(f"""\+ import sys, time+ sys.path.insert(0, {str(CI_DIR)!r})+ import launch+ launch.INFLIGHT = __import__("pathlib").Path({str(tmp_path / "inflight.json")!r})+ {body}+ """),+ encoding = "utf-8",+ )+ env = {**os.environ, "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}"}+ proc = subprocess.Popen(+ [sys.executable, str(script)],+ env = env,+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ text = True,+ )+ try:+ _await_ready(proc)+ time.sleep(2) # let the pipe fill and the write park+ proc.send_signal(signal.SIGTERM)+ _wait_for_death(proc)+ finally:+ if proc.poll() is None:+ proc.kill()+ assert proc.returncode == -signal.SIGTERM, (+ f"the launcher exited {proc.returncode} rather than dying of SIGTERM. Its "+ f"warning about the kernel it could not delete is the last thing it writes, "+ f"and on a full pipe that write is where it stopped."+ )+ # It really did reach the branch, so the assertion above is not vacuous.+ assert _deletions(tmp_path), "no delete was attempted, so nothing could leak"+++def _failing_kaggle(bin_dir: Path, record: Path) -> None:+ """A `kaggle` that records the call and then refuses it, so nothing is ever+ released and release() reaches its leaked-kernel warning."""+ bin_dir.mkdir(parents = True, exist_ok = True)+ shim = bin_dir / "kaggle"+ shim.write_text(+ textwrap.dedent(f"""\+ #!{sys.executable}+ import sys, pathlib+ pathlib.Path({str(record)!r}).open("a").write(" ".join(sys.argv[1:]) + "\\n")+ sys.stderr.write("500 Server Error\\n")+ sys.exit(1)+ """),+ encoding = "utf-8",+ )+ shim.chmod(0o755)+++def test_the_leaked_warning_is_still_a_github_annotation(tmp_path, monkeypatch, capsys):+ """Routing it through the safe writer must not add the [launch] prefix.++ GitHub matches an annotation from the START of the line, so a prefixed one is an+ ordinary log line that nothing surfaces, and this warning exists precisely to be+ surfaced: it is the only thing that tells a human a kernel is still billing.++ Driven through main() with a kaggle that always refuses, so this reads what+ release() actually wrote. Calling the writer directly would pass whatever the call+ site does, which is the thing that can regress.+ """+ _run_main(tmp_path, monkeypatch, push_impl = _push_ok("me/k-1"), kaggle = _failing_kaggle)+ lines = capsys.readouterr().out.splitlines()+ warnings = [l for l in lines if "Kaggle kernels may still be running" in l]+ assert warnings, (+ f"release() never warned about the kernel it could not delete. Output was: " f"{lines[-8:]}"+ )+ assert warnings[0].startswith("::warning"), (+ f"the annotation was written as {warnings[0]!r}. GitHub matches ::warning at the "+ f"start of the line, so a prefix silently demotes the one message that says a "+ f"kernel is still billing into an ordinary log line nobody sees."+ )++def test_an_unhandled_exception_still_deletes(tmp_path):"""atexit covers the path no signal handler sees.