Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(python-client): never repeat the slack approval GET and bound GET…
… retries to 15s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
rubenfiszel and claude committed Nov 18, 2026
commit 2824541480fbd95b9251a7930ec951dd0017626b
48 changes: 29 additions & 19 deletions python-client/wmill/tests/test_get_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from wmill.client import Windmill


def _get(statuses, monkeypatch):
def _client(statuses, monkeypatch):
sent, sleeps = [], []
responses = iter(statuses)

Expand All @@ -18,27 +18,37 @@ def handler(request: httpx.Request) -> httpx.Response:
monkeypatch.setattr("wmill.client.time.sleep", sleeps.append)
client = Windmill(base_url="http://wm.test", token="t", workspace="ws")
client.client = httpx.Client(base_url=client.base_url, transport=httpx.MockTransport(handler))
resp = client.get("/w/ws/variables/get_value/u/a/b", raise_for_status=False)
return resp.status_code, len(sent), sleeps
return client, sent, sleeps


@pytest.mark.parametrize(
"statuses, expected",
"statuses, retry_budget, expected",
[
([(503, {}), (429, {"Retry-After": "5"}), (200, {})], (200, 3, [1, 5])),
([(503, {})] * 4, (503, 4, [1, 2, 4])),
([(502, {}), (504, {"Retry-After": "120"}), (200, {})], (200, 3, [1, 60])),
(
[
(503, {"Retry-After": "Fri, 01 Jan 2100 00:00:00 GMT"}),
(503, {"Retry-After": "Wed, 21 Oct 2015 07:28:00 GMT"}),
(200, {}),
],
(200, 3, [60, 0]),
),
([(404, {})], (404, 1, [])),
([(200, {})], (200, 1, [])),
([(503, {}), (429, {"Retry-After": "5"}), (200, {})], None, (200, 3, [1, 5])),
([(503, {})] * 4, None, (503, 4, [1, 2, 4])),
# a Retry-After past the remaining budget ends the retries
([(502, {}), (504, {"Retry-After": "120"})], None, (504, 2, [1])),
([(429, {"Retry-After": "10"}), (429, {"Retry-After": "10"})], None, (429, 2, [10])),
([(503, {"Retry-After": "Fri, 01 Jan 2100 00:00:00 GMT"})], None, (503, 1, [])),
([(503, {"Retry-After": "Wed, 21 Oct 2015 07:28:00 GMT"}), (200, {})], None, (200, 2, [0])),
([(503, {})] * 3, 3, (503, 3, [1, 2])),
([(404, {})], None, (404, 1, [])),
([(200, {})], None, (200, 1, [])),
],
)
def test_get_retries_transient_errors(statuses, expected, monkeypatch):
assert _get(statuses, monkeypatch) == expected
def test_get_retries_transient_errors(statuses, retry_budget, expected, monkeypatch):
client, sent, sleeps = _client(statuses, monkeypatch)
resp = client.get(
"/w/ws/variables/get_value/u/a/b", raise_for_status=False, retry_budget=retry_budget
)
assert (resp.status_code, len(sent), sleeps) == expected


def test_slack_approval_request_is_not_repeated(monkeypatch):
# the endpoint posts the approval message: a proxy 502 after it did must not post a second
client, sent, sleeps = _client([(502, {}), (200, {})], monkeypatch)
monkeypatch.setenv("WM_JOB_ID", "job")
monkeypatch.setenv("WM_FLOW_JOB_ID", "flow")
with pytest.raises(Exception):
client.request_interactive_slack_approval("u/a/slack", "C1")
assert (len(sent), sleeps) == (1, [])
67 changes: 55 additions & 12 deletions python-client/wmill/wmill/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,27 @@

JobStatus = Literal["RUNNING", "WAITING", "COMPLETED"]

_TRANSIENT_GET_STATUSES = (429, 502, 503, 504)
_GET_RETRIES = 3
# Total sleep one GET may spend retrying; a Retry-After beyond it ends the retries.
_GET_RETRY_BUDGET_SECONDS = 15.0


def _retry_after_seconds(retry_after: str, default: float) -> float:
"""Seconds a Retry-After header (delay-seconds or an HTTP-date) asks to wait."""
retry_after = retry_after.strip()
if not retry_after:
return default
if retry_after.isdigit():
return float(retry_after)
Comment thread
burrows99 marked this conversation as resolved.
Resolved
try:
when = parsedate_to_datetime(retry_after)
except (TypeError, ValueError):
return default
if when.tzinfo is None:
when = when.replace(tzinfo=dt.timezone.utc)
return max((when - dt.datetime.now(dt.timezone.utc)).total_seconds(), 0.0)


def _sign_s3_objects_body(s3_objects: list, expiry_secs: int | None) -> dict:
# `expiry_secs` is optional but not nullable in the spec, so omit it rather than
Expand Down Expand Up @@ -112,30 +133,49 @@ def get_client(self) -> httpx.Client:
timeout=httpx.Timeout(900.0),
)

def get(self, endpoint, raise_for_status=True, **kwargs) -> httpx.Response:
def get(
self,
endpoint,
raise_for_status=True,
*,
retry_transient: bool = True,
retry_budget: float | None = None,
**kwargs,
) -> httpx.Response:
"""Make an HTTP GET request to the Windmill API.

Args:
endpoint: API endpoint path
raise_for_status: Whether to raise an exception on HTTP errors
retry_transient: Retry on 429 and 502-504 with exponential backoff, honoring
Retry-After. Pass False for an endpoint with a side effect.
retry_budget: Most seconds to spend sleeping between retries (at most 15)
**kwargs: Additional arguments passed to httpx.get

Returns:
HTTP response object
"""
endpoint = endpoint.lstrip("/")
# a burst of requests can be answered 429/502-504; a GET is safe to repeat, a POST is not
for attempt in range(4):
# A 502/504 can come from a proxy after the server handled the request, so only
# a GET without side effects may be repeated: one with them passes retry_transient=False.
budget = _GET_RETRY_BUDGET_SECONDS
if retry_budget is not None:
budget = min(budget, max(retry_budget, 0.0))
attempt = 0
while True:
resp = self.client.get(f"/{endpoint}", **kwargs)
if resp.status_code not in (429, 502, 503, 504) or attempt == 3:
if (
not retry_transient
or resp.status_code not in _TRANSIENT_GET_STATUSES
or attempt == _GET_RETRIES
):
break
delay = _retry_after_seconds(resp.headers.get("Retry-After", ""), 2**attempt)
if delay > budget:
break
retry_after = resp.headers.get("Retry-After", "")
try: # delay-seconds or an HTTP-date
when = parsedate_to_datetime(retry_after) if not retry_after.isdigit() else None
delay = int(retry_after) if when is None else (when - dt.datetime.now(dt.timezone.utc)).total_seconds()
except (TypeError, ValueError):
delay = 2**attempt
time.sleep(min(max(delay, 0), 60))
time.sleep(delay)
budget -= delay
attempt += 1
if raise_for_status:
try:
resp.raise_for_status()
Expand Down Expand Up @@ -432,7 +472,9 @@ def cancel_job():

while True:
result_res = self.get(
f"/w/{self.workspace}/jobs_u/completed/get_result_maybe/{job_id}", True
f"/w/{self.workspace}/jobs_u/completed/get_result_maybe/{job_id}",
True,
retry_budget=(timeout - (time.time() - start_time)) if timeout else None,
).json()

started = result_res["started"]
Expand Down Expand Up @@ -1551,6 +1593,7 @@ def request_interactive_slack_approval(
self.get(
f"/w/{workspace}/jobs/slack_approval/{os.environ.get('WM_JOB_ID', 'NO_JOB_ID')}",
params=params,
retry_transient=False,
)

def username_to_email(self, username: str) -> str:
Expand Down
Loading