forked from Alishahryar1/free-claude-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmission.py
More file actions
942 lines (854 loc) · 32.4 KB
/
Copy pathadmission.py
File metadata and controls
942 lines (854 loc) · 32.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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
"""Provider-owned admission, concurrency, and coordinated retry lifecycle."""
import asyncio
import math
import random
import time
import uuid
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
from enum import StrEnum
from typing import TypeVar
from loguru import logger
from free_claude_code.core.rate_limit import StrictSlidingWindowLimiter
from free_claude_code.core.trace import trace_event
from free_claude_code.providers.failure_policy import (
ProviderFailureOverride,
ProviderRecoveryExhausted,
is_retryable_provider_error,
retryable_upstream_status,
)
T = TypeVar("T")
UPSTREAM_TRANSIENT_TOTAL_ATTEMPTS = 5
DEFAULT_UPSTREAM_BASE_DELAY = 2.0
DEFAULT_UPSTREAM_MAX_DELAY = 60.0
DEFAULT_UPSTREAM_JITTER = 1.0
class ProviderOperationKind(StrEnum):
"""Safe trace category for one physical provider call."""
MODEL_DISCOVERY = "model_discovery"
GENERATION = "generation"
CONTINUATION = "continuation"
TOOL_REPAIR = "tool_repair"
class ProviderExecutionState(StrEnum):
"""Terminal state of one logical provider operation."""
ACTIVE = "active"
SUCCEEDED = "succeeded"
FAILED = "failed"
ABANDONED = "abandoned"
class ProviderCorrectionAction(StrEnum):
"""Whether one deterministic request correction may consume another attempt."""
RETRY = "retry"
FINAL = "final"
@dataclass(frozen=True, slots=True)
class ProviderFailureDecision:
"""Immutable provider qualification and execution-budget decision."""
retryable: bool
retry_allowed: bool
@dataclass(frozen=True, slots=True)
class _AttemptClaim:
execution_id: str
ordinal: int
operation_kind: ProviderOperationKind
class ProviderExecution:
"""Own one logical provider operation and its physical-attempt budget."""
def __init__(
self,
controller: ProviderAdmissionController,
*,
max_attempts: int,
request_id: str | None,
) -> None:
self._controller = controller
self._execution_id = str(uuid.uuid4())
self._max_attempts = max_attempts
self._request_id = request_id
self._attempts_started = 0
self._active_claim: _AttemptClaim | None = None
self._last_failure: Exception | None = None
self._state = ProviderExecutionState.ACTIVE
@property
def execution_id(self) -> str:
return self._execution_id
@property
def max_attempts(self) -> int:
return self._max_attempts
@property
def request_id(self) -> str | None:
return self._request_id
@property
def attempts_started(self) -> int:
return self._attempts_started
@property
def can_attempt(self) -> bool:
return (
self._state is ProviderExecutionState.ACTIVE
and self._attempts_started < self._max_attempts
)
@property
def attempts_remaining(self) -> int:
if self._state is not ProviderExecutionState.ACTIVE:
return 0
return max(0, self._max_attempts - self._attempts_started)
@property
def state(self) -> ProviderExecutionState:
return self._state
@property
def last_failure(self) -> Exception | None:
return self._last_failure
async def open_attempt(
self,
operation_kind: ProviderOperationKind,
) -> ProviderAttempt:
"""Open the sole active physical call for this execution."""
return await self._controller._open_attempt(self, operation_kind)
async def run_call(
self,
fn: Callable[[], Awaitable[T]],
*,
operation_kind: ProviderOperationKind,
provider_failure_override: ProviderFailureOverride | None = None,
) -> T:
"""Run a callable that performs exactly one provider call per invocation."""
try:
while self.can_attempt:
attempt = await self.open_attempt(operation_kind)
try:
result = await fn()
except asyncio.CancelledError:
raise
except Exception as error:
decision = await attempt.fail(
error,
provider_failure_override=provider_failure_override,
)
if not decision.retry_allowed:
raise
else:
await attempt.accept()
self.succeed()
return result
finally:
await attempt.aclose()
except asyncio.CancelledError:
self.abandon()
raise
except Exception as error:
self.fail(error)
raise
if self._last_failure is not None:
self.fail(self._last_failure)
raise self._last_failure
self.abandon()
raise RuntimeError("provider execution ended without an attempt outcome")
def succeed(self) -> None:
"""Mark the complete logical provider operation successful."""
if self._state is ProviderExecutionState.ACTIVE:
self._state = ProviderExecutionState.SUCCEEDED
def fail(self, error: Exception) -> None:
"""Mark the complete logical provider operation failed."""
if self._state is ProviderExecutionState.ACTIVE:
self._last_failure = error
self._state = ProviderExecutionState.FAILED
def abandon(self) -> None:
"""Mark an unfinished logical provider operation abandoned."""
if self._state is ProviderExecutionState.ACTIVE:
self._state = ProviderExecutionState.ABANDONED
def _claim_attempt(
self,
operation_kind: ProviderOperationKind,
) -> _AttemptClaim:
if not self.can_attempt:
raise RuntimeError("provider execution is terminal or exhausted")
if self._active_claim is not None:
raise RuntimeError("provider execution already has an active attempt")
self._attempts_started += 1
claim = _AttemptClaim(
execution_id=self._execution_id,
ordinal=self._attempts_started,
operation_kind=operation_kind,
)
self._active_claim = claim
return claim
def _close_attempt(self, claim: _AttemptClaim) -> None:
if self._active_claim == claim:
self._active_claim = None
def _record_failure(self, error: Exception) -> None:
if self._state is ProviderExecutionState.ACTIVE:
self._last_failure = error
def _fail_recovery(self, error: Exception) -> None:
self.fail(error)
def _terminal_failure(self) -> Exception | None:
if self._state is ProviderExecutionState.FAILED:
return self._last_failure
return None
@dataclass(frozen=True, slots=True)
class _GatePermit:
generation: int | None
probe: bool
@dataclass(slots=True)
class _RecoveryEpisode:
generation: int
leader: ProviderExecution | None
ready_at: float
last_error: Exception
waiters: set[ProviderExecution] = field(default_factory=set)
probe_active: bool = False
terminal_until: float | None = None
class ProviderAttempt:
"""One admitted upstream attempt and its held concurrency slot."""
def __init__(
self,
controller: ProviderAdmissionController,
execution: ProviderExecution,
permit: _GatePermit,
claim: _AttemptClaim,
) -> None:
self._controller = controller
self._execution = execution
self._permit = permit
self._claim = claim
self._resolved = False
self._accepted = False
self._closed = False
@property
def accepted(self) -> bool:
"""Return whether upstream acceptance has resolved this attempt."""
return self._accepted
async def __aenter__(self) -> ProviderAttempt:
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
traceback: object | None,
) -> None:
del exc_type, exc, traceback
await self.aclose()
async def accept(self) -> None:
"""Record first upstream reachability and close a recovery episode if probing."""
if self._resolved or self._closed:
return
await self._controller._attempt_accepted(self._execution, self._permit)
self._resolve("accepted", accepted=True)
async def correct(self, error: Exception) -> ProviderCorrectionAction:
"""Resolve one deterministic request correction without provider backoff."""
if self._resolved or self._closed:
return ProviderCorrectionAction.FINAL
self._execution._record_failure(error)
status = _exception_status(error)
if self._execution.can_attempt:
await self._controller._attempt_corrected(self._execution, self._permit)
self._resolve("corrected", status=status, error=error)
return ProviderCorrectionAction.RETRY
await self._controller._attempt_rejected(self._execution, self._permit)
self._execution.fail(error)
self._resolve("rejected", status=status, error=error)
return ProviderCorrectionAction.FINAL
async def fail(
self,
error: Exception,
*,
provider_failure_override: ProviderFailureOverride | None = None,
) -> ProviderFailureDecision:
"""Classify one failure and return its immutable retry decision."""
if self._resolved or self._closed:
return ProviderFailureDecision(retryable=False, retry_allowed=False)
effective_error = (
provider_failure_override(error)
if provider_failure_override is not None
else None
)
if effective_error is None:
effective_error = error
status = retryable_upstream_status(effective_error)
retryable = is_retryable_provider_error(effective_error)
self._execution._record_failure(error)
if not retryable:
await self._controller._attempt_rejected(self._execution, self._permit)
self._execution.fail(error)
self._resolve("rejected", status=status, error=effective_error)
return ProviderFailureDecision(retryable=False, retry_allowed=False)
await self._controller._attempt_failed(
self._execution,
self._permit,
error=error,
status=status,
)
retry_allowed = self._execution.can_attempt
if not retry_allowed:
self._execution.fail(error)
self._resolve(
"retryable_failure",
status=status,
error=effective_error,
retry_allowed=retry_allowed,
)
return ProviderFailureDecision(
retryable=True,
retry_allowed=retry_allowed,
)
async def aclose(self) -> None:
"""Release attempt ownership and its concurrency slot exactly once."""
if self._closed:
return
self._closed = True
try:
if not self._resolved:
try:
await asyncio.shield(
self._controller._attempt_abandoned(
self._execution,
self._permit,
)
)
finally:
self._resolve("abandoned")
finally:
self._execution._close_attempt(self._claim)
self._controller._release_concurrency()
def _resolve(
self,
outcome: str,
*,
accepted: bool = False,
status: int | None = None,
error: BaseException | None = None,
retry_allowed: bool | None = None,
) -> None:
if self._resolved:
return
self._resolved = True
self._accepted = accepted
trace_event(
stage="provider",
event="provider.attempt.resolved",
source="provider",
provider=self._controller._provider_name,
request_id=self._execution.request_id,
execution_id=self._execution.execution_id,
operation_kind=self._claim.operation_kind.value,
attempt=self._claim.ordinal,
max_attempts=self._execution.max_attempts,
probe=self._permit.probe,
recovery_generation=self._permit.generation,
outcome=outcome,
status_code=status,
exc_type=(None if error is None else type(error).__name__),
retry_allowed=retry_allowed,
)
class ProviderAdmissionController:
"""Coordinate one provider's rate, concurrency, and recovery state.
Normal attempts pass through a strict sliding window and concurrency bulkhead.
The first shared transient failure opens one recovery episode. Exactly one
logical execution owns its half-open probes; concurrent callers wait for that
episode instead of starting independent retry loops.
"""
def __init__(
self,
*,
provider_name: str,
rate_limit: int = 40,
rate_window: float = 60.0,
max_concurrency: int = 5,
max_attempts: int = UPSTREAM_TRANSIENT_TOTAL_ATTEMPTS,
base_delay: float = DEFAULT_UPSTREAM_BASE_DELAY,
max_delay: float = DEFAULT_UPSTREAM_MAX_DELAY,
jitter: float = DEFAULT_UPSTREAM_JITTER,
) -> None:
if rate_limit <= 0:
raise ValueError("rate_limit must be > 0")
if rate_window <= 0:
raise ValueError("rate_window must be > 0")
if max_concurrency <= 0:
raise ValueError("max_concurrency must be > 0")
if max_attempts <= 0:
raise ValueError("max_attempts must be > 0")
if base_delay < 0:
raise ValueError("base_delay must be >= 0")
if max_delay < base_delay:
raise ValueError("max_delay must be >= base_delay")
if jitter < 0:
raise ValueError("jitter must be >= 0")
self._provider_name = provider_name
self._max_attempts = max_attempts
self._base_delay = base_delay
self._max_delay = max_delay
self._jitter = jitter
self._proactive_limiter = StrictSlidingWindowLimiter(
rate_limit, float(rate_window)
)
self._concurrency_sem = asyncio.Semaphore(max_concurrency)
self._condition = asyncio.Condition()
self._episode: _RecoveryEpisode | None = None
self._next_generation = 1
logger.info(
"Provider admission initialized for {} ({} req / {}s, "
"max_concurrency={}, max_attempts={})",
provider_name,
rate_limit,
rate_window,
max_concurrency,
max_attempts,
)
def start_execution(
self,
*,
request_id: str | None = None,
) -> ProviderExecution:
"""Create the sole lifecycle owner for one logical provider operation."""
return ProviderExecution(
self,
max_attempts=self._max_attempts,
request_id=request_id,
)
async def _open_attempt(
self,
execution: ProviderExecution,
operation_kind: ProviderOperationKind,
) -> ProviderAttempt:
"""Wait for provider admission and hold one active-operation slot."""
if not isinstance(operation_kind, ProviderOperationKind):
raise TypeError("operation_kind must be a ProviderOperationKind")
if (terminal_error := execution._terminal_failure()) is not None:
raise ProviderRecoveryExhausted(terminal_error)
if not execution.can_attempt:
raise RuntimeError("provider execution is terminal or exhausted")
if execution._active_claim is not None:
raise RuntimeError("provider execution already has an active attempt")
while True:
permit = await self._wait_for_gate(execution)
slot_acquired = False
claim: _AttemptClaim | None = None
try:
admitted = await self._proactive_limiter.acquire_if(
lambda permit=permit: self._permit_is_current(execution, permit)
)
if not admitted:
await self._abandon_probe_permit(execution, permit)
continue
await self._concurrency_sem.acquire()
slot_acquired = True
if not self._permit_is_current(execution, permit):
self._concurrency_sem.release()
slot_acquired = False
await self._abandon_probe_permit(execution, permit)
continue
claim = execution._claim_attempt(operation_kind)
attempt = ProviderAttempt(self, execution, permit, claim)
trace_event(
stage="provider",
event="provider.attempt.started",
source="provider",
provider=self._provider_name,
request_id=execution.request_id,
execution_id=execution.execution_id,
operation_kind=operation_kind.value,
attempt=claim.ordinal,
max_attempts=execution.max_attempts,
probe=permit.probe,
recovery_generation=permit.generation,
)
return attempt
except BaseException:
if claim is not None:
execution._close_attempt(claim)
if slot_acquired:
self._concurrency_sem.release()
await self._abandon_probe_permit(execution, permit)
raise
async def _wait_for_gate(self, execution: ProviderExecution) -> _GatePermit:
while True:
if (terminal_error := execution._terminal_failure()) is not None:
raise ProviderRecoveryExhausted(terminal_error)
sleep_delay: float | None = None
claimed_generation: int | None = None
async with self._condition:
episode = self._episode
if episode is None:
return _GatePermit(generation=None, probe=False)
now = time.monotonic()
if episode.terminal_until is not None:
if now < episode.terminal_until:
raise ProviderRecoveryExhausted(episode.last_error)
episode = self._start_recovery_episode(
leader=execution,
ready_at=now,
last_error=episode.last_error,
)
if episode.leader is None:
episode.leader = execution
episode.waiters.discard(execution)
if episode.leader is execution:
if episode.probe_active:
await self._condition.wait()
continue
sleep_delay = max(0.0, episode.ready_at - now)
claimed_generation = episode.generation
if sleep_delay == 0:
episode.probe_active = True
return self._probe_permit(execution, episode)
else:
episode.waiters.add(execution)
try:
await self._condition.wait()
except asyncio.CancelledError:
current = self._episode
if (
current is not None
and current.generation == episode.generation
):
current.waiters.discard(execution)
raise
continue
if sleep_delay is None or claimed_generation is None:
continue
try:
if sleep_delay > 0:
logger.warning(
"Provider {} recovery active, waiting {:.1f}s for one probe",
self._provider_name,
sleep_delay,
)
await asyncio.sleep(sleep_delay)
async with self._condition:
episode = self._episode
if (
episode is not None
and episode.generation == claimed_generation
and episode.terminal_until is None
and episode.leader is execution
and not episode.probe_active
):
episode.probe_active = True
return self._probe_permit(execution, episode)
except asyncio.CancelledError:
await self._abandon_waiting_leader(execution, claimed_generation)
raise
def _probe_permit(
self,
execution: ProviderExecution,
episode: _RecoveryEpisode,
) -> _GatePermit:
trace_event(
stage="provider",
event="provider.recovery.probe",
source="provider",
provider=self._provider_name,
request_id=execution.request_id,
generation=episode.generation,
attempt=execution.attempts_started + 1,
max_attempts=execution.max_attempts,
)
return _GatePermit(generation=episode.generation, probe=True)
def _permit_is_current(
self,
execution: ProviderExecution,
permit: _GatePermit,
) -> bool:
episode = self._episode
if not permit.probe:
return episode is None
return (
episode is not None
and episode.generation == permit.generation
and episode.terminal_until is None
and episode.leader is execution
and episode.probe_active
)
async def _attempt_accepted(
self,
execution: ProviderExecution,
permit: _GatePermit,
) -> None:
if not permit.probe:
return
async with self._condition:
episode = self._matching_probe(execution, permit)
if episode is None:
return
self._episode = None
self._condition.notify_all()
trace_event(
stage="provider",
event="provider.recovery.closed",
source="provider",
provider=self._provider_name,
request_id=execution.request_id,
generation=permit.generation,
attempt=execution.attempts_started,
outcome="success",
)
async def _attempt_corrected(
self,
execution: ProviderExecution,
permit: _GatePermit,
) -> None:
if not permit.probe:
return
async with self._condition:
episode = self._matching_probe(execution, permit)
if episode is None:
return
episode.probe_active = False
episode.ready_at = time.monotonic()
self._condition.notify_all()
async def _attempt_rejected(
self,
execution: ProviderExecution,
permit: _GatePermit,
) -> None:
"""Close a probe episode when upstream responds with a final rejection."""
if not permit.probe:
return
async with self._condition:
episode = self._matching_probe(execution, permit)
if episode is None:
return
self._episode = None
self._condition.notify_all()
trace_event(
stage="provider",
event="provider.recovery.closed",
source="provider",
provider=self._provider_name,
request_id=execution.request_id,
generation=permit.generation,
attempt=execution.attempts_started,
outcome="rejected",
)
async def _attempt_abandoned(
self,
execution: ProviderExecution,
permit: _GatePermit,
) -> None:
if not permit.probe:
return
async with self._condition:
episode = self._matching_probe(execution, permit)
if episode is None:
return
episode.leader = None
episode.probe_active = False
episode.ready_at = time.monotonic()
self._condition.notify_all()
async def _attempt_failed(
self,
execution: ProviderExecution,
permit: _GatePermit,
*,
error: Exception,
status: int | None,
) -> None:
can_retry = execution.can_attempt
delay = self._retry_delay(error, execution.attempts_started)
became_leader = False
exhausted_episode = False
async with self._condition:
episode = self._episode
matching_probe = self._matching_probe(execution, permit)
if can_retry:
if episode is None:
episode = self._start_recovery_episode(
leader=execution,
ready_at=time.monotonic() + delay,
last_error=error,
)
became_leader = True
elif matching_probe is not None:
episode.last_error = error
episode.probe_active = False
episode.ready_at = time.monotonic() + delay
became_leader = True
elif episode.terminal_until is not None:
execution._fail_recovery(episode.last_error)
else:
episode.waiters.add(execution)
self._condition.notify_all()
elif episode is None or matching_probe is not None:
terminal_delay = self._retry_delay(
error,
execution.attempts_started,
)
if episode is None:
episode = self._start_recovery_episode(
leader=None,
ready_at=time.monotonic(),
last_error=error,
request_id=execution.request_id,
)
episode.last_error = error
episode.leader = None
episode.probe_active = False
episode.terminal_until = time.monotonic() + terminal_delay
for waiter in episode.waiters:
waiter._fail_recovery(error)
episode.waiters.clear()
exhausted_episode = True
self._condition.notify_all()
label = self._failure_label(status, error)
if became_leader:
logger.warning(
"{}, attempt {}/{} failed; one provider recovery probe in {:.1f}s",
label,
execution.attempts_started,
execution.max_attempts,
delay,
)
trace_event(
stage="provider",
event="provider.retry.scheduled",
source="provider",
provider=self._provider_name,
request_id=execution.request_id,
status_code=status,
exc_type=type(error).__name__,
attempt=execution.attempts_started,
max_attempts=execution.max_attempts,
delay_s=round(delay, 3),
coordinated=True,
)
elif can_retry:
trace_event(
stage="provider",
event="provider.retry.coalesced",
source="provider",
provider=self._provider_name,
request_id=execution.request_id,
status_code=status,
exc_type=type(error).__name__,
attempt=execution.attempts_started,
max_attempts=execution.max_attempts,
)
else:
logger.warning(
"{} retry exhausted (attempts={})",
label,
execution.attempts_started,
)
trace_event(
stage="provider",
event="provider.retry.exhausted",
source="provider",
provider=self._provider_name,
request_id=execution.request_id,
status_code=status,
exc_type=type(error).__name__,
attempts=execution.attempts_started,
episode_exhausted=exhausted_episode,
)
def _start_recovery_episode(
self,
*,
leader: ProviderExecution | None,
ready_at: float,
last_error: Exception,
request_id: str | None = None,
) -> _RecoveryEpisode:
episode = _RecoveryEpisode(
generation=self._next_generation,
leader=leader,
ready_at=ready_at,
last_error=last_error,
)
self._next_generation += 1
self._episode = episode
trace_event(
stage="provider",
event="provider.recovery.opened",
source="provider",
provider=self._provider_name,
request_id=(leader.request_id if leader is not None else request_id),
generation=episode.generation,
)
return episode
def _matching_probe(
self,
execution: ProviderExecution,
permit: _GatePermit,
) -> _RecoveryEpisode | None:
episode = self._episode
if (
not permit.probe
or episode is None
or episode.generation != permit.generation
or episode.leader is not execution
or not episode.probe_active
):
return None
return episode
async def _abandon_probe_permit(
self,
execution: ProviderExecution,
permit: _GatePermit,
) -> None:
if not permit.probe:
return
async with self._condition:
episode = self._matching_probe(execution, permit)
if episode is None:
return
episode.leader = None
episode.probe_active = False
episode.ready_at = time.monotonic()
self._condition.notify_all()
async def _abandon_waiting_leader(
self,
execution: ProviderExecution,
generation: int,
) -> None:
async with self._condition:
episode = self._episode
if (
episode is None
or episode.generation != generation
or episode.leader is not execution
or episode.probe_active
):
return
episode.leader = None
self._condition.notify_all()
def _release_concurrency(self) -> None:
self._concurrency_sem.release()
def _retry_delay(self, error: Exception, attempt: int) -> float:
exponent = max(0, attempt - 1)
backoff = min(self._base_delay * (2**exponent), self._max_delay)
backoff += random.uniform(0, self._jitter)
retry_after = _retry_after_seconds(error)
return max(backoff, retry_after or 0.0)
@staticmethod
def _failure_label(status: int | None, error: Exception) -> str:
if status == 429:
return "Rate limited (429)"
if status is not None:
return f"Upstream server error ({status})"
return f"Provider transient error ({type(error).__name__})"
def _retry_after_seconds(error: Exception) -> float | None:
response = getattr(error, "response", None)
headers = getattr(response, "headers", None)
if headers is None:
return None
value = headers.get("retry-after")
if not isinstance(value, str) or not value.strip():
return None
stripped = value.strip()
try:
seconds = float(stripped)
except ValueError:
try:
retry_at = parsedate_to_datetime(stripped)
except TypeError, ValueError, OverflowError:
return None
if retry_at.tzinfo is None:
retry_at = retry_at.replace(tzinfo=UTC)
seconds = (retry_at - datetime.now(UTC)).total_seconds()
if not math.isfinite(seconds):
return None
return max(0.0, seconds)
def _exception_status(error: BaseException) -> int | None:
status = getattr(error, "status_code", None)
if isinstance(status, int):
return status
response = getattr(error, "response", None)
response_status = getattr(response, "status_code", None)
return response_status if isinstance(response_status, int) else None