karenina.utils.retry_policy¶
retry_policy
¶
Category-aware retry policy and executor for LLM operations.
This module provides: - CategoryRetryConfig: per-category retry parameters (attempts, backoff). - RetryPolicy: groups CategoryRetryConfig for each ErrorCategory. - ErrorPatternConfig: declarative pattern registration for serialization. - RetryExecutor: sync/async executor that retries with per-category budgets. - track_retries: contextvar-based context manager that lets callers record retries (with the budgets that were available) over the course of a pipeline execution.
Classes¶
CategoryRetryConfig
¶
Bases: BaseModel
Retry parameters for a single error category.
Attributes:
| Name | Type | Description |
|---|---|---|
max_attempts |
int
|
Number of retries (not total calls). 0 means no retry. |
backoff_min |
float
|
Minimum backoff delay in seconds. |
backoff_max |
float
|
Maximum backoff delay in seconds. |
backoff_multiplier |
float
|
Multiplier applied to delay after each retry. |
Source code in src/karenina/utils/retry_policy.py
ErrorPatternConfig
¶
Bases: BaseModel
Declarative error pattern for serialization in configs.
Attributes:
| Name | Type | Description |
|---|---|---|
pattern |
str
|
The string to match (type name or message substring). |
category |
Literal['connection', 'timeout', 'rate_limit', 'server_error', 'permanent']
|
Which ErrorCategory to assign. |
match_type |
Literal['type_name', 'message_substring']
|
How to match: "type_name" or "message_substring". |
Source code in src/karenina/utils/retry_policy.py
RetryExecutor
¶
Category-aware retry executor with per-category budgets.
Each call to execute() or aexecute() creates fresh budget counters. Errors are classified via the ErrorRegistry, and each category is retried up to its configured max_attempts. Permanent errors are never retried.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
RetryPolicy
|
The RetryPolicy defining per-category budgets and backoff. |
required |
|
ErrorRegistry
|
The ErrorRegistry used to classify exceptions. |
required |
Example
executor = RetryExecutor(RetryPolicy(), ErrorRegistry()) result = executor.execute(my_function, arg1, arg2)
Source code in src/karenina/utils/retry_policy.py
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 | |
Functions¶
aexecute
async
¶
Execute fn with category-aware retry (async).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
¶ |
Any
|
Async callable to invoke. |
required |
*args
¶ |
Any
|
Positional arguments forwarded to fn. |
()
|
**kwargs
¶ |
Any
|
Keyword arguments forwarded to fn. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
The return value of fn on success. |
Source code in src/karenina/utils/retry_policy.py
aexecute_with_timeout
async
¶
Execute fn with category-aware retry and timeout escalation (async).
Like aexecute, but the timeout keyword argument forwarded to
fn is escalated on each TIMEOUT-category retry according to
self._policy.timeout_escalation. Other retry categories reuse
the original timeout value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
¶ |
Any
|
Async callable to invoke. Must accept |
required |
*args
¶ |
Any
|
Positional arguments forwarded to fn. |
()
|
timeout
¶ |
float | None
|
Initial wall-clock timeout passed on the first attempt and used as the base for escalation. None disables timeout. |
required |
**kwargs
¶ |
Any
|
Additional keyword arguments forwarded to fn. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
The return value of fn on success. |
Source code in src/karenina/utils/retry_policy.py
execute
¶
Execute fn with category-aware retry (sync).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
¶ |
Any
|
Callable to invoke. |
required |
*args
¶ |
Any
|
Positional arguments forwarded to fn. |
()
|
**kwargs
¶ |
Any
|
Keyword arguments forwarded to fn. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
The return value of fn on success. |
Source code in src/karenina/utils/retry_policy.py
execute_with_timeout
¶
Execute fn with category-aware retry and timeout escalation (sync).
Like execute, but the timeout keyword argument forwarded to
fn is escalated on each TIMEOUT-category retry according to
self._policy.timeout_escalation. Other retry categories reuse
the original timeout value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
¶ |
Any
|
Sync callable to invoke. Must accept |
required |
*args
¶ |
Any
|
Positional arguments forwarded to fn. |
()
|
timeout
¶ |
float | None
|
Initial wall-clock timeout passed on the first attempt and used as the base for escalation. None disables timeout. |
required |
**kwargs
¶ |
Any
|
Additional keyword arguments forwarded to fn. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
The return value of fn on success. |
Source code in src/karenina/utils/retry_policy.py
RetryPolicy
¶
Bases: BaseModel
Grouped retry configuration for all error categories.
Each field maps to an ErrorCategory and defines the retry budget and backoff parameters for that category.
Attributes:
| Name | Type | Description |
|---|---|---|
connection |
CategoryRetryConfig
|
Config for connection errors (DNS, network failures). |
timeout |
CategoryRetryConfig
|
Config for timeout errors. |
rate_limit |
CategoryRetryConfig
|
Config for rate limiting (429, overloaded). |
server_error |
CategoryRetryConfig
|
Config for server errors (5xx). |
Source code in src/karenina/utils/retry_policy.py
Functions¶
derive_sdk_max_retries
¶
Return the maximum retry count across all categories.
This value can be passed to SDK clients that accept a single max_retries parameter, ensuring no category is starved.
Returns:
| Type | Description |
|---|---|
int
|
The highest max_attempts among all categories. |
Source code in src/karenina/utils/retry_policy.py
TimeoutEscalationConfig
¶
Bases: BaseModel
Progressive timeout strategy applied to TIMEOUT-category retries.
On each retry triggered by a TIMEOUT error, the per-attempt request timeout is increased according to the chosen strategy. Other retry categories (connection, rate_limit, server_error) keep using the base request_timeout unchanged.
Strategies
additive: timeout(n) = min(base + increment * n, max_timeout) multiplicative: timeout(n) = min(base * multiplier ** n, max_timeout) linear: timeout(n) = base + (max_timeout - base) * n / max_attempts where max_attempts is the configured timeout retry budget. n=0 returns the base; n=max_attempts returns max_timeout.
Attributes:
| Name | Type | Description |
|---|---|---|
strategy |
Literal['additive', 'multiplicative', 'linear']
|
Which growth function to use. |
increment |
float
|
Seconds added per retry. Used by additive only. |
multiplier |
float
|
Factor applied per retry. Used by multiplicative only. |
max_timeout |
float | None
|
Optional cap (additive/multiplicative) or required endpoint (linear). |
Source code in src/karenina/utils/retry_policy.py
Functions¶
compute_escalated_timeout
¶
compute_escalated_timeout(
base_timeout: float | None,
timeout_attempt: int,
config: TimeoutEscalationConfig | None,
max_attempts: int,
) -> float | None
Compute the request timeout for the next attempt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
float | None
|
The original timeout configured for the call. If None, escalation is a no-op and None is returned. |
required |
|
int
|
How many TIMEOUT retries have been used so far, counting the upcoming attempt. 0 means the original call (returns base unchanged). k in 1..max_attempts means the k-th retry. |
required |
|
TimeoutEscalationConfig | None
|
The escalation configuration. None disables escalation and returns base_timeout unchanged. |
required |
|
int
|
The TIMEOUT category retry budget. Used by the "linear" strategy to interpolate between base and max. |
required |
Returns:
| Type | Description |
|---|---|
float | None
|
The escalated timeout in seconds, or base_timeout if escalation |
float | None
|
is disabled. |
Source code in src/karenina/utils/retry_policy.py
track_retries
¶
track_retries(
policy: RetryPolicy | None = None,
) -> Iterator[RetryTracker]
Bind a fresh retry tracker to the current execution context.
The tracker is pre-populated with the per-category budgets from
policy (defaulting to RetryPolicy() when None). Within the
with block, every retry decision made by RetryExecutor
increments used for the matching category. The tracker is yielded so
the caller can read counts and budgets after exiting the block.
Propagation: recording works wherever the binding context travels.
This includes async code on the same loop, BlockingPortal.call
dispatch (anyio copies the caller's contextvars into the portal task),
and the adapters' sync wrappers' ThreadPoolExecutor fallbacks (which
re-enter a copy of the caller's context in the fresh thread). Code
that spawns threads without copying the caller's context will not
record into this tracker. Increments are thread-safe.
Example
with track_retries(RetryPolicy()) as tracker: ... adapter.stream_invoke(messages) tracker["timeout"] {'used': 2, 'budget': 3}