Python errors and retries
Every exception class the Python SDK raises, the attributes of an error, how failed calls are retried, how idempotency keys work, and what per-call options do.
Every error the package raises on purpose is a SailforkError. Server errors are typed by their code, so code can branch on a class instead of a string. A failed call may be retried first, by rules set out below.
Catching errors
Catch the narrowest class you can act on, then APIStatusError, then SailforkError.
from sailfork import (
APIConnectionError,
ConflictError,
NotFoundError,
RateLimitError,
Sailfork,
SailforkError,
)
sf = Sailfork()
try:
sf.repo("acme/api").pull(9999).get()
except NotFoundError as err:
print("no such pull request", err.request_id)
except RateLimitError as err:
print(f"slow down, retry in {err.retry_after}s")
except ConflictError as err:
print(err.code, err.hint)
except APIConnectionError as err:
print("no answer:", err.message)
except SailforkError as err:
print(err) Printing an APIStatusError gives one line: the code and message, then param, hint, the request id and the docs link when there are any.
not_found: not found | request: req_b23fa0e526ae4d63a30821b1f20042ac | docs: https://sailfork.com/docs/api#error-codes Without a code the line starts HTTP <status>: <message>.
Attributes of an error
A status error has these attributes:
| Attribute | Holds |
|---|---|
message | The server's message. |
status | The HTTP status. |
code | The stable code to branch on, or None from an older server. |
param | What the error is about, such as the missing scope. |
hint | What to do next. |
doc_url | A link to the docs. |
request_id | Quote it when reporting a failure. |
retry_after | Seconds from Retry-After, or None. |
body | The decoded response body, or None when it was not JSON. |
APIConnectionError and APITimeoutError have message, and the underlying httpx error as __cause__.
from sailfork import InsufficientScopeError
try:
sf.repo("acme/api").pull(128).merge()
except InsufficientScopeError as err:
print(f"the token needs {err.param}") Exception classes
The class comes from the error's code first and its status second. The codes are in Errors.
| Class | Parent | Raised for |
|---|---|---|
SailforkError | Exception | Base of all of them. Also raised directly when an answer is not JSON. |
APIConnectionError | SailforkError | No answer: DNS, TLS, reset, refused. |
APITimeoutError | APIConnectionError | No answer inside the timeout. |
APIStatusError | SailforkError | Base of every error the server sent. Raised as itself for a status no subclass covers. |
InvalidRequestError | APIStatusError | 422 and invalid_request, or a 400. |
AuthenticationError | APIStatusError | 401: unauthenticated, invalid_token. |
PermissionDeniedError | APIStatusError | 403 without a more specific code. |
InsufficientScopeError | PermissionDeniedError | insufficient_scope; param names the scope. |
AgentPolicyError | PermissionDeniedError | agent_policy: the organization's agent policy refuses it. |
HeldDeclinedError | PermissionDeniedError | held_declined: a person declined the held write. |
UnexpectedHeldError | APIStatusError | 202, held: a call not declared as holdable came back held for a person. body has the request's url. |
BypassNeedsPersonError | PermissionDeniedError | bypass_needs_person: only a person may do this. |
AgentChangeCapError | APIStatusError | 402, agent_change_cap: the monthly agent change limit is used up. Not retried. |
NotFoundError | APIStatusError | 404. Also a private repository you cannot read. |
ConflictError | APIStatusError | 409, conflict. |
FileChangedError | ConflictError | file_changed: read the file again and retry. |
IdempotencyInProgressError | ConflictError | idempotency_in_progress: the first request under this key still runs. |
PreconditionFailedError | APIStatusError | 412, precondition_failed. |
PayloadError | APIStatusError | 413 or 415. |
RateLimitError | APIStatusError | 429, rate_limited. |
ServerError | APIStatusError | Any 5xx without a more specific code. |
LegalBlockError | APIStatusError | 451: disabled, region_blocked. |
Because of the code-first rule, a 403 with agent_policy is an AgentPolicyError, which is also a PermissionDeniedError. A 202 on a method that cannot be held is an UnexpectedHeldError, a subclass of APIStatusError with code == "held", as in Held writes and waits. sailfork.errors.error_for(status, body) builds the right class if you handle raw responses.
Mistakes in your own call are not SailforkErrors:
| Raised | When |
|---|---|
TypeError | An unknown or missing argument, before any request. |
ValueError | A repository name that is not owner/name, or a host that is not an address. |
pydantic.ValidationError | An answer that does not match the model. |
KeyError | sailfork.tools.run given a tool name it does not know. |
Retries and idempotency
The catalog gives each operation a retry class, and the client follows it:
- Reads and most writes are retried. A handful of writes are never retried, such as
caissons.bash,labels.create,repos.createandtokens.create, because repeating them could do the work twice. - A call is retried on a network error, a timeout, and the statuses 408, 429, 500, 502, 503 and 504. Nothing else is, 402 included.
max_retries(default2) is the number of retries, so a call is tried up to three times.max_retries=0turns retrying off.- The wait before a retry is
Retry-Afterwhen the server sent one, as seconds or a date and never more than 60 seconds. Without it the wait is 0.5, 1, 2 seconds and so on up to 8, each scaled by a random factor between one half and one. idempotency_in_progresson a retryable write means the first try is still running. The client waits whatRetry-Aftersays, 1 second if it says nothing, and sends the same request again, up to 30 times. These waits do not use upmax_retries.
Every call that changes something sends one Idempotency-Key, a fresh random value made when the call starts and reused on each retry of it. A retried write therefore runs once. Two separate calls always have different keys.
from sailfork import Sailfork
patient = Sailfork(max_retries=6) # a flaky network
strict = Sailfork(max_retries=0) # fail at the first error Per-call options
Every generated method, sync, async and on handles, takes a keyword-only options of type RequestOptions, exported from sailfork. It is a frozen dataclass whose fields override the client's settings for that one call:
| Field | Overrides |
|---|---|
timeout | Seconds one request may take. It also replaces the longer window of a call that waits on purpose. |
max_retries | How many times the call is retried. 0 turns retrying off for it. |
idempotency_key | The Idempotency-Key of a write, in place of a random one. |
headers | Extra headers for this request. |
Fields left as None keep the client's value.
from sailfork import RequestOptions, Sailfork
with Sailfork() as sf:
pr = sf.repo("acme/api").pull(128)
pr.get(options=RequestOptions(timeout=5.0, max_retries=0))
pr.merge(
method="squash",
options=RequestOptions(idempotency_key="merge-acme-api-128", headers={"x-trace": "nightly"}),
) A fixed idempotency_key makes a write safe to send again after a crash: the server runs it once per key and answers a repeat with the first result. Derive the key from the job, such as the pull request number, and use another key for each distinct write. The agent workflow shows the pattern.
Next to the TypeScript version of this page: TypeScript errors and retries.