Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 50 additions & 14 deletions sdk/rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,23 +266,52 @@ when recall credit was not disclosed. An omitted risk label is empty in
`SearchHit.governed` and `SearchResponse.term_leg`; `retrieval_risk` describes the
other hits.

The typed error methods and the retry behavior below apply to the SDK installed
from this checkout. The published `0.1.1` crate exposes the raw `ApiError`
fields, including `category` and `retryable`.

```rust
use clickhouse_loom::Error;

match bot.get("deploy_window").await {
Err(Error::Api(error)) => {
eprintln!("{} {} {:?} {:?}", error.status, error.code, error.category, error.retryable);
eprintln!("{} {} {:?} {}", error.status, error.code, error.kind(), error.category());
}
Err(error) => eprintln!("{error}"),
Ok(memory) => println!("found={}", memory.found),
}
```

API errors preserve the server's code, message, optional category and retryable
flag, retry hints, request ID and raw detail. Unknown error codes and categories
remain strings. An error response without a JSON body still carries the HTTP
status. `Error::Transport` reports HTTP transport failures; `Error::Protocol`
reports an invalid successful response.
API errors preserve the server's code, message, optional category and
retryable flag, retry hints, request ID and raw detail. Unknown error codes and
categories remain strings in those fields. An error response without a JSON
body still carries the HTTP status. `Error::Transport` reports HTTP transport
failures; `Error::Protocol` reports an invalid successful response.

`ApiError::kind` is the typed class of an API error. A known code picks it;
otherwise the HTTP status does: 400 and 422 are `Validation`, 401 and 403
`Auth`, 404 `NotFound`, and 409 and 412 `PreconditionFailed`. HTTP 429 is
always `RateLimited`. HTTP 5xx is `BackendUnavailable` unless the code is
`IDEMPOTENT_IN_PROGRESS`. If neither the code nor the status supplies a kind,
`kind()` returns `Other`; inspect `code` for more detail.

`Error::category` and `Error::retryable` give the class in effect: the category
and flag the server declared, else the SDK's own class. By status alone, 401
and 403 are `Auth`; 408 and 429 are `Capacity` and retryable; 502, 503 and 504
are `Dependency` and retryable; any other 5xx is `Internal` and any other
status `Input`, neither retryable. A code the SDK never retries, such as
`ANALYSIS_UNAVAILABLE` or `PUBLICATION_PENDING`, keeps its own category and is
never retryable. A 5xx on an operation that is not declared idempotent is not
retryable when its body names no flag, since the call may have written;
`AUTH_UNAVAILABLE` shows that nothing ran. A transport failure is
`Dependency`: retryable when the server was never reached, otherwise not, since
the call may have run. An invalid response is `Internal`.

A `PreconditionFailed` can carry the live row's hash in `current_sha256()`.
Use it to check which revision the server rejected the request against. For a definition's approval,
show the current text again and never resend the hash unseen. A `WrongCell`
answer names the `org` and the `cell` to call instead; `cell` is empty when the
server does not know it.

## Per-call options and metadata

Expand Down Expand Up @@ -338,13 +367,18 @@ metadata.

## Retries and logging

Operation policies come from the full server registry. Retries after dispatch
require declared idempotence, including HTTP status retries, incomplete responses
and 429 pacing. `RetryTimeouts::Always` does not enable nonidempotent operations.
Operation policies come from the full server registry. A 429 is paced on
every operation: the server answers it before running anything. Other retries
after dispatch require declared idempotence, for HTTP status retries and
incomplete responses, unless the answer shows nothing ran. HTTP 408 and
`AUTH_UNAVAILABLE` are retried on any operation. `RetryTimeouts::Always` does
not enable nonidempotent operations.

Calls do not follow redirects. Retry and pacing defaults are:

- Up to 3 attempts on connection failures, HTTP 408 and HTTP 500–599.
For a nonidempotent operation, only HTTP 408 and `AUTH_UNAVAILABLE`
qualify for status retries under this budget.
Configuration errors and the SDK's excluded error codes stop retries;
`retryable=false` alone does not stop a status retry.
- Exponential backoff starts at 100 ms, doubles to a 5 second ceiling, and uses
Expand All @@ -354,9 +388,10 @@ Calls do not follow redirects. Retry and pacing defaults are:
- Declared idempotent writes generate one UUID idempotency key per call and reuse it
across retries and pacing. Timeouts and incomplete responses retry these
writes by default. `get` and `search` do not retry those failures by default.
- Pacing is enabled separately from retries. A 429 waits at most 5 seconds per
round, with a 15 second total sleep budget per call. Missing, invalid or
over-cap hints use 1 second; a zero hint returns the error immediately.
- Pacing is enabled separately from retries. On a 429, the client waits for the
server's hint if it fits the remaining sleep budget (15 seconds per call by
default). Missing or invalid hints use 1 second. A zero hint or a wait
beyond the remaining budget returns the 429 without resending.
Each pacing round starts a fresh retry budget. Recorded `X-RateLimit-*`
headers can also delay a subsequent call to the same operation.

Expand Down Expand Up @@ -438,8 +473,9 @@ omitted target fields to the client identity.
`memory.recall` and `memory.brief` default only their required agent; optional
filters use server defaults. `code.grep` omits `include_body` unless supplied,
so the server chooses its default from `mode`. Unknown operations receive
bound org and namespace only and retry connection failures before dispatch.
They do not retry HTTP errors, timeouts, incomplete responses or 429 responses.
bound org and namespace only. They retry connection failures before dispatch
and an answer that shows nothing ran (HTTP 408, `AUTH_UNAVAILABLE`); a 429 is
paced. They do not retry other HTTP errors, timeouts or incomplete responses.
The server validates fields and authorizes every operation.

## Routes outside the op registry
Expand Down
35 changes: 22 additions & 13 deletions sdk/rust/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,8 @@ impl Client {
}
let mut error = ApiError::from_response(status.as_u16(), &headers, &bytes);
error.request_id.get_or_insert_with(|| request_id.clone());
if status.as_u16() == 429 && self.pacing && idempotent {
// The server answers a 429 before running any operation.
if status.as_u16() == 429 && self.pacing {
let delay = pacing_delay(
error.retry_after_s,
self.ratelimit_max_wait.saturating_sub(paced),
Expand All @@ -360,7 +361,9 @@ impl Client {
continue;
}
}
let allowed = idempotent
// A status retry runs the operation again. Only a declared
// idempotent one is safe, unless the answer proves nothing ran.
let allowed = (idempotent || error.handler_never_ran())
&& status.as_u16() != 429
&& retry.statuses.contains(&status.as_u16())
&& !error.forbids_retry();
Expand All @@ -380,6 +383,10 @@ impl Client {
.is_some_and(|budget| delay > budget.saturating_sub(slept))
{
log::error!(target: "clickhouse_loom", "{op} failed status={status} elapsed_ms={} attempts={sent} rid={request_id}", started.elapsed().as_millis());
let mut error = error;
if let Error::Api(api) = &mut error {
api.mark_maybe_applied(idempotent);
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
return Err(CallFailure {
error,
metadata: Some(Box::new(metadata)),
Expand Down Expand Up @@ -576,13 +583,12 @@ fn valid_operation(op: &str) -> bool {
}

pub(crate) fn pacing_delay(hint: Option<f64>, budget: Duration) -> Duration {
let hint = hint
.filter(|s| s.is_finite() && *s <= 60.0)
.unwrap_or(1.0)
.max(0.0);
Duration::from_secs_f64(hint)
.min(Duration::from_secs(5))
.min(budget)
let seconds = hint.filter(|s| s.is_finite()).unwrap_or(1.0).max(0.0);
// A shorter wait would resend before the server asked us to.
Duration::try_from_secs_f64(seconds)
.ok()
.filter(|delay| *delay <= budget)
.unwrap_or_default()
}

fn env_value(name: &str) -> Option<String> {
Expand Down Expand Up @@ -655,16 +661,19 @@ mod tests {
}

#[test]
fn pacing_caps_hints_and_budget_and_does_not_spin_on_zero() {
fn pacing_waits_for_the_hint_only_when_it_fits() {
for (hint, budget, expected) in [
(None, 15, 1),
(Some(61.0), 15, 1),
(Some(60.0), 15, 5),
(Some(30.0), 2, 2),
(None, 0, 0),
(Some(61.0), 15, 0),
(Some(60.0), 60, 60),
(Some(8.0), 15, 8),
(Some(30.0), 2, 0),
(Some(0.0), 15, 0),
(Some(1.0), 0, 0),
(Some(-1.0), 15, 0),
(Some(f64::NAN), 15, 1),
(Some(f64::MAX), 15, 0),
] {
assert_eq!(
pacing_delay(hint, Duration::from_secs(budget)),
Expand Down
Loading
Loading