Repository navigation
Expand file tree
/
Copy pathtest_retries.py
More file actions
717 lines (585 loc) · 22.4 KB
/
Copy pathtest_retries.py
File metadata and controls
717 lines (585 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
import asyncio
import time as time_module
from unittest.mock import MagicMock
import httpx
import pytest
from unstructured_client import UnstructuredClient
from unstructured_client.models.errors import ServerError
from unstructured_client.utils import retries as retries_module
from unstructured_client.utils.retries import (
BackoffStrategy,
PermanentError,
Retries,
RetryConfig,
TemporaryError,
retry,
retry_async,
)
class FakeClock:
def __init__(self):
self.now_ms = 0
def time(self) -> float:
return self.now_ms / 1000.0
def advance(self, milliseconds: int) -> None:
self.now_ms += int(milliseconds)
@pytest.fixture
def fake_clock(monkeypatch):
clock = FakeClock()
def fake_time():
return clock.time()
def fake_sync_sleep(seconds):
clock.advance(int(seconds * 1000))
async def fake_async_sleep(seconds):
clock.advance(int(seconds * 1000))
monkeypatch.setattr(retries_module.time, "time", fake_time)
monkeypatch.setattr(retries_module.time, "sleep", fake_sync_sleep)
monkeypatch.setattr(retries_module.asyncio, "sleep", fake_async_sleep)
monkeypatch.setattr(retries_module.random, "uniform", lambda a, b: 0.0)
return clock
def _retries(
*,
initial_interval: int = 100,
max_interval: int = 200,
exponent: float = 1.5,
max_elapsed_time: int = 5_000,
min_attempts: int = 0,
absolute_max_elapsed_time_ms=None,
retry_connection_errors: bool = True,
status_codes=None,
) -> Retries:
return Retries(
config=RetryConfig(
strategy="backoff",
backoff=BackoffStrategy(
initial_interval=initial_interval,
max_interval=max_interval,
exponent=exponent,
max_elapsed_time=max_elapsed_time,
min_attempts=min_attempts,
absolute_max_elapsed_time_ms=absolute_max_elapsed_time_ms,
),
retry_connection_errors=retry_connection_errors,
),
status_codes=status_codes or [],
)
def _make_ok_response(status_code: int = 200) -> httpx.Response:
resp = MagicMock(spec=httpx.Response)
resp.status_code = status_code
return resp
def _make_retries(retry_connection_errors: bool) -> Retries:
return Retries(
config=RetryConfig(
strategy="backoff",
backoff=BackoffStrategy(
initial_interval=100,
max_interval=200,
exponent=1.5,
max_elapsed_time=5000,
),
retry_connection_errors=retry_connection_errors,
),
status_codes=[],
)
TRANSPORT_ERRORS = [
(httpx.ConnectError, "Connection refused"),
(httpx.RemoteProtocolError, "Server disconnected without sending a response."),
(httpx.ReadError, ""),
(httpx.WriteError, ""),
(httpx.ConnectTimeout, "Timed out"),
(httpx.ReadTimeout, "Timed out"),
]
class TestTransportErrorRetry:
@pytest.mark.parametrize("exc_class,msg", TRANSPORT_ERRORS)
def test_transport_error_retried_when_enabled(self, exc_class, msg):
retries_config = _make_retries(retry_connection_errors=True)
mock_response = MagicMock(spec=httpx.Response)
mock_response.status_code = 200
call_count = 0
def func():
nonlocal call_count
call_count += 1
if call_count == 1:
raise exc_class(msg)
return mock_response
result = retry(func, retries_config)
assert result.status_code == 200
assert call_count == 2
@pytest.mark.parametrize("exc_class,msg", TRANSPORT_ERRORS)
def test_transport_error_not_retried_when_disabled(self, exc_class, msg):
retries_config = _make_retries(retry_connection_errors=False)
def func():
raise exc_class(msg)
with pytest.raises(exc_class):
retry(func, retries_config)
class TestTransportErrorRetryAsync:
@pytest.mark.parametrize("exc_class,msg", TRANSPORT_ERRORS)
def test_transport_error_retried_async(self, exc_class, msg):
retries_config = _make_retries(retry_connection_errors=True)
mock_response = MagicMock(spec=httpx.Response)
mock_response.status_code = 200
call_count = 0
async def func():
nonlocal call_count
call_count += 1
if call_count == 1:
raise exc_class(msg)
return mock_response
result = asyncio.run(retry_async(func, retries_config))
assert result.status_code == 200
assert call_count == 2
@pytest.mark.parametrize("exc_class,msg", TRANSPORT_ERRORS)
def test_transport_error_not_retried_async_when_disabled(self, exc_class, msg):
retries_config = _make_retries(retry_connection_errors=False)
async def func():
raise exc_class(msg)
with pytest.raises(exc_class):
asyncio.run(retry_async(func, retries_config))
class TestBackoffStrategyValidation:
def test_t12_negative_min_attempts_rejected(self):
with pytest.raises(ValueError, match="min_attempts must be >= 0"):
BackoffStrategy(
initial_interval=100,
max_interval=200,
exponent=1.5,
max_elapsed_time=5_000,
min_attempts=-1,
)
def test_t13_zero_absolute_max_rejected(self):
with pytest.raises(ValueError, match="absolute_max_elapsed_time_ms must be > 0"):
BackoffStrategy(
initial_interval=100,
max_interval=200,
exponent=1.5,
max_elapsed_time=5_000,
absolute_max_elapsed_time_ms=0,
)
def test_t14_absolute_max_below_soft_max_rejected(self):
with pytest.raises(
ValueError,
match="absolute_max_elapsed_time_ms must be >= max_elapsed_time",
):
BackoffStrategy(
initial_interval=100,
max_interval=200,
exponent=1.5,
max_elapsed_time=10_000,
absolute_max_elapsed_time_ms=5_000,
)
def test_min_attempts_zero_accepted(self):
BackoffStrategy(
initial_interval=100,
max_interval=200,
exponent=1.5,
max_elapsed_time=5_000,
min_attempts=0,
)
def test_absolute_max_equal_to_soft_max_accepted(self):
BackoffStrategy(
initial_interval=100,
max_interval=200,
exponent=1.5,
max_elapsed_time=5_000,
absolute_max_elapsed_time_ms=5_000,
)
class TestBackwardCompat:
def test_t1_no_failures_sync(self, fake_clock):
retries_config = _retries()
call_count = 0
def func():
nonlocal call_count
call_count += 1
return _make_ok_response()
result = retry(func, retries_config)
assert result.status_code == 200
assert call_count == 1
def test_t1_no_failures_async(self, fake_clock):
retries_config = _retries()
call_count = 0
async def func():
nonlocal call_count
call_count += 1
return _make_ok_response()
result = asyncio.run(retry_async(func, retries_config))
assert result.status_code == 200
assert call_count == 1
def test_t2_one_transient_then_success_sync(self, fake_clock):
retries_config = _retries()
call_count = 0
def func():
nonlocal call_count
call_count += 1
if call_count == 1:
raise httpx.ConnectError("transient")
return _make_ok_response()
result = retry(func, retries_config)
assert result.status_code == 200
assert call_count == 2
def test_t2_one_transient_then_success_async(self, fake_clock):
retries_config = _retries()
call_count = 0
async def func():
nonlocal call_count
call_count += 1
if call_count == 1:
raise httpx.ConnectError("transient")
return _make_ok_response()
result = asyncio.run(retry_async(func, retries_config))
assert result.status_code == 200
assert call_count == 2
class TestSoftCapFloor:
def test_t3_slow_first_attempt_then_success_sync(self, fake_clock):
retries_config = _retries(
max_elapsed_time=5_000,
min_attempts=2,
)
call_count = 0
def func():
nonlocal call_count
call_count += 1
if call_count == 1:
fake_clock.advance(6_000) # 6s
raise httpx.ReadTimeout("slow")
return _make_ok_response()
result = retry(func, retries_config)
assert result.status_code == 200
assert call_count == 2
def test_t3_slow_first_attempt_then_success_async(self, fake_clock):
retries_config = _retries(
max_elapsed_time=5_000,
min_attempts=2,
)
call_count = 0
async def func():
nonlocal call_count
call_count += 1
if call_count == 1:
fake_clock.advance(6_000)
raise httpx.ReadTimeout("slow")
return _make_ok_response()
result = asyncio.run(retry_async(func, retries_config))
assert result.status_code == 200
assert call_count == 2
def test_t3_baseline_pre_fix_behavior(self, fake_clock):
retries_config = _retries(
max_elapsed_time=5_000,
min_attempts=0,
)
call_count = 0
def func():
nonlocal call_count
call_count += 1
if call_count == 1:
fake_clock.advance(6_000)
raise httpx.ReadTimeout("slow")
return _make_ok_response()
# Without the floor, soft cap fires on attempt 1's failure and
# the loop raises the wrapped ReadTimeout.
with pytest.raises(httpx.ReadTimeout):
retry(func, retries_config)
assert call_count == 1
class TestFloorIsNotCeiling:
def test_t4_floor_does_not_cap_attempts_sync(self, fake_clock):
retries_config = _retries(
initial_interval=100,
max_interval=200,
exponent=1.5,
max_elapsed_time=60_000, # generous budget
min_attempts=2,
)
call_count = 0
def func():
nonlocal call_count
call_count += 1
if call_count <= 5:
raise httpx.ConnectError("transient")
return _make_ok_response()
result = retry(func, retries_config)
assert result.status_code == 200
assert call_count == 6
def test_t5_floor_then_soft_cap_sync(self, fake_clock):
retries_config = _retries(
initial_interval=100,
max_interval=200,
exponent=1.5,
max_elapsed_time=10_000,
min_attempts=2,
)
call_count = 0
def func():
nonlocal call_count
call_count += 1
# sleep advances the fake clock.
raise httpx.ConnectError("transient")
with pytest.raises(httpx.ConnectError):
retry(func, retries_config)
assert call_count >= 3
class TestHardCap:
def test_t6_hard_cap_overrides_floor_sync(self, fake_clock):
retries_config = _retries(
max_elapsed_time=5_000,
min_attempts=2,
absolute_max_elapsed_time_ms=10_000,
)
call_count = 0
def func():
nonlocal call_count
call_count += 1
if call_count == 1:
fake_clock.advance(11_000) # 11s > 10s hard cap
raise httpx.ReadTimeout("slow")
return _make_ok_response()
with pytest.raises(httpx.ReadTimeout):
retry(func, retries_config)
assert call_count == 1
def test_t6_hard_cap_overrides_floor_async(self, fake_clock):
retries_config = _retries(
max_elapsed_time=5_000,
min_attempts=2,
absolute_max_elapsed_time_ms=10_000,
)
call_count = 0
async def func():
nonlocal call_count
call_count += 1
if call_count == 1:
fake_clock.advance(11_000)
raise httpx.ReadTimeout("slow")
return _make_ok_response()
with pytest.raises(httpx.ReadTimeout):
asyncio.run(retry_async(func, retries_config))
assert call_count == 1
def test_t7_sleep_truncation_prevents_doomed_retry_sync(self, fake_clock):
# Sleep starts at 100ms * 1.5^0 = 100ms (no jitter in tests),
# but we want to assert the sleep+elapsed > hard_cap path
# fires. Use larger initial_interval to make the calculation
# land deterministically.
retries_config = _retries(
initial_interval=200, # 200ms initial
max_interval=1_000,
exponent=2.0,
max_elapsed_time=5_000,
min_attempts=2, # floor is unsatisfied; only hard cap can cut
absolute_max_elapsed_time_ms=10_000,
)
call_count = 0
def func():
nonlocal call_count
call_count += 1
if call_count == 1:
# attempt 1 lasts 9.95s -> elapsed = 9.95s, sleep would be
# 200ms -> projected = 10.15s >= hard cap 10s -> raise.
fake_clock.advance(9_950)
raise httpx.ReadTimeout("slow")
return _make_ok_response()
with pytest.raises(httpx.ReadTimeout):
retry(func, retries_config)
assert call_count == 1
class TestTemporaryErrorEarlyReturn:
def test_t8_soft_cap_5xx_returns_last_response_sync(self, fake_clock):
retries_config = _retries(
initial_interval=100,
max_interval=200,
exponent=1.5,
max_elapsed_time=500,
min_attempts=0,
status_codes=["5xx"],
)
bad_response = _make_ok_response(status_code=503)
call_count = 0
def func():
nonlocal call_count
call_count += 1
return bad_response
result = retry(func, retries_config)
assert result.status_code == 503
assert call_count >= 1
def test_t9_floor_then_soft_cap_5xx_returns_last_response_sync(self, fake_clock):
retries_config = _retries(
initial_interval=100,
max_interval=200,
exponent=1.5,
max_elapsed_time=1_000,
min_attempts=2,
status_codes=["5xx"],
)
bad_response = _make_ok_response(status_code=503)
call_count = 0
def func():
nonlocal call_count
call_count += 1
return bad_response
result = retry(func, retries_config)
assert result.status_code == 503
assert call_count >= 3
def test_t10_hard_cap_5xx_returns_last_response_sync(self, fake_clock):
retries_config = _retries(
initial_interval=100,
max_interval=200,
exponent=1.5,
max_elapsed_time=5_000,
min_attempts=2,
absolute_max_elapsed_time_ms=10_000,
status_codes=["5xx"],
)
bad_response = _make_ok_response(status_code=503)
call_count = 0
def func():
nonlocal call_count
call_count += 1
if call_count == 1:
fake_clock.advance(11_000) # past hard cap
return bad_response
result = retry(func, retries_config)
assert result.status_code == 503
assert call_count == 1
class TestPermanentErrorShortCircuit:
def test_t11_permanent_error_one_attempt_sync(self, fake_clock):
retries_config = _retries(min_attempts=10)
call_count = 0
def func():
nonlocal call_count
call_count += 1
raise ValueError("permanent")
with pytest.raises(ValueError, match="permanent"):
retry(func, retries_config)
assert call_count == 1
def test_t11_permanent_error_one_attempt_async(self, fake_clock):
retries_config = _retries(min_attempts=10)
call_count = 0
async def func():
nonlocal call_count
call_count += 1
raise ValueError("permanent")
with pytest.raises(ValueError, match="permanent"):
asyncio.run(retry_async(func, retries_config))
assert call_count == 1
def _send_with_retry(respond, config, async_mode, *, stream=False):
transport = httpx.MockTransport(respond)
if async_mode:
async def run():
async with httpx.AsyncClient(transport=transport) as client:
return await retry_async(
lambda: client.send(client.build_request("GET", "http://test.invalid"), stream=stream),
config,
)
return asyncio.run(run())
with httpx.Client(transport=transport) as client:
return retry(
lambda: client.send(client.build_request("GET", "http://test.invalid"), stream=stream),
config,
)
@pytest.mark.parametrize("async_mode", [False, True])
@pytest.mark.parametrize(
"body,content_type,stop",
[
(b'{"detail":"unsupported","retryable":false}', "application/json", True),
(b'{"retryable":false}', "application/problem+json; charset=utf-8", True),
(b'{"retryable":true}', "application/json", False),
(b'{"detail":"Internal server error"}', "application/json", False),
(b'{"retryable":"false"}', "application/json", False),
(b'{"retryable":0}', "application/json", False),
(b'{"retryable":null}', "application/json", False),
(b'[{"retryable":false}]', "application/json", False),
(b'false', "application/json", False),
(b'{broken', "application/json", False),
pytest.param(
b'{"retryable":false,"detail":' + b"[" * 100_000 + b"]" * 100_000 + b"}",
"application/json",
False,
id="deeply-nested",
),
(b'upstream error', "text/plain", False),
(b'{"retryable":false}', "text/plain", True),
(b'{"retryable":false}', "", True),
],
)
def test_declared_retry_verdict(
fake_clock, async_mode, body, content_type, stop
):
status_code = 503
attempts = []
def respond(request):
attempts.append(request)
if len(attempts) == 1:
return httpx.Response(status_code, content=body, headers={"Content-Type": content_type})
return httpx.Response(200, json=[])
config = _retries(status_codes=["5xx"], initial_interval=1, max_interval=1)
result = _send_with_retry(respond, config, async_mode)
assert len(attempts) == (1 if stop else 2)
assert result.status_code == (status_code if stop else 200)
if stop:
assert result.content == body
@pytest.mark.parametrize("async_mode", [False, True])
@pytest.mark.parametrize("verdict", [False, True])
def test_declared_verdict_does_not_retry_non_matching_status(fake_clock, async_mode, verdict):
attempts = []
def respond(request):
attempts.append(request)
return httpx.Response(400, json={"retryable": verdict})
config = _retries(status_codes=["5xx"])
response = _send_with_retry(respond, config, async_mode)
assert response.status_code == 400
assert len(attempts) == 1
@pytest.mark.parametrize("async_mode", [False, True])
def test_unread_stream_is_not_consumed(fake_clock, async_mode):
class SyncStream(httpx.SyncByteStream):
def __iter__(self):
pytest.fail("retry inspected an unread stream")
yield b""
class AsyncStream(httpx.AsyncByteStream):
async def __aiter__(self):
pytest.fail("retry inspected an unread stream")
yield b""
attempts = []
def respond(request):
attempts.append(request)
if len(attempts) == 1:
return httpx.Response(
503, headers={"Content-Type": "application/json"},
stream=AsyncStream() if async_mode else SyncStream(),
)
return httpx.Response(200)
config = _retries(status_codes=["5xx"])
result = _send_with_retry(respond, config, async_mode, stream=True)
assert result.status_code == 200
assert len(attempts) == 2
@pytest.mark.parametrize("async_mode", [False, True])
@pytest.mark.parametrize("status_code", [500, 503])
def test_public_partition_preserves_declared_error(fake_clock, async_mode, status_code):
body = {"detail": "unsupported document", "retryable": False}
attempts = []
def respond(request):
attempts.append(request)
return httpx.Response(status_code, json=body)
async def run():
transport = httpx.MockTransport(respond)
with httpx.Client(transport=transport) as client:
async with httpx.AsyncClient(transport=transport) as async_client:
sdk = UnstructuredClient(
server_url="http://test.invalid", client=client, async_client=async_client
)
request = {"partition_parameters": {
"files": {"content": b"hello", "file_name": "test.txt"},
"split_pdf_page": False,
}}
config = _retries(initial_interval=1, max_interval=1, max_elapsed_time=2).config
with pytest.raises(ServerError) as exc:
if async_mode:
await sdk.general.partition_async(request=request, retries=config)
else:
sdk.general.partition(request=request, retries=config)
assert exc.value.raw_response.json() == body
assert "unsupported document" in str(exc.value)
asyncio.run(run())
assert len(attempts) == 1
@pytest.mark.parametrize("async_mode", [False, True])
@pytest.mark.parametrize("status_code", [500, 503])
@pytest.mark.parametrize("status_codes", [["5xx"], ["500", "503"]])
def test_declared_verdict_stops_matching_status(fake_clock, async_mode, status_code, status_codes):
attempts = []
def respond(request):
attempts.append(request)
return httpx.Response(status_code, json={"retryable": False})
response = _send_with_retry(respond, _retries(status_codes=status_codes), async_mode)
assert response.status_code == status_code
assert len(attempts) == 1