Skip to content

fix(api): honour 429 retry-after instead of failing immediately - #187

Merged
astrinh0 merged 12 commits into
fustom:mainfrom
flupkede:fix/429-backoff
Nov 14, 2026
Merged

astrinh0 merged 12 commits into
fustom:mainfrom
flupkede:fix/429-backoff

Conversation

@flupkede

@flupkede flupkede commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When the Ariston cloud rate-limits a request it returns HTTP 429 with the block duration in the body (Requests are blocked for 66 seconds), but the client discarded that body and raised immediately. Home Assistant setups typically run multiple DataUpdateCoordinators against the same API (main state, bus errors, energy), so after the exception every coordinator kept polling on its normal interval — often still inside the block window — causing a storm of repeated 429s. The coordinators had no shared knowledge of a running block.

Solution

  • Parse the block duration with a case-insensitive bytes regex (blocked for (\d+) seconds).
  • Sleep N+1 seconds (sync and async paths), then retry exactly once via the existing is_retry mechanism. A second 429 raises — no loop.
  • Unparsable body falls back to a 5s wait, matching the existing generic error case.
  • Per-instance AristonAPI._blocked_until (review round 2026-11-12): a 429 seen by one instance fails fast locally until the window passes, without silencing instances for other accounts; the three coordinators for one account share one API instance, so they keep the shared short-circuit. The deliberate post-sleep retry (is_retry=True) bypasses the guard so it cannot deadlock against its own deadline.
  • The 405 (re-login) and 404 paths are untouched.

The second commit adds Velis holiday support, mirroring the existing Galevo holiday API:

  • set_velis_holiday / async_set_velis_holiday on AristonAPI and AristonVelisDevice.
  • POST velis/slpPlantData/{gw}/holiday with {"new": "YYYY-MM-DDT00:00:00"} to enable and {"new": null} to cancel. Verified against the live API: {"success":true}, and the holidayUntil field in velis/slpPlantData reflects the change on the next read.
  • The date format is centralized in a new HOLIDAY_DATE_FORMAT constant, now shared with the Galevo implementation.

Nuos Split GREEN via the R2 web-app endpoint (new)

api/v2 velis/slpPlantData/{gw}/operativeMode silently drops value 0 (GREEN): HTTP 200, no effect — a classic falsy-zero bug (upstream issues #407/#461; GreenPlus=6 is also missing from the enum, #185). Values 1+ apply fine.

The official web app sets GREEN through the R2 route POST /R2/PlantHomeSlp/SetData/{gw} with an envelope {plantData: <echo>, viewModel: {opMode: 0, ...}}, which does apply value 0 (verified live: opMode=0 in api/v2 and on the device tile).

  • async_set_nuos_mode_via_r2: lazy R2 forms-auth login (GET login page → parse __RequestVerificationToken → form POST), shared cookie jar created lazily inside the event loop, and one fresh-login retry when a read fails (an expired forms-auth session surfaces as login-page HTML / missing plantData, now wrapped into ConnectionException so the retry fires).
  • NuosSplitOperativeMode.GREEN routes through R2 (async and sync); COMFORT/FAST keep the proven direct api/v2 POST.
  • Enum fix: IMEMORY → AUTO (value 3), matching the official app's range (Green=0 / Comfort=1 / Fast=2 / Auto=3 / HcHp=4 / Electric=5 / GreenPlus=6).
  • Local echo after a mode write goes into opMode (the live state the device reports), not mode (the plant-mode field, Manual=2/Program=1) — both setters.
  • R2 route constants centralized in const.py.

Tests

25 unit tests added by this PR (the branch additionally carries the maintainer-merged CI suite; combined on the branch: 74 tests + 144 subtests, all green): duration parsing, the N+1 wait with a single retry, the 5s fallback, second-429 raise, the shared _blocked_until short-circuit (no network call inside the window), their async equivalents, the holiday URL/payload/date-format contract, and the R2 GREEN set (payload shape, GREEN→R2 routing, COMFORT direct routing, official enum range, bad-body→ConnectionException parametrized, fresh-login retry). All hermetic, no network.

Note: pyproject.toml stays at 0.19.9 (kept clean for the Sonar gate); our deployment installs this from a locally built wheel — happy to rebase onto whatever versioning you prefer.

The API returns the block duration in the response body but the client
discarded it and raised straight away, so the next poll often landed
inside the same window. Parse the value, wait it out, and share the
blocked-until deadline across all callers.

Closes: AGENTS_ariston-429-holiday.md
The app exposes holiday mode for Velis water heaters but the library had
no method for it. POST velis/slpPlantData/{gw}/holiday with {"new": date}
to enable (ISO midnight format) and {"new": null} to cancel, mirroring the
existing Galevo holiday API. Date format centralized in a shared constant.

Proven against the live API: POST returns {"success":true} and the field
holidayUntil appears in velis/slpPlantData afterwards.

Closes: AGENTS_ariston-429-holiday.md
The +patchN version suffix is only needed for our local wheel
deployment; release versioning belongs to the maintainer, so the PR
diff no longer touches pyproject.toml (this also clears the Sonar
S8565 lock-file finding from new code). Tests now use the monkeypatch
fixture for the shared _blocked_until state and keep a single
invocation inside pytest.raises blocks (S8997, S5778).
- Replace dict()/list() constructor calls with {}/[] literals
  across ariston_api, galevo_device, velis_device (Sonar S7498)
- Extract the 429 branch from __request/__async_request into
  __handle_rate_limit/__async_handle_rate_limit helpers plus a
  module-level _rate_limit_wait_seconds() (Sonar S3776)

No behavior change; full suite 10/10 green (ariston-test:py313).
…ode drops value 0

Review-fixes:
- [Important] R2 read retry caught only ConnectionException; expired forms-auth session surfaces as ContentTypeError/KeyError (login-HTML as JSON) -> read+parse now wrapped, surfaces as ConnectionException so the fresh-login retry fires
Round-2 review remark: the expired-session path fixed in 853b5a4 was
executed by no test. Two hermetic guards: bad GetData body (KeyError/
ValueError) surfaces ConnectionException; one failed read triggers
exactly one fresh login and one retry read. Suite 17/17.
@astrinh0

Copy link
Copy Markdown
Collaborator

@flupkede I will review this. I'm making test suite for this repo before that. :)

@astrinh0 astrinh0 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.

Request changes: please address the three required inline findings. The final inline comment is a suggestion.

operativeMode route silently drops value 0 (proven 2026-10-18).
"""
mode = NuosSplitOperativeMode[operation_mode]
if mode is NuosSplitOperativeMode.GREEN:

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.

Required: This change routes only the async setter through R2. The synchronous sibling set_water_heater_operation_mode() still calls set_nuos_mode() for GREEN (0), which this PR says the api/v2 route silently ignores. Synchronous callers therefore still cannot set GREEN. Add the equivalent sync R2 path or handle GREEN in the sync setter.

@flupkede flupkede Nov 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in f173bcb: added the sync twin — set_nuos_mode_via_r2() (requests-based R2 login/read/POST with the same one-fresh-login retry on a failed read), and the sync set_water_heater_operation_mode() now routes GREEN through it while COMFORT/FAST keep the direct route. The sync local echo also went into MODE before; it now writes OP_MODE like the async setter (mode is the plant-mode field and never changes on an operativeMode write). Covered by 4 new tests: full sync flow (login form → read → envelope with opMode 0), fresh-login retry, and GREEN/COMFORT routing.

Comment thread ariston/ariston_api.py Outdated

# Shared across all instances: one 429 silences every caller (all three
# HA coordinators) until the block window has passed.
_blocked_until: float = 0.0

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.

Required: This is a class attribute, so every AristonAPI instance shares the same deadline. A 429 for one account or API URL will make all other instances raise local 429 errors until the deadline expires. Keep the deadline on the instance or key it by account/API URL; the three coordinators for one account can still share one API instance.

@flupkede flupkede Nov 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in f173bcb: _blocked_until is now a per-instance attribute set in __init__; both the sync and async handlers read/write self._blocked_until. The three coordinators for one account still share a single API instance, so they keep the shared short-circuit. Added per-instance isolation tests for both paths (a 429 on one instance leaves other instances untouched).

Comment thread tests/test_nuos_green_r2.py Outdated


class _FakeResponse:
def __init__(self, status: int, json_err: Exception | None = None) -> None:

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.

Required: This test module evaluates the union annotation at import time. On Python 3.9, Exception | None raises TypeError; pyproject.toml supports Python >=3.9. Use Optional[Exception] or add from future import annotations.

@flupkede flupkede Nov 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in f173bcb: added from __future__ import annotations to the test module and verified on a py3.9 interpreter (the Exception | None TypeError reproduces without it, clean with it).

Related finding while verifying: ariston/__init__.py uses match/case, so the package import itself fails on Python 3.9 despite requires-python = ">=3.9" — that one I left untouched since it predates this PR and bumping the floor vs. replacing the match is your call.

Comment thread ariston/ariston_api.py
async with session.post(
ARISTON_R2_SLP_SET_DATA.format(gw_id), json=payload
) as response:
if response.status != 200:

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.

Optional: This treats any HTTP 200 as a successful write. If SetData returns success:false, or follows an expired-session redirect to a 200 login page, this method returns normally and the caller updates local opMode. Validate the response body or detect authentication responses and retry or raise.

@flupkede flupkede Nov 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in f173bcb (both sync and async SetData POSTs now validate the response): a non-JSON 200 body (expired-session redirect to the login page) and a JSON body with success: false raise ConnectionException instead of reporting success. Two tests cover both shapes. I did not add an automatic POST retry: the GetData immediately before the write already validated the session, so an auth failure at the POST surfaces honestly to the caller (HA's write-verify marks it write_failed) rather than silently re-sending a state change.

… SetData validation, py3.9 test annotations

- _blocked_until: class attribute -> instance attribute; a 429 on one
  account must not silence other AristonAPI instances (the three HA
  coordinators for one account still share one instance)
- sync set_nuos_mode_via_r2 (requests twin of the async R2 flow); the
  sync device setter now routes GREEN through it and echoes into
  opMode like the async setter (was MODE)
- R2 SetData response validated (sync + async): non-JSON body (expired
  session redirect to the login page) and success:false raise
  ConnectionException instead of reporting success; no POST retry —
  the read just before the write already validated the session
- test module: from __future__ import annotations (py3.9 import
  TypeError); verified on a py3.9 interpreter

Note: ariston/__init__.py uses match/case, so the package itself does
not import on py3.9 despite requires-python = ">=3.9" (pre-existing,
flagged in the PR thread). Suite 25/25.
@astrinh0

Copy link
Copy Markdown
Collaborator

@flupkede please fix the conflicts I will merge it :)

@flupkede

Copy link
Copy Markdown
Contributor Author

@flupkede please fix the conflicts I will merge it :)

Done! and thank you so much for all the nice work !

Conflict resolution:
- const.py: keep AUTO=3 (review-accepted rename of IMEMORY) and add
  main's GREEN_PLUS=6 in the same enum
- test_device_models.py: keep the OP_MODE echo contract (sync + async,
  FAST and GREEN_PLUS asserts — mode is the plant-mode field, opMode the
  live operative state) and main's Nuos target-temperature cache fix
  (assert 60)
- holiday: main's set_velis_slp_holiday and this branch's
  set_velis_holiday coexist (distinct names, same endpoint)
- version follows main (0.19.12)

Suite: 83 tests + 150 subtests green.
@flupkede

Copy link
Copy Markdown
Contributor Author

Conflicts are now actually resolved in 3071974 (merge of upstream/main): kept the AUTO rename alongside your GREEN_PLUS=6, kept the OP_MODE echo contract in the tests (mode is the plant-mode field, opMode the live operative state), and took your Nuos target-temperature cache fix. Holiday support coexists: your set_velis_slp_holiday and this branch's set_velis_holiday hit the same endpoint under distinct names. Suite: 83 tests + 150 subtests green. Ready to merge — thanks!

… set_velis_slp_holiday

main gained set_velis_slp_holiday/async_set_velis_slp_holiday (same
velis/slpPlantData holiday endpoint) after this branch introduced
set_velis_holiday/async_set_velis_holiday. Keep main's pair as the
canonical API; this branch keeps only the device-level wrapper
(AristonVelisDevice.set_velis_holiday, which adds HOLIDAY_DATE_FORMAT
date handling and is what the HA integration calls) and now delegates
to main's methods. Suite 83 tests + 150 subtests green.
@flupkede

Copy link
Copy Markdown
Contributor Author

While resolving the merge I noticed main now carries set_velis_slp_holiday/async_set_velis_slp_holiday, which duplicates the Velis holiday API pair this branch originally added (set_velis_holiday/async_set_velis_holiday — same velis/slpPlantData/{gw}/holiday endpoint, same payload).

Deduplicated in ace3bb8, in favour of yours: your pair stays the canonical API, ours is removed. The branch keeps only the device-level wrapper (AristonVelisDevice.set_velis_holiday / async_set_velis_holiday, which adds the HOLIDAY_DATE_FORMAT date handling and is what the HA integration calls) and it now delegates to your methods. No functional change; suite 83 tests + 150 subtests green.

@astrinh0

Copy link
Copy Markdown
Collaborator

@flupkede fix tests please. I'm trying to mark that as required with @fustom

@astrinh0

Copy link
Copy Markdown
Collaborator

Preserve the existing Nuos mode name or make the break explicit. Replacing IMEMORY with AUTO removes an existing public enum member. Callers using that member or passing "IMEMORY" to the string-based setter will now fail. Retain a compatibility alias or handle this as a documented breaking API change.

The Tests workflow installs only locked runtime deps (no pytest) and
runs 'coverage run -m unittest discover'. Two of this branch's test
modules imported pytest (ModuleNotFoundError in CI) and the third used
module-level functions, which unittest discovery silently skips.

Converted test_rate_limit.py, test_nuos_green_r2.py and
test_velis_holiday.py to stdlib unittest.TestCase style; the pytest
parametrize became a subTest loop, pytest.raises became
assertRaises/assertRaisesRegex. No test logic changed.

Verified with the exact CI commands on a pytest-less interpreter:
82 tests OK, coverage 99% (gate is 90%). Suite also still passes
under pytest.
@flupkede

Copy link
Copy Markdown
Contributor Author

Fixed in 52a017e. The three test modules this branch adds were written pytest-style, but the Tests workflow installs only the locked runtime deps (no pytest) and runs coverage run -m unittest discover — so two modules failed on import pytest and the third (module-level functions) was silently skipped by unittest discovery. All three are now stdlib unittest.TestCase style; the pytest parametrize became a subTest loop and pytest.raises became assertRaises/assertRaisesRegex. No test logic changed.

Verified on a pytest-less interpreter with the exact workflow commands: 82 tests OK, coverage 99% (gate is 90%).

One thing on your side: the new run on 52a017e is sitting in "action_required" (needs your approval to start) — presumably from the workflow-approval setting you touched while configuring required checks. Once you approve it, it should go green.

@astrinh0

Copy link
Copy Markdown
Collaborator

Check only the last comment

Renaming the mislabeled IMEMORY=3 to AUTO removed an existing public
enum member: callers using NuosSplitOperativeMode.IMEMORY or passing
"IMEMORY" to the string-based setter would break. AUTO stays the
canonical name; IMEMORY is retained as an enum alias (same value 3),
so attribute access and NuosSplitOperativeMode["IMEMORY"] keep
working. Iteration and the mode options only expose AUTO — no
duplicate value in water_heater_mode_options. The @unique decorator
was dropped for this enum only (an alias is a duplicate value by
definition); all other enums keep it.

Tests: alias identity, string lookup, no duplicate option value, and
the device setter accepting "IMEMORY". Suite: 84 tests + 152 subtests
green under both unittest (CI, coverage 99%) and pytest.
@flupkede

Copy link
Copy Markdown
Contributor Author

Fair point — fixed in 9ab0a1a. AUTO stays the canonical name (value 3 is what the official web app calls Auto), and IMEMORY is retained as a deprecated enum alias pointing at the same value, so both NuosSplitOperativeMode.IMEMORY and the string-based setter with "IMEMORY" keep working unchanged. Iteration and water_heater_mode_options only expose AUTO, so the HA operation list gains no duplicate. The @unique decorator was dropped for this one enum only (an alias is a duplicate value by definition); every other enum keeps it. Covered by tests for alias identity, string lookup, no duplicate option, and the device setter path. Suite: 84 tests + 152 subtests green under both runners, coverage 99%.

@astrinh0
astrinh0 merged commit 1e5dbc6 into fustom:main Nov 14, 2026
5 checks passed
@astrinh0

Copy link
Copy Markdown
Collaborator

merged @flupkede I will update this next week on the home assistant integration

@astrinh0

Copy link
Copy Markdown
Collaborator

Already on 0.20.5 !

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