Skip to content

Don't let a channel teardown abort before the channel is removed - #37

Open
drHouse-gif wants to merge 1 commit into
victronenergy:masterfrom
drHouse-gif:fix/channel-stop-aborts-teardown
Open

drHouse-gif wants to merge 1 commit into
victronenergy:masterfrom
drHouse-gif:fix/channel-stop-aborts-teardown

Conversation

@drHouse-gif

Copy link
Copy Markdown
Collaborator

One commit on master (d8cb65d, v2.21). shelly_device.py +19/-2, mock/mock_shelly_server.py +11/-2, one new test file +82: 112 insertions, 4 deletions.

The problem

A channel whose handlers fail to initialise is torn down by _init_channel_and_handlers
calling stop_channel. That teardown can raise, and when it does the channel is never removed:

# shelly_device.py, stop_channel()
channel_obj = entry.get("channel")
if channel_obj is not None:
    await channel_obj.stop()      # <- raises
del self._channels[ch]            # <- does not run

ShellyChannel.stop() calls Service.close(), which unexports every item and then awaits
release_name(self.name). set_service_name runs from the handlers' ainit, so a channel
whose handlers failed never got a name, and release_name(None) raises.

What is left behind is a channel entry whose service has had all of its items unexported:

  • it is never retried, because start_channel returns early for a channel already in
    _channels, so the channel-enable retry reports success without registering anything;
  • every reconnect makes _reinit_channel_and_handlers write /Connected to that service,
    which raises KeyError: '/Connected' because close() already removed the item;
  • the secondary handlers do the same to their own paths, e.g. Error in update: '/BatteryVoltage'.

Where it shows up on real hardware

A Shelly H&T Gen3. Since v2.20 the temperature and humidity channels of a sleepy device are
enabled by default, and this device is sleepy. Two things put a channel into the state above and
both were observed on this unit: a handler's ainit() returning False, and the init task being
cancelled before it finishes because the device's wake window is shorter than the init. What
they share, and what this change addresses, is that the channel is torn down before
set_service_name ran.

Measured on an Ekrano GX running unmodified v2.21, aioshelly 12.0.0:

in ~45 minutes
Failed to initialize channel 0 and its handlers 1
teardown failure reaching the channel operation worker 1
KeyError: '/Connected' 7, one per wake cycle

Over a 5.8 hour run: 42. Throughout, the device has no working service.

INFO     Starting channel 0 for shelly device 9070694DFA90
ERROR    Failed to initialize channel 0 and its handlers
WARNING  Stopping channel 0 for shelly device 9070694DFA90
ERROR    Error in channel operation worker: invalid bus name: None
...
  File "shelly_device.py", line 449, in _reinit_channel_and_handlers
    s['/Connected'] = 1
  File "ext/aiovelib/aiovelib/service.py", line 177, in __setitem__
    ob = self.service.objects[path]
KeyError: '/Connected'

The change

shelly_device.py only:

  • stop_channel removes the channel from _channels whatever the teardown does;
  • ShellyChannel.stop() keeps going when closing the service fails, so the rest of the
    teardown still runs.

The channel-operation worker already restarts itself through
add_done_callback(self._restart_channel_op_worker), so the exception reaching it is not fatal
on its own. The damage is the channel left behind.

Tests

tests/test_channel_init_failure.py, 3 tests. The mock gains --fault-methods and
--fault-mode, seeding the state Mock.SetFaults already sets at runtime - the fault has to be
in place before the driver's first connection, because the channel is enabled by default and is
already being started before a test could issue an RPC.

With the change Change reverted (file byte-identical to v2.21)
the channel is enabled by default and its init fails passed passed
the channel recovers once the component answers again passed FAILED (no service after 300 s)
the failed teardown left nothing broken behind passed FAILED (Error in channel operation worker)
3 passed, 15 s 2 failed, 1 passed

The second test is the point of the change: with a channel left behind, start_channel returns
early and the retry reports success without registering anything, so the device never appears
however long you wait.

What this change achieves on hardware, and what it does not

Measured on the Ekrano GX with the same Shelly H&T Gen3, same network, same enabled channels.

clean v2.21, 51 min with this change, 869 s
KeyError: '/Connected' 9 0
Error in channel operation worker 1 0
channel-enable retry attempted never - no retry line at all, because the channel never left _channels yes: 10, 20, 40, 80, 160, 320 s
Error while closing the dbus service (new warning) - 2, as designed
a working service for the device no no

The last row is the honest limit of this change. It removes the leftover channel, the error
storm and the dead retry, and it does not by itself get this device a service, because the
init never completes.

Why it does not complete here is a separate matter, and I have not settled it. The device
answers Temperature.GetStatus perfectly over HTTP when awake ({"id":0,"tC":21.3}), but the
driver's sequence is Starting channel 0 -> Stopping channel 0 with no "Failed to
initialize channel" and no failed-handler line, which means the init task is cancelled
mid-flight rather than failing: the wake window is shorter than the init. Two later sampling
attempts got no answer from the unit at all. Whether that is normal H&T Gen3 behaviour or this
particular unit I cannot say - its devicepower:0 reports battery 0.01 V / 0 % with
external.present = true.

What this does not fix

Upstream's channel-enable retry consults the persisted setting:

enabled = self.settings.get_value(self.settings.alias(f'enabled_{serial}_{channel}'))
if enabled == 1 and item is not None: ...

but that setting is only written when the enable succeeds. A channel a user enables by hand
whose first init fails is therefore never retried: the setting is still 0 and the dbus item is
flipped back to 0. The H&T case escapes this only because its channel is enabled by default, so
the setting is already 1.

That is a separate defect, and fixing it means persisting a requested-but-inactive state, which
is a design decision rather than a bug fix. Reported, not changed here.

Interactions

Every other proposed branch merges cleanly with this one in the driver sources, including
fix/channel-dbus-connection-leak (#26), which edits the same ShellyChannel.stop().
Verified with git merge-tree.

This change also makes PR #26 effective in this path: with the exception caught, the
bus.disconnect() that #26 adds after service.close() finally runs, where today the raise
skips it.

The only textual overlap with any other branch is mock/mock_shelly_server.py, where several
branches add arguments at the end of the same constructor parameter list; the resolution is to
keep all the lines.

A channel whose handlers fail to initialise is torn down by
_init_channel_and_handlers calling stop_channel. That teardown can raise,
and when it does the channel is never removed from _channels:

  channel_obj.stop()
    -> Service.close()
         unexports every item, then
         await self.bus.release_name(self.name)

set_service_name runs from the handlers' ainit, so a channel whose
handlers failed never got a name and release_name(None) raises.
stop_channel's "del self._channels[ch]" is the next statement and does
not run.

What is left behind is a channel entry whose service has had all of its
items unexported. It is never retried, because start_channel returns
early for a channel already in _channels, so the channel-enable retry
reports success without registering anything. And on every reconnect
_reinit_channel_and_handlers writes /Connected to that service, which
raises KeyError because close() already removed the item. The secondary
handlers do the same to their own paths.

Seen on a GX with a Shelly H&T Gen3, whose temperature and humidity
channels are enabled by default since v2.20 because the device is sleepy.
On unmodified v2.21 the sequence is one "Failed to initialize channel",
one failed teardown reaching the channel operation worker, and then
KeyError: '/Connected' on every wake -- 9 times in 51 minutes -- with no
working service for the device. Two things put a channel in that state,
a handler's ainit() returning False and the init task being cancelled
before it finishes, and both were observed on that device. What they
share is that the channel is torn down before set_service_name ran.

Remove the channel whatever the teardown does, and keep the teardown
going when closing the service fails so the rest of it still runs.

tests/test_channel_init_failure.py drives the ainit-failure route, the
one a mock can produce, with a sleepy mock whose Temperature.GetStatus
fails from startup. The fault has to be in place before the driver's
first connection, because the channel is enabled by default and is
already being started before an RPC hook could be used, so the mock
gains --fault-methods and --fault-mode, seeding the state Mock.SetFaults
already sets at runtime.

Three tests: the channel is enabled by default and its init fails; the
channel recovers once the component answers again; and the teardown left
no KeyError or dead channel operation behind. With this change reverted,
the second and third fail.
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.

1 participant