Skip to content

The agent that grows with you

fix(gateway): refuse WS writes on a restart_wait owner

Teknium492a075d3979
diff --git a/gateway/drain_control.py b/gateway/drain_control.py
index 33f7950cb21..219b063ef3a 100644
--- a/gateway/drain_control.py
+++ b/gateway/drain_control.py
@@ -61,6 +61,22 @@ def restart_wait_read(runner, method, path) -> bool:
return (method == "GET" and bool(_RESTART_WAIT_READS.fullmatch(path or ""))
and restart_wait_open(runner))
+# The WebSocket verbs an interactive client may still call during that wait: attach to and read the
+# parked session, answer its prompt (or interrupt the turn so the restart can finish) and commit
+# queued input for the next owner. Every other verb (config.set, session.save, rollback.restore,
+# process.kill, reload.*, ...) would run on an owner that is shutting down, so it is refused with
+# ``runtime_draining`` exactly like the REST writes above.
+RESTART_WAIT_WS_METHODS = frozenset({
+ "ping", "runtime.describe", "session.resume", "session.detach", "session.events.since",
+ "session.info", "session.list", "prompt.submit", "prompt.receipt", "session.interrupt",
+ "approval.pending", "approval.received", "approval.respond", "clarify.respond",
+})
+
+
+def ws_method_refused_while_draining(runner, method) -> bool:
+ """True when an interactive WebSocket verb must be refused because *runner* is draining."""
+ return bool(getattr(runner, "_draining", False)) and method not in RESTART_WAIT_WS_METHODS
+
_DRAIN_REQUEST_FILENAME = ".drain_request.json"
# Drain-gated lifecycle actions complete in minutes; an hour bounds the wedge a leaked
# marker can cause. Long drains refresh the marker instead of raising this.
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index a81103a9a7b..b12525d6d2e 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -197,6 +197,14 @@ class AuthorityConnection:
# Every handler indexes params as a mapping; refuse the frame before ``.get``.
return {'jsonrpc': '2.0', 'id': rid, 'error': {
'code': 4001, 'message': 'invalid_params', 'data': {'reason': 'invalid_params'}}}
+ from gateway.drain_control import ws_method_refused_while_draining
+ if self._operator is True and ws_method_refused_while_draining(getattr(self.authority, 'runner', None), method):
+ # An interactive socket reaches a draining owner only in a restart's after-turn wait:
+ # it may answer the parked turn and queue input, never change this owner's state.
+ exc = RuntimeStoreError('runtime_draining')
+ _log_refusal(getattr(self.actor, 'profile_id', None), method, exc)
+ return {'jsonrpc': '2.0', 'id': rid, 'error': {
+ 'code': 4001, 'message': exc.reason, 'data': _refusal_data(exc)}}
profile = params.get('profile')
if isinstance(profile, str) and profile:
try:
diff --git a/tests/gateway/test_restart_wait_prompt_reach.py b/tests/gateway/test_restart_wait_prompt_reach.py
index e1229c354af..da6ef2b7ade 100644
--- a/tests/gateway/test_restart_wait_prompt_reach.py
+++ b/tests/gateway/test_restart_wait_prompt_reach.py
@@ -118,3 +118,38 @@ async def test_restart_wait_serves_only_the_reads_that_open_the_parked_session()
del runner.session_runtime_descriptor['drain_reason'] # stop() began: nothing is served anymore
assert await status('GET', '/api/profiles/sessions/sidebar') == 503
assert reached == [('GET', path) for path in reads]
+
+
+async def test_restart_wait_ws_serves_the_parked_turn_and_refuses_every_other_verb(tmp_path):
+ """The interactive socket a restart's after-turn wait admits may resume, read and answer the
+ parked prompt; a write verb (config.set, session.save, process.kill, reload.*, ...) is refused
+ with runtime_draining before its handler runs on the shutting-down owner."""
+ from gateway.session_authority import LiveSession, SessionAuthority
+ from gateway.session_controls import AuthorityConnection
+
+ db = SessionDB(tmp_path / "state.db")
+ db.create_session("s", source="test")
+ runner = SimpleNamespace(_draining=True, _running=True,
+ session_runtime_descriptor={"state": "draining", "drain_reason": "restart_wait"})
+ authority = SessionAuthority(runner, profile_id="p", instance_id="owner", db=db,
+ epoch=begin_runtime_epoch(db, instance_id="owner"))
+ authority.sessions["s"] = LiveSession(None, "route")
+ viewer = AuthorityConnection(authority, object(), {"user_id": "human"}, operator=True)
+
+ async def call(method, **params):
+ return await viewer.dispatch({"id": 1, "method": method, "params": {"session_id": "s", **params}})
+
+ try:
+ assert "result" in await call("session.resume")
+ answered = await call("approval.respond", execution_generation=1, prompt_id="gone", choice="once")
+ # Reached the authority: a stale prompt is its own verdict, never the drain's refusal.
+ assert answered.get("error", {}).get("message") != "runtime_draining"
+ for method, params in [("config.set", {"key": "model", "value": "x"}), ("session.save", {}),
+ ("process.kill", {"pid": 1}), ("reload.mcp", {}), ("rollback.restore", {})]:
+ refused = await call(method, **params)
+ assert refused["error"]["message"] == "runtime_draining", method
+ finally:
+ await viewer.close()
+ db.close()
+