Skip to content

Commit 8dcf953

Browse files
fadi-georgeclaude
andcommitted
test: [SDK-5535] match the retry harness to the final backoff and fix review issues
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4d9d3be commit 8dcf953

5 files changed

Lines changed: 188 additions & 112 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
.state/
2+
__pycache__/

‎examples/demo/scripts/retry/README.md‎

Lines changed: 34 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,13 @@ cd examples/demo/scripts/retry
3434
| --- | --- |
3535
| `fail <route> <status> [--times N] [--retry-after S] [--add]` | Fail matching requests. Status `0` drops the connection, like being offline. Without `--times` it fails until `clear`. `--add` keeps earlier rules. Applies right away. |
3636
| `clear` / `rules` | Remove or show the rules |
37-
| `report [regex]` | Per route: each attempt, the gap since the previous one, and the gap expected |
37+
| `report [regex]` | Per operation: each attempt, the gap since the previous one, and the gap expected. Also lists any SDK request sent during a Retry-After |
3838
| `reset-log` | Forget recorded attempts, for example between scenarios |
3939
| `tap <action> [args]` | Use the demo: `add-tag <key> <value>`, `add-alias <label> <id>`, `add-email <email>`, `login <external id>`, `logout`, `toggle-push`, `allow-notifications` |
4040
| `install` | Build the demo against the local SDK and install it |
4141
| `fresh` / `relaunch` | Clear the demo's data and relaunch / kill and relaunch |
4242
| `background` / `foreground` | Press Home / bring the demo back |
43-
| `network-flap [s]` | Turn the device's Wi-Fi and mobile data off for `s` seconds (default 10) |
43+
| `network-flap [s]` | Turn the device's Wi-Fi and mobile data off for `s` seconds (default 10). Turns back on only what was on, even after Ctrl-C. Not over wireless adb |
4444
| `logs` | Stream the demo's OperationRepo and HttpClient logs |
4545

4646
Routes: `create-user`, `fetch-user`, `update-user` (tags, properties, session data), `identity`
@@ -50,41 +50,54 @@ Routes: `create-user`, `fetch-user`, `update-user` (tags, properties, session da
5050
## Reading `report`
5151

5252
```
53-
POST apps/<app>/users
53+
POST apps/<app>/users body=b8398c6a
5454
# time status body gap expected note
5555
1 0.0s 408* b8398c6a
56-
2 15.0s 408* b8398c6a 15.0s 15.0-21.0s backoff #1
57-
3 45.3s 201 b8398c6a 30.3s 30.0-36.0s backoff #2
56+
2 3.9s 408* b8398c6a 3.9s 2.5-10.0s backoff #1
57+
3 11.2s 201 b8398c6a 7.3s 5.0-15.0s backoff #2
5858
```
5959

60+
Attempts are grouped per record (full path), and by body for routes without an id in the path
61+
(Create User, custom events).
62+
6063
What the SDK should do:
6164

62-
- **Backoff per operation**: after the Nth retryable failure an operation waits N × 15s
63-
(`opRepoDefaultFailRetryBackoff`), capped at 1h, with no jitter. `HttpClient` does not re-send on
64-
its own. Retryable is anything but 400, 401, 402, 403, 404, 409 and 410.
65-
- **Retry-After** is the minimum wait for that operation, capped at 1h. Foreground and network
66-
return do not cut it short. Other routes are not held. A 429 without Retry-After waits 60s.
67-
- **Other records keep going**: while one operation waits, operations on other records are sent.
68-
Operations on the same record wait behind it, so order is kept.
69-
- **Foreground and network return** end the backoff. The next attempt goes out after the queue's
70-
usual 5s batching wait (`opRepoExecutionInterval`), so `report` allows up to 6s of slack, and
71-
flags shorter gaps as EARLY with a note.
65+
- **Backoff per request**: after the Nth retryable failure the request waits 5s × 2^(N-1), capped at
66+
300s (`opRepoBaseFailRetryBackoff`, `opRepoMaxFailRetryBackoff`), times a jitter of 0.5 to 1.
67+
Operations batched into one request share the wait. `HttpClient` does not re-send on its own.
68+
Retryable is anything but 400, 401, 402, 403, 404, 409 and 410.
69+
- **Retry-After** is the minimum wait for that request, capped at 1h. `HttpClient` also holds
70+
every SDK request, on any route, until it passes, and `report` lists any that weren't. Foreground
71+
and network return do not cut it short. A 429 without Retry-After, or with an unparsable one,
72+
waits 60s.
73+
- **Other records keep going**: while one request backs off, operations on other records are sent
74+
(outside a Retry-After). Operations on the same record wait behind it, so order is kept.
75+
- **Foreground, and network return while in the foreground,** end the backoff, and the attempt goes
76+
out right away without the queue's 5s batching wait. `report` flags those gaps as EARLY with a
77+
note. A network return in the background does nothing; the timed retry or the next foreground
78+
picks it up.
79+
- `report` allows 5s of slack past the window (`opRepoExecutionInterval`), since an enqueue near
80+
the end of a backoff can add the batching wait.
7281
- Backoff state is in memory. After a relaunch, queued operations are sent right away.
7382

7483
## Scenarios
7584

7685
Run `reset-log` before each one. Unless noted, the request should succeed after the last failure,
7786
and nothing should need a relaunch.
7887

79-
1. **Backoff**: `fail create-user 408 --times 2`, then `fresh`. Gaps of 15s and 30s, then 201.
88+
1. **Backoff**: `fail create-user 408 --times 3`, then `fresh`. Gaps within 2.5-5s, 5-10s and
89+
10-20s (plus slack), then 201.
8090
2. **Other records are not blocked**: `fail update-user 408`, `tap add-tag k v`, then after the
8191
first failure `tap toggle-push`. The subscription PATCH goes out while the tag keeps retrying.
8292
3. **Retry-After**: `fail update-user 429 --times 1 --retry-after 40`, then `tap add-tag k v`.
83-
One retry after about 40s. `background` then `foreground` during the wait does not cut it short.
84-
4. **Foreground ends the backoff**: `fail update-user 408`, `tap add-tag k v`, wait for two
85-
failures, then `background` and `foreground`. An attempt goes out about 5s after foreground.
86-
5. **Network return**: as in 4, but `network-flap 5` instead. An attempt goes out shortly after the
87-
network is back.
93+
One retry after about 40s. `background` then `foreground` during the wait does not cut it short,
94+
and a `tap toggle-push` during the wait is not sent until it ends.
95+
4. **Foreground ends the backoff**: `fail update-user 408`, `tap add-tag k v`, wait for four
96+
failures (a 20-40s wait), then `background` and `foreground`. An attempt goes out right after
97+
foreground.
98+
5. **Network return**: as in 4, but `network-flap 5` with the demo in the foreground. An attempt
99+
goes out right after the network is back. With the demo in the background, the flap changes
100+
nothing.
88101
6. **Order is kept**: `fail create-user 408 --times 2`, then `fresh` and `tap login <id>` during
89102
the failures. Identify User (PATCH `.../identity`) is not sent until Create User succeeds.
90103
7. **Fetch User**: `fail fetch-user 408 --times 2`, then `tap login <id>`. Fetch User retries in

‎examples/demo/scripts/retry/fault_proxy.py‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@
66
pass through. Every SDK request is appended to attempts.jsonl for `retry-test.sh report`.
77
88
Rules are re-read whenever rules.json changes. Each rule:
9-
{"route": "update-user", "method": "PATCH", "path": "<regex>", "status": 503,
9+
{"id": "<unique>", "route": "update-user", "method": "PATCH", "path": "<regex>", "status": 503,
1010
"retry_after": "30", "times": 3}
1111
`status` 0 drops the connection (the SDK sees status 0, like being offline). `times` is how many
12-
matching requests fail before the rule passes them through; null fails forever.
12+
matching requests fail before the rule passes them through; null fails forever. A rule keeps its
13+
remaining count across reloads, keyed by `id`.
1314
"""
1415

1516
import hashlib
@@ -31,7 +32,7 @@ class FaultProxy:
3132
def __init__(self):
3233
self.rules_mtime = None
3334
self.rules = []
34-
self.remaining = []
35+
self.remaining = {}
3536

3637
def load_rules(self):
3738
try:
@@ -45,26 +46,29 @@ def load_rules(self):
4546
if mtime is not None:
4647
with open(RULES_PATH) as f:
4748
self.rules = json.load(f)
48-
self.remaining = [rule.get("times") for rule in self.rules]
49+
self.remaining = {rule["id"]: self.remaining.get(rule["id"], rule.get("times")) for rule in self.rules}
4950
print(f"[fault] rules: {json.dumps(self.rules) if self.rules else 'none, passing everything'}")
5051

5152
def match(self, flow):
5253
path = API_PATH_PREFIX.sub("", flow.request.path.split("?")[0])
53-
for i, rule in enumerate(self.rules):
54+
for rule in self.rules:
5455
if rule.get("method") and rule["method"] != flow.request.method:
5556
continue
5657
if not re.search(rule["path"], path):
5758
continue
58-
if self.remaining[i] is not None:
59-
if self.remaining[i] <= 0:
59+
remaining = self.remaining[rule["id"]]
60+
if remaining is not None:
61+
if remaining <= 0:
6062
continue
61-
self.remaining[i] -= 1
63+
self.remaining[rule["id"]] = remaining - 1
6264
return rule
6365
return None
6466

6567
def request(self, flow: http.HTTPFlow):
6668
if "onesignal.com" not in flow.request.pretty_host or "SDK-Version" not in flow.request.headers:
6769
return
70+
# Timed at the request, so gaps are between sends rather than between responses.
71+
flow.metadata["fault_sent_at"] = time.time()
6872
self.load_rules()
6973
rule = self.match(flow)
7074
flow.metadata["fault_rule"] = rule
@@ -91,13 +95,14 @@ def error(self, flow: http.HTTPFlow):
9195

9296
def record(self, flow, status, rule):
9397
path = API_PATH_PREFIX.sub("", flow.request.path.split("?")[0])
98+
retry_after = flow.response.headers.get("Retry-After") if flow.response else None
9499
entry = {
95-
"t": time.time(),
100+
"t": flow.metadata["fault_sent_at"],
96101
"method": flow.request.method,
97102
"path": path,
98103
"status": status,
99104
"injected": rule is not None,
100-
"retry_after": rule.get("retry_after") if rule else None,
105+
"retry_after": retry_after,
101106
"body": hashlib.sha1(flow.request.raw_content or b"").hexdigest()[:8],
102107
}
103108
with open(ATTEMPTS_PATH, "a") as f:

‎examples/demo/scripts/retry/report.py‎

Lines changed: 114 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -1,105 +1,148 @@
11
"""
2-
Prints each SDK route's attempts from attempts.jsonl with the gap since the previous attempt, and
3-
the gap the SDK should have waited. Usage: report.py <attempts.jsonl> [route regex]
2+
Prints each SDK operation's attempts from attempts.jsonl with the gap since the previous attempt,
3+
and the gap the SDK should have waited. Usage: report.py <attempts.jsonl> [route regex]
44
5-
Expected gaps model OperationRepo's per-operation backoff:
6-
- After the Nth retryable failure an operation waits N * 15s (opRepoDefaultFailRetryBackoff),
7-
capped at 1h. There is no jitter and HttpClient does not re-send on its own.
5+
Expected gaps model OperationRepo's backoff:
6+
- After the Nth retryable failure a request waits 5s * 2^(N-1), capped at 300s, times a jitter
7+
of 0.5 to 1. HttpClient does not re-send on its own.
88
- Retry-After is the minimum wait, capped at 1h. An unparsable value, or a 429 without one,
9-
counts as 60s.
10-
- The queue may wait up to opRepoExecutionInterval (5s) more if something else was enqueued
11-
during the backoff, so a few seconds of slack is allowed.
12-
A foreground or network return ends the backoff early (but not Retry-After), so short gaps right
13-
after those are fine.
9+
counts as 60s. HttpClient also holds every SDK request until it passes, which is checked
10+
separately at the end.
11+
- A timed retry skips the queue's batching wait, but an enqueue near the end of a backoff can add
12+
up to opRepoExecutionInterval (5s), so that much slack is allowed.
13+
A foreground, or a network return while in the foreground, ends the backoff early (but not
14+
Retry-After), so short gaps right after those are fine.
1415
"""
1516

1617
import json
18+
import math
1719
import re
1820
import sys
1921
from collections import OrderedDict
2022

21-
BACKOFF_STEP = 15
22-
MAX_DELAY = 3600
23+
BASE_BACKOFF = 5
24+
MAX_BACKOFF = 300
25+
MIN_JITTER = 0.5
26+
MAX_RETRY_AFTER = 3600
2327
RETRY_AFTER_PARSE_FAIL = 60
24-
QUEUE_SLACK = 6.0
28+
QUEUE_SLACK = 5.0
2529
CLOCK_SLACK = 1.0
2630
NOT_RETRIED = (400, 401, 402, 403, 404, 409, 410)
2731
EXECUTOR_ROUTE = re.compile(r"^apps/[^/]+/(users(/by/.*)?|subscriptions/.+|custom_events)$")
2832
IGNORED_ROUTE = re.compile(r"/iams$")
29-
ID_SEGMENT = re.compile(r"(by/[^/]+/|subscriptions/|identity/)[^/]+")
33+
# Routes without a record id in the path. Their attempts are told apart by body instead.
34+
NO_ID_ROUTE = re.compile(r"(/users|/subscriptions|/custom_events)$")
3035

3136

32-
def route_key(entry):
33-
path = ID_SEGMENT.sub(r"\1:id", entry["path"])
34-
return f"{entry['method']} {path}"
37+
def operation_key(entry):
38+
key = f"{entry['method']} {entry['path']}"
39+
if entry["method"] == "POST" and NO_ID_ROUTE.search(entry["path"]):
40+
key += f" body={entry.get('body', '')}"
41+
return key
3542

3643

37-
def backoff_window(failures, status, retry_after):
38-
low = min(failures * BACKOFF_STEP, MAX_DELAY)
39-
if retry_after is None and status == 429:
40-
retry_after = RETRY_AFTER_PARSE_FAIL
41-
has_floor = retry_after is not None
42-
if has_floor:
43-
try:
44-
floor = min(max(float(retry_after), 0), MAX_DELAY)
45-
except ValueError:
46-
floor = RETRY_AFTER_PARSE_FAIL
47-
low = max(low, floor)
48-
return low, low + QUEUE_SLACK, has_floor
44+
def retry_after_seconds(status, header):
45+
"""Mirrors HttpClient.retryAfterFromResponse."""
46+
if header is None:
47+
return RETRY_AFTER_PARSE_FAIL if status == 429 else None
48+
try:
49+
value = float(str(header).strip())
50+
except ValueError:
51+
return RETRY_AFTER_PARSE_FAIL
52+
if not math.isfinite(value) or value < 0:
53+
return RETRY_AFTER_PARSE_FAIL
54+
return math.ceil(min(value, MAX_RETRY_AFTER))
55+
56+
57+
def backoff_window(failures, retry_after):
58+
backoff = min(BASE_BACKOFF * 2 ** (failures - 1), MAX_BACKOFF)
59+
low, high = backoff * MIN_JITTER, backoff
60+
if retry_after is not None:
61+
low, high = max(low, retry_after), max(high, retry_after)
62+
return low, high + QUEUE_SLACK
63+
64+
65+
def print_operation(key, entries):
66+
print(f"\n{key}")
67+
print(f" {'#':>3} {'time':>8} {'status':>6} {'body':>8} {'gap':>8} {'expected':>16} note")
68+
failures = 0
69+
expected = None
70+
start = entries[0]["t"]
71+
for i, entry in enumerate(entries):
72+
gap = entry["t"] - entries[i - 1]["t"] if i else None
73+
note = ""
74+
if expected and gap is not None:
75+
low, high, kind = expected
76+
if gap < low - CLOCK_SLACK:
77+
note = f"EARLY ({kind})"
78+
if not kind.endswith("Retry-After"):
79+
note += "; fine if right after a foreground or network return"
80+
elif gap > high + CLOCK_SLACK:
81+
note = f"LATE ({kind})"
82+
else:
83+
note = kind
84+
elif gap is not None:
85+
note = "new attempt"
86+
expected_text = f"{expected[0]:.1f}-{expected[1]:.1f}s" if expected else ""
87+
gap_text = f"{gap:.1f}s" if gap is not None else ""
88+
mark = "*" if entry["injected"] else " "
89+
print(f" {i + 1:>3} {entry['t'] - start:>7.1f}s {entry['status']:>5}{mark} {entry.get('body', ''):>8} {gap_text:>8} {expected_text:>16} {note}")
90+
91+
status = entry["status"]
92+
if 200 <= status < 300 or status in NOT_RETRIED:
93+
failures = 0
94+
expected = None
95+
else:
96+
failures += 1
97+
retry_after = retry_after_seconds(status, entry.get("retry_after"))
98+
low, high = backoff_window(failures, retry_after)
99+
expected = (low, high, f"backoff #{failures}" + (", Retry-After" if retry_after is not None else ""))
100+
101+
102+
def print_gate_violations(entries):
103+
"""HttpClient holds every SDK request, on any route, until a Retry-After passes."""
104+
windows = []
105+
for entry in entries:
106+
retry_after = retry_after_seconds(entry["status"], entry.get("retry_after"))
107+
if retry_after:
108+
windows.append((entry["t"], entry["t"] + retry_after))
109+
violations = [
110+
entry
111+
for entry in entries
112+
if any(start < entry["t"] < end - CLOCK_SLACK for start, end in windows)
113+
]
114+
if not windows:
115+
return
116+
if not violations:
117+
print("\nNo SDK request was sent during a Retry-After.")
118+
return
119+
print("\nSENT DURING A RETRY-AFTER (HttpClient should have held these):")
120+
for entry in violations:
121+
print(f" {entry['method']} {entry['path']} status={entry['status']} body={entry.get('body', '')}")
49122

50123

51124
def main():
52125
path = sys.argv[1]
53126
route_filter = re.compile(sys.argv[2]) if len(sys.argv) > 2 else None
54-
groups = OrderedDict()
127+
entries = []
55128
with open(path) as f:
56129
for line in f:
57130
if line.strip():
58-
entry = json.loads(line)
59-
groups.setdefault(route_key(entry), []).append(entry)
131+
entries.append(json.loads(line))
60132

61-
if not groups:
133+
if not entries:
62134
print("No SDK requests recorded yet.")
63135
return
64136

65-
for key, entries in groups.items():
66-
if route_filter and not route_filter.search(key):
67-
continue
68-
if not EXECUTOR_ROUTE.search(entries[0]["path"]) or IGNORED_ROUTE.search(entries[0]["path"]):
69-
continue
70-
print(f"\n{key}")
71-
print(f" {'#':>3} {'time':>8} {'status':>6} {'body':>8} {'gap':>8} {'expected':>16} note")
72-
failures = 0
73-
expected = None
74-
start = entries[0]["t"]
75-
for i, entry in enumerate(entries):
76-
gap = entry["t"] - entries[i - 1]["t"] if i else None
77-
note = ""
78-
if expected and gap is not None:
79-
low, high, kind = expected
80-
if gap < low - CLOCK_SLACK:
81-
note = f"EARLY ({kind})"
82-
if not kind.endswith("Retry-After"):
83-
note += "; fine if right after a foreground or network return"
84-
elif gap > high + CLOCK_SLACK:
85-
note = f"LATE ({kind})"
86-
else:
87-
note = kind
88-
elif gap is not None:
89-
note = "new attempt"
90-
expected_text = f"{expected[0]:.1f}-{expected[1]:.1f}s" if expected else ""
91-
gap_text = f"{gap:.1f}s" if gap is not None else ""
92-
mark = "*" if entry["injected"] else " "
93-
print(f" {i + 1:>3} {entry['t'] - start:>7.1f}s {entry['status']:>5}{mark} {entry.get('body', ''):>8} {gap_text:>8} {expected_text:>16} {note}")
94-
95-
status = entry["status"]
96-
if 200 <= status < 300 or status in NOT_RETRIED:
97-
failures = 0
98-
expected = None
99-
else:
100-
failures += 1
101-
low, high, has_floor = backoff_window(failures, status, entry.get("retry_after"))
102-
expected = (low, high, f"backoff #{failures}" + (", Retry-After" if has_floor else ""))
137+
operations = OrderedDict()
138+
for entry in entries:
139+
if EXECUTOR_ROUTE.search(entry["path"]) and not IGNORED_ROUTE.search(entry["path"]):
140+
operations.setdefault(operation_key(entry), []).append(entry)
141+
142+
for key, op_entries in operations.items():
143+
if not route_filter or route_filter.search(key):
144+
print_operation(key, op_entries)
145+
print_gate_violations(entries)
103146
print("\n* = failure injected by the proxy")
104147

105148

0 commit comments

Comments
 (0)