diff --git a/docs/system-specs/modules/instances.md b/docs/system-specs/modules/instances.md index 39b13feaa7c5..ad47e994c5b1 100644 --- a/docs/system-specs/modules/instances.md +++ b/docs/system-specs/modules/instances.md @@ -799,9 +799,9 @@ tunnel read it. `POST /api/instances/{id}/connect` answers `409` with `code: restarting` before the manager is called, and the startup revive stops at the next instance (the `was_connected` intent stays, so the new image revives the rest). `?only_if_connected=1` starts nothing and is answered as -usual. The seam stops the tunnels one after another inside `shutdown()`, so its -10 s bound covers about two forwarders that ignore SIGTERM (each costs its 5 s -wait), not an arbitrary number. +usual. `shutdown()` stops every tunnel at once, so the 5 s wait of each +forwarder that ignores SIGTERM runs beside the others' and the seam's 10 s +bound covers any number of them. The seam is for owners that supervise a child process. A cleanup hook whose resources end with the exec (in-memory state, files, sockets the exec closes) @@ -822,9 +822,8 @@ that lock, so it stops nothing. The connect gate above stops new connects from starting, but a connect already in flight keeps its lock. Making `shutdown()` independent of that lock is separate work. -A forwarder the seam does not stop in time (the lock wait above, or more -forwarders ignoring SIGTERM than the bound covers) outlives the exec as before -this seam existed, and that leak is accepted. The new image does not reclaim it +A forwarder the seam does not stop in time (the lock wait above) outlives the +exec as before this seam existed, and that leak is accepted. The new image does not reclaim it at startup. On POSIX the exec keeps both the pid and the process start time, so kernel facts cannot tell a child of the old image from one of the new image. Telling them apart would need an in-process boot mark compared against each platform's start token, on diff --git a/src/kiro_crew/instances/ssh_tunnel_manager_lifecycle.py b/src/kiro_crew/instances/ssh_tunnel_manager_lifecycle.py index 120b26ad1aca..fbd0653eaf42 100644 --- a/src/kiro_crew/instances/ssh_tunnel_manager_lifecycle.py +++ b/src/kiro_crew/instances/ssh_tunnel_manager_lifecycle.py @@ -889,8 +889,8 @@ async def shutdown(self: SshTunnelManager) -> None: self._recover_since.clear() for instance_id in list(self._refresh_tasks): self._cancel_token_refresh(instance_id) - ids = list(self._tunnels) - for instance_id in ids: + + async def _stop(instance_id: str) -> None: tunnel = self._tunnels.get(instance_id) self._tokens.pop(instance_id, None) self._peer_sessions.pop(instance_id, None) @@ -901,6 +901,12 @@ async def shutdown(self: SshTunnelManager) -> None: # Only once the stop has returned: a shutdown cut mid-stop leaves the # tunnel here, so the next shutdown (the gateway's exit path) stops it. self._tunnels.pop(instance_id, None) + + ids = list(self._tunnels) + # All at once: a forwarder that ignores SIGTERM is killed only after its + # stop's 5 s wait, and the restart gives this whole call one 10 s bound, + # which stopping them in turn would outrun from the second such one on. + await asyncio.gather(*(_stop(instance_id) for instance_id in ids)) # Every lent hop port goes with the process, so nothing stays bound by a # guard whose gateway is gone. The LEASE survives this, and # `sync_hop_holds` at the next startup is what re-takes the ports. diff --git a/test/test_restart_stops_instance_tunnels.py b/test/test_restart_stops_instance_tunnels.py index 85134d204ee1..e94c86875c6f 100644 --- a/test/test_restart_stops_instance_tunnels.py +++ b/test/test_restart_stops_instance_tunnels.py @@ -15,7 +15,9 @@ the poll and releases the block, and a restart reaches the exec released), that the skill-usage ledger's debounced hits reach disk before the exec, that a real child is reaped through the seam on each path and left running when -the path skips it, that an SSM forwarder's tree kill never blocks the loop, and +the path skips it, that the manager stops all its forwarders at once, so the +one bound covers every forwarder that ignores SIGTERM, that an SSM forwarder's +tree kill never blocks the loop, and that a fresh manager over the same registry (the new image) reconnects on the recorded port. """ @@ -672,6 +674,47 @@ async def _skipped(*_a, **_k): assert proc.returncode is not None +class TestTheForwardersStopTogether: + """A forwarder that ignores SIGTERM is killed only after its stop's 5 s wait, + under the restart's one 10 s bound, so a teardown that stops them one after + another is cut before the second one's SIGKILL. Each stop here waits for the + other to start, so a teardown that runs them in turn never finishes.""" + + @pytest.fixture(autouse=True) + def _free_ports(self, _floor_monkeypatch): + _pin_port_probe(_floor_monkeypatch) + + @pytest.mark.asyncio + async def test_every_forwarder_stop_is_under_way_at_once(self, tmp_path): + from kiro_crew.instances.registry import InstancesRegistry + from kiro_crew.instances.ssh_tunnel_manager import SshTunnelManager + + started = {"a": asyncio.Event(), "b": asyncio.Event()} + + class _WaitsForTheOther(_FakeTunnel): + async def stop(self): + own = self.status.instance_id + started[own].set() + await started["b" if own == "a" else "a"].wait() + await super().stop() + + reg = InstancesRegistry(path=tmp_path / "instances.json") + reg.add(name="A", ssh_host="a-alias", instance_id="a") + reg.add(name="B", ssh_host="b-alias", instance_id="b") + manager = SshTunnelManager( + reg, base_port=53900, mint_token=_mint, tunnel_factory=_WaitsForTheOther + ) + await manager.connect("a") + await manager.connect("b") + tunnels = dict(manager._tunnels) + register_pre_exec_stop("Instance tunnels", manager.shutdown) + + await run_pre_exec_stops() + + assert {iid: t.stopped for iid, t in tunnels.items()} == {"a": True, "b": True} + assert manager.status_all() == {} + + # ── the SSM tree kill runs off the loop ───────────────────────────────────