Use shared aiohttp session to fix 'RuntimeError: Session is closed' - #214
Merged
Merged
Conversation
async_create_clientsession creates a session owned by the integration, but Home Assistant can close it outside the integration's control (e.g. when the config entry whose setup context leaked into the platform setup is unloaded/reloaded). Once that happens every update fails with 'RuntimeError: Session is closed' until Home Assistant is restarted, and the sensor silently freezes at its last value. Using async_get_clientsession returns Home Assistant's shared session, which stays open for the lifetime of the instance.
Member
|
Thanks! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
After running for a while, the sensor can permanently stop updating. Every update then fails with:
The sensor silently freezes at its last value until Home Assistant is restarted.
Cause
async_setup_platformcreates a private session viaasync_create_clientsession(hass). Home Assistant can close such a session outside the integration's control — in recent HA versions, sessions created while a config-entry setup context is active are auto-closed when that entry is unloaded/reloaded. The integration never recreates the session, so once it is closed every subsequent update raisesRuntimeError: Session is closed.Fix
Use
async_get_clientsession(hass)instead — the shared session owned by Home Assistant, which stays open for the whole lifetime of the instance. This is also the recommended approach for integrations that don't need custom session parameters.Observed on HA 2026.6 with avanza_stock 1.5.4.
🤖 Generated with Claude Code