0057. Rust Anthropic client and the `ai` crate's dependencies
Source:
docs/decisions/0057-rust-anthropic-client-and-crates.md. Generated at build time; edit the source file.
Date: 2026-11-21 Status: Accepted (crate table, R3 Task 1; client design, R3 Task 11). Renumbered by R3 Task 26 (it was the R3 placeholder record). Builds on 0030 and 0031. Amends ADR 0011. Amended by ADR 0062.
Context
Section titled “Context”R3 ports the TS AI coaching layer (TS M3, packages/ai) to one Rust crate, ai. It runs in parallel lanes, so as in R1 and R2 one bootstrap task declares every dependency, module and shared type, and commits Cargo.lock. Later R3 tasks never edit a Cargo.toml dependency list or the lockfile.
Decision
Section titled “Decision”The Anthropic client is our own reqwest client (Messages, streaming SSE and Batches). Superseded by ADR 0062: interactive calls go through the Agent SDK sidecar, and only batches use our own reqwest client. No Anthropic SDK crate is added. The client design is recorded below (Task 11).
New crates
Section titled “New crates”Each was checked on crates.io on 2026-11-21: newest stable release, published at least 7 days earlier, licence on the allowlist. All are pinned exactly in [workspace.dependencies].
| crate | version | published | licence | why |
|---|---|---|---|---|
| serde_path_to_error | =0.1.20 | 2025-09-15 | MIT OR Apache-2.0 | dotted error paths for parse issues |
| unicode-normalization | =0.1.26 | 2026-10-16 | (MIT OR Apache-2.0) AND Unicode-3.0 | NFKC for the leak detector (it was already in the lockfile as a transitive dependency at this version) |
Already in the workspace table (R2, ADR-R2-1), reused at the same pins: schemars =1.2.3 (MIT; features derive, uuid1) and sha2 =0.11.1 (MIT OR Apache-2.0) for prompt and input hashes, plus hex =0.4.3 for their lowercase-hex form.
From R1’s table, unchanged: reqwest, rustls, tokio, tokio-util, futures, bytes, serde, serde_json, thiserror, anyhow, tracing, uuid, time, sqlx, regex, rand, cozy-chess, wiremock (dev). The plan’s chrono is not used (R1 amendment, ADR 0031): timestamps are time::OffsetDateTime.
Crate wiring
Section titled “Crate wiring”aidepends onchess-core,common,db,queue,events,engine(forANALYSIS_PROTOCOLonly) andcoaching-input(the contract type), and dev-depends ontestkit,wiremockand tokiotest-util.workerdepends onainow, so Task 26 can wire it without editing a manifest.- No crate may enable
serde_json/preserve_order:canonical_jsonand the path index rely on sorted keys. CI’srustjob checks thatcargo tree -e features -i serde_json | grep -c preserve_orderis0, failing closed ifcargo treefails; anaiunit test asserts sorted map keys.
Shared types and fixtures
Section titled “Shared types and fixtures”ai::input::typesre-exports R2’scoaching-inputcrate (ADR-R2-2), so there is one contract type (fix round 1). Required + nullable JSON schemas use one mechanism, R2’scontract_transform(every property required,OptionstaysT | null), which is re-exported for Task 3’s output schemas. Serde-side, nullable keys must be present (coaching_input::nullable, now public).tests/input_shape.rsruns R2’s schema walker (coaching-input/tests/support/shape.rs, shared via#[path]) against the zod export.backend/fixtures/ai/input/holds byte-for-byte copies of the three M3 fixtures.backend/fixtures/ai/ts-export/holdsz.toJSONSchema(CoachingInput)andzodOutputFormat(ReportSectionEnvelope).schemafrom m3/base@4ff8220, each wrapped as{"source":"m3/base@4ff8220","schema":…}. Provenance (full commit, zod options, sha256) is infixtures/ai/ts-export/SOURCE. They were exported innode:22.23.5-slimwithpnpm install --frozen-lockfileand Node type stripping on a throwaway copy of the m3 checkout. Only the JSON is committed. The CoachingInput export equals R2’sfixtures/coaching-input/ts-schema.json.
Client design (Task 11)
Section titled “Client design (Task 11)”This amends ADR 0011 (Claude API with structured outputs): the call path changes, the structured-output contract and the claim validator do not.
- Interactive calls go through the sidecar (
client::sidecar, ADR 0062).structuredisPOST /v1/querywithoutputFormatandmaxTurns: 3;stream_turnisPOST /v1/chatover SSE and is one whole agentic turn.AiRuntimeimplementsAiClient: sidecar for interactive calls,BatchesClientfor batches. Bodies are camelCase serde types (client::sidecar_wire). The bearer isSidecarToken(AI_SIDECAR_TOKEN); the URL isAI_SIDECAR_URL. - Rust flattens the conversation (
client::flatten). The SDK takes user messages only, so the system blocks are joined with a blank line and earlier messages become tagged text blocks (<previous_user_message>,<previous_assistant_output>with assistant text only,<instruction>for a mid-conversation system message), followed by the last user message.cache_controlis dropped: caching on the sidecar path is automatic. - Our schema check is authoritative. The order is refusal,
max_tokens, the SDK’serror_max_structured_output_retries(schema mismatch, no issues), a missing output (no text), thenschema.checkonstructuredOutputin Rust. The SDK’s own validation never replaces ours.contentcarries the serialised output as one text block, so repair prompts can replay it. - Usage and metering. Results carry
model_usageper model (the sum isusage) and the SDK’ssdk_cost_usd, kept only for comparison. Chat turns also carrysession_model_usageand thesessionpath;port::metered_turn_usageapplies the ADR 0062 rule (a resumed turn meters the difference of session totals, falling back tomodelUsagewhen negative). - Streaming events.
delta.messageIdbecomesTurnEvent::Messagebefore the first delta of each API message,retractbecomesTurnEvent::Retract,tool_useevents are collected intoTurnResult.tool_uses,donegivesDone(its text is authoritative) anderroris classified by status and type. A body that ends before a terminal event, or is idle longer thanstream_idle_timeout(60 s, which also bounds the wait for headers while the sidecar queues), isUnavailable(Connection). Undecodable data isResponsewith fixed text. - The tool endpoint (
client::tool_server) is axum onAI_TOOL_BIND(default0.0.0.0:7311), reachable from the sidecar atAI_TOOL_PUBLIC_URL. Each turn registers itsToolHandlerunder a per-turn token (32 random bytes, hex); dropping the registration unregisters it, so turns never cross. The client drops it as soon as the terminal event is queued, and every token also expires after a TTL ofchat_timeout + TIMEOUT_GRACE + stream_idle_timeout, the longest a turn can run on our side (fix rounds 1 and 2). 401 without a token, 404 for an unknown or expired one, a 64 KiB body limit, and a 50 s per-call timeout that answersisErrorwith{"available":false,"reason":"engine busy"}(T23’s 45 s engine wait < 50 s < the sidecar’s 55 s callback fetch). Tokens are looked up by SHA-256, compared in constant time and never logged. - The batch client (
client::batches) is our own reqwest client atanthropic-version: 2026-10-21, because the SDK has no batch support and there is no official Rust SDK.submit,statusandresultsuseANTHROPIC_API_KEY(ApiKey); without itbatches_enabled()is false and the batch calls giveUnavailable(NoApiKey). A dev OAuth token never reaches Rust. Results are always read from{base}/v1/messages/batches/{id}/results; the batch’sresults_urlis never followed, so a forged host never receives the key. Batch ids are checked against[A-Za-z0-9_-]before they go into a path. - Retries (
client::retry). Retryable: a connection failure, 408, 409, 429, 5xx and 529, overridden byx-should-retry. Aretry-afterat or under the cap (30 s for batches) is slept; over the cap the call gives up at once and surfacesretry_after. Otherwisebase * 2^attemptplus 0 to 250 ms of jitter.statusretries up to 2 times (the results stream does not retry).submitcreates a paid, non-idempotent batch, so it retries only when no batch can have been created: a refused connection, 429 or 529. A 5xx, a timeout after sending, or any other failure is returned for the reconciler (Task 21) to resolve (fix round 1). The sidecar client retries at most once, only before the first response byte, and only on a refused connection or a 529, because the sidecar may already be running the call after any other failure. A 409turn_in_progressis “busy” and never retried within the turn. - Limits. A single SSE line or event, and a single results JSONL line, is capped at 4 MiB. Beyond it the chat stream ends with
Response, and the results stream yields oneResponseerror, skips that line and goes on. Both scanners search each byte for a newline only once. - User-Agent (ADR 0043). Every request the
aicrate sends carries the one sharedwire::USER_AGENT,chess-improver/0.1 (+https://github.com/chess-improver), with no email address. - Secrets.
SidecarTokenandApiKeyredact inDebugandDisplayand have noSerialize; the tool callback token is redacted inDebug. Error types read from bodies are kept only when they look like an API type ([a-z_]{1,64}), andredact(thesk-ant-pattern, which also covers OAuthsk-ant-oat…tokens) runs on every error message. Logs aredebugonly: method, path, status, attempt, duration andrequest-id. - New crate:
axum =0.8.9(MIT, released 2026-04-14),default-features = falsewithtokio,http1andjson, added by the coordinator. It reuses the hyper 1.x already in the lockfile; the lockfile gains onlyaxum,axum-core,matchitandmime.cargo denyandscripts/check-crate-age.shpass.
Consequences
Section titled “Consequences”- Lanes add behaviour inside the declared modules only. A lane that needs a new crate stops and reports it.