Skip to content

Detach gateway listeners before controller shutdown - #1022

Open
jonathancurrie wants to merge 2 commits into
zigpy:devfrom
jonathancurrie:codex/detach-gateway-listeners
Open

jonathancurrie wants to merge 2 commits into
zigpy:devfrom
jonathancurrie:codex/detach-gateway-listeners

Conversation

@jonathancurrie

@jonathancurrie jonathancurrie commented Nov 16, 2026 •

Copy link
Copy Markdown

Proposed change

Gateway initialization registers the gateway as a listener on both the zigpy controller and its groups. Shutdown does not remove those registrations. If a pending task or another owner retains the controller after reload, it also retains the retired gateway and can deliver events to it.

Remove both registrations at the start of shutdown, before awaited teardown. This balances the existing registrations and works even if controller shutdown subsequently raises. The existing duplicate-shutdown guard remains unchanged.

Regression tests emit controller and group events before shutdown, from inside a device's awaited teardown, and after shutdown, including a failing controller shutdown. They verify delivery while active and no delivery after shutdown starts. No timeout, retry, concurrency, or radio policy changes are included.

Validation

Bundled Python 3.12.14 on Windows: tests/test_gateway.py passes (61 tests). Both cases in the strengthened listener-cleanup test fail if listener removal is moved until after device teardown, and pass with the current ordering. The original two listener-cleanup cases also fail against upstream. The local runner selects the Windows selector loop for looptime compatibility; this runner is not part of the patch. Ruff lint/format checks and git diff --check pass. CI for follow-up commit 891e40f0c976c54ba14ba13149b19772ca85f5c0 is awaiting maintainer approval (action_required); no jobs have run for this commit yet.

Related fixes

These four proposals address separate ownership and timeout gaps in the same failure chain. Each can be reviewed independently; none requires a new API from another proposal. Library releases and Home Assistant dependency updates will be needed to deliver the complete library repair.

  • zigpy/zigpy#1971: Tie cluster background tasks to device teardown; normal network removal additionally needs zigpy/zigpy#1922.
  • zigpy/bellows#777: Apply the existing command timeout to send_data as well as the response wait, and release pending replies on every exit.
  • home-assistant/core#192859: Unsubscribe HA device proxy callbacks on device removal and gateway shutdown; reuse cleanup on rebind.

Investigation context

An affected Home Assistant installation accumulated approximately 196,000 pending cluster tasks across retired controllers. Retention tracing linked these tasks through devices/controllers and listener tables to old gateways and HA proxies. A combined local repair cancelled obsolete work and detached listeners; tracked old gateways were then collected and memory use fell. That local repair also included policy safeguards which are deliberately excluded from these proposals. Its field results therefore do not establish that any one of these narrower patches alone resolves every stall. The regression tests establish the individual lifecycle/timeout defects. Raw diagnostic archives remain private.

Prepared with AI assistance.

@codecov

codecov Bot commented Nov 16, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 97.48%. Comparing base (2da1a5b) to head (ef52120).

Additional details and impacted files
@@           Coverage Diff           @@
##              dev    #1022   +/-   ##
=======================================
  Coverage   97.48%   97.48%           
=======================================
  Files          61       61           
  Lines       10870    10873    +3     
=======================================
+ Hits        10597    10600    +3     
  Misses        273      273           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@zigpy-review-bot zigpy-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. The gateway now removes the two listener registrations that _async_initialize() adds, at the start of shutdown().

Verified (5 checks)
  • ListenableMixin.remove_listener() is a no-op for a listener that was never added. So the async_initialize() failure path, which calls shutdown() possibly before add_listener() ran, stays safe. The duplicate-shutdown guard is untouched.
  • Detaching before device/group teardown and controller.shutdown() drops connection_lost, device_joined and similar events while shutting down. That is wanted; the HA gateway proxy unsubscribes from the gateway before calling shutdown() anyway.
  • Both parametrizations of the new test fail with dev's zha/application/gateway.py and pass with the PR.
  • Full suite at the PR head: 1783 passed (Python 3.14). Pre-commit (codespell, ruff, ruff format, mypy) passes on the changed files.
  • CI passes on this head.

Unchanged by this PR: when controller.shutdown() raises, self.application_controller stays set, so the gateway keeps a reference to the old controller in that case. This is the reverse direction of what this PR fixes, and fine to leave out of scope.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The shutdown test does not verify that callbacks are blocked during device/group teardown, leaving the requirement that callbacks stop when shutdown begins unprotected.

1 open issue
What changed in this PR

This PR detaches gateway listeners during shutdown so retained zigpy controllers and groups no longer retain or notify retired gateways.

Changes:

  • Removes both listener registrations before awaited teardown, preserving the duplicate-shutdown guard.
  • Adds regression coverage for event delivery before shutdown and suppression afterward, including when controller shutdown raises.
File Description
zha/​application/​gateway.py Removes controller and group listeners before asynchronous cleanup.
tests/​test_gateway.py Tests listener cleanup for successful and failing shutdowns.

Review effort: Balanced

Comment thread tests/test_gateway.py Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bugfix This PR fixes a bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants