Skip to content

Commit 9f2b077

Browse files
acn-ericlawclaude
andcommitted
feat(platform): Platform.on_shutdown - the agent-question streams end when the application stops; the bundle rebuilt
Found by the live drive of the React UI (mercury-composable docs/test-reports/agent-question-ui-live-drive.md): a device holding the agent-question stream kept a stopping backend alive - after SIGTERM the host stopped listening within two seconds but aiohttp waited for the stream, which never ends on its own, and the process was still there 75 seconds later; in a container, the grace period and a SIGKILL. Platform.on_shutdown maps to aiohttp's on_shutdown: the moment the application starts to stop, before the host waits for the requests in flight; the agent-question app ends every device's stream there (close_streams) and the devices reconnect to the next instance from their last sequence. Re-driven: the process gone within a second of SIGTERM, the device connected again three seconds after the restart. The bundle rebuilt in the Node.js pack (the card order within a case, mark all notices as seen) and recommitted here. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
1 parent 96629e2 commit 9f2b077

7 files changed

Lines changed: 74 additions & 10 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,18 @@
185185
bundle is served (`/`, the hashed script and stylesheet, `/favicon.svg`) and the five actuator endpoints answer
186186
beside it.
187187

188+
10. **`Platform.on_shutdown(callback)`: the moment the application starts to stop, while the host still holds its
189+
connections and before it waits for the requests in flight - aiohttp's `on_shutdown`, the place to end a
190+
long-lived response; in lockstep with the Node.js pack's `Platform.onShutdown`.** The live drive of the React UI
191+
(2026-11-20) found that a device holding the agent-question stream kept a stopping backend alive: after SIGTERM
192+
the host stopped listening within two seconds but waited for the stream, which never ends on its own, and the
193+
process was still there 75 seconds later - in a container, the manager's grace period and a SIGKILL. The
194+
agent-question app now ends every connected device's stream in that hook (`close_streams`: the wake-ups close, a
195+
stream opened while stopping ends at once) and the devices reconnect to the next instance from their last
196+
sequence, missing nothing; the cleanup (`on_cleanup`) still closes the stores after the last request. **How to
197+
apply:** an extension that holds a stream or a socket open ends it in `on_shutdown` and closes its stores in
198+
`on_cleanup`.
199+
188200
### Fixed
189201

190202
1. **The agent-question app keeps the first accepted decision when two devices decide one card at the same moment**

‎extensions/agent-question/agent_question.py‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -605,24 +605,35 @@ def failure(exc: BaseException) -> str:
605605

606606

607607
class Wakeups:
608-
"""Every connected device holds a queue; a changed row goes to all of them."""
608+
"""Every connected device holds a queue; a changed row goes to all of them. ``close`` ends every
609+
stream (``None`` on the queue) when the application stops, so the host can close its connections."""
609610

610611
def __init__(self) -> None:
611-
self._queues: set[asyncio.Queue[Row]] = set()
612+
self._queues: set[asyncio.Queue[Row | None]] = set()
613+
self.closing = False
612614

613-
def subscribe(self) -> asyncio.Queue[Row]:
614-
queue: asyncio.Queue[Row] = asyncio.Queue()
615+
def subscribe(self) -> asyncio.Queue[Row | None]:
616+
queue: asyncio.Queue[Row | None] = asyncio.Queue()
615617
self._queues.add(queue)
618+
if self.closing:
619+
queue.put_nowait(None)
616620
return queue
617621

618-
def unsubscribe(self, queue: asyncio.Queue[Row]) -> None:
622+
def unsubscribe(self, queue: asyncio.Queue[Row | None]) -> None:
619623
self._queues.discard(queue)
620624

621625
def publish(self, rows: Sequence[Row]) -> None:
622626
for queue in list(self._queues):
623627
for row in rows:
624628
queue.put_nowait(row)
625629

630+
def close(self) -> None:
631+
"""The application is stopping: every connected device's stream ends now, and a stream opened
632+
from here on ends at once; the devices reconnect to the next instance."""
633+
self.closing = True
634+
for queue in list(self._queues):
635+
queue.put_nowait(None)
636+
626637
@property
627638
def connected(self) -> int:
628639
return len(self._queues)
@@ -920,6 +931,8 @@ async def events(request: web.Request) -> web.StreamResponse:
920931
except asyncio.TimeoutError:
921932
await response.write(b": ping\n\n")
922933
continue
934+
if row is None:
935+
break # the application is stopping; the device reconnects
923936
if row.seq > since:
924937
await response.write(_frame(row))
925938
since = row.seq
@@ -1095,6 +1108,13 @@ async def boot() -> None:
10951108
_reader.name, _feed.cursor, EVENTS_PATH, settings.poll_ms, settings.auth)
10961109

10971110

1111+
async def close_streams() -> None:
1112+
"""The application is stopping (``Platform.on_shutdown``): end every connected device's stream, so the
1113+
host can close its connections and exit within a container manager's grace period; a device reconnects to
1114+
the next instance from its last sequence and misses nothing."""
1115+
_wakeups.close()
1116+
1117+
10981118
async def shutdown() -> None:
10991119
global _http
11001120
await _feed.stop()
@@ -1107,6 +1127,7 @@ async def shutdown() -> None:
11071127

11081128
def _attach() -> None:
11091129
platform.on_startup(boot)
1130+
platform.on_shutdown(close_streams)
11101131
platform.on_cleanup(shutdown)
11111132
platform.add_routes(mount)
11121133

extensions/agent-question/resources/public/assets/index-CgA82AJ7.js renamed to extensions/agent-question/resources/public/assets/index-DLhN8ruL.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

extensions/agent-question/resources/public/assets/index-Dqfn5cl4.css renamed to extensions/agent-question/resources/public/assets/index-fkLr7X1H.css

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎extensions/agent-question/resources/public/index.html‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
<meta name="color-scheme" content="light dark" />
77
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
88
<title>Agent questions</title>
9-
<script type="module" crossorigin src="/assets/index-CgA82AJ7.js"></script>
10-
<link rel="stylesheet" crossorigin href="/assets/index-Dqfn5cl4.css">
9+
<script type="module" crossorigin src="/assets/index-DLhN8ruL.js"></script>
10+
<link rel="stylesheet" crossorigin href="/assets/index-fkLr7X1H.css">
1111
</head>
1212
<body>
1313
<div id="root"></div>

‎src/mercury_composable/server.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,7 @@ class Platform:
458458
def __init__(self, registry: FunctionRegistry | None = None):
459459
self.registry = registry or default_registry
460460
self._startup: list[Callable[[], Awaitable[None]]] = []
461+
self._shutdown: list[Callable[[], Awaitable[None]]] = []
461462
self._cleanup: list[Callable[[], Awaitable[None]]] = []
462463
self._routes: list[RouteMounter] = []
463464

@@ -468,6 +469,14 @@ def on_startup(self, callback: Callable[[], Awaitable[None]]) -> None:
468469
before it listens, so a boot failure is a failure to start, never a run-time surprise."""
469470
self._startup.append(callback)
470471

472+
def on_shutdown(self, callback: Callable[[], Awaitable[None]]) -> None:
473+
"""Run an async callback the moment the application starts to stop (SIGTERM, SIGINT), while
474+
the host still holds its connections and before it waits for the requests in flight - the
475+
place to end a long-lived response, such as a stream a browser holds, which otherwise keeps
476+
the process alive past a container manager's grace period. The cleanup callbacks run after
477+
the last request."""
478+
self._shutdown.append(callback)
479+
471480
def on_cleanup(self, callback: Callable[[], Awaitable[None]]) -> None:
472481
"""Run an async callback when the application shuts down, after the last request."""
473482
self._cleanup.append(callback)
@@ -481,7 +490,7 @@ def add_routes(self, mount: RouteMounter) -> None:
481490
self._routes.append(mount)
482491

483492
def create_app(self) -> web.Application:
484-
"""The Event API application with this platform's startup and cleanup callbacks
493+
"""The Event API application with this platform's startup, shutdown and cleanup callbacks
485494
attached, and the opt-in OpenTelemetry forwarder activated on its extension route;
486495
``run`` serves it, and a test may serve it with aiohttp's own runner."""
487496
config = app_config()
@@ -491,6 +500,8 @@ def create_app(self) -> web.Application:
491500
app = EventApiServer(self.registry).create_app(self._routes)
492501
for callback in self._startup:
493502
app.on_startup.append(_lifecycle(callback))
503+
for callback in self._shutdown:
504+
app.on_shutdown.append(_lifecycle(callback))
494505
for callback in self._cleanup:
495506
app.on_cleanup.append(_lifecycle(callback))
496507
if exporter is not None:

0 commit comments

Comments
 (0)