From ceb9970c0365c0f6d54ee11b787dd69763a06e26 Mon Sep 17 00:00:00 2001 From: Jason Antman Date: Fri, 20 Nov 2026 07:18:05 -0500 Subject: [PATCH 1/2] Retry transient failures of the Neon account search in neongetter neongetter runs every 15 minutes and failed about 12 times between 2026-11-16 and 11-20 (11 read timeouts, 1 HTTP 500 from /v2/accounts/search). The next run always succeeded, but each failure marked the systemd unit failed and fired a "Failed Systemd Units" alert. The account search POST in _get_users_page now goes through a new _post_search helper that retries connection errors, timeouts and HTTP 429/5xx, up to 3 total attempts with linear backoff (10s, then 20s). Other 4xx responses are not retried. Each retry is logged at WARNING. After the last attempt the exception is raised (or the last response is returned so raise_for_status() fails as before), so a real outage still fails the unit. Worst case added time is 30s of sleep plus the extra 30s read timeouts, far below the 15-minute timer interval. The search is a read-only query, so repeating the POST is safe. The existing HTTPAdapter(max_retries=3) only retries connection failures, never read timeouts or status codes, so it is left alone. A urllib3 Retry was not used because the tests mock HTTP with `responses`, which bypasses the adapter, and a plain loop also allows WARNING logs. Adds unit tests for retry-then-succeed (timeout then 500), HTTP 429, exhausted timeouts, exhausted 500, and a non-retried 403. The repo has no CHANGELOG and bumps the version in separate commits, so neither is touched. Co-Authored-By: Claude Opus 5.5 --- src/dm_mac/neongetter.py | 45 ++++++++++++++++++++- tests/test_neongetter.py | 86 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 130 insertions(+), 1 deletion(-) diff --git a/src/dm_mac/neongetter.py b/src/dm_mac/neongetter.py index 570ccac..15bce99 100644 --- a/src/dm_mac/neongetter.py +++ b/src/dm_mac/neongetter.py @@ -5,6 +5,7 @@ import logging import os import sys +import time from datetime import datetime from datetime import timedelta from typing import Any @@ -173,6 +174,10 @@ class NeonUserUpdater: BASE_URL: str = "https://api.neoncrm.com/v2/" MAX_PAGE_SIZE: int = 200 + #: Total attempts for the account search POST (transient failures only). + SEARCH_ATTEMPTS: int = 3 + #: Seconds to sleep before retry N (1-based) is ``N * SEARCH_BACKOFF_SEC``. + SEARCH_BACKOFF_SEC: int = 10 def __init__(self, dump_fields: bool = False): """Initialize NeonUserUpdater.""" @@ -310,6 +315,44 @@ def fields_to_get(self) -> List[Union[str, int, List[str]]]: logger.info("Fields to get from Neon API: %s", field_names) return field_names + def _post_search(self, url: str, data: Dict[str, Any]) -> requests.Response: + """ + POST the (read-only, so idempotent) account search, with retries. + + Connection errors, timeouts and HTTP 429/5xx are retried, up to + ``SEARCH_ATTEMPTS`` total attempts with linear backoff. Other 4xx + responses are returned immediately. After the final attempt, the last + exception is raised, or the last response returned (so the caller's + ``raise_for_status()`` fails as it always has). + """ + for attempt in range(1, self.SEARCH_ATTEMPTS + 1): + last: bool = attempt == self.SEARCH_ATTEMPTS + try: + r: requests.Response = self._sess.post( + url, timeout=self._timeout, json=data + ) + except (requests.ConnectionError, requests.Timeout) as ex: + if last: + raise + reason: str = f"{type(ex).__name__}: {ex}" + else: + if r.status_code != 429 and r.status_code < 500: + return r + if last: + return r + reason = f"HTTP {r.status_code}" + delay: int = attempt * self.SEARCH_BACKOFF_SEC + logger.warning( + "Neon account search attempt %d of %d failed (%s); " + "retrying in %d seconds", + attempt, + self.SEARCH_ATTEMPTS, + reason, + delay, + ) + time.sleep(delay) + raise AssertionError("unreachable") # pragma: no cover + def _get_users_page( self, page: int, fields: List[Union[str, int, List[str]]], cutoff: str ) -> Tuple[int, List[Dict[str, Any]]]: @@ -337,7 +380,7 @@ def _get_users_page( logger.debug( "POST %s with data: %s", url, json.dumps(data, sort_keys=True, indent=4) ) - r: requests.Response = self._sess.post(url, timeout=self._timeout, json=data) + r: requests.Response = self._post_search(url, data) try: r.raise_for_status() except Exception: diff --git a/tests/test_neongetter.py b/tests/test_neongetter.py index bd06072..0424e60 100644 --- a/tests/test_neongetter.py +++ b/tests/test_neongetter.py @@ -5,6 +5,7 @@ from base64 import b64encode from pathlib import Path from typing import Any +from typing import Dict from typing import List from typing import Tuple from typing import cast @@ -13,6 +14,7 @@ from unittest.mock import patch import pytest +import requests import responses from _pytest.capture import CaptureFixture from jsonschema.exceptions import ValidationError @@ -543,3 +545,87 @@ def test_dump_example_config( captured.out == json.dumps({"my": "config"}, sort_keys=True, indent=4) + "\n" ) + + +SEARCH_URL: str = "https://api.neoncrm.com/v2/accounts/search" +SEARCH_OK: Dict[str, Any] = { + "pagination": {"totalPages": 3}, + "searchResults": [{"Account ID": "1"}], +} + + +class TestSearchRetry: + """Test retry behavior of the account search POST.""" + + @pytest.fixture + def nuu(self) -> NeonUserUpdater: + """Return an updater with config loading stubbed out.""" + with patch(f"{pb}._load_and_validate_config", autospec=True): + with patch(f"{pbm}.env_var_or_die", return_value="x"): + return NeonUserUpdater() + + @responses.activate(registry=OrderedRegistry) + def test_retry_then_succeed( + self, nuu: NeonUserUpdater, caplog: pytest.LogCaptureFixture + ) -> None: + """A read timeout and an HTTP 500 are retried; then success.""" + responses.add( + responses.POST, SEARCH_URL, body=requests.exceptions.ReadTimeout("slow") + ) + responses.add(responses.POST, SEARCH_URL, status=500) + responses.add(responses.POST, SEARCH_URL, json=SEARCH_OK) + with patch(f"{pbm}.time.sleep") as m_sleep: + last, results = nuu._get_users_page(0, ["a"], "2026-01-01") + assert last == 2 + assert results == [{"Account ID": "1"}] + assert len(responses.calls) == 3 + assert m_sleep.mock_calls == [call(10), call(20)] + warnings = [r for r in caplog.records if r.levelname == "WARNING"] + assert len(warnings) == 2 + assert "attempt 1 of 3" in warnings[0].getMessage() + assert "ReadTimeout" in warnings[0].getMessage() + assert "HTTP 500" in warnings[1].getMessage() + + @responses.activate(registry=OrderedRegistry) + def test_retry_429(self, nuu: NeonUserUpdater) -> None: + """HTTP 429 is retried.""" + responses.add(responses.POST, SEARCH_URL, status=429) + responses.add(responses.POST, SEARCH_URL, json=SEARCH_OK) + with patch(f"{pbm}.time.sleep"): + nuu._get_users_page(0, ["a"], "2026-01-01") + assert len(responses.calls) == 2 + + @responses.activate(registry=OrderedRegistry) + def test_exhausted_timeout_raises(self, nuu: NeonUserUpdater) -> None: + """Persistent timeouts raise after all attempts.""" + for _ in range(3): + responses.add( + responses.POST, + SEARCH_URL, + body=requests.exceptions.ReadTimeout("slow"), + ) + with patch(f"{pbm}.time.sleep") as m_sleep: + with pytest.raises(requests.exceptions.ReadTimeout): + nuu._get_users_page(0, ["a"], "2026-01-01") + assert len(responses.calls) == 3 + assert m_sleep.call_count == 2 + + @responses.activate(registry=OrderedRegistry) + def test_exhausted_500_raises(self, nuu: NeonUserUpdater) -> None: + """Persistent HTTP 500 raises HTTPError after all attempts.""" + for _ in range(3): + responses.add(responses.POST, SEARCH_URL, status=500) + with patch(f"{pbm}.time.sleep"): + with pytest.raises(HTTPError): + nuu._get_users_page(0, ["a"], "2026-01-01") + assert len(responses.calls) == 3 + + @responses.activate(registry=OrderedRegistry) + def test_4xx_not_retried(self, nuu: NeonUserUpdater) -> None: + """A 403 is not retried.""" + responses.add(responses.POST, SEARCH_URL, status=403) + with patch(f"{pbm}.time.sleep") as m_sleep: + with pytest.raises(HTTPError): + nuu._get_users_page(0, ["a"], "2026-01-01") + assert len(responses.calls) == 1 + assert m_sleep.mock_calls == [] From f68d2c0d52e6cf228a726a006e5d877ddcbc2b8a Mon Sep 17 00:00:00 2001 From: Jason Antman Date: Fri, 20 Nov 2026 18:48:48 -0500 Subject: [PATCH 2/2] bump version 0.15.0 to 0.15.1 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KQ8DrMbV7veQfdQT7K6tD1 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index e984709..79415fa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ requires = [ [tool.poetry] name = "machine_access_control" -version = "0.15.0" +version = "0.15.1" description = "Decatur Makers Machine Access Control package" license = "MIT" authors = [ "Jason Antman " ]