Skip to content

Send requests one at a time to keep one connection open per device - #642

Merged
lexpostma merged 2 commits into
mainfrom
serialize-v1-requests
Nov 23, 2026
Merged

lexpostma merged 2 commits into
mainfrom
serialize-v1-requests

Conversation

@lexpostma

Copy link
Copy Markdown
Member

combined() gathers its requests at the same time. With a shared ClientSession that has no per-host limit, as in Home Assistant, each poll opens several parallel keep-alive connections to the device. An Energy Socket only has about three client socket slots in total (HTTP and HTTPS together), so these idle connections block every new connection. That includes the HTTPS POST /api/user token request that Home Assistant's "migrate to v2" repair needs. Measured on firmware PR-601: with Home Assistant's v1 entry loaded, there were 3 open connections to port 80, and 20 out of 20 new connections were refused. The firmware side is tracked in EMB-1474.

This PR makes both clients send one request at a time, so they reuse a single keep-alive connection:

  • v1: _request now holds the instance lock (self._lock, which already existed but was unused in v1).
  • v2: already had a lock, but it had two flaws, fixed here:
    • It was released as soon as the response headers arrived, so the next request could open a second connection while the body was still being read.
    • It was taken inside asyncio.timeout, so time spent waiting in line counted toward a request's timeout.

In both clients, the lock is now:

  • taken separately for each backoff attempt, so it's free while a failed request waits to retry;
  • taken before the timeout starts, so waiting in line doesn't cause timeouts;
  • held while the whole response body is read (await resp.read()), so the connection is back in the pool before the next request starts. It also covers session creation, which removes a race, and in v2 the SSL context.

Error handling and return values are unchanged, and all existing tests and snapshots pass.

Effect on Home Assistant

  • One connection per device instead of about three.
  • A poll takes about the sum of its 3–5 requests instead of the slowest one. Since the connection stays open between requests, that adds roughly tens of milliseconds on a LAN.
  • A user action, such as switching the socket, can wait behind a poll that's in progress. In the worst case, a request that hangs delays it by up to the request timeout.

Tests

tests/v1/test_v1_request_serialization.py and tests/v2/test_v2_request_serialization.py run against a local aiohttp server. The server sends each response body in two halves with a pause between them, and records whether requests overlap and which client connections it saw. The tests check that:

  • concurrent combined() and other calls never overlap and all use one connection;
  • the next request starts only after the previous body has been fully read;
  • a request that waits in line longer than the timeout still succeeds, without retries;
  • another request can run while a failed request waits to retry.

Each test fails against a broken version of _request: the original code, a v2-style lock released after the headers, a lock taken inside the timeout, and a lock held through retries. The v2 tests use plain HTTP by rewriting the https:// address in the test. TLS doesn't change how requests are queued.

Not yet tested against real socket hardware.

🤖 Generated with Claude Code

lexpostma and others added 2 commits November 23, 2026 14:11
combined() gathers device, measurement, system and state concurrently.
With a shared ClientSession without a per-host limit (as in Home
Assistant) this opens several parallel keep-alive connections per poll.
Energy Sockets only have about three client socket slots in total, so
these idle connections block every new connection to the device,
including the HTTPS token request needed to migrate to the v2 API.

Serialize HomeWizardEnergyV1._request with the instance lock:
- the lock covers reading the full response body, so the connection is
  back in the pool before the next request starts and is reused;
- the lock is taken before the request timeout starts, so time spent
  queued behind other requests does not cause spurious timeouts;
- the lock is taken per backoff attempt, so it is released while a
  failed request waits for its retry.

Error handling and return values are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The v2 client already took a lock around session.request, but:
- it released the lock as soon as the response headers arrived, so the
  next request could start while the body was still being read and open
  a second connection to the device;
- it took the lock inside the request timeout, so time spent queued
  behind other requests counted towards the timeout and could cause
  spurious RequestErrors and retries.

Apply the same structure as v1: the lock is taken per backoff attempt
before the timeout starts, and covers session/SSL context creation, the
request and reading the full response body. Error handling and return
values are unchanged.

The tests run against a local plain-HTTP fake device by rewriting the
request URL; TLS does not affect how requests are serialized.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.28%. Comparing base (05db121) to head (6c5c6c3).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #642   +/-   ##
=======================================
  Coverage   99.28%   99.28%           
=======================================
  Files           9        9           
  Lines         699      704    +5     
  Branches       70       70           
=======================================
+ Hits          694      699    +5     
  Misses          2        2           
  Partials        3        3           

☔ 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.

@lexpostma

Copy link
Copy Markdown
Member Author

Also contributes to EMB-1474

@lexpostma

Copy link
Copy Markdown
Member Author

Tested on hardware

I tested this on a real Energy Socket (firmware PR-601) with Home Assistant dev, running in a devcontainer. HA was installed with this branch (6c5c6c3) and started with --skip-pip-packages python-homewizard-energy.

10.3.0 This PR
HA connections open to the socket (v1 entry) 3 1 (reused)
20 new HTTP connections from outside HA 0 succeeded 20 succeeded
20 new HTTPS connections from outside HA 0 succeeded 20 succeeded
v1 poll duration, average 0.068 s (200 polls) 0.135 s (13 polls)
Failed polls 0 0

"Migrate to v2" repair, end to end:

  • During the repair, identify() kept running every 2 s through the same single v1 connection.
  • Every POST /api/user reached the socket. It answered 403 user:creation-not-enabled until the button was pressed, then 200 with a token on the 4th request. Before this PR, these requests couldn't connect.
  • HA stored the token, reloaded the entry and switched to v2. It now keeps 1 HTTPS connection open.
  • Over the first 9 v2 polls (about 25 s), the average was 0.29 s and none failed. The slowest was 1.2 s, almost certainly the first poll, which includes the TLS handshake. 20 out of 20 new HTTP and HTTPS connections from outside HA still succeed.

HA's own tests/components/homewizard tests pass against this branch (186 tests, 923 snapshots).

🤖 Generated with Claude Code

@lexpostma
lexpostma merged commit 9b891cc into main Nov 23, 2026
33 checks passed
@lexpostma
lexpostma deleted the serialize-v1-requests branch November 23, 2026 15:39
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