Skip to content

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:

AttributeHolds
messageThe server's message.
statusThe HTTP status.
codeThe stable code to branch on, or None from an older server.
paramWhat the error is about, such as the missing scope.
hintWhat to do next.
doc_urlA link to the docs.
request_idQuote it when reporting a failure.
retry_afterSeconds from Retry-After, or None.
bodyThe 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.

ClassParentRaised for
SailforkErrorExceptionBase of all of them. Also raised directly when an answer is not JSON.
APIConnectionErrorSailforkErrorNo answer: DNS, TLS, reset, refused.
APITimeoutErrorAPIConnectionErrorNo answer inside the timeout.
APIStatusErrorSailforkErrorBase of every error the server sent. Raised as itself for a status no subclass covers.
InvalidRequestErrorAPIStatusError422 and invalid_request, or a 400.
AuthenticationErrorAPIStatusError401: unauthenticated, invalid_token.
PermissionDeniedErrorAPIStatusError403 without a more specific code.
InsufficientScopeErrorPermissionDeniedErrorinsufficient_scope; param names the scope.
AgentPolicyErrorPermissionDeniedErroragent_policy: the organization's agent policy refuses it.
HeldDeclinedErrorPermissionDeniedErrorheld_declined: a person declined the held write.
UnexpectedHeldErrorAPIStatusError202, held: a call not declared as holdable came back held for a person. body has the request's url.
BypassNeedsPersonErrorPermissionDeniedErrorbypass_needs_person: only a person may do this.
AgentChangeCapErrorAPIStatusError402, agent_change_cap: the monthly agent change limit is used up. Not retried.
NotFoundErrorAPIStatusError404. Also a private repository you cannot read.
ConflictErrorAPIStatusError409, conflict.
FileChangedErrorConflictErrorfile_changed: read the file again and retry.
IdempotencyInProgressErrorConflictErroridempotency_in_progress: the first request under this key still runs.
PreconditionFailedErrorAPIStatusError412, precondition_failed.
PayloadErrorAPIStatusError413 or 415.
RateLimitErrorAPIStatusError429, rate_limited.
ServerErrorAPIStatusErrorAny 5xx without a more specific code.
LegalBlockErrorAPIStatusError451: 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:

RaisedWhen
TypeErrorAn unknown or missing argument, before any request.
ValueErrorA repository name that is not owner/name, or a host that is not an address.
pydantic.ValidationErrorAn answer that does not match the model.
KeyErrorsailfork.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.create and tokens.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 (default 2) is the number of retries, so a call is tried up to three times. max_retries=0 turns retrying off.
  • The wait before a retry is Retry-After when 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_progress on a retryable write means the first try is still running. The client waits what Retry-After says, 1 second if it says nothing, and sends the same request again, up to 30 times. These waits do not use up max_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:

FieldOverrides
timeoutSeconds one request may take. It also replaces the longer window of a call that waits on purpose.
max_retriesHow many times the call is retried. 0 turns retrying off for it.
idempotency_keyThe Idempotency-Key of a write, in place of a random one.
headersExtra 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.

Loading Sailfork