`_should_retry_exception` correctly refuses to retry a cancellation, but the inner request frame wraps it in `APIConnectionError` first, so the guard never sees it
Đánh giá
- Độ khó
- 4/5
- Thời gian dự kiến
- 3-5 ngày
- Mức phù hợp với người mới
- 48/100
- Loại issue
- Lỗi
- Độ rõ ràng
- Đặc tả rõ ràng
- Mức độ hoạt động
- Sôi nổi
- Công nghệ
- python
- Lĩnh vực
- backend-api-design
Hướng nghiên cứu
Start in src/anthropic/_base_client.py at the sync and async inner exception handlers and their outer _should_retry_exception calls; read the guard's __cause__ chain logic and its tests. Reproduce with a cancellation derived from Exception during a blocked request while retries are enabled, then check that it reaches the caller without retrying and that transient failures still retry. The issue does not name a test file, so locate the relevant retry tests in the repository.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
Summary
The SDK already knows a cancellation-style exception must not be retried — _should_retry_exception returns False for one. But the inner request frame catches every non-AnthropicError Exception and re-raises it as APIConnectionError(...) from err before that guard runs. The guard then walks __cause__, finds the APIConnectionError it was just wrapped in, and returns True.
Net effect: a cancellation raised into the client (e.g. a Celery soft_time_limit, or anything delivered by a signal handler) is swallowed and the HTTP request is re-issued. Nothing propagates to the caller, so no except SoftTimeLimitExceeded handler can fire.
This is a tighter variant of openai/openai-python#2737 (same Stainless-generated shape): there the client had no such guard; here the SDK has the guard and defeats it itself.
Where — verified against 1.13.0
All line numbers below are from anthropic==1.13.0 (src/anthropic/_base_client.py), read out of the published wheel. The shape is unchanged since 0.120.0; only offsets have moved across releases.
# L1325-1331 — inner frame (sync). Wraps ANY non-AnthropicError Exception, including cancellations.
except Exception as err:
if isinstance(err, AnthropicError):
# SDK-originated errors already carry their own type; don't wrap.
raise
log.debug("Encountered Exception", exc_info=True)
raise APIConnectionError(request=request) from err
# L1188-1191 — outer frame (sync). Consults the guard, but only AFTER the wrap above.
except Exception as err:
should_retry, failed_response = self._should_retry_exception(err)
if remaining_retries <= 0 or not should_retry:
raise
# L910-921 — the guard (`_should_retry_exception`, def at L898), walking __cause__ outermost-first
seen: set[int] = set()
current: BaseException | None = err
while current is not None and id(current) not in seen:
seen.add(id(current))
if isinstance(current, RetryableError):
return True, None
if isinstance(current, APIStatusError):
return self._should_retry(current.response), current.response
if isinstance(current, APIConnectionError):
return True, None
current = current.__cause__
return False, None
The async path is the same shape: inner wrap at L2056-2062, outer guard call at L1914.
The chain-walk is deliberate and documented — the docstring (L904-908) says "The check walks each error's __cause__ chain, so wrapping a retryable failure via raise ... from err preserves retries." That is correct and desirable for genuine transient failures. The defect is that the inner frame wraps non-retryable cancellations into a retryable type, so the faithful chain-walk then makes them retryable too. The guard is reached with the wrapper as the outermost exception, so it returns True on the first iteration and never inspects the real cause.
Scope: which cancellations are affected
Both frames catch Exception, not BaseException. So:
| exception | base | caught + wrapped? |
|---|---|---|
billiard.exceptions.SoftTimeLimitExceeded (Celery soft_time_limit) |
Exception |
yes — affected |
billiard.exceptions.TimeLimitExceeded |
Exception |
yes — affected |
billiard.exceptions.Terminated |
Exception |
yes — affected |
asyncio.CancelledError |
BaseException |
no — correctly propagates |
KeyboardInterrupt / SystemExit |
BaseException |
no — correctly propagates |
So a fix here is narrower than openai/openai-python#2739's: only the Exception-derived cancellation set needs handling.
Measured behaviour
Real prefork Celery worker, soft_time_limit=6, a stand-in HTTP server that sleeps 25s, so the deadline lands while blocked inside the SDK's read. These two arms were measured on 0.121.0; the code path quoted above is unchanged in 1.13.0, but I have not re-run the timing on 1.13.0.
max_retries |
outcome | HTTP requests issued | elapsed vs 6s deadline |
|---|---|---|---|
2 (SDK default) |
returned normally — no deadline reached the caller | 2 | 54.0s |
0 |
APIConnectionError with __cause__ = SoftTimeLimitExceeded |
1 | 5.8s |
With retries available the deadline is lost entirely; with retries exhausted it survives as __cause__ and a caller can recover it.
Minimal reproduction
# celery -A m worker --concurrency=1 (prefork)
from celery import Celery
from anthropic import Anthropic # module scope: see gotcha below
app = Celery("m", broker="redis://localhost:6379/14", backend="redis://localhost:6379/14")
@app.task(soft_time_limit=6, time_limit=120)
def probe(max_retries):
c = Anthropic(api_key="x", base_url="http://127.0.0.1:8731",
max_retries=max_retries, timeout=300.0)
c.messages.create(model="claude-sonnet-4-6", max_tokens=16,
messages=[{"role": "user", "content": "hi"}])
return "returned normally — deadline never surfaced"
Point base_url at any server that sleeps longer than soft_time_limit.
Repro gotcha that produces a false negative. Import
anthropicat module scope and assert the server's request count. If the import happens inside the task, a cold import can exceed a shortsoft_time_limit, the SDK never issues a request, and both arms report "the deadline reached the caller" — which reads exactly like the bug not existing. Only the request count distinguishes refuted from never ran.
Suggested fix
Check non-retryability before the wrap, or make the guard consider the innermost cause rather than stopping at the wrapper. openai/openai-python#2739 took the first shape: a _should_not_retry() helper checked before retrying, detecting Celery by module name so the SDK needs no Celery dependency.
Per the Python docs, "an exception raised in a signal handler will be put anywhere on the Python VM stack" — so any signal-delivered deadline is structurally exposed to broad except handling in library code that never expected it. That makes this a general cancellation-safety issue rather than a Celery-specific one.
Workaround for users
Use client.with_options(max_retries=0) for calls made from a cancellable context. It converts every case into the exhausted branch, where the deadline survives as __cause__. Cost: no SDK retry for genuine transient errors on those calls.
We chose with_options — a public constructor-level argument — deliberately over anything keyed on SDK internals, because at the time our dependency floor was unpinned and an internals-keyed patch could have been silently un-fixed by an ordinary dependency re-resolve. That is the downstream cost of the guard being defeated one frame below itself: the only safe workaround is to give up retries entirely for the affected call sites.
- Ngôn ngữ chính
- Python
- Star
- 4.1k
- Fork
- 915
- Chỉ số merge pull request
- Không có pull request nào được merge trong 30 ngày
Chuẩn bị môi trường
Khởi chạy dev container của dự án ngay trên trình duyệt, bằng tài khoản GitHub của bạn.
- Không có Dockerfile hay tệp Docker Compose
- Không có mẫu pull request
- Đọc hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của anthropics/anthropic-sdk-python
-
beta_tool validation errors reach the model as "Invalid arguments for function X" with no detailCó thể đã có người làm @mangeshraut712 đã nhận 32 ngày trước. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
anthropics/anthropic-sdk-python#2033 · 3 bình luận ·
-
`AnthropicBedrock` 2.x sends `anthropic_version: 2026-10-21`, which Bedrock rejects for Claude Sonnet 4.5, Opus 4.5 and Opus 4.6Có thể đã có người làm @charan-rathore đã nhận 36 ngày trước. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 70/100
anthropics/anthropic-sdk-python#2031 · 1 bình luận ·
-
Three symlink tests in test_agent_toolset.py are missing the needs_symlinks markerCó thể đã có người làm @okxint đã nhận 82 ngày trước. Đang mở
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 92/100
anthropics/anthropic-sdk-python#1915 · 3 bình luận ·
-
Messages.parse (and AsyncMessages.parse) don't take cache_control?Có thể đã có người làm @AlphaFDE đã nhận 86 ngày trước. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
anthropics/anthropic-sdk-python#1907 · 2 bình luận ·
-
Windows: os.fchmod in credential write-back bricks the OAuth refresh tokenCó thể đã có người làm @OllieinCanada đã nhận 99 ngày trước. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
anthropics/anthropic-sdk-python#1868 · 1 bình luận ·
Tất cả issue của anthropics/anthropic-sdk-python
Issue tương tự
-
bug harness
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
mruangutai/harness#2687 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 68/100
modal-labs/modal-client#4158 ·
-
good first issue
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 72/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 Nửa ngày Mức phù hợp với người mới 72/100
The-Swarm-Corporation/swarms-rs#168 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[BUG] SMTP listener now binds to EMAIL_PORT instead of 2525 since the gunicorn switch 5.0.3-ls373Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
linuxserver/docker-healthchecks#137 · 1 bình luận ·