Skip to content

Use shared aiohttp session to fix 'RuntimeError: Session is closed' - #214

Merged
claha merged 1 commit into
custom-components:mainfrom
miczu71:fix/shared-clientsession
Jul 6, 2026
Merged

Use shared aiohttp session to fix 'RuntimeError: Session is closed'#214
claha merged 1 commit into
custom-components:mainfrom
miczu71:fix/shared-clientsession

Conversation

@miczu71

@miczu71 miczu71 commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Problem

After running for a while, the sensor can permanently stop updating. Every update then fails with:

ERROR [homeassistant.helpers.entity] Update for sensor.nokia_stock fails
  File ".../pyavanza/__init__.py", line 67, in request_url_async
    async with session.get(url, raise_for_status=True) as resp:
RuntimeError: Session is closed

The sensor silently freezes at its last value until Home Assistant is restarted.

Cause

async_setup_platform creates a private session via async_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 raises RuntimeError: 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

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.
@claha
claha merged commit c08cf9c into custom-components:main Jul 6, 2026
4 checks passed
@claha

claha commented Jul 6, 2026

Copy link
Copy Markdown
Member

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants