omi icon indicating copy to clipboard operation
omi copied to clipboard

Python CLI ignores Retry-After on HTTP 503

Open looternikhil-cpu opened this issue 2 months ago • 1 comments

On main at f42089f53c8010dd971b3702ece05a231c9c0c66, the Python CLI discards Retry-After on HTTP 503. In OmiClient._request, the 5xx branch constructs _RetryableHttp(response, retry_after=None), while the 429 branch parses the header.

For example, omi --json memory list receiving a 503 with Retry-After: 3 retries using jitter instead of the requested three-second delay. This can send requests back to a recovering service too soon. RFC 9110 §10.2.3 describes this use of the header.

The patch below passes the numeric hint through the existing retry policy. It keeps the 60-second cap, four-attempt limit, fallback backoff, and final server-error behavior. HTTP-date hints remain outside this patch's scope.

Verification on Python 3.12:

  • Before the fix: three new regression cases fail; two fallback cases pass.
  • After the fix: all five new cases pass, including CLI invocation, capped delay, fallback, and exhausted retries.
  • Full CLI suite: 280 passed, 1 skipped, 1 failed. The remaining failure, test_transport_failure_during_login_leaves_saved_config_unchanged, also fails on unchanged upstream in the same environment.
  • Black and patch whitespace checks pass. Repository-wide setup/preflight is incomplete in this sparse checkout; this is a proposed patch, not a merge-ready PR.

@josancamon19, following the contribution guide's bounty suggestion process, would you approve a US$15 bounty for this fix and regression coverage, payable after an accepted merge? No bounty is assumed approved.

Prepared with Codex and tested locally using mocked HTTP responses.

Proposed patch against the commit above
diff --git a/sdks/python-cli/README.md b/sdks/python-cli/README.md
index bbbff7f..263bdb2 100644
--- a/sdks/python-cli/README.md
+++ b/sdks/python-cli/README.md
@@ -305,6 +305,10 @@ The CLI retries `429` automatically with exponential backoff and honors the
 server's `Retry-After` hint where present. After all retries are exhausted you
 get exit code `4` plus a message telling you how long to wait.
 
+Retries for `5xx` responses also use a positive numeric `Retry-After` hint
+(seconds), capped at 60 seconds per wait. Missing or invalid hints use
+exponential backoff. Server errors that exhaust retries return exit code `3`.
+
 ## Datetime options
 Conversation and action-item datetime options accept ISO timestamps with `Z`
 (UTC), numeric offsets, and optional fractional seconds, for example
diff --git a/sdks/python-cli/omi_cli/client.py b/sdks/python-cli/omi_cli/client.py
index fc34c54..97a8e14 100644
--- a/sdks/python-cli/omi_cli/client.py
+++ b/sdks/python-cli/omi_cli/client.py
@@ -39,7 +39,7 @@ DEFAULT_TIMEOUT = httpx.Timeout(30.0, connect=10.0)
 MAX_RETRY_ATTEMPTS = 4
 # Cap on how long we'll honor a server-supplied Retry-After hint. Without this,
 # a misconfigured upstream could pin the CLI for hours; agents will get a
-# RateLimitError they can act on much sooner.
+# RateLimitError or ServerError they can act on much sooner.
 MAX_RETRY_AFTER_SECONDS = 60.0
 
 # Backend rate-limit policies surfaced to users on 429 (see
@@ -146,7 +146,10 @@ class OmiClient:
                     response = self._http.request(method, path, params=cleaned_params, json=json_body)
                     self._maybe_log(method, path, response)
                     if response.status_code >= 500:
-                        raise _RetryableHttp(response, retry_after=None)
+                        raise _RetryableHttp(
+                            response,
+                            retry_after=_parse_retry_after(response.headers.get("Retry-After")),
+                        )
                     if response.status_code == 429:
                         # Surface the structured RateLimitError so callers can show
                         # a useful message; tenacity treats this as retryable.
@@ -234,7 +237,7 @@ class OmiClient:
 class _RetryableHttp(Exception):
     """Internal sentinel: a retryable HTTP response (5xx or 429).
 
-    ``retry_after`` is populated for 429s when the server sent a ``Retry-After``
+    ``retry_after`` is populated when the server sent a numeric ``Retry-After``
     header — the wait function reads it to honor the server's hint.
     """
 
@@ -251,12 +254,11 @@ _jittered_backoff = wait_exponential_jitter(initial=0.5, max=8.0)
 def _retry_wait(retry_state: RetryCallState) -> float:
     """Wait strategy: server-supplied Retry-After when available, jitter otherwise.
 
-    A 429 that includes ``Retry-After`` ends up here as a ``_RetryableHttp``
+    A 429 or 5xx that includes numeric ``Retry-After`` ends up here as a ``_RetryableHttp``
     with ``retry_after`` populated. We honor it but cap to
     :data:`MAX_RETRY_AFTER_SECONDS` so a pathological upstream can't pin the
-    CLI for an unbounded time. For 5xx (no ``Retry-After`` from this backend)
-    and transport errors we fall back to exponential jitter — same behavior
-    the client had before this fix.
+    CLI for an unbounded time. Without a positive numeric hint, and for
+    transport errors, we fall back to exponential jitter.
     """
     outcome = retry_state.outcome
     exc = outcome.exception() if outcome is not None and outcome.failed else None
diff --git a/sdks/python-cli/tests/test_client_retry.py b/sdks/python-cli/tests/test_client_retry.py
index beef372..c4525e5 100644
--- a/sdks/python-cli/tests/test_client_retry.py
+++ b/sdks/python-cli/tests/test_client_retry.py
@@ -160,6 +160,53 @@ def test_500_then_200_succeeds_after_retry(authed_profile, respx_mock) -> None:
     assert result == []
 
 
[email protected](
+    ("retry_after", "expected_wait"),
+    [("3", 3.0), ("99999", 60.0), ("invalid", 0.25), (None, 0.25)],
+)
+def test_cli_503_uses_retry_after_or_backoff(
+    authed_profile, respx_mock, monkeypatch, cli_runner, retry_after, expected_wait
+) -> None:
+    """RFC 9110 section 10.2.3 permits Retry-After on Service Unavailable."""
+    import json
+
+    from omi_cli import client as client_module
+    from omi_cli.main import app
+
+    sleeps: list[float] = []
+    monkeypatch.setattr(time, "sleep", sleeps.append)
+    monkeypatch.setattr(client_module, "_jittered_backoff", lambda _: 0.25)
+    headers = {"Retry-After": retry_after} if retry_after is not None else {}
+    route = respx_mock.get("/v1/dev/user/memories").mock(
+        side_effect=[
+            httpx.Response(503, headers=headers, json={"detail": "Temporarily unavailable"}),
+            httpx.Response(200, json=[]),
+        ]
+    )
+
+    result = cli_runner.invoke(app, ["--json", "memory", "list"])
+
+    assert result.exit_code == 0, result.output
+    assert json.loads(result.stdout) == []
+    assert route.call_count == 2
+    assert sleeps == [expected_wait]
+
+
+def test_503_retry_after_exhaustion_preserves_server_error(authed_profile, respx_mock, monkeypatch) -> None:
+    sleeps: list[float] = []
+    monkeypatch.setattr(time, "sleep", sleeps.append)
+    route = respx_mock.get("/v1/dev/user/goals").mock(
+        side_effect=[httpx.Response(503, headers={"Retry-After": "3"}, json={"detail": "Maintenance"})] * 4
+    )
+    with OmiClient(authed_profile) as client:
+        with pytest.raises(ServerError) as info:
+            client.get("/v1/dev/user/goals")
+    assert route.call_count == 4
+    assert sleeps == [3.0, 3.0, 3.0]
+    assert info.value.exit_code == 3
+    assert info.value.detail == "Maintenance"
+
+
 def test_429_surfaces_rate_limit_with_policy(authed_profile, respx_mock) -> None:
     respx_mock.post("/v1/dev/user/conversations").mock(
         side_effect=[

looternikhil-cpu avatar Sep 08 '26 19:09 looternikhil-cpu

I have resolved this issue and added regression test coverage in PR #13314.

/claim #13186

CreamPle avatar Sep 09 '26 13:09 CreamPle