From 76a52d6add417290d9770effc22aee8716288ca1 Mon Sep 17 00:00:00 2001 From: Allen Porter Date: Tue, 24 Nov 2026 17:11:34 -0800 Subject: [PATCH] Make stream source handoff atomic with worker restart (#194217) Co-authored-by: Paulus Schoutsen --- homeassistant/components/stream/__init__.py | 45 ++++++++++++------- homeassistant/components/stream/worker.py | 2 + tests/components/stream/test_init.py | 49 ++++++++++++++++++++- 3 files changed, 77 insertions(+), 19 deletions(-) diff --git a/homeassistant/components/stream/__init__.py b/homeassistant/components/stream/__init__.py index 711acf21a8f5..beb74a2ec2f6 100644 --- a/homeassistant/components/stream/__init__.py +++ b/homeassistant/components/stream/__init__.py @@ -323,9 +323,10 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: class _WorkerControl: """Thread-safe lifecycle control for a single stream worker thread.""" - def __init__(self) -> None: + def __init__(self, source: str) -> None: """Initialize worker control.""" self._lock = threading.Lock() + self._source = source self._stopped = False self._restart = False self.interrupt = threading.Event() @@ -335,28 +336,36 @@ class _WorkerControl: """Return True once stop() has been called.""" return self._stopped + @property + def is_restarting(self) -> bool: + """Return True if a restart is pending and the worker is not stopped.""" + with self._lock: + return self._restart and not self._stopped + def stop(self) -> None: """Permanently stop this worker.""" with self._lock: self._stopped = True self.interrupt.set() - def request_restart(self) -> None: - """Interrupt the current read or retry backoff to reload the source.""" + def request_restart(self, source: str) -> None: + """Update the source and interrupt the current read or retry backoff.""" with self._lock: + self._source = source if self._stopped: return self._restart = True self.interrupt.set() - def consume_restart(self) -> bool: - """Consume a pending restart if not stopped.""" + def begin_attempt(self) -> tuple[str | None, bool]: + """Consume any pending restart and return (source, restarted).""" with self._lock: - if self._stopped or not self._restart: - return False + if self._stopped: + return None, False + restarted = self._restart self._restart = False self.interrupt.clear() - return True + return self._source, restarted class Stream: @@ -481,7 +490,7 @@ class Stream: # The thread must have crashed/exited. Join to clean up the # previous thread. self._thread.join(timeout=0) - control = _WorkerControl() + control = _WorkerControl(self.source) self._worker_control = control self._thread = threading.Thread( name="stream_worker", @@ -501,7 +510,7 @@ class Stream: ) self.source = new_source if self._worker_control is not None: - self._worker_control.request_restart() + self._worker_control.request_restart(new_source) def _set_state(self, available: bool) -> None: """Set the stream state by updating the callback.""" @@ -523,12 +532,14 @@ class Stream: ) wait_timeout = 0 while True: - if wait_timeout and control.interrupt.wait(timeout=wait_timeout): - if not control.consume_restart(): - break - wait_timeout = 0 - elif control.is_stopped: + if wait_timeout: + control.interrupt.wait(timeout=wait_timeout) + + source, restarted = control.begin_attempt() + if source is None: break + if restarted: + wait_timeout = 0 start_time = time.time() self._set_state(True) @@ -541,7 +552,7 @@ class Stream: self._diagnostics.increment("start_worker") try: stream_worker( - self.source, + source, self.pyav_options, self._stream_settings, stream_state, @@ -553,7 +564,7 @@ class Stream: self._logger.error("Error from stream worker: %s", str(err)) stream_state.discontinuity() - if control.consume_restart(): + if control.is_restarting: wait_timeout = 0 continue if not _should_retry() or control.is_stopped: diff --git a/homeassistant/components/stream/worker.py b/homeassistant/components/stream/worker.py index 5b4a70c75c17..4f42ae1c037b 100644 --- a/homeassistant/components/stream/worker.py +++ b/homeassistant/components/stream/worker.py @@ -641,6 +641,8 @@ def stream_worker( # the stimeout option was renamed to timeout as of ffmpeg 5.0 pyav_options["timeout"] = pyav_options["stimeout"] del pyav_options["stimeout"] + if quit_event.is_set(): + return container = try_open_stream(source, pyav_options) try: video_stream = container.streams.video[0] diff --git a/tests/components/stream/test_init.py b/tests/components/stream/test_init.py index a42bf2dd8ba4..5316e25b8fb2 100644 --- a/tests/components/stream/test_init.py +++ b/tests/components/stream/test_init.py @@ -522,11 +522,11 @@ async def test_stop_during_retry_backoff_with_pending_source_update( class HeldWorkerControl(_WorkerControl): """Holds the worker just before it takes a pending restart.""" - def consume_restart(self) -> bool: + def begin_attempt(self) -> tuple[str | None, bool]: if self._restart: restart_seen.set() restart_release.wait(TIMEOUT) - return super().consume_restart() + return super().begin_attempt() stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings()) stream.add_provider(HLS_PROVIDER) @@ -556,3 +556,48 @@ async def test_stop_during_retry_backoff_with_pending_source_update( assert not thread.is_alive() assert opened_sources == [STREAM_SOURCE] + + +async def test_update_source_before_retry_attempt_opens_once( + hass: HomeAssistant, h264_video: io.BytesIO, should_retry: Mock +) -> None: + """Test update_source() right as a retry starts does not open the new source twice.""" + await async_setup_component(hass, DOMAIN, {"stream": {}}) + should_retry.return_value = True + updated_source = f"{STREAM_SOURCE}-updated" + opened_sources: list[str] = [] + real_open = av.open + + def fake_open(stream_source: Any, *args: Any, **kwargs: Any) -> Any: + if isinstance(stream_source, str): + opened_sources.append(stream_source) + if len(opened_sources) == 1: + raise av.FFmpegError(1, "Simulated open failure") + should_retry.return_value = False + return real_open(io.BytesIO(h264_video.getvalue())) + return real_open(stream_source, *args, **kwargs) + + stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings()) + stream.add_provider(HLS_PROVIDER) + real_set_state = stream._set_state + + def trigger_update_on_retry(available: bool) -> None: + if ( + available + and opened_sources == [STREAM_SOURCE] + and stream.source != updated_source + ): + stream.update_source(updated_source) + real_set_state(available) + + with ( + patch("av.open", new=fake_open), + patch("homeassistant.components.stream.STREAM_RESTART_INCREMENT", 0.01), + patch.object(stream, "_set_state", side_effect=trigger_update_on_retry), + ): + await stream.start() + assert stream._thread is not None + await hass.async_add_executor_job(stream._thread.join, TIMEOUT) + await stream.stop() + + assert opened_sources == [STREAM_SOURCE, updated_source]