GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Preserve hub child module data across partial updates by o-gent · Pull Request #1813 · python-kasa/python-kasa

Preserve hub child module data across partial updates #1813

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
o-gent wants to merge 2 commits into python-kasa:master
base: master
Loading
Loading
from o-gent:fix-child-partial-update

Uh oh!

There was an error while loading. Please reload this page.

Open

Preserve hub child module data across partial updates #1813

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
2 commits
Select commit Hold shift + click to select a range
bd49aa4
Preserve hub child module data across partial updates
o-gent Oct 25, 2026
b8fc90c
Log retained child module responses at debug level
o-gent Nov 1, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

12 changes: 11 additions & 1 deletion 12 kasa/smart/smartchilddevice.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,17 @@ async def _update(self, update_children: bool = True) -> None:
resp = await self._handle_modular_update_error(
ex, first_update, ", ".join(mod.name for mod in module_queries), req
)
self._last_update = resp
if _LOGGER.isEnabledFor(logging.DEBUG) and (
cached_keys := self._last_update.keys() - resp.keys()
):
_LOGGER.debug(
"Keeping cached responses for %s (%s): %s",
self.alias,
self._id,
sorted(cached_keys),
)
# Modules not due for an update still need their cached responses.
self._last_update.update(resp)
Comment thread
Comment on lines +121 to +122

@rytilahti rytilahti Oct 31, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

The approach is great and I agree that we should do this! Please add a debug log entry for the case when the data was not received, as that can help debugging caching issues this may cause.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

for module in self.modules.values():
await self._handle_module_post_update(
Expand Down
109 changes: 108 additions & 1 deletion 109 tests/test_childdevice.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import inspect
import logging
import time
from datetime import UTC, datetime

import pytest
from freezegun.api import FrozenDateTimeFactory
from pytest_mock import MockerFixture

from kasa import Device, DeviceUnavailableError
from kasa import Device, DeviceUnavailableError, Module
from kasa.device_type import DeviceType
from kasa.exceptions import SmartErrorCode
from kasa.protocols.smartprotocol import SmartProtocol, _ChildProtocolWrapper
from kasa.smart.smartchilddevice import SmartChildDevice
from kasa.smart.smartdevice import NON_HUB_PARENT_ONLY_MODULES, SmartDevice
Expand Down Expand Up @@ -260,3 +262,108 @@ def __init__(self) -> None:
assert DummyDevice().device_type is DeviceType.Unknown
msg = "Unknown child device type foobar for model None, please open issue"
assert msg in caplog.text


@parametrize(
"hub with cloud-connected sensor",
model_filter={"H100(EU)_1.0_1.5.10", "KH100(UK)_1.0_1.5.6"},
protocol_filter={"SMART"},
)
@pytest.mark.requires_dummy
@pytest.mark.xdist_group(name="caplog")
async def test_child_partial_update_keeps_module_data(
dev: SmartDevice, mocker: MockerFixture, caplog: pytest.LogCaptureFixture
) -> None:
"""Keep cached module data when only another child module is queried."""
child = next(
child
for child in dev.children
if Module.Cloud in child.modules and Module.TriggerLogs in child.modules
)
assert isinstance(child, SmartChildDevice)
cached = child.modules[Module.TriggerLogs]
cached_data = cached.data.copy()
cached_logs = cached.logs
for module in child.modules.values():
module._last_update_time = time.monotonic()
due = child.modules[Module.Cloud]
due._last_update_time = None
query = mocker.spy(child.protocol, "query")
retained_keys = sorted(child._last_update.keys() - due.query().keys())

with caplog.at_level(logging.DEBUG, logger="kasa.smart.smartchilddevice"):
await child.update()

query.assert_called_once_with(due.query())
assert cached.data == cached_data
assert cached.logs == cached_logs
assert due.data
assert cached._last_update_error is None
assert caplog.messages == [
f"Keeping cached responses for {child.alias} ({child.device_id}): "
f"{retained_keys}"
]

caplog.clear()
with caplog.at_level(logging.DEBUG, logger="kasa.smart.smartchilddevice"):
await child.update()

query.assert_called_once_with(due.query())
assert not caplog.messages


@parametrize(
"hub with cloud-connected sensor",
model_filter={"H100(EU)_1.0_1.5.10", "KH100(UK)_1.0_1.5.6"},
protocol_filter={"SMART"},
)
@pytest.mark.requires_dummy
@pytest.mark.xdist_group(name="caplog")
@pytest.mark.parametrize("response", ["missing", "complete", "error"])
async def test_child_update_cached_response_logging(
dev: SmartDevice,
mocker: MockerFixture,
caplog: pytest.LogCaptureFixture,
response: str,
) -> None:
"""Log retained responses without retaining stale data over explicit errors."""
child = next(child for child in dev.children if Module.Cloud in child.modules)
assert isinstance(child, SmartChildDevice)
cloud = child.modules[Module.Cloud]
query_key = next(iter(cloud.query()))
cached_data = cloud.data.copy()
responses = child._last_update.copy()
if response == "missing":
responses.pop(query_key)
elif response == "error":
responses[query_key] = SmartErrorCode.INTERNAL_QUERY_ERROR

request = {}
for module in child.modules.values():
module._last_update_time = None
request.update(module.query())
query = mocker.patch.object(child.protocol, "query", return_value=responses)

with caplog.at_level(logging.DEBUG, logger="kasa.smart.smartchilddevice"):
await child.update()

query.assert_called_once_with(request)
cache_messages = [
message
for message in caplog.messages
if message.startswith("Keeping cached responses")
]
if response == "missing":
assert cache_messages == [
f"Keeping cached responses for {child.alias} ({child.device_id}): "
f"{[query_key]}"
]
else:
assert not cache_messages

if response == "error":
assert child._last_update[query_key] is SmartErrorCode.INTERNAL_QUERY_ERROR
assert cloud._last_update_error is not None
else:
assert cloud.data == cached_data
assert cloud._last_update_error is None
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

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.
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.