diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index ae3aa89b7..5a81c5b46 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -640,8 +640,17 @@ Kernels stay resident while their session uses them. A resting session releases ## drops - the connection drops (the relay's socket closes, or the bridge dies): the port owner reattaches with backoff (50 ms doubling to - 2 s, 40 tries); exit 3 or a refusal means the kernel is gone and the old - abandon path reaps it. a port owner attaching after a restart starts from + 2 s, 40 tries); exit 3 (no socket, or nothing listening on it) or a + refusal means the kernel is gone and the old abandon path reaps it. only + that proves a recorded kernel gone: an attach that fails any other way (a + socket that refuses the connection for another reason, an invalid + handshake, no hello within the startup window) logs + `kernel_unreachable_at_attach` with the reason, hands the session the kernel + as reattaching, and keeps attaching in the background. a local kernel still + unreachable after the 40 tries is let go like a detach (`kernel_unreachable` + in the log): its record stays, its own grace ends it, or the next open + attaches to it. a failed boot or proven-gone attach logs + `kernel_startup_failed` before it is reaped. a port owner attaching after a restart starts from the record's pid/pgid/leader and groups, so a kernel that died hard while nobody was attached still has its process group and its jobs' groups ended. the leader token (start time, from `/proc` or Darwin's `sysctl`) diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index 89923bf28..c694e5ab0 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -555,28 +555,35 @@ startup(S = #{port := Port}, Mode, Parent, Ref, Deadline) -> end; {refused, _, S1} -> startup_fail(S1, Parent, Ref, lost); {skip, S1} -> startup(S1, Mode, Parent, Ref, Deadline); + invalid when Mode =:= attach -> unreachable(S, Parent, Ref, invalid_handshake); invalid -> startup_fail(S, Parent, Ref, {unavailable, <<"invalid kernel handshake">>}) end; {host_reply, Id, Reply} -> startup(host_reply(Id, Reply, S), Mode, Parent, Ref, Deadline); flush_ack -> startup(flush_ack(S), Mode, Parent, Ref, Deadline); + {Port, {data, _}} when Mode =:= attach -> unreachable(S, Parent, Ref, invalid_handshake); {Port, {data, _}} -> startup_fail(S, Parent, Ref, {unavailable, <<"invalid kernel handshake">>}); {Port, {exit_status, ?GONE}} when Mode =:= attach -> startup_fail(S#{port => none}, Parent, Ref, lost); - %% Only "no kernel there" or a refusal proves a remote kernel gone. Any - %% other end of an attach (ssh down, a timeout) is a connection that - %% dropped: the kernel stays ours and is attached again in the - %% background, as after a drop mid-session. - {Port, {exit_status, _}} when Mode =:= attach, map_get(remote, S) =/= none -> - detached_start(S#{port => none}, Parent, Ref); + %% Only "no kernel there" or a refusal proves a recorded kernel gone. + %% Any other end of an attach (ssh down, a socket that refuses us for + %% another reason, a timeout) is a connection that dropped: the kernel + %% stays ours and is attached again in the background, as after a drop + %% mid-session. Ending it here would end a live namespace and its jobs. + {Port, {exit_status, Status}} when Mode =:= attach -> + unreachable(S#{port => none}, Parent, Ref, {exit_status, Status}); {Port, {exit_status, ?NO_FOLDER}} when Mode =:= start, map_get(remote, S) =/= none -> startup_fail(S#{port => none}, Parent, Ref, {unavailable, <<(maps:get(cwd, S))/binary, " is not a folder there">>}); {Port, {exit_status, ?SSH_FAILED}} when map_get(remote, S) =/= none -> startup_fail(S#{port => none}, Parent, Ref, {unavailable, <<"ssh to the kernel's host failed">>}); {Port, {exit_status, _}} -> startup_fail(S#{port => none}, Parent, Ref, {unavailable, <<"python exited at startup">>}); + {'DOWN', _, process, _, _} when Mode =:= attach -> + %% The daemon is stopping: let the kernel be, as a detach would. + close_port(Port), + Parent ! {Ref, {error, {unavailable, <<"kernel owner stopped during attach">>}}}; {'DOWN', _, process, _, _} -> startup_fail(S, Parent, Ref, lost) after After -> - case Mode =:= attach andalso maps:get(remote, S) =/= none of - true -> close_port(Port), detached_start(S#{port => none}, Parent, Ref); - false -> startup_fail(S, Parent, Ref, {unavailable, <<"python startup timed out">>}) + case Mode of + attach -> unreachable(S, Parent, Ref, startup_timeout); + start -> startup_fail(S, Parent, Ref, {unavailable, <<"python startup timed out">>}) end end. @@ -623,13 +630,20 @@ observation_value(S) -> {observation, maps:get(kernel, S), Build, maps:get(port, S) =/= none, Stale, Count, JobIds, job_summaries(Jobs, Remote), Unlisted}. -%% A remote kernel on record that ssh can't reach right now: the session gets -%% it at once, reattaching, and the attach goes on in the background. +%% A kernel on record that did not answer this attach and was not proved +%% gone: the session gets it at once, reattaching, and the attach goes on in +%% the background. +unreachable(S = #{port := Port}, Parent, Ref, Reason) -> + close_port(Port), + log({kernel_unreachable_at_attach, maps:get(kernel, S), Reason}), + detached_start(S#{port => none}, Parent, Ref). + detached_start(S, Parent, Ref) -> albedo_clock:send_after(backoff(S), self(), reattach), started(lost_at(S), Parent, Ref). startup_fail(S, Parent, Ref, Error) -> + log({kernel_startup_failed, maps:get(kernel, S), Error}), reap_start(S), Parent ! {Ref, {error, Error}}. execute(Pid, Id, Data, Timeout) -> call(Pid, {execute, Id, Data, Timeout}). @@ -972,22 +986,29 @@ reattach(S = #{remote := {some, _}, give_up := GiveUp}) when is_integer(GiveUp) true -> expire(S); false -> attach_again(S) end; +%% Out of tries without proof the kernel is gone: let it go as a detach does, +%% keeping its record, so its own grace ends it or the next open attaches. reattach(S = #{retries := Tries}) when Tries >= ?REATTACH_TRIES -> log({kernel_unreachable, maps:get(kernel, S)}), - abandon(S); + release(S), + nil; reattach(S) -> attach_again(S). %% A remote kernel unreachable for longer than its grace has exited by itself %% and reaped its own jobs: forget it without reaching for the host again. expire(S) -> + link_forget(release(S)), + nil. + +%% Stop owning the kernel without touching it: a waiting cell hears it is lost. +release(S) -> case maps:get(active, S) of {From, Ref, Timer, Caller, _} -> erlang:cancel_timer(Timer), demonitor(Caller, [flush]), From ! {Ref, {error, lost}}; none -> ok end, - link_forget(S), - nil. + S. attach_again(S = #{retries := Tries}) -> case open_bridge(S, attach) of diff --git a/src/albedo/harness/extensions/python/kernel.gleam b/src/albedo/harness/extensions/python/kernel.gleam index 769c39ddd..5ef2be3ab 100644 --- a/src/albedo/harness/extensions/python/kernel.gleam +++ b/src/albedo/harness/extensions/python/kernel.gleam @@ -755,25 +755,26 @@ fn reattach( case link.find(store, session) { None -> Error(Nil) Some(record) -> - case boot(record, False), location.parse(cwd) { - Error(Lost), _ | Error(_), Ok(location.Local(_)) -> { - // Gone. The port owner forgets what it found gone; this also covers - // a local bridge that never started. + case boot(record, False) { + // Gone: no kernel at its socket, or one that refused its token. The + // port owner forgets what it found gone. Any other failure proves + // nothing, so the record stays for the kernel's next attach. + Error(Lost) -> { link.lose(store, record) let _ = link.forget(store, record) Error(Nil) } - Error(_), _ -> Error(Nil) - Ok(kernel), _ if record.cwd == cwd && record.modules == modules -> + Error(_) -> Error(Nil) + Ok(kernel) if record.cwd == cwd && record.modules == modules -> Ok(kernel) // Another module set: kept, like an older bundle, and swapped at the // session's next idle moment so its variables come along. - Ok(kernel), _ if record.cwd == cwd -> { + Ok(kernel) if record.cwd == cwd -> { mark_stale(kernel, Modules) Ok(kernel) } // Another workspace is a move, which never keeps the namespace. - Ok(kernel), _ -> { + Ok(kernel) -> { io.println_error( "kernel " <> record.kernel diff --git a/test/e2e/kernel_detach_test.py b/test/e2e/kernel_detach_test.py index a4986f446..cd33f0624 100644 --- a/test/e2e/kernel_detach_test.py +++ b/test/e2e/kernel_detach_test.py @@ -13,6 +13,7 @@ import signal import sqlite3 import subprocess from contextlib import closing +from pathlib import Path import time import unittest @@ -132,6 +133,33 @@ class KernelDetachTests(unittest.TestCase): after = self.cell("survivor += 1\n(survivor, os.getpid())") self.assertEqual(after["value"], f"(42, {first['value']})") + @exclusive + def test_a_kernel_unreachable_at_restart_is_kept_until_it_answers(self): + """Only proof of absence forgets a kernel: a socket that refuses the + attach for another reason leaves the kernel, its namespace and its + jobs alone, and the daemon attaches once the socket answers.""" + first = self.cell(HOLD + "import os\nsurvivor = 41\nos.getpid()") + kernel = int(first["value"]) + with closing(sqlite3.connect(self.app.home / "albedo.sqlite")) as db: + (run_dir,) = db.execute( + "SELECT run_dir FROM kernel_links WHERE session=?", (self.session,) + ).fetchone() + socket_path = Path(run_dir) / "kernel.sock" + # connect(2) fails with EACCES, which says nothing about the kernel. + self.app.restart(prepare=lambda app: socket_path.chmod(0)) + log = self.app.home / "daemon.log" + harness.wait_until( + lambda: ( + not alive(kernel) or "kernel_unreachable_at_attach" in log.read_text() + ), + 15, + "the daemon never tried to attach", + ) + self.assertTrue(alive(kernel), "an unreachable kernel was ended") + socket_path.chmod(0o600) + after = self.cell("survivor += 1\n(survivor, os.getpid())") + self.assertEqual(after["value"], f"(42, {kernel})") + @exclusive def test_a_connection_dropped_mid_cell_still_delivers_the_result(self): first = self.cell(HOLD + "import os\nos.getpid()")