From def618bccf5041bc3a59e08bb0062129c438cfca Mon Sep 17 00:00:00 2001 From: Stefan Agner Date: Mon, 16 Mar 2026 15:15:45 +0100 Subject: [PATCH] Wait for startup to complete before running shutdown If PrepareForShutdown fires while Supervisor is still starting up, wait for startup to complete before running the graceful shutdown sequence. This prevents shutting down partially initialized containers and services. The _startup_complete event is set automatically in set_state() whenever state transitions to RUNNING. If SIGTERM arrives during startup, core.stop() cancels the monitor task via host.unload(), cleanly interrupting the wait. Co-Authored-By: Claude Opus 4.6 --- supervisor/core.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/supervisor/core.py b/supervisor/core.py index 4ce1bb08d..4ba861455 100644 --- a/supervisor/core.py +++ b/supervisor/core.py @@ -43,6 +43,7 @@ class Core(CoreSysAttributes): self._state: CoreState = CoreState.INITIALIZE self.exit_code: int = 0 self._shutdown_event: asyncio.Event = asyncio.Event() + self._startup_complete: asyncio.Event = asyncio.Event() @property def state(self) -> CoreState: @@ -83,6 +84,9 @@ class Core(CoreSysAttributes): self._state = new_state await self._write_run_state() + if self._state == CoreState.RUNNING: + self._startup_complete.set() + # Don't attempt to notify anyone on CLOSE as we're about to stop the event loop if self._state != CoreState.CLOSE: self.sys_bus.fire_event(BusEvent.SUPERVISOR_STATE_CHANGE, self._state) @@ -361,6 +365,12 @@ class Core(CoreSysAttributes): Reentrant: if a shutdown is already in progress, subsequent calls await completion of the existing shutdown rather than starting a second one. """ + if self.state in STARTING_STATES: + _LOGGER.debug( + "Shutdown requested while Supervisor is still starting up, waiting for startup to complete" + ) + await self._startup_complete.wait() + # Supervisor is already tearing down, no point running shutdown if self.state in (CoreState.STOPPING, CoreState.CLOSE): _LOGGER.warning("Ignoring shutdown request, Supervisor is already stopping")