Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| edf2f8e03c | |||
| 80c1fc6a69 | |||
|
|
3f87b19a2d | ||
|
|
f52eef1657 | ||
|
|
e80e522c10 | ||
| 9d0f4b400c | |||
| 2a65c4e7a2 | |||
| 42a157b049 | |||
| c47597b421 | |||
| 61cc59d9a0 | |||
|
|
0282244114 | ||
|
|
51982b7f63 | ||
|
|
254cf83d9d | ||
|
|
8331859537 | ||
|
|
6e87cf2e6c | ||
|
|
549962cb8a | ||
|
|
7d4c1bf56e | ||
|
|
8fb8b5a71d | ||
|
|
f242290ca5 | ||
|
|
481428a7ce | ||
|
|
e17ef16d48 | ||
|
|
c1cc349b19 | ||
|
|
6982cbca7e | ||
|
|
7f3a46313e | ||
|
|
9143d2c5e2 | ||
|
|
79792eea85 | ||
|
|
c1802d85be | ||
|
|
cfea6854ab | ||
|
|
9f10887169 | ||
|
|
9db62027eb | ||
|
|
7d9a6392a7 | ||
|
|
a828602649 | ||
|
|
bb8909f2c2 | ||
|
|
28f2e5d2e7 | ||
|
|
dcb5f109f7 | ||
|
|
af5da3dfaa | ||
|
|
702e903fdd | ||
|
|
06a47bb13f |
65 changed files with 6484 additions and 6093 deletions
2
.gitattributes
vendored
2
.gitattributes
vendored
|
|
@ -1,2 +1,2 @@
|
|||
schemas/*.json text eol=lf
|
||||
crates/model-connector/tests/fixtures/wire_v3/* -text
|
||||
crates/model-connector/tests/fixtures/wire_v4/* -text
|
||||
|
|
|
|||
140
Cargo.lock
generated
140
Cargo.lock
generated
|
|
@ -73,6 +73,12 @@ version = "0.22.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.23.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
|
|
@ -94,6 +100,12 @@ version = "3.20.3"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.4.4"
|
||||
|
|
@ -139,15 +151,19 @@ name = "claude-connector"
|
|||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"cultcache-rs",
|
||||
"hmac",
|
||||
"libc",
|
||||
"model-connector",
|
||||
"rand_core 0.6.4",
|
||||
"rmp-serde",
|
||||
"rmpv",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror",
|
||||
"ureq",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
|
|
@ -229,7 +245,7 @@ source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f111
|
|||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"cultcache-rs",
|
||||
"ed25519-dalek",
|
||||
|
|
@ -434,6 +450,22 @@ dependencies = [
|
|||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"itoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.65"
|
||||
|
|
@ -508,7 +540,7 @@ version = "0.1.0"
|
|||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"cultcache-rs",
|
||||
"cultnet-rs",
|
||||
"rand_core 0.6.4",
|
||||
|
|
@ -553,6 +585,12 @@ version = "0.3.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
|
|
@ -697,6 +735,20 @@ dependencies = [
|
|||
"syn 3.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"getrandom 0.2.17",
|
||||
"libc",
|
||||
"untrusted",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmp"
|
||||
version = "0.8.15"
|
||||
|
|
@ -736,6 +788,41 @@ dependencies = [
|
|||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pki-types"
|
||||
version = "1.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
|
|
@ -983,6 +1070,46 @@ dependencies = [
|
|||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "untrusted"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "ureq"
|
||||
version = "3.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"log",
|
||||
"percent-encoding",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"ureq-proto",
|
||||
"utf8-zero",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ureq-proto"
|
||||
version = "0.6.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"http",
|
||||
"httparse",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf8-zero"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.25.0"
|
||||
|
|
@ -1060,6 +1187,15 @@ dependencies = [
|
|||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
version = "0.3.9"
|
||||
|
|
|
|||
58
README.md
58
README.md
|
|
@ -4,14 +4,19 @@ The connector kit for GameCult minds: one typed, encrypted, replay-safe contract
|
|||
between a caller that needs a model turn and a daemon that holds the provider
|
||||
credential, so no project wires its own provider calls.
|
||||
|
||||
Status: the `model-connector` crate and the `claude-connector` backend crate are live. No
|
||||
connector binary exists yet (the Claude connector binary is first, then an OpenAI-compatible one).
|
||||
The connector meters nothing in dollars. It holds the subscription token, lends it, and
|
||||
publishes the plan's usage windows (`usage_readout`, `claude_usage_readout` on the lease socket, and `plan_quota` on every lease grant) for the
|
||||
minds to read and decide their own burn. The one usage-derived refusal is the provider's own
|
||||
(`ProviderRejected`), repeated until its reset.
|
||||
|
||||
Status: the `model-connector` crate and the `claude-connector` backend crate and binary are live
|
||||
(`claude-connector serve|config|ask`); an OpenAI-compatible connector is not written.
|
||||
|
||||
## Entry points
|
||||
|
||||
Crate `crates/model-connector`:
|
||||
|
||||
- `src/contract.rs` - the v3 wire contract (`gamecult.model.*.v3`): `ProviderRequest`, `TransportInvocation`,
|
||||
- `src/contract.rs` - the v4 wire contract (`gamecult.model.*.v4`): `ProviderRequest`, `TransportInvocation`,
|
||||
`TransportResult`, `TransportReceipt`, the typed `StopReason`, `FailureKind` and `Refusal`,
|
||||
`InputItem::ReasoningState` (a provider's opaque reasoning block, replayed by callers
|
||||
verbatim via `TransportResult::transcript_items`; the service refuses another provider's
|
||||
|
|
@ -21,12 +26,12 @@ Crate `crates/model-connector`:
|
|||
- `src/envelope.rs` - the AES-256-GCM `TransportEnvelope` (binary ciphertext), its
|
||||
identity-binding AAD, the length-prefixed framing, and the CultNet carriage: each frame is a
|
||||
`cultnet.operation_request.v0` / `operation_response.v0` for service
|
||||
`gamecult.model.connector`, operation `invoke` (or `spend_readout`), its `message_id` the
|
||||
request id and its payload the base64 of the sealed envelope. `spend_readout` answers a
|
||||
`SpendReadout` (`gamecult.model.spend_readout.v1`): each caller's spent and reserved
|
||||
micro-USD against its ceiling in its current window, and the backend's plan quota;
|
||||
`ConnectorClient::spend_readout` asks.
|
||||
- `schemas/` - one JSON Schema per v3 document, generated from the types.
|
||||
`gamecult.model.connector`, operation `invoke` (or `usage_readout`), its `message_id` the
|
||||
request id and its payload the base64 of the sealed envelope. `usage_readout` answers a
|
||||
`UsageReadout` (`gamecult.model.usage_readout.v1`): the backend's plan quota windows, each with
|
||||
utilization, reset, status and age;
|
||||
`ConnectorClient::usage_readout` asks.
|
||||
- `schemas/` - one JSON Schema per v4 document, generated from the types.
|
||||
- `src/client.rs` - `ConnectorClient`, the one-request caller side.
|
||||
- `src/service.rs` (feature `daemon`) - `TransportService`: caller admission, durable
|
||||
replay (a retried request is answered byte-identically and the provider runs once),
|
||||
|
|
@ -35,7 +40,7 @@ Crate `crates/model-connector`:
|
|||
`ProviderBackend` trait. A connector binary implements `ProviderBackend` for its
|
||||
provider and calls `serve`; the kit names no provider.
|
||||
|
||||
Crate `crates/claude-connector` (library only; the binary that wires it to `serve` is not written):
|
||||
Crate `crates/claude-connector` (library and the `claude-connector` binary that wires it to `serve`):
|
||||
|
||||
- `ClaudeCodeBackend` implements `ProviderBackend` for provider `claude-code` by driving the
|
||||
unmodified `claude` binary, one child per call, in print stream-json mode with no tools, no MCP
|
||||
|
|
@ -45,11 +50,30 @@ Crate `crates/claude-connector` (library only; the binary that wires it to `serv
|
|||
- Reasoning state is a session handle (`ClaudeCodeHandle`) authenticated with a connector secret
|
||||
and bound to the caller it was minted for; a handle that cannot be proven to match the request
|
||||
and its caller re-seeds from the caller's transcript, and every resume forks.
|
||||
- `MessagesBackend` implements `ProviderBackend` for provider `anthropic-messages` when the config document says `auth` is an API key (`config init --auth api-key`; one choice for the whole connector, held in the credential `--token-credential` names). One non-streaming `POST /v1/messages` per call: tools, tool calls and results, thinking blocks (replayed unchanged as reasoning state), `cache_control` (5 minutes, or 1 hour for long retention) and cache read and write usage map natively. The key is read from the systemd credential at every call and travels only as the `x-api-key` header. A request's output schema is `output_config.format`; `Required` tool choice is `tool_choice: any` where the model accepts it and a refusal before sending where it does not (the current Sonnet and Opus reject it). A key has no plan: no meter runs, the plan windows stay empty, and a key document refuses leases.
|
||||
- `ProcessPort` is the one OS seam (`StdProcessPort`, unix, kills the child's whole process
|
||||
group); `SessionStore` and `StderrSink` are the other ports. `ClaudeCodeConfig` is what the
|
||||
binary hands in; the credential is read from a systemd credential and reaches the child on a
|
||||
pipe (`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`), never in an environment. `QuotaCell` keeps the
|
||||
plan windows the CLI's `rate_limit_event`s report, for the spend readout.
|
||||
binary hands in; the subscription token is read from a systemd credential and reaches the child on a
|
||||
pipe, never in an environment (`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`). `QuotaCell` keeps the
|
||||
plan windows the CLI's `rate_limit_event`s report, for the usage readout and the lease grant.
|
||||
|
||||
## Asking for one no-tools completion
|
||||
|
||||
`claude-connector ask` is a caller of a running connector for a Mind's Self run: the prompt is all
|
||||
of stdin, the answer text is stdout.
|
||||
|
||||
```
|
||||
claude-connector ask --caller-id ID --connection-key-file FILE --model MODEL (--system TEXT | --system-file FILE) [--endpoint HOST:PORT] [--effort low|medium|high|max] [--max-output-tokens N] [--timeout-secs N] < prompt > answer
|
||||
```
|
||||
|
||||
Defaults: endpoint `127.0.0.1:4110`, 8192 output tokens, 300 s. The key is read from the file (the
|
||||
same text the connector reads for the caller; never argv or environment). There is no tools flag,
|
||||
no working-directory flag and no other endpoint: the request is built by `ProviderRequest::new`
|
||||
(no tools) and the model child's cwd and environment stay the connector's. Any failure (refused,
|
||||
over a cap, model not allowed, wrong key or caller, timeout, provider failure, empty answer, empty
|
||||
stdin) exits nonzero with one `claude-connector: <cause>` line on stderr and nothing on stdout;
|
||||
the line never carries the key, the prompt or the provider's message. Each run uses a fresh request
|
||||
id. Code: `crates/claude-connector/src/ask.rs`; tests: `crates/claude-connector/tests/ask.rs`.
|
||||
|
||||
Frame arithmetic is public in `src/envelope.rs`, measured on the carriage frame: `frame_bytes_for_payload(n)` is the frame a
|
||||
caller payload bound of `n` needs, `payload_bytes_for_frame(frame)` is the largest payload bound
|
||||
|
|
@ -58,7 +82,7 @@ a frame allows, and `MAX_IDENTITY_BYTES` (256) bounds caller ids, request ids an
|
|||
needed); the smallest legal frame is `frame_bytes_for_payload(MIN_PAYLOAD_BYTES)`. A request id past
|
||||
the bound is refused on the wire as `Refusal::Malformed`, the reply echoing the id (the connection is dropped only if that reply cannot fit the frame); `ConnectorClient` refuses such an id locally with `RequestIdTooLong`.
|
||||
|
||||
The default feature set compiles contract, envelope and client only. The kit speaks v3
|
||||
The default feature set compiles contract, envelope and client only. The kit speaks v4
|
||||
only: a v2 frame gets no answer.
|
||||
|
||||
## Verify
|
||||
|
|
@ -68,9 +92,9 @@ cargo test --locked --workspace
|
|||
cargo test --locked --workspace --features model-connector/daemon
|
||||
```
|
||||
|
||||
`crates/model-connector/tests/wire_golden_v3.rs` pins the v3 documents and one sealed carriage
|
||||
frame to the fixtures in `crates/model-connector/tests/fixtures/wire_v3` (regenerate with
|
||||
`WIRE_V3_REGENERATE=1`; see the fixtures' README), and
|
||||
`crates/model-connector/tests/wire_golden_v4.rs` pins the v4 documents and one sealed carriage
|
||||
frame to the fixtures in `crates/model-connector/tests/fixtures/wire_v4` (regenerate with
|
||||
`WIRE_V4_REGENERATE=1`; see the fixtures' README), and
|
||||
`crates/model-connector/tests/published_schemas.rs` fails when `schemas/` differs from the types
|
||||
(`MODEL_CONNECTOR_REGENERATE_SCHEMAS=1` rewrites it).
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "claude-connector"
|
||||
description = "Claude backend for the connector kit: drives the unmodified claude binary in print stream-json mode"
|
||||
description = "Claude backends for the connector kit: the claude CLI on a subscription token, the Messages API on an API key"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
|
@ -13,15 +13,21 @@ path = "src/main.rs"
|
|||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
chrono = { version = "0.4", default-features = false }
|
||||
hmac = "0.12"
|
||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "a4eae9056152335662f1115f97bf35fb00ab6d23", package = "cultcache-rs" }
|
||||
model-connector = { path = "../model-connector", features = ["daemon"] }
|
||||
rand_core = { version = "0.6", features = ["getrandom"] }
|
||||
rmp-serde = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
thiserror = "2"
|
||||
ureq = { version = "~3.3", default-features = false, features = ["rustls"] }
|
||||
zeroize = "1"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
rmpv = "1"
|
||||
|
|
|
|||
336
crates/claude-connector/src/ask.rs
Normal file
336
crates/claude-connector/src/ask.rs
Normal file
|
|
@ -0,0 +1,336 @@
|
|||
//! `claude-connector ask`: one no-tools completion through a running connector.
|
||||
//!
|
||||
//! A thin caller over [`ConnectorClient`]. It builds a [`ProviderRequest`] with
|
||||
//! `ProviderRequest::new`, which carries no tools, and has no field, flag or
|
||||
//! path by which a caller could add one; the working directory and environment
|
||||
//! of the model child belong to the connector. Every failure is an
|
||||
//! [`AskError`] whose text names a cause and never echoes the key, the prompt
|
||||
//! or the instructions.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use model_connector::{
|
||||
ConnectorClient, ConnectorClientError, FailureKind, InputItem, ProviderRequest,
|
||||
ReasoningEffort, StopReason, TransportDisposition, TransportEventPayload, TransportInvocation,
|
||||
TransportOutcome, TransportResult, frame_bytes_for_payload, provider_request_sha256,
|
||||
};
|
||||
use rand_core::{OsRng, RngCore};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// The loopback endpoint a claude connector listens on.
|
||||
pub const DEFAULT_ENDPOINT: &str = "127.0.0.1:4110";
|
||||
/// The payload bound the connector's own `config init` defaults to.
|
||||
pub const PAYLOAD_BYTES: usize = 1 << 20;
|
||||
const MAX_KEY_BYTES: usize = 1024;
|
||||
pub const MAX_SYSTEM_BYTES: usize = 64 * 1024;
|
||||
|
||||
pub struct AskArgs {
|
||||
pub endpoint: SocketAddr,
|
||||
pub caller_id: String,
|
||||
pub key_file: std::path::PathBuf,
|
||||
pub model: String,
|
||||
pub instructions: String,
|
||||
pub effort: Option<ReasoningEffort>,
|
||||
pub max_output_tokens: u32,
|
||||
pub timeout: Duration,
|
||||
pub prompt: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum AskError {
|
||||
#[error("the prompt on stdin is empty")]
|
||||
EmptyPrompt,
|
||||
#[error("the prompt on stdin is larger than the {PAYLOAD_BYTES} byte payload bound")]
|
||||
PromptTooLarge,
|
||||
#[error("the instructions are empty")]
|
||||
EmptyInstructions,
|
||||
#[error("the connection key file cannot be read")]
|
||||
KeyUnreadable,
|
||||
#[error("the connection key file is not text")]
|
||||
KeyEncoding,
|
||||
#[error("the connection key file is not a regular file")]
|
||||
KeyNotRegular,
|
||||
#[error("the connection key file is readable by group or world (chmod 600)")]
|
||||
KeyExposed,
|
||||
#[error("the instructions file cannot be read as text from a regular file")]
|
||||
SystemUnreadable,
|
||||
#[error("the instructions file is larger than {MAX_SYSTEM_BYTES} bytes")]
|
||||
SystemTooLarge,
|
||||
#[error("standard input cannot be read")]
|
||||
StdinRead,
|
||||
#[error("standard input is not UTF-8 text")]
|
||||
StdinNotText,
|
||||
#[error("the answer cannot be written to standard output")]
|
||||
StdoutWrite,
|
||||
#[error("nothing is listening at the connector endpoint")]
|
||||
NotListening,
|
||||
#[error(
|
||||
"the connector closed the connection without answering (key, caller or frame not accepted)"
|
||||
)]
|
||||
ClosedWithoutAnswer,
|
||||
#[error("the connection key file is empty or longer than {MAX_KEY_BYTES} bytes")]
|
||||
KeyLength,
|
||||
#[error("the connection key is not usable as a key (surrounding whitespace?)")]
|
||||
KeyUnusable,
|
||||
#[error("the request is invalid for the connector contract")]
|
||||
Request,
|
||||
#[error("timed out waiting for the connector")]
|
||||
Timeout,
|
||||
#[error("the connector connection failed: {0}")]
|
||||
Connection(std::io::ErrorKind),
|
||||
#[error("the connector answer was not accepted (wrong key, caller or tampered frame): {0}")]
|
||||
Transport(model_connector::ServiceError),
|
||||
#[error("the request exceeded a frame bound")]
|
||||
FrameSize,
|
||||
#[error("the connector refused the request: {0:?}")]
|
||||
Refused(model_connector::Refusal),
|
||||
#[error("the provider failed: {0:?}")]
|
||||
Failed(FailureKind),
|
||||
#[error("the answer stopped as {0:?}, not a completed text")]
|
||||
NotCompleted(StopReason),
|
||||
#[error("the answer carried a tool call, which this command never requests")]
|
||||
ToolCall,
|
||||
#[error("the answer is empty")]
|
||||
EmptyAnswer,
|
||||
}
|
||||
|
||||
enum ReadFailure {
|
||||
Unreadable,
|
||||
NotRegular,
|
||||
TooLarge,
|
||||
Exposed,
|
||||
}
|
||||
|
||||
/// Opens `path` without blocking (a FIFO must not hang the open), requires the
|
||||
/// opened file to be a regular file (a symlink is followed and its target
|
||||
/// judged), optionally refuses one readable by group or world, and reads at
|
||||
/// most `cap` bytes, failing if there are more.
|
||||
fn read_regular(path: &Path, cap: usize, private: bool) -> Result<Zeroizing<Vec<u8>>, ReadFailure> {
|
||||
use std::io::Read;
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.read(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.custom_flags(libc::O_NONBLOCK);
|
||||
}
|
||||
let file = options.open(path).map_err(|_| ReadFailure::Unreadable)?;
|
||||
let metadata = file.metadata().map_err(|_| ReadFailure::Unreadable)?;
|
||||
if !metadata.is_file() {
|
||||
return Err(ReadFailure::NotRegular);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if private && metadata.permissions().mode() & 0o077 != 0 {
|
||||
return Err(ReadFailure::Exposed);
|
||||
}
|
||||
}
|
||||
let mut bytes = Zeroizing::new(Vec::new());
|
||||
file.take(cap as u64 + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|_| ReadFailure::Unreadable)?;
|
||||
if bytes.len() > cap {
|
||||
return Err(ReadFailure::TooLarge);
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Reads the key as the connector reads its own key file (the text without the
|
||||
/// trailing line ending). The bytes are zeroized on drop and never shown.
|
||||
pub fn read_key(path: &Path) -> Result<Zeroizing<String>, AskError> {
|
||||
let raw = read_regular(path, MAX_KEY_BYTES, true).map_err(|failure| match failure {
|
||||
ReadFailure::Unreadable => AskError::KeyUnreadable,
|
||||
ReadFailure::NotRegular => AskError::KeyNotRegular,
|
||||
ReadFailure::TooLarge => AskError::KeyLength,
|
||||
ReadFailure::Exposed => AskError::KeyExposed,
|
||||
})?;
|
||||
let text = std::str::from_utf8(raw.as_slice()).map_err(|_| AskError::KeyEncoding)?;
|
||||
let key = Zeroizing::new(text.trim_end_matches(['\r', '\n']).to_string());
|
||||
if key.is_empty() || key.len() > MAX_KEY_BYTES {
|
||||
return Err(AskError::KeyLength);
|
||||
}
|
||||
if key.trim() != key.as_str() {
|
||||
return Err(AskError::KeyUnusable);
|
||||
}
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
/// The instructions file: a regular file of at most [`MAX_SYSTEM_BYTES`] of text.
|
||||
pub fn read_system_file(path: &Path) -> Result<String, AskError> {
|
||||
let raw = read_regular(path, MAX_SYSTEM_BYTES, false).map_err(|failure| match failure {
|
||||
ReadFailure::TooLarge => AskError::SystemTooLarge,
|
||||
_ => AskError::SystemUnreadable,
|
||||
})?;
|
||||
String::from_utf8(raw.to_vec()).map_err(|_| AskError::SystemUnreadable)
|
||||
}
|
||||
|
||||
fn fresh_id(prefix: &str) -> String {
|
||||
let mut nonce = [0_u8; 16];
|
||||
OsRng.fill_bytes(&mut nonce);
|
||||
let hex: String = nonce.iter().map(|b| format!("{b:02x}")).collect();
|
||||
format!("{prefix}-{hex}")
|
||||
}
|
||||
|
||||
/// The one invocation `ask` ever sends: instructions, one user text, no tools.
|
||||
pub fn build_invocation(args: &AskArgs) -> Result<TransportInvocation, AskError> {
|
||||
if args.prompt.trim().is_empty() {
|
||||
return Err(AskError::EmptyPrompt);
|
||||
}
|
||||
if args.prompt.len() > PAYLOAD_BYTES {
|
||||
return Err(AskError::PromptTooLarge);
|
||||
}
|
||||
if args.instructions.trim().is_empty() {
|
||||
return Err(AskError::EmptyInstructions);
|
||||
}
|
||||
let mut request = ProviderRequest::new(
|
||||
fresh_id("ask"),
|
||||
fresh_id("ask-conversation"),
|
||||
args.model.clone(),
|
||||
args.instructions.clone(),
|
||||
args.max_output_tokens,
|
||||
);
|
||||
request.input = vec![InputItem::UserText {
|
||||
text: args.prompt.clone(),
|
||||
}];
|
||||
request.reasoning_effort = args.effort;
|
||||
let digest = provider_request_sha256(&request).map_err(|_| AskError::Request)?;
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_millis() as u64);
|
||||
let invocation =
|
||||
TransportInvocation::new(args.caller_id.clone(), now + 120_000, digest, request)
|
||||
.map_err(|_| AskError::Request)?;
|
||||
invocation
|
||||
.validate(now, 300_000)
|
||||
.map_err(|_| AskError::Request)?;
|
||||
Ok(invocation)
|
||||
}
|
||||
|
||||
/// The answer text of a result, or the one cause it is not an answer.
|
||||
pub fn answer_text(result: &TransportResult) -> Result<String, AskError> {
|
||||
let (events, receipt) = match &result.disposition {
|
||||
TransportDisposition::Refused(reason) => return Err(AskError::Refused(reason.clone())),
|
||||
TransportDisposition::Transported { events, receipt } => (events, receipt),
|
||||
};
|
||||
match &receipt.outcome {
|
||||
TransportOutcome::Failed { kind, .. } => return Err(AskError::Failed(*kind)),
|
||||
TransportOutcome::Completed { stop_reason, .. } => {
|
||||
if !matches!(stop_reason, StopReason::EndTurn | StopReason::StopSequence) {
|
||||
return Err(AskError::NotCompleted(*stop_reason));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut text = String::new();
|
||||
for event in events {
|
||||
match &event.payload {
|
||||
TransportEventPayload::TextDelta { text: delta } => text.push_str(delta),
|
||||
TransportEventPayload::ToolCall { .. } => return Err(AskError::ToolCall),
|
||||
TransportEventPayload::ReasoningState { .. } => {}
|
||||
}
|
||||
}
|
||||
if text.trim().is_empty() {
|
||||
return Err(AskError::EmptyAnswer);
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
pub fn ask(args: &AskArgs) -> Result<String, AskError> {
|
||||
let invocation = build_invocation(args)?;
|
||||
let key = read_key(&args.key_file)?;
|
||||
let client = ConnectorClient::new(
|
||||
args.endpoint,
|
||||
key.as_str(),
|
||||
frame_bytes_for_payload(PAYLOAD_BYTES),
|
||||
Some(args.timeout),
|
||||
)
|
||||
.map_err(|error| match error {
|
||||
ConnectorClientError::Transport(_) => AskError::KeyUnusable,
|
||||
_ => AskError::Request,
|
||||
})?;
|
||||
let result = client.execute(&invocation).map_err(|error| match error {
|
||||
ConnectorClientError::Connection(io)
|
||||
if matches!(
|
||||
io.kind(),
|
||||
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
|
||||
) =>
|
||||
{
|
||||
AskError::Timeout
|
||||
}
|
||||
ConnectorClientError::Connection(io) => match io.kind() {
|
||||
std::io::ErrorKind::ConnectionRefused => AskError::NotListening,
|
||||
std::io::ErrorKind::UnexpectedEof
|
||||
| std::io::ErrorKind::ConnectionReset
|
||||
| std::io::ErrorKind::BrokenPipe => AskError::ClosedWithoutAnswer,
|
||||
kind => AskError::Connection(kind),
|
||||
},
|
||||
ConnectorClientError::Transport(error) => AskError::Transport(error),
|
||||
ConnectorClientError::FrameSize => AskError::FrameSize,
|
||||
ConnectorClientError::InvalidConfig | ConnectorClientError::RequestIdTooLong => {
|
||||
AskError::Request
|
||||
}
|
||||
})?;
|
||||
answer_text(&result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::{ClaudeCodeConfig, ClaudeCodeLimits};
|
||||
use crate::handle::{SessionStore, plan};
|
||||
use model_connector::ToolDefinition;
|
||||
|
||||
struct NoSessions;
|
||||
impl SessionStore for NoSessions {
|
||||
fn exists(&self, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn args() -> AskArgs {
|
||||
AskArgs {
|
||||
endpoint: DEFAULT_ENDPOINT.parse().unwrap(),
|
||||
caller_id: "c".into(),
|
||||
key_file: "/nonexistent".into(),
|
||||
model: "m".into(),
|
||||
instructions: "i".into(),
|
||||
effort: None,
|
||||
max_output_tokens: 16,
|
||||
timeout: Duration::from_secs(1),
|
||||
prompt: "p".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The claude backend's own planner accepts what `ask` builds and refuses
|
||||
/// the same request once a tool is forced into it.
|
||||
#[test]
|
||||
fn the_backend_planner_refuses_a_forced_tool_and_accepts_the_asked_request() {
|
||||
let config = ClaudeCodeConfig {
|
||||
claude_binary: "/claude".into(),
|
||||
claude_binary_sha256: [0; 32],
|
||||
work_dir: "/w".into(),
|
||||
config_dir: "/c".into(),
|
||||
prompt_dir: "/p".into(),
|
||||
token_credential: "t".into(),
|
||||
handle_secret_credential: "h".into(),
|
||||
instance: "i".into(),
|
||||
limits: ClaudeCodeLimits {
|
||||
deadline: Duration::from_secs(1),
|
||||
max_line_bytes: 1024,
|
||||
max_total_bytes: 4096,
|
||||
stderr_tail_bytes: 64,
|
||||
},
|
||||
};
|
||||
let mut request = build_invocation(&args()).unwrap().request;
|
||||
let secret = [7_u8; 32];
|
||||
assert!(plan(&request, &config, &secret, "c", &NoSessions).is_ok());
|
||||
request.tools.push(ToolDefinition {
|
||||
name: "t".into(),
|
||||
description: "d".into(),
|
||||
parameters_json: "{}".into(),
|
||||
});
|
||||
assert!(plan(&request, &config, &secret, "c", &NoSessions).is_err());
|
||||
}
|
||||
}
|
||||
|
|
@ -20,6 +20,12 @@ use crate::process::{ProcessPort, RunningChild, StdoutRead};
|
|||
use crate::quota::QuotaCell;
|
||||
use crate::stream::{Failure, Finished, Step, StreamState};
|
||||
|
||||
/// The meter's call: the cheapest model, a trivial prompt, and an answer cap
|
||||
/// that only bounds a runaway.
|
||||
const METER_MODEL: &str = "claude-haiku-5-5";
|
||||
const METER_CALLER: &str = "meter";
|
||||
const METER_MAX_OUTPUT_TOKENS: u32 = 16;
|
||||
|
||||
/// Where the child's credential comes from, read afresh at every use. The
|
||||
/// connector's own environment is never a source (ruling
|
||||
/// claude-connector-token-credential).
|
||||
|
|
@ -156,16 +162,40 @@ impl ClaudeCodeBackend {
|
|||
self.quota.clone()
|
||||
}
|
||||
|
||||
/// The meter's call: the smallest real one, through the same child,
|
||||
/// stream and cell as any other. The stream's `rate_limit_event` is what
|
||||
/// the caller wants; this returns what the call billed, or the failure's
|
||||
/// kind (never its message).
|
||||
pub(crate) fn read_meter(&self) -> Result<Usage, String> {
|
||||
let mut request = ProviderRequest::new(
|
||||
METER_CALLER,
|
||||
METER_CALLER,
|
||||
METER_MODEL,
|
||||
"Reply with the single word ok.",
|
||||
METER_MAX_OUTPUT_TOKENS,
|
||||
);
|
||||
request.input = vec![InputItem::UserText {
|
||||
text: "ok?".to_string(),
|
||||
}];
|
||||
match self.run(&request, METER_CALLER, true).1 {
|
||||
TransportOutcome::Completed { usage, .. } => Ok(usage),
|
||||
TransportOutcome::Failed { kind, .. } => Err(format!("{kind:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one pin check: `ready` and every spawn use it, and nothing caches
|
||||
/// its answer.
|
||||
fn binary_matches_pin(&self) -> bool {
|
||||
binary_matches_pin(&self.config)
|
||||
}
|
||||
|
||||
/// `ephemeral` leaves no transcript behind: the meter keeps no handle and
|
||||
/// resumes nothing, every other call is resumed by its session.
|
||||
fn run(
|
||||
&self,
|
||||
request: &ProviderRequest,
|
||||
caller: &str,
|
||||
ephemeral: bool,
|
||||
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
let Some(secret) = usable_secret(self.handle_secret.as_ref()) else {
|
||||
return failed(
|
||||
|
|
@ -209,7 +239,7 @@ impl ClaudeCodeBackend {
|
|||
"claude-code: the system prompt could not be staged",
|
||||
));
|
||||
};
|
||||
let argv = argv(&self.config, request, &plan, prompt.path());
|
||||
let argv = argv(&self.config, request, &plan, prompt.path(), ephemeral);
|
||||
let env = child_env(&self.config, request);
|
||||
let deadline = Instant::now() + self.config.limits.deadline;
|
||||
|
||||
|
|
@ -231,7 +261,7 @@ impl ClaudeCodeBackend {
|
|||
deadline,
|
||||
&request.model,
|
||||
request.output_schema_json.as_deref(),
|
||||
&self.quota,
|
||||
Some(&*self.quota),
|
||||
);
|
||||
child.kill();
|
||||
child.wait();
|
||||
|
|
@ -323,7 +353,7 @@ impl ProviderBackend for ClaudeCodeBackend {
|
|||
}
|
||||
|
||||
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
||||
let (events, outcome) = self.run(call.request(), call.caller_runtime_id());
|
||||
let (events, outcome) = self.run(call.request(), call.caller_runtime_id(), false);
|
||||
call.transported(events, outcome)
|
||||
}
|
||||
|
||||
|
|
@ -337,7 +367,7 @@ fn read_stream(
|
|||
deadline: Instant,
|
||||
model: &str,
|
||||
schema: Option<&str>,
|
||||
quota: &QuotaCell,
|
||||
quota: Option<&QuotaCell>,
|
||||
) -> Result<Finished, Failure> {
|
||||
let mut state = StreamState::new(model, schema, quota);
|
||||
let finished = loop {
|
||||
|
|
|
|||
|
|
@ -5,9 +5,9 @@ use std::sync::{Arc, Mutex};
|
|||
use std::time::Duration;
|
||||
|
||||
use model_connector::{
|
||||
CallerAdmission, ModelPrice, PriceTable, Rates, ReasoningEffort, SpendCeiling, SpendWindowMs,
|
||||
StopReason, ToolDefinition, TransportAdmission, TransportDisposition, TransportInvocation,
|
||||
TransportKey, TransportReceipt, TransportService, decrypt_result, encrypt_invocation,
|
||||
CallerAdmission, PlanQuotaSnapshot, ReasoningEffort, StopReason, ToolDefinition,
|
||||
TransportAdmission, TransportDisposition, TransportInvocation, TransportKey, TransportReceipt,
|
||||
TransportService, decrypt_result, encrypt_invocation,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
|
@ -61,7 +61,7 @@ const USAGE: &str = r#"{"claude-haiku-5-5":{"inputTokens":2,"outputTokens":4,"ca
|
|||
|
||||
/// What a resumed session's `modelUsage` says: every turn so far. Every result
|
||||
/// fixture carries it beside the turn's own `model_usage_since_last_result`,
|
||||
/// so reading the wrong field shows in a price.
|
||||
/// so reading the wrong field shows in a count.
|
||||
const CUMULATIVE: &str = r#"{"claude-haiku-5-5":{"inputTokens":900000,"outputTokens":900000,"cacheReadInputTokens":900000,"cacheCreationInputTokens":900000,"thinkingTokens":900000,"costUSD":99.0}}"#;
|
||||
|
||||
fn result_line(stop_reason: &str, since_last: &str) -> String {
|
||||
|
|
@ -460,25 +460,6 @@ struct Door {
|
|||
service: TransportService,
|
||||
}
|
||||
|
||||
fn prices() -> PriceTable {
|
||||
PriceTable::from([MODEL, OTHER_MODEL].map(|model| {
|
||||
(
|
||||
model.to_string(),
|
||||
ModelPrice {
|
||||
rates: Rates {
|
||||
input: 3_000_000,
|
||||
cache_write_short: 3_750_000,
|
||||
cache_write_long: 6_000_000,
|
||||
cache_read: 300_000,
|
||||
output: 15_000_000,
|
||||
},
|
||||
long_context: None,
|
||||
overhead_tokens: 100,
|
||||
},
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
||||
impl Door {
|
||||
fn new() -> Self {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
|
|
@ -496,14 +477,11 @@ impl Door {
|
|||
4,
|
||||
FRAME / 2,
|
||||
32_768,
|
||||
SpendCeiling(1 << 40),
|
||||
SpendWindowMs(3_600_000),
|
||||
)
|
||||
.unwrap()
|
||||
});
|
||||
let service =
|
||||
TransportService::open(&dir.join("replay.cc"), PROVIDER, prices(), callers, 5_000)
|
||||
.unwrap();
|
||||
TransportService::open(&dir.join("replay.cc"), PROVIDER, callers, 5_000).unwrap();
|
||||
Self { dir, service }
|
||||
}
|
||||
|
||||
|
|
@ -520,10 +498,13 @@ impl Door {
|
|||
request: ProviderRequest,
|
||||
) -> (model_connector::ExecutionClaim, TransportInvocation) {
|
||||
let key = TransportKey::from_connection_secret(&format!("{caller}-key")).unwrap();
|
||||
let invocation =
|
||||
TransportInvocation::new(caller, 2_000, [7; 32], 10_000_000, request).unwrap();
|
||||
let invocation = TransportInvocation::new(caller, 2_000, [7; 32], request).unwrap();
|
||||
let envelope = encrypt_invocation(&invocation, &key).unwrap();
|
||||
match self.service.begin(&envelope, 1_000, FRAME).unwrap() {
|
||||
match self
|
||||
.service
|
||||
.begin(&envelope, 1_000, &PlanQuotaSnapshot::default(), FRAME)
|
||||
.unwrap()
|
||||
{
|
||||
TransportAdmission::Execute(claim) => (*claim, invocation),
|
||||
TransportAdmission::Reply(_) => panic!("the door answered instead of admitting"),
|
||||
}
|
||||
|
|
@ -693,6 +674,15 @@ fn child_env_is_cleared_and_names_the_token_descriptor_never_the_token() {
|
|||
assert!(!format!("{result:?}").contains(CANARY_TOKEN));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cell_is_fed_and_the_oauth_descriptor_named() {
|
||||
let rig = rig(vec![structured_script()]);
|
||||
rig.run(schema_request());
|
||||
assert!(!quota_of(&rig).windows.is_empty());
|
||||
let seen = rig.seen();
|
||||
assert!(seen.env.iter().any(|(name, _)| name == TOKEN_FD_ENV));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_token_never_reaches_a_message_an_event_or_a_debug_form() {
|
||||
// A failing run, so a message is built, and the env's own Debug.
|
||||
|
|
@ -1457,12 +1447,8 @@ fn usage_sums_model_usage_across_models() {
|
|||
panic!("completed expected");
|
||||
};
|
||||
assert_eq!(*summed, usage(12, 37, 1083, 24, Some(8)));
|
||||
// The receipt is priced from usage alone: 12*3 + 37*0.3 + 1083*6 + 24*15 micro-USD, rounded up.
|
||||
assert_eq!(parts(&cheap).1.cost_micro_usd, 36 + 12 + 6498 + 360);
|
||||
assert_eq!(
|
||||
parts(&cheap).1.cost_micro_usd,
|
||||
parts(&dear).1.cost_micro_usd
|
||||
);
|
||||
// The receipt is the usage alone: the CLI's own total never reaches it.
|
||||
assert_eq!(parts(&cheap).1, parts(&dear).1);
|
||||
|
||||
// No model reported thinking tokens: none is claimed.
|
||||
let plain = r#"{"claude-haiku-5-5":{"inputTokens":1,"outputTokens":1,"cacheReadInputTokens":0,"cacheCreationInputTokens":0}}"#;
|
||||
|
|
@ -1599,7 +1585,6 @@ fn no_result_event_is_a_failure_with_unknown_usage() {
|
|||
};
|
||||
assert_eq!(zero_billed, Some(usage_zero()));
|
||||
|
||||
let mut costs = Vec::new();
|
||||
for (script, expected) in ends {
|
||||
let rig = rig(vec![script]);
|
||||
let result = rig.run(request(vec![user("hi")]));
|
||||
|
|
@ -1607,20 +1592,7 @@ fn no_result_event_is_a_failure_with_unknown_usage() {
|
|||
assert_eq!(kind, expected);
|
||||
assert_eq!(usage, None, "{message}");
|
||||
assert!(result.transcript_items().is_empty());
|
||||
costs.push(parts(&result).1.cost_micro_usd);
|
||||
}
|
||||
// Unknown usage is charged the reservation, which is far above a typical turn.
|
||||
assert!(costs.iter().all(|cost| *cost >= 15_000), "{costs:?}");
|
||||
assert_eq!(
|
||||
parts(&rig(vec![]).run({
|
||||
let mut bad = request(vec![user("a")]);
|
||||
bad.tools.push(a_tool());
|
||||
bad
|
||||
}))
|
||||
.1
|
||||
.cost_micro_usd,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1719,7 +1691,6 @@ fn a_port_that_cannot_spawn_is_a_provider_failure() {
|
|||
Some(usage_zero()),
|
||||
"a child that never ran bills nothing"
|
||||
);
|
||||
assert_eq!(parts(&result).1.cost_micro_usd, 0);
|
||||
assert!(
|
||||
!message.contains(dir.path().to_str().unwrap()),
|
||||
"no path in a message"
|
||||
|
|
@ -1742,9 +1713,7 @@ fn backend_end_to_end_through_the_service() {
|
|||
let (events, receipt) = parts(&opened);
|
||||
assert_eq!(receipt.provider, "claude-code");
|
||||
assert_eq!(receipt.model, MODEL);
|
||||
// USAGE priced at the table: 2*3 + 7*0.3 + 1043*6 + 4*15 micro-USD, rounded up.
|
||||
assert_eq!(receipt.cost_micro_usd, 6 + 3 + 6258 + 60);
|
||||
assert_eq!(receipt.overrun_micro_usd, 0);
|
||||
// USAGE counted: 2 input, 7 cache read, 1043 cache write, 4 output.
|
||||
assert_eq!(events.len(), 2);
|
||||
let items = opened.transcript_items();
|
||||
assert_eq!(items[0], assistant("hello back"));
|
||||
|
|
@ -1757,13 +1726,6 @@ fn backend_end_to_end_through_the_service() {
|
|||
|
||||
const USAGE_TURN_2: &str = r#"{"claude-haiku-5-5":{"inputTokens":3,"outputTokens":5,"cacheReadInputTokens":1100,"cacheCreationInputTokens":9}}"#;
|
||||
|
||||
/// What a call whose usage is unknown is billed: the kit's reservation.
|
||||
fn reservation() -> u64 {
|
||||
let result = rig(vec![Script::lines(vec![])]).run(request(vec![user("hi")]));
|
||||
assert_eq!(failure_of(&result).2, None);
|
||||
parts(&result).1.cost_micro_usd
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resumed_turn_is_charged_only_its_own_usage() {
|
||||
let rig = rig(vec![
|
||||
|
|
@ -1788,13 +1750,10 @@ fn a_resumed_turn_is_charged_only_its_own_usage() {
|
|||
};
|
||||
assert_eq!(*billed, usage(3, 1100, 9, 5, None));
|
||||
// 3*3 + 1100*0.3 + 9*6 + 5*15 micro-USD.
|
||||
assert_eq!(parts(&second).1.cost_micro_usd, 9 + 330 + 54 + 75);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_the_result_does_not_report_is_billed_the_reservation() {
|
||||
let reservation = reservation();
|
||||
assert!(reservation >= 15_000, "{reservation}");
|
||||
fn usage_the_result_does_not_report_stays_unknown() {
|
||||
let success = |fields: &str| {
|
||||
format!(
|
||||
r#"{{"type":"result","subtype":"success","is_error":false,"stop_reason":"end_turn","modelUsage":{CUMULATIVE}{fields}}}"#
|
||||
|
|
@ -1838,7 +1797,6 @@ fn usage_the_result_does_not_report_is_billed_the_reservation() {
|
|||
let (kind, _, usage) = failure_of(&result);
|
||||
assert_eq!(kind, expected, "{line}");
|
||||
assert_eq!(usage, None, "{line}");
|
||||
assert_eq!(parts(&result).1.cost_micro_usd, reservation, "{line}");
|
||||
}
|
||||
for line in cases {
|
||||
let result = rig(vec![Script::lines(vec![
|
||||
|
|
@ -1850,22 +1808,20 @@ fn usage_the_result_does_not_report_is_billed_the_reservation() {
|
|||
let (kind, _, usage) = failure_of(&result);
|
||||
assert_eq!(kind, FailureKind::Provider, "{line}");
|
||||
assert_eq!(usage, None, "{line}");
|
||||
assert_eq!(parts(&result).1.cost_micro_usd, reservation, "{line}");
|
||||
assert!(result.transcript_items().is_empty(), "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn door_set_is_exactly_401_403_429() {
|
||||
// Ruling claude-code-plan-quota-fuse-2 with spend-bills-on-identity-not-
|
||||
// Ruling claude-code-plan-quota-fuse-2 with its
|
||||
// validity: a refusal at the door is charged nothing, for exactly the
|
||||
// statuses the provider cannot have billed (401, 403, 429) and only when
|
||||
// the result says its usage is explicitly empty. Every other shape is
|
||||
// billed the reservation. The 401 shape is a real claude 2.1.312 capture
|
||||
// the usage is unknown. The 401 shape is a real claude 2.1.312 capture
|
||||
// with a bogus token.
|
||||
let retry = r#"{"type":"system","subtype":"api_retry","error":"authentication_failed"}"#;
|
||||
let synthetic = r#"{"type":"assistant","api_error_status":401,"error":"authentication_failed","message":{"id":"e48001b7-cf4f-49b1-9810-db8fd7f73c73","model":"<synthetic>","stop_reason":"stop_sequence","content":[{"type":"text","text":"Failed to authenticate. API Error: 401 OAuth access token is invalid."}]}}"#;
|
||||
let reservation = reservation();
|
||||
let statuses: [Option<u16>; 9] = [
|
||||
Some(400),
|
||||
Some(401),
|
||||
|
|
@ -1904,10 +1860,8 @@ fn door_set_is_exactly_401_403_429() {
|
|||
let case = format!("{status:?} {shape}");
|
||||
if matches!(status, Some(401 | 403 | 429)) && shape == "empty" {
|
||||
assert_eq!(usage, Some(usage_zero()), "{case}");
|
||||
assert_eq!(parts(&result).1.cost_micro_usd, 0, "{case}");
|
||||
} else {
|
||||
assert_eq!(usage, None, "{case}");
|
||||
assert_eq!(parts(&result).1.cost_micro_usd, reservation, "{case}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1979,7 +1933,6 @@ fn prompt_file_lives_in_prompt_dir_exclusively() {
|
|||
let result = rig.run(request(vec![user("hi")]));
|
||||
let (kind, _, usage) = failure_of(&result);
|
||||
assert_eq!((kind, usage), (FailureKind::Provider, Some(usage_zero())));
|
||||
assert_eq!(parts(&result).1.cost_micro_usd, 0);
|
||||
assert_eq!(rig.spawns(), 0);
|
||||
}
|
||||
|
||||
|
|
@ -1996,11 +1949,6 @@ fn pin_is_checked_before_every_spawn() {
|
|||
let result = rig.run(request(vec![user("hi")]));
|
||||
let (kind, message, usage) = failure_of(&result);
|
||||
assert_eq!((kind, usage), (FailureKind::Provider, Some(usage_zero())));
|
||||
assert_eq!(
|
||||
parts(&result).1.cost_micro_usd,
|
||||
0,
|
||||
"billed nothing, not the reservation"
|
||||
);
|
||||
assert!(!message.contains(rig.dir.path().to_str().unwrap()));
|
||||
assert_eq!(rig.spawns(), 1, "no child for a binary off its pin");
|
||||
assert!(!rig.backend.binary_matches_pin());
|
||||
|
|
@ -2174,7 +2122,16 @@ fn quota_of(rig: &Rig) -> model_connector::PlanQuotaSnapshot {
|
|||
|
||||
/// The windows with their observation stamps zeroed, for comparing readings.
|
||||
fn readings(rig: &Rig) -> Vec<model_connector::PlanQuota> {
|
||||
let mut windows = quota_of(rig).windows;
|
||||
readings_at(rig, None)
|
||||
}
|
||||
|
||||
/// The held windows as of `now` (unix ms), or as of the wall clock when none.
|
||||
fn readings_at(rig: &Rig, now: Option<u64>) -> Vec<model_connector::PlanQuota> {
|
||||
let cell = rig.backend.quota();
|
||||
let mut windows = match now {
|
||||
Some(now) => cell.snapshot_at(now).windows,
|
||||
None => cell.snapshot().windows,
|
||||
};
|
||||
for window in &mut windows {
|
||||
window.observed_at_unix_ms = 0;
|
||||
}
|
||||
|
|
@ -2221,7 +2178,7 @@ fn rate_limit_event_updates_quota_cell() {
|
|||
|
||||
#[test]
|
||||
fn a_rejected_turn_still_reports_its_windows_and_a_bad_window_costs_only_itself() {
|
||||
let event = r#"{"type":"rate_limit_event","rate_limit_info":{"status":"rejected","unifiedWindows":{"five_hour":{"utilization":0.9996,"resetsAt":4102444800,"status":"rejected"},"seven_day":{"resetsAt":4102531200,"status":"allowed"},"idle":{"utilization":0,"resetsAt":4102444800,"status":"allowed"},"odd":{"utilization":"high","resetsAt":1,"status":"allowed"},"negative":{"utilization":-0.5,"resetsAt":1,"status":"allowed"}}}}"#;
|
||||
let event = r#"{"type":"rate_limit_event","rate_limit_info":{"status":"rejected","unifiedWindows":{"five_hour":{"utilization":0.9996,"resetsAt":4102444800,"status":"rejected"},"seven_day":{"utilization":0,"resetsAt":4102531200,"status":"allowed"},"seven_day_overage_included":{"utilization":1,"resetsAt":4102531200,"status":"rejected"},"idle":{"utilization":0,"resetsAt":4102444800,"status":"allowed"}}}}"#;
|
||||
let rig = rig(vec![Script::lines(vec![
|
||||
init_line(MODEL, SESSION),
|
||||
event.to_string(),
|
||||
|
|
@ -2231,12 +2188,12 @@ fn a_rejected_turn_still_reports_its_windows_and_a_bad_window_costs_only_itself(
|
|||
assert_eq!(kind, FailureKind::RateLimited);
|
||||
let mut rejected = window("five_hour", 1000, 4_102_444_800_000);
|
||||
rejected.status = "rejected".to_string();
|
||||
// Unknown is never zero: a window missing a field or of another type is
|
||||
// skipped, not read as empty.
|
||||
// A window at exactly zero use is a reading, and is kept.
|
||||
// A window at exactly zero use is a reading, and is kept. Only the two
|
||||
// windows pacing reads are taken: a per-model bucket that reads rejected
|
||||
// must not close every lease, and no other name is a window of the plan.
|
||||
assert_eq!(
|
||||
readings(&rig),
|
||||
vec![rejected, window("idle", 0, 4_102_444_800_000)]
|
||||
vec![rejected, window("seven_day", 0, 4_102_531_200_000)]
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -2695,7 +2652,6 @@ fn not_logged_in_line(status: &str, api_ms: u64, extra: &str) -> String {
|
|||
|
||||
#[test]
|
||||
fn a_result_that_made_no_api_call_bills_nothing() {
|
||||
let reservation = reservation();
|
||||
let empty = r#","model_usage_since_last_result":{}"#;
|
||||
let cases = [
|
||||
// (status field, api ms, usage field, billed nothing)
|
||||
|
|
@ -2703,7 +2659,7 @@ fn a_result_that_made_no_api_call_bills_nothing() {
|
|||
("", 0, empty, true),
|
||||
("", 0, "", true),
|
||||
// An API call was made, or the status names a server fault, or the
|
||||
// CLI reported rows: the reservation stands.
|
||||
// CLI reported rows: the usage stays unknown.
|
||||
("", 2300, empty, false),
|
||||
(r#""api_error_status":500,"#, 0, empty, false),
|
||||
(
|
||||
|
|
@ -2723,10 +2679,8 @@ fn a_result_that_made_no_api_call_bills_nothing() {
|
|||
let (_, _, usage) = failure_of(&result);
|
||||
if free {
|
||||
assert_eq!(usage, Some(usage_zero()), "{line}");
|
||||
assert_eq!(parts(&result).1.cost_micro_usd, 0, "{line}");
|
||||
} else {
|
||||
assert_eq!(usage, None, "{line}");
|
||||
assert_eq!(parts(&result).1.cost_micro_usd, reservation, "{line}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -2810,3 +2764,48 @@ fn a_turn_after_a_schema_turn_is_seeded_not_resumed() {
|
|||
assert!(!argv.iter().any(|a| a == "--resume"), "{argv:?}");
|
||||
assert!(!argv.iter().any(|a| a == "--json-schema"));
|
||||
}
|
||||
|
||||
// ---- the meter's call ----
|
||||
|
||||
/// One real call of the pinned CLI (2.1.312), captured on Yggdrasil on
|
||||
/// 2026-11-03 with the connector's own argv: haiku, no tools, the trivial
|
||||
/// prompt. Its `rate_limit_event` names only the week.
|
||||
const METER_CALL: &str = include_str!("../../tests/fixtures/claude-2.1.312-meter-call.jsonl");
|
||||
|
||||
#[test]
|
||||
fn the_meter_call_reads_the_week_from_a_real_captured_event() {
|
||||
let rig = rig(vec![Script::lines(
|
||||
METER_CALL.lines().map(str::to_string).collect(),
|
||||
)]);
|
||||
let usage = rig
|
||||
.backend
|
||||
.read_meter()
|
||||
.expect("the captured call completes");
|
||||
assert_eq!((usage.input_tokens, usage.output_tokens), (384, 4));
|
||||
// 0.06 of the week used; it resets at 1794261600 (unix s). Read as of an instant before
|
||||
// that reset, so the captured event stays a live reading whatever the wall clock says.
|
||||
assert_eq!(
|
||||
readings_at(&rig, Some(1_794_261_600_000 - 1)),
|
||||
vec![window("seven_day", 60, 1_794_261_600_000)]
|
||||
);
|
||||
let argv = rig.seen().argv;
|
||||
let after = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
|
||||
assert_eq!(after("--model"), METER_MODEL);
|
||||
assert_eq!(after("--tools"), "", "the call can use no tool");
|
||||
assert!(
|
||||
argv.iter().any(|a| a == "--no-session-persistence"),
|
||||
"the meter's transcript is nobody's to keep: {argv:?}"
|
||||
);
|
||||
assert_eq!(rig.spawns(), 1, "one child, never run again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_meter_call_names_its_kind_and_leaves_the_cell_alone() {
|
||||
let rig = rig(vec![Script::lines(vec![
|
||||
init_line(MODEL, SESSION),
|
||||
error_result_line(r#","api_error_status":500"#),
|
||||
])]);
|
||||
let failed = rig.backend.read_meter().expect_err("the call fails");
|
||||
assert!(!failed.is_empty() && !failed.contains(' '), "{failed}");
|
||||
assert!(quota_of(&rig).windows.is_empty());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,27 @@
|
|||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The provider tag the kit puts on every receipt and on the reasoning state
|
||||
/// of this backend. It is distinct from any Messages-API backend's tag, so the
|
||||
/// of the CLI backend. It is distinct from the Messages backend's tag, so the
|
||||
/// kit treats each backend's state as foreign to the other.
|
||||
pub(crate) const PROVIDER: &str = "claude-code";
|
||||
|
||||
/// Which credential the connector authenticates with. One choice for the whole
|
||||
/// connector, held in the systemd credential the config document's
|
||||
/// `token_credential` names.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ClaudeAuth {
|
||||
/// The subscription's OAuth token, given to the `claude` CLI child by
|
||||
/// [`ClaudeCodeBackend`](crate::ClaudeCodeBackend). The plan's usage is
|
||||
/// metered.
|
||||
OAuthToken,
|
||||
/// An Anthropic API key, used by [`MessagesBackend`](crate::MessagesBackend)
|
||||
/// over HTTP; the CLI is never spawned. Nothing is metered: a key has no
|
||||
/// subscription plan.
|
||||
ApiKey,
|
||||
}
|
||||
|
||||
/// What the connector's binary hands the backend. Every path is absolute.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ClaudeCodeConfig {
|
||||
|
|
@ -22,7 +38,7 @@ pub struct ClaudeCodeConfig {
|
|||
/// A directory the connector owns (mode 0700), where each call's system
|
||||
/// prompt is staged for the child.
|
||||
pub prompt_dir: PathBuf,
|
||||
/// The name of the systemd credential that holds the child's token, under
|
||||
/// The name of the systemd credential that holds the child's subscription token, under
|
||||
/// `$CREDENTIALS_DIRECTORY`.
|
||||
pub token_credential: String,
|
||||
/// The name of the systemd credential that holds the handle secret: the
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
//! run with; nothing in the connector's environment, flags or JSON can change
|
||||
//! them. Validation errors name a field and never echo a value.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::BTreeSet;
|
||||
use std::net::{SocketAddr, TcpListener};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
|
@ -11,8 +11,8 @@ use std::time::Duration;
|
|||
|
||||
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||
use model_connector::{
|
||||
CallerAdmission, CallerConfig, LeaseTurn, MIN_PAYLOAD_BYTES, ModelPrice, ProviderBackend,
|
||||
ServeError, ServeLimits, ServiceError, TransportService, load_admissions, serve_service,
|
||||
CallerAdmission, CallerConfig, LeaseTurn, MIN_PAYLOAD_BYTES, ProviderBackend, ServeError,
|
||||
ServeLimits, ServiceError, TransportService, load_admissions, serve_service,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
|
@ -22,8 +22,11 @@ use crate::backend::readiness;
|
|||
use crate::lease::{LeaseCaller, LeaseLimits, serve_leases, user_uid};
|
||||
#[cfg(target_os = "linux")]
|
||||
use crate::unit::SystemdUnits;
|
||||
#[cfg(unix)]
|
||||
use crate::meter;
|
||||
use crate::{
|
||||
ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, CredentialTokenSource, StderrSink,
|
||||
ClaudeAuth, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, CredentialTokenSource,
|
||||
MessagesBackend, MessagesConfig, StderrSink,
|
||||
};
|
||||
|
||||
const CONFIG_KEY: &str = "runtime";
|
||||
|
|
@ -31,8 +34,8 @@ const MODEL_PREFIX: &str = "claude-";
|
|||
|
||||
/// A unix account that may lease the subscription token for a Self run or a
|
||||
/// Persona turn, the unit its process must run in (`mind-self@<unit_instance>`
|
||||
/// or `mind-persona@<unit_instance>`, by `turn`), the configured caller whose
|
||||
/// spend window its leases reserve in, and what each lease reserves there.
|
||||
/// or `mind-persona@<unit_instance>`, by `turn`), and the configured caller
|
||||
/// whose name its leases carry.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LeaseCallerConfig {
|
||||
pub unix_user: String,
|
||||
|
|
@ -41,11 +44,10 @@ pub struct LeaseCallerConfig {
|
|||
/// or `mind-persona@`, its process must run in.
|
||||
pub turn: LeaseTurn,
|
||||
pub unit_instance: String,
|
||||
pub reservation_micro_usd: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(type = "gamecult.model_connector.claude_connector_config.v1")]
|
||||
#[cultcache(type = "gamecult.model_connector.claude_connector_config.v2")]
|
||||
pub struct ClaudeConnectorConfig {
|
||||
/// A loopback socket address.
|
||||
#[cultcache(key = 0)]
|
||||
|
|
@ -86,14 +88,10 @@ pub struct ClaudeConnectorConfig {
|
|||
#[cultcache(key = 16)]
|
||||
pub max_expiry_skew_ms: u64,
|
||||
/// Every caller of this connector: its own connection key and epoch, models,
|
||||
/// concurrency, payload and output bounds, and spend ceiling and window.
|
||||
/// concurrency, payload and output bounds.
|
||||
/// Ids are unique. Handles are bound to the caller that was given them.
|
||||
#[cultcache(key = 17)]
|
||||
pub callers: Vec<CallerConfig>,
|
||||
/// What each allowed model costs. The keys are the known list of models:
|
||||
/// ids exactly as the CLI reports them in its init event.
|
||||
#[cultcache(key = 18)]
|
||||
pub prices: BTreeMap<String, ModelPrice>,
|
||||
/// Where the Self-run lease socket is bound (a systemd RuntimeDirectory),
|
||||
/// or none when this connector lends no token.
|
||||
#[cultcache(key = 19)]
|
||||
|
|
@ -109,6 +107,11 @@ pub struct ClaudeConnectorConfig {
|
|||
/// least 32 bytes), the key every handle is authenticated with.
|
||||
#[cultcache(key = 22)]
|
||||
pub handle_secret_credential: String,
|
||||
/// Which credential `token_credential` holds: the subscription token, or an
|
||||
/// Anthropic API key. A document written before this field existed is refused at
|
||||
/// load (the canonical-form check): the installer authors the document again.
|
||||
#[cultcache(key = 23)]
|
||||
pub auth: ClaudeAuth,
|
||||
}
|
||||
|
||||
/// A refusal. It names the field or stage that failed and nothing the
|
||||
|
|
@ -143,7 +146,6 @@ impl From<ServeError> for ConfigError {
|
|||
ServeError::ConnectionKey(_) => Self::Unusable("connection_key_file"),
|
||||
ServeError::Service(error) => match error {
|
||||
ServiceError::ReplayStore(_) => Self::Unusable("replay_store"),
|
||||
ServiceError::UnpricedModel(_) => Self::Invalid("prices"),
|
||||
ServiceError::InvalidAdmission
|
||||
| ServiceError::DuplicateCaller
|
||||
| ServiceError::SharedCallerKey => Self::Invalid("callers"),
|
||||
|
|
@ -228,8 +230,6 @@ impl ClaudeConnectorConfig {
|
|||
if caller.max_concurrent_requests == 0
|
||||
|| caller.max_payload_bytes < MIN_PAYLOAD_BYTES
|
||||
|| caller.max_output_tokens == 0
|
||||
|| caller.spend_ceiling_micro_usd == 0
|
||||
|| caller.spend_window_ms == 0
|
||||
{
|
||||
return Err(ConfigError::Invalid("caller bounds"));
|
||||
}
|
||||
|
|
@ -238,26 +238,23 @@ impl ClaudeConnectorConfig {
|
|||
}
|
||||
let mut seen = BTreeSet::new();
|
||||
for model in &caller.allowed_models {
|
||||
if !has_model_id_form(model)
|
||||
|| !seen.insert(model.as_str())
|
||||
|| !self.prices.contains_key(model)
|
||||
{
|
||||
if !has_model_id_form(model) || !seen.insert(model.as_str()) {
|
||||
return Err(ConfigError::Invalid("allowed_models"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !self
|
||||
.prices
|
||||
.iter()
|
||||
.all(|(model, price)| has_model_id_form(model) && is_fully_priced(price))
|
||||
{
|
||||
return Err(ConfigError::Invalid("prices"));
|
||||
}
|
||||
self.validate_leases()?;
|
||||
Ok(listen)
|
||||
}
|
||||
|
||||
fn validate_leases(&self) -> Result<(), ConfigError> {
|
||||
// A key has no plan and is never lent: no lease socket, no lease row, whatever else the
|
||||
// document says. Personas call with their own connection keys and need neither.
|
||||
if self.auth == ClaudeAuth::ApiKey
|
||||
&& (self.lease_socket.is_some() || !self.lease_callers.is_empty())
|
||||
{
|
||||
return Err(ConfigError::Invalid("auth"));
|
||||
}
|
||||
let Some(socket) = &self.lease_socket else {
|
||||
return if self.lease_callers.is_empty() {
|
||||
Ok(())
|
||||
|
|
@ -278,11 +275,7 @@ impl ClaudeConnectorConfig {
|
|||
&& self
|
||||
.callers
|
||||
.iter()
|
||||
.find(|caller| caller.caller_runtime_id == lease.caller_id)
|
||||
.is_some_and(|caller| {
|
||||
(1..=caller.spend_ceiling_micro_usd)
|
||||
.contains(&lease.reservation_micro_usd)
|
||||
})
|
||||
.any(|caller| caller.caller_runtime_id == lease.caller_id)
|
||||
&& is_unit_instance(&lease.unit_instance)
|
||||
&& users.insert(lease.unix_user.as_str())
|
||||
})
|
||||
|
|
@ -311,6 +304,14 @@ impl ClaudeConnectorConfig {
|
|||
}
|
||||
}
|
||||
|
||||
fn messages_config(&self) -> MessagesConfig {
|
||||
MessagesConfig {
|
||||
key_credential: self.token_credential.clone(),
|
||||
deadline: Duration::from_millis(self.deadline_ms),
|
||||
max_response_bytes: self.max_total_bytes,
|
||||
}
|
||||
}
|
||||
|
||||
fn serve_limits(&self) -> ServeLimits {
|
||||
ServeLimits {
|
||||
max_frame_bytes: self.max_frame_bytes,
|
||||
|
|
@ -336,8 +337,7 @@ fn is_trimmed_nonempty(text: &str) -> bool {
|
|||
/// The loose shape of a model id, only to catch typos:
|
||||
/// `claude-<family>-<major>`, then an optional `-<minor>` and an optional
|
||||
/// `-YYYYMMDD`, the family lowercase letters. No shape can tell an alias from
|
||||
/// a canonical id, so the known list is the price table's keys (ruling
|
||||
/// claude-model-ids-from-price-table); an alias that slips in fails its first
|
||||
/// a canonical id, so the known list is `allowed_models` itself; an alias that slips in fails its first
|
||||
/// call, when the stream's `init.model` differs from the request.
|
||||
fn has_model_id_form(model: &str) -> bool {
|
||||
let Some(rest) = model.strip_prefix(MODEL_PREFIX) else {
|
||||
|
|
@ -365,26 +365,6 @@ fn has_model_id_form(model: &str) -> bool {
|
|||
&& after_ok
|
||||
}
|
||||
|
||||
/// A price is a fuse only if every component it bills is nonzero: a zero rate
|
||||
/// lets a call cost nothing against the caller's ceiling.
|
||||
fn is_fully_priced(price: &ModelPrice) -> bool {
|
||||
let long = price.long_context.map(|long| long.rates);
|
||||
[Some(price.rates), long]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.all(|rates| {
|
||||
[
|
||||
rates.input,
|
||||
rates.cache_write_short,
|
||||
rates.cache_write_long,
|
||||
rates.cache_read,
|
||||
rates.output,
|
||||
]
|
||||
.iter()
|
||||
.all(|rate| *rate > 0)
|
||||
})
|
||||
}
|
||||
|
||||
/// One file name under `$CREDENTIALS_DIRECTORY`, never a path.
|
||||
fn is_credential_name(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
|
|
@ -477,18 +457,27 @@ impl<W: std::io::Write + Send> StderrSink for LogSink<W> {
|
|||
/// key and the frame and connection bounds. Returns the admitted callers.
|
||||
fn readiness_of(config: &ClaudeConnectorConfig) -> Result<Vec<CallerAdmission>, ConfigError> {
|
||||
config.validate()?;
|
||||
#[cfg(unix)]
|
||||
check_prompt_dir(&config.prompt_dir)?;
|
||||
let admissions = load_admissions(&config.callers)?;
|
||||
config.serve_limits().validate(&admissions)?;
|
||||
let backend = config.backend_config();
|
||||
readiness(
|
||||
&backend,
|
||||
&CredentialTokenSource::from_environment(backend.token_credential.clone()),
|
||||
&CredentialTokenSource::from_environment(backend.handle_secret_credential.clone())
|
||||
.for_field("handle_secret_credential"),
|
||||
)
|
||||
.map_err(ConfigError::Unusable)?;
|
||||
match config.auth {
|
||||
// The CLI is never spawned on a key: its binary, directories and
|
||||
// handle secret are not this backend's, only the key is.
|
||||
ClaudeAuth::ApiKey => MessagesBackend::new(config.messages_config())
|
||||
.ready()
|
||||
.map_err(ConfigError::Unusable)?,
|
||||
ClaudeAuth::OAuthToken => {
|
||||
#[cfg(unix)]
|
||||
check_prompt_dir(&config.prompt_dir)?;
|
||||
let backend = config.backend_config();
|
||||
readiness(
|
||||
&backend,
|
||||
&CredentialTokenSource::from_environment(backend.token_credential.clone()),
|
||||
&CredentialTokenSource::from_environment(backend.handle_secret_credential.clone())
|
||||
.for_field("handle_secret_credential"),
|
||||
)
|
||||
.map_err(ConfigError::Unusable)?;
|
||||
}
|
||||
}
|
||||
if config.lease_socket.is_some() {
|
||||
lease_callers_of(config)?;
|
||||
}
|
||||
|
|
@ -509,7 +498,6 @@ fn lease_callers_of(config: &ClaudeConnectorConfig) -> Result<Vec<LeaseCaller>,
|
|||
caller_id: lease.caller_id.clone(),
|
||||
turn: lease.turn,
|
||||
unit_instance: lease.unit_instance.clone(),
|
||||
reservation_micro_usd: lease.reservation_micro_usd,
|
||||
})
|
||||
.ok_or(ConfigError::Unusable("lease_callers"))
|
||||
})
|
||||
|
|
@ -531,6 +519,7 @@ fn start_leases(
|
|||
config: &ClaudeConnectorConfig,
|
||||
socket: &Path,
|
||||
service: Arc<Mutex<TransportService>>,
|
||||
quota: Arc<crate::QuotaCell>,
|
||||
) -> Result<(), ConfigError> {
|
||||
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
|
||||
use std::os::unix::net::UnixListener;
|
||||
|
|
@ -559,6 +548,7 @@ fn start_leases(
|
|||
callers,
|
||||
limits,
|
||||
service,
|
||||
quota,
|
||||
tokens,
|
||||
Arc::new(SystemdUnits::system()),
|
||||
);
|
||||
|
|
@ -577,27 +567,54 @@ pub fn check_ready(config: &ClaudeConnectorConfig) -> Result<(), ConfigError> {
|
|||
/// Loads the document and serves until the listener fails.
|
||||
#[cfg(unix)]
|
||||
pub fn serve_config(path: &Path) -> Result<(), ConfigError> {
|
||||
serve_config_with(path, |_| ())
|
||||
}
|
||||
|
||||
/// [`serve_config`] handing the quota cell to `started` once the meter runs:
|
||||
/// a test stands in for the swarm's lease requests only through here.
|
||||
#[cfg(unix)]
|
||||
fn serve_config_with(
|
||||
path: &Path,
|
||||
started: impl FnOnce(&Arc<crate::QuotaCell>),
|
||||
) -> Result<(), ConfigError> {
|
||||
let config = load_config(path)?;
|
||||
let admissions = readiness_of(&config)?;
|
||||
let listen = config.validate()?;
|
||||
let backend = Arc::new(ClaudeCodeBackend::new(
|
||||
config.backend_config(),
|
||||
Box::new(LogSink(std::sync::Mutex::new(std::io::stderr()))),
|
||||
));
|
||||
// The CLI backend on a subscription token, the Messages backend on a key.
|
||||
let claude = (config.auth == ClaudeAuth::OAuthToken).then(|| {
|
||||
Arc::new(ClaudeCodeBackend::new(
|
||||
config.backend_config(),
|
||||
Box::new(LogSink(std::sync::Mutex::new(std::io::stderr()))),
|
||||
))
|
||||
});
|
||||
let backend: Arc<dyn ProviderBackend> = match &claude {
|
||||
Some(claude) => claude.clone(),
|
||||
None => Arc::new(MessagesBackend::new(config.messages_config())),
|
||||
};
|
||||
let listener = TcpListener::bind(listen).map_err(|_| ConfigError::Listen)?;
|
||||
let service = Arc::new(Mutex::new(
|
||||
TransportService::open(
|
||||
&config.replay_store,
|
||||
backend.provider(),
|
||||
config.prices.clone(),
|
||||
admissions,
|
||||
config.max_expiry_skew_ms,
|
||||
)
|
||||
.map_err(|error| ConfigError::from(ServeError::Service(error)))?,
|
||||
));
|
||||
// The meter is running before the first lease can ask, so that lease can
|
||||
// wait for its first read. An API key has no subscription plan to read:
|
||||
// no meter runs, the cell stays empty, and no lease waits for it.
|
||||
let quota = claude
|
||||
.as_ref()
|
||||
.map_or_else(|| Arc::new(crate::QuotaCell::new()), |claude| claude.quota());
|
||||
if let Some(claude) = &claude {
|
||||
meter::start(quota.clone(), Box::new(claude.clone()))
|
||||
.map_err(|_| ConfigError::Serving("meter"))?;
|
||||
}
|
||||
started("a);
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Some(socket) = &config.lease_socket {
|
||||
start_leases(&config, socket, service.clone())?;
|
||||
start_leases(&config, socket, service.clone(), quota.clone())?;
|
||||
}
|
||||
serve_service(listener, config.serve_limits(), service, backend)?;
|
||||
Ok(())
|
||||
|
|
@ -607,6 +624,8 @@ pub fn serve_config(path: &Path) -> Result<(), ConfigError> {
|
|||
mod tests {
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use sha2::Digest;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A log that a test can read back.
|
||||
|
|
@ -623,6 +642,105 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
/// `serve` starts the meter beside the listener, wired to the backend's own
|
||||
/// cell: it makes no call while nobody asks, and once a lease is asked for
|
||||
/// it runs the claude binary and serve stays up. The binary is a script
|
||||
/// that replays a real captured call.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn serve_config_starts_the_meter_and_stays_up() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
const CALL: &str = include_str!("../tests/fixtures/claude-2.1.312-meter-call.jsonl");
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("claude-connector-serve-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let at = |name: &str| dir.join(name);
|
||||
for sub in ["work", "home", "prompts", "credentials"] {
|
||||
std::fs::create_dir_all(at(sub)).unwrap();
|
||||
}
|
||||
std::fs::set_permissions(at("prompts"), std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
std::fs::write(at("call.jsonl"), CALL).unwrap();
|
||||
let script = format!(
|
||||
"#!/bin/sh\ncat > /dev/null\necho spawned >> '{}'\ncat '{}'\n",
|
||||
at("spawned").display(),
|
||||
at("call.jsonl").display()
|
||||
);
|
||||
std::fs::write(at("claude"), &script).unwrap();
|
||||
std::fs::set_permissions(at("claude"), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
std::fs::write(at("caller.key"), "k".repeat(48)).unwrap();
|
||||
std::fs::write(at("credentials/claude-token"), "sk-ant-oat01-fake-token").unwrap();
|
||||
std::fs::write(at("credentials/claude-handle-secret"), "s".repeat(48)).unwrap();
|
||||
let config = ClaudeConnectorConfig {
|
||||
listen: "127.0.0.1:0".to_string(),
|
||||
replay_store: at("replay.cc"),
|
||||
claude_binary: at("claude"),
|
||||
claude_binary_sha256: sha2::Sha256::digest(script.as_bytes()).into(),
|
||||
work_dir: at("work"),
|
||||
config_dir: at("home"),
|
||||
prompt_dir: at("prompts"),
|
||||
instance: "persona-a".to_string(),
|
||||
token_credential: "claude-token".to_string(),
|
||||
handle_secret_credential: "claude-handle-secret".to_string(),
|
||||
auth: ClaudeAuth::OAuthToken,
|
||||
deadline_ms: 600_000,
|
||||
max_line_bytes: 4 << 20,
|
||||
max_total_bytes: 64 << 20,
|
||||
stderr_tail_bytes: 8192,
|
||||
max_frame_bytes: 2 << 20,
|
||||
max_connections: 8,
|
||||
socket_timeout_ms: 10_000,
|
||||
max_expiry_skew_ms: 300_000,
|
||||
callers: vec![CallerConfig {
|
||||
caller_runtime_id: "persona-a-caller".to_string(),
|
||||
connection_key_file: at("caller.key"),
|
||||
connection_key_epoch: 1,
|
||||
allowed_models: vec!["claude-haiku-5-5".to_string()],
|
||||
max_concurrent_requests: 4,
|
||||
max_payload_bytes: 1 << 20,
|
||||
max_output_tokens: 32_768,
|
||||
}],
|
||||
lease_socket: None,
|
||||
lease_callers: Vec::new(),
|
||||
lease_max_ms: 3_600_000,
|
||||
};
|
||||
write_config(&at("connector.cc"), &config).unwrap();
|
||||
// SAFETY: set once, to a directory only this test reads, before the
|
||||
// serve thread it starts.
|
||||
unsafe { std::env::set_var("CREDENTIALS_DIRECTORY", at("credentials")) };
|
||||
|
||||
let path = at("connector.cc");
|
||||
let lease = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
let swarm = lease.clone();
|
||||
let served = std::thread::spawn(move || {
|
||||
serve_config_with(&path, |cell| {
|
||||
*swarm.lock().unwrap() = Some(cell.clone());
|
||||
})
|
||||
});
|
||||
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(30);
|
||||
let cell = loop {
|
||||
if let Some(cell) = lease.lock().unwrap().clone() {
|
||||
break cell;
|
||||
}
|
||||
assert!(std::time::Instant::now() < deadline, "serve never started");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
assert!(!at("spawned").exists(), "a quiet swarm spends nothing");
|
||||
let _lease = cell.asking();
|
||||
|
||||
while !at("spawned").exists() {
|
||||
assert!(
|
||||
std::time::Instant::now() < deadline,
|
||||
"the meter never ran the claude binary"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
assert!(!served.is_finished(), "serve returned after starting the meter");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_errors_name_a_field_or_stage_and_never_a_stored_value() {
|
||||
const CANARY: &str = "canary-path-8e2a";
|
||||
|
|
@ -643,10 +761,6 @@ mod tests {
|
|||
ServeError::Service(ServiceError::ReplayStore(format!("{CANARY}/replay.cc"))),
|
||||
"replay_store",
|
||||
),
|
||||
(
|
||||
ServeError::Service(ServiceError::UnpricedModel(CANARY.to_string())),
|
||||
"prices",
|
||||
),
|
||||
(
|
||||
ServeError::Service(ServiceError::InvalidAdmission),
|
||||
"callers",
|
||||
|
|
|
|||
|
|
@ -13,13 +13,13 @@ use model_connector::{ProviderRequest, ReasoningEffort};
|
|||
use crate::config::ClaudeCodeConfig;
|
||||
use crate::handle::Plan;
|
||||
|
||||
/// The variable that tells the CLI which file descriptor holds its credential.
|
||||
/// The token itself never enters the environment: the process port writes it
|
||||
/// into a pipe and hands the child the read end at [`TOKEN_FD`].
|
||||
pub(crate) const TOKEN_FD_VAR: &str = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR";
|
||||
/// The descriptor number the child finds the token pipe at: the first one
|
||||
/// after stdin, stdout and stderr.
|
||||
/// The credential never enters the environment:
|
||||
/// the process port writes it into a pipe and hands the child the read end at
|
||||
/// [`TOKEN_FD`], the first descriptor after stdin, stdout and stderr, and the
|
||||
/// environment names that descriptor.
|
||||
pub(crate) const TOKEN_FD: i32 = 3;
|
||||
/// The variable that tells the CLI which descriptor holds the subscription token.
|
||||
const TOKEN_FD_VAR: &str = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR";
|
||||
const CHILD_PATH: &str = "/usr/local/bin:/usr/bin:/bin";
|
||||
|
||||
/// The environment of the child: exactly these names and nothing inherited.
|
||||
|
|
@ -107,13 +107,15 @@ fn effort(effort: ReasoningEffort) -> &'static str {
|
|||
/// rather than an argument because one argument is capped near 128 KiB
|
||||
/// (E2BIG) and instructions are not, the child has
|
||||
/// no tools, no MCP servers, no settings, no slash commands and nobody to ask
|
||||
/// for permission, and a resume always forks. A request's output schema goes
|
||||
/// to the CLI as `--json-schema`; without one the flag is absent.
|
||||
/// for permission, and a resume always forks. An ephemeral call (the
|
||||
/// meter's) keeps no session on disk. A request's output schema goes to the
|
||||
/// CLI as `--json-schema`; without one the flag is absent.
|
||||
pub(crate) fn argv(
|
||||
config: &ClaudeCodeConfig,
|
||||
request: &ProviderRequest,
|
||||
plan: &Plan,
|
||||
system_prompt_file: &Path,
|
||||
ephemeral: bool,
|
||||
) -> Vec<String> {
|
||||
let mut argv: Vec<String> = [
|
||||
config.claude_binary.to_string_lossy().as_ref(),
|
||||
|
|
@ -139,6 +141,9 @@ pub(crate) fn argv(
|
|||
.into_iter()
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
if ephemeral {
|
||||
argv.push("--no-session-persistence".to_string());
|
||||
}
|
||||
if let Some(level) = request.reasoning_effort {
|
||||
argv.extend(["--effort".to_string(), effort(level).to_string()]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,18 @@
|
|||
//! The Self-run credential lease. The connector is the only holder of the
|
||||
//! subscription token and the one owner of Self-run admission, reservation and
|
||||
//! the spend ledger (rulings self-runs-through-connector,
|
||||
//! self-run-credential-lease and self-run-lease-billing-and-binding). A Self
|
||||
//! run asks over a unix socket for a lease. The connector decides who may ask
|
||||
//! (the peer's uid, and the systemd unit invocation its process runs in),
|
||||
//! reserves its own configured amount in the caller's spend window, and only
|
||||
//! then hands back one pipe fd that holds the token. The run settles with the
|
||||
//! per-model usage it reports, and the connector bills that at true cost,
|
||||
//! uncapped; a run that vanishes or lets its lease expire is billed the whole
|
||||
//! reservation. Nothing the run says about itself decides who it is, what it
|
||||
//! reserves, or what the plan allows.
|
||||
//! subscription token and the one owner of Self-run admission (rulings
|
||||
//! self-runs-through-connector and self-run-credential-lease). A Self run asks
|
||||
//! over a unix socket for a lease. The connector decides who may ask (the
|
||||
//! peer's uid, and the systemd unit invocation its process runs in), and hands
|
||||
//! back one pipe fd that holds the token, with the plan's usage windows. The
|
||||
//! lease lasts while the holder keeps the socket open: it ends when the holder
|
||||
//! closes it, when its unit invocation ends, or when its expiry passes. Nothing
|
||||
//! is reserved and nothing is billed; the only usage-derived refusal is the
|
||||
//! provider's own, repeated until its own reset. Nothing the run says about
|
||||
//! itself decides who it is or what the plan allows.
|
||||
//!
|
||||
//! The same socket also answers a usage readout to any peer that can reach it
|
||||
//! (the claude-lease group): no lease, no caller check, no token read and no
|
||||
//! wake of the meter. Usage is state every Mind reads.
|
||||
//!
|
||||
//! The token exists in this process only as the value the token source returns
|
||||
//! and in the pipe. It is not in an environment, an argument, a file, a log or
|
||||
|
|
@ -28,12 +31,11 @@ use std::thread;
|
|||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use model_connector::{
|
||||
LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseSettlement, LeaseTurn, LeaseUse, ModelUsage,
|
||||
TransportService,
|
||||
LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseTurn, PlanQuota, TransportService, UsageReadout,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::TokenSource;
|
||||
use crate::{QuotaCell, TokenSource};
|
||||
|
||||
/// The largest frame either side sends or accepts, in bytes. It is wire
|
||||
/// contract: a Huginn client sizes against it, so it is pinned as a literal.
|
||||
|
|
@ -50,30 +52,36 @@ pub enum LeaseMessage {
|
|||
/// holds the token, its write end closed.
|
||||
ClaudeLeaseGrant(LeaseGranted),
|
||||
ClaudeLeaseRefusal(LeaseRefused),
|
||||
ClaudeLeaseSettle(LeaseSettle),
|
||||
ClaudeLeaseSettled(LeaseSettled),
|
||||
/// Asks for the plan's usage windows. Opens no lease.
|
||||
ClaudeUsageReadoutRequest(LeaseUsageReadoutRequest),
|
||||
/// The answer to a readout request: the cell's windows as of now, no fd.
|
||||
ClaudeUsageReadout(UsageReadout),
|
||||
}
|
||||
|
||||
/// A request names only when the lease ends. Who asks, and what is reserved,
|
||||
/// are the connector's to know.
|
||||
/// A request names only when the lease ends. Who asks is the connector's to know.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LeaseRequest {
|
||||
pub expires_at_unix_ms: u64,
|
||||
}
|
||||
|
||||
/// A readout request names nothing: the answer is the same for every asker.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LeaseUsageReadoutRequest {}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LeaseGranted {
|
||||
pub lease_id: String,
|
||||
pub reserved_micro_usd: u64,
|
||||
/// The plan's usage windows as the connector last saw them, so the run
|
||||
/// can read its own burn.
|
||||
pub plan_quota: Vec<PlanQuota>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum LeaseRefusalKind {
|
||||
SpendCeiling,
|
||||
CostBound,
|
||||
UnknownCaller,
|
||||
Expired,
|
||||
Busy,
|
||||
ProviderRejected,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -82,20 +90,6 @@ pub struct LeaseRefused {
|
|||
pub detail: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LeaseSettle {
|
||||
pub lease_id: String,
|
||||
/// What the run used of each model, as the run reports it.
|
||||
pub usage: Vec<ModelUsage>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LeaseSettled {
|
||||
pub billed_micro_usd: u64,
|
||||
/// How far the bill passed the reservation; zero when it did not.
|
||||
pub overrun_micro_usd: u64,
|
||||
}
|
||||
|
||||
/// A frame: the length, then the named-map MessagePack of `message`.
|
||||
pub fn encode_frame(message: &LeaseMessage) -> Vec<u8> {
|
||||
// Every field of the message is plain data, so encoding cannot fail.
|
||||
|
|
@ -180,8 +174,8 @@ fn read_message(stream: &mut impl Bounded, deadline: Instant) -> io::Result<Leas
|
|||
const PIPE_BUF: usize = 4096;
|
||||
|
||||
/// A unix account allowed to lease, the unit its process must run in (the
|
||||
/// Self or the Persona unit of its instance, by `turn`), and the caller whose
|
||||
/// spend window its leases reserve in.
|
||||
/// Self or the Persona unit of its instance, by `turn`), and the
|
||||
/// caller whose name its leases carry.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct LeaseCaller {
|
||||
pub uid: u32,
|
||||
|
|
@ -191,8 +185,6 @@ pub struct LeaseCaller {
|
|||
/// The `<instance>` of `mind-self@<instance>.service` or
|
||||
/// `mind-persona@<instance>.service`.
|
||||
pub unit_instance: String,
|
||||
/// What each of this caller's leases reserves, whatever the run asks.
|
||||
pub reservation_micro_usd: u64,
|
||||
}
|
||||
|
||||
impl LeaseCaller {
|
||||
|
|
@ -400,12 +392,25 @@ struct Lender {
|
|||
callers: Vec<LeaseCaller>,
|
||||
limits: LeaseLimits,
|
||||
service: Arc<Mutex<TransportService>>,
|
||||
quota: Arc<QuotaCell>,
|
||||
tokens: Arc<dyn TokenSource>,
|
||||
units: Arc<dyn PeerUnits>,
|
||||
/// Connections holding or waiting on a lease, at most `max_connections`.
|
||||
leases: Arc<AtomicUsize>,
|
||||
/// Connections being answered a readout, at most `READOUT_CONNECTIONS`.
|
||||
readouts: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
/// Serves leases on `listener` until it fails. Each connection is one lease:
|
||||
/// request, then grant or refusal, then (after a grant) settle. A caller is
|
||||
/// How many usage readouts are served at once, beside the leases. A readout
|
||||
/// holds nothing, so a few suffice, and a flood of them cannot take a lease's
|
||||
/// slot: the accept loop admits `max_connections` plus this many.
|
||||
const READOUT_CONNECTIONS: usize = 4;
|
||||
|
||||
/// Serves leases on `listener` until it fails. Each connection is one lease or
|
||||
/// one usage readout. A lease: request, then grant or refusal, then (after a
|
||||
/// grant) the hold. A readout: request, then one frame, then close; its reach
|
||||
/// is the socket's group, and it reads the plan's windows without waking the
|
||||
/// meter. A caller is
|
||||
/// the account whose uid the kernel reports for the connection, and only a
|
||||
/// process in that caller's unit may lease, once per unit invocation for a Self
|
||||
/// run and once per turn for a Persona; no
|
||||
|
|
@ -415,6 +420,7 @@ pub fn serve_leases(
|
|||
callers: Vec<LeaseCaller>,
|
||||
limits: LeaseLimits,
|
||||
service: Arc<Mutex<TransportService>>,
|
||||
quota: Arc<QuotaCell>,
|
||||
tokens: Arc<dyn TokenSource>,
|
||||
units: Arc<dyn PeerUnits>,
|
||||
) -> io::Result<()> {
|
||||
|
|
@ -422,13 +428,17 @@ pub fn serve_leases(
|
|||
callers,
|
||||
limits,
|
||||
service,
|
||||
quota,
|
||||
tokens,
|
||||
units,
|
||||
leases: Arc::new(AtomicUsize::new(0)),
|
||||
readouts: Arc::new(AtomicUsize::new(0)),
|
||||
});
|
||||
let active = Arc::new(AtomicUsize::new(0));
|
||||
loop {
|
||||
let (stream, _) = listener.accept()?;
|
||||
let Some(permit) = Permit::acquire(&active, limits.max_connections) else {
|
||||
let admitted = limits.max_connections.saturating_add(READOUT_CONNECTIONS);
|
||||
let Some(permit) = Permit::acquire(&active, admitted) else {
|
||||
continue;
|
||||
};
|
||||
let lender = lender.clone();
|
||||
|
|
@ -437,22 +447,46 @@ pub fn serve_leases(
|
|||
.spawn(move || {
|
||||
let _permit = permit;
|
||||
// A connection that fails is dropped; the lease it may have
|
||||
// held is settled inside `lend`.
|
||||
let _ = lender.lend(stream);
|
||||
// held is ended inside `lend`.
|
||||
let _ = lender.serve_one(stream);
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
impl Lender {
|
||||
fn lend(&self, mut stream: UnixStream) -> io::Result<()> {
|
||||
fn serve_one(&self, mut stream: UnixStream) -> io::Result<()> {
|
||||
stream.set_write_timeout(Some(self.limits.socket_timeout))?;
|
||||
let peer = peer_credentials(&stream)?;
|
||||
let request_deadline = Instant::now() + self.limits.socket_timeout;
|
||||
let LeaseMessage::ClaudeLeaseRequest(request) =
|
||||
read_message(&mut stream, request_deadline)?
|
||||
else {
|
||||
return Err(io::Error::from(io::ErrorKind::InvalidData));
|
||||
};
|
||||
match read_message(&mut stream, request_deadline)? {
|
||||
LeaseMessage::ClaudeLeaseRequest(request) => {
|
||||
// A lease over the limit is dropped unanswered; readouts
|
||||
// never count against it.
|
||||
let Some(_slot) = Permit::acquire(&self.leases, self.limits.max_connections) else {
|
||||
return Ok(());
|
||||
};
|
||||
let peer = peer_credentials(&stream)?;
|
||||
self.lend(stream, peer, request)
|
||||
}
|
||||
LeaseMessage::ClaudeUsageReadoutRequest(_) => {
|
||||
let Some(_slot) = Permit::acquire(&self.readouts, READOUT_CONNECTIONS) else {
|
||||
return refuse(
|
||||
&mut stream,
|
||||
LeaseRefusalKind::Busy,
|
||||
"too many usage readouts at once",
|
||||
);
|
||||
};
|
||||
stream.write_all(&encode_frame(&readout(&self.quota, unix_ms())))
|
||||
}
|
||||
_ => Err(io::Error::from(io::ErrorKind::InvalidData)),
|
||||
}
|
||||
}
|
||||
|
||||
fn lend(
|
||||
&self,
|
||||
mut stream: UnixStream,
|
||||
peer: PeerCredentials,
|
||||
request: LeaseRequest,
|
||||
) -> io::Result<()> {
|
||||
let Some(caller) = self.callers.iter().find(|caller| caller.uid == peer.uid) else {
|
||||
return refuse(
|
||||
&mut stream,
|
||||
|
|
@ -484,9 +518,15 @@ impl Lender {
|
|||
"the expiry is not in the future or is past the lease bound",
|
||||
);
|
||||
}
|
||||
// The reservation is claimed in the ledger before the token is read,
|
||||
// let alone lent. A ledger that fails closes the connection with no
|
||||
// answer and no lease.
|
||||
// The lease is claimed before the token is read, let alone lent. The
|
||||
// plan the refusal reads is the one this process last observed, but a
|
||||
// cell with no weekly reading (a restart empties it) gets the meter's
|
||||
// first read, bounded, before the lease is lent "unobserved" for its
|
||||
// whole life. The request is the swarm's sign of life, however it
|
||||
// ends: the meter reads while one is held or lately asked for.
|
||||
let _asking = self.quota.asking();
|
||||
let plan = self.quota.snapshot_with_week(FIRST_READ_WAIT);
|
||||
let now = unix_ms();
|
||||
let admission = self
|
||||
.service
|
||||
.lock()
|
||||
|
|
@ -495,120 +535,144 @@ impl Lender {
|
|||
&caller.caller_id,
|
||||
caller.turn,
|
||||
&invocation.invocation_id,
|
||||
caller.reservation_micro_usd,
|
||||
request.expires_at_unix_ms,
|
||||
now,
|
||||
&plan,
|
||||
)
|
||||
.map_err(|_| io::Error::other("ledger"))?;
|
||||
.map_err(|_| io::Error::other("lease"))?;
|
||||
let grant = match admission {
|
||||
LeaseAdmission::Granted(grant) => grant,
|
||||
LeaseAdmission::Refused(why) => {
|
||||
let (kind, detail) = match why {
|
||||
LeaseRefusal::SpendCeiling => (
|
||||
LeaseRefusalKind::SpendCeiling,
|
||||
"the window cannot hold this reservation",
|
||||
),
|
||||
LeaseRefusal::CostBound => (
|
||||
LeaseRefusalKind::CostBound,
|
||||
"the reservation must be above zero",
|
||||
),
|
||||
LeaseRefusal::UnknownCaller => (
|
||||
LeaseRefusalKind::UnknownCaller,
|
||||
"this account is bound to no admitted caller",
|
||||
),
|
||||
LeaseRefusal::Busy => (
|
||||
LeaseRefusalKind::Busy,
|
||||
"a lease is open for this caller or this unit invocation leased",
|
||||
"a lease is open for this caller or this unit invocation",
|
||||
),
|
||||
LeaseRefusal::ProviderRejected => (
|
||||
LeaseRefusalKind::ProviderRejected,
|
||||
"the provider is refusing until its own reset",
|
||||
),
|
||||
};
|
||||
return refuse(&mut stream, kind, detail);
|
||||
}
|
||||
};
|
||||
self.hold(stream, caller, &grant, request.expires_at_unix_ms)
|
||||
self.hold(
|
||||
stream,
|
||||
caller,
|
||||
&grant,
|
||||
&invocation,
|
||||
peer.process,
|
||||
request.expires_at_unix_ms,
|
||||
plan.windows,
|
||||
)
|
||||
}
|
||||
|
||||
/// Everything after a reservation exists: lend the token, then settle the
|
||||
/// lease exactly once whatever happens.
|
||||
/// Everything after a lease exists: lend the token, then keep the lease
|
||||
/// while its holder keeps the socket and its unit invocation, and end it
|
||||
/// exactly once whatever happens.
|
||||
// One argument per fact the held lease binds.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn hold(
|
||||
&self,
|
||||
mut stream: UnixStream,
|
||||
caller: &LeaseCaller,
|
||||
grant: &LeaseGrant,
|
||||
invocation: &PeerUnit,
|
||||
process: Option<OwnedFd>,
|
||||
expires_at_unix_ms: u64,
|
||||
plan_quota: Vec<PlanQuota>,
|
||||
) -> io::Result<()> {
|
||||
// A token that cannot be read or piped was never lent: nothing was
|
||||
// used, so nothing is billed.
|
||||
let held = self.keep(
|
||||
&mut stream,
|
||||
caller,
|
||||
grant,
|
||||
invocation,
|
||||
process.as_ref(),
|
||||
expires_at_unix_ms,
|
||||
plan_quota,
|
||||
);
|
||||
self.service
|
||||
.lock()
|
||||
.map_err(|_| io::Error::other("service lock"))?
|
||||
.end_lease(&caller.caller_id, &grant.lease_id);
|
||||
held
|
||||
}
|
||||
|
||||
// One argument per fact the held lease binds.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn keep(
|
||||
&self,
|
||||
stream: &mut UnixStream,
|
||||
caller: &LeaseCaller,
|
||||
grant: &LeaseGrant,
|
||||
invocation: &PeerUnit,
|
||||
process: Option<&OwnedFd>,
|
||||
expires_at_unix_ms: u64,
|
||||
plan_quota: Vec<PlanQuota>,
|
||||
) -> io::Result<()> {
|
||||
// A token that cannot be read or piped was never lent: the lease ends.
|
||||
let Some(read_end) = self
|
||||
.tokens
|
||||
.read()
|
||||
.and_then(|token| token_pipe(token.as_bytes()).ok())
|
||||
else {
|
||||
self.settle(caller, grant, LeaseUse::NeverLent)?;
|
||||
return Ok(());
|
||||
};
|
||||
let frame = encode_frame(&LeaseMessage::ClaudeLeaseGrant(LeaseGranted {
|
||||
lease_id: grant.lease_id.clone(),
|
||||
reserved_micro_usd: grant.reserved_micro_usd,
|
||||
plan_quota,
|
||||
}));
|
||||
let sent = send_with_fd(&stream, &frame, read_end.as_raw_fd());
|
||||
let sent = send_with_fd(stream, &frame, read_end.as_raw_fd());
|
||||
drop(read_end);
|
||||
if sent.is_err() {
|
||||
// The descriptor may have been delivered: the reservation is billed.
|
||||
self.settle(caller, grant, LeaseUse::Reservation)?;
|
||||
return Ok(());
|
||||
}
|
||||
let outcome = self.await_settle(&mut stream, grant, expires_at_unix_ms);
|
||||
match outcome {
|
||||
Some(settle) => {
|
||||
let settlement = self.settle(caller, grant, LeaseUse::Reported(&settle.usage))?;
|
||||
let _ = stream.write_all(&encode_frame(&LeaseMessage::ClaudeLeaseSettled(
|
||||
LeaseSettled {
|
||||
billed_micro_usd: settlement.billed_micro_usd,
|
||||
overrun_micro_usd: settlement.overrun_micro_usd,
|
||||
},
|
||||
)));
|
||||
sent?;
|
||||
// The holder says nothing more. The lease ends when it closes the
|
||||
// socket, when its unit invocation is no longer the one that leased,
|
||||
// or at the expiry.
|
||||
let mut byte = [0_u8; 1];
|
||||
loop {
|
||||
let left = expires_at_unix_ms.saturating_sub(unix_ms());
|
||||
if left == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
None => {
|
||||
self.settle(caller, grant, LeaseUse::Reservation)?;
|
||||
stream.set_read_timeout(Some(Duration::from_millis(left.min(HOLD_POLL_MS))))?;
|
||||
match stream.read(&mut byte) {
|
||||
Ok(0) => return Ok(()),
|
||||
Ok(_) => {}
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
|
||||
) => {}
|
||||
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
|
||||
Err(_) => return Ok(()),
|
||||
}
|
||||
let still = process
|
||||
.and_then(|process| self.units.invocation_in(process.as_fd(), &caller.unit()))
|
||||
.is_some_and(|found| found == *invocation);
|
||||
if !still {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The run's settle, if its whole frame arrives for this lease before the
|
||||
/// lease expires. Anything else (end of file, silence, a frame still
|
||||
/// trickling at the expiry, a malformed frame, the wrong lease) is no
|
||||
/// report.
|
||||
fn await_settle(
|
||||
&self,
|
||||
stream: &mut UnixStream,
|
||||
grant: &LeaseGrant,
|
||||
expires_at_unix_ms: u64,
|
||||
) -> Option<LeaseSettle> {
|
||||
let remaining = expires_at_unix_ms.saturating_sub(unix_ms());
|
||||
let deadline = Instant::now() + Duration::from_millis(remaining);
|
||||
match read_message(stream, deadline).ok()? {
|
||||
LeaseMessage::ClaudeLeaseSettle(settle) if settle.lease_id == grant.lease_id => {
|
||||
Some(settle)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn settle(
|
||||
&self,
|
||||
caller: &LeaseCaller,
|
||||
grant: &LeaseGrant,
|
||||
usage: LeaseUse<'_>,
|
||||
) -> io::Result<LeaseSettlement> {
|
||||
self.service
|
||||
.lock()
|
||||
.map_err(|_| io::Error::other("service lock"))?
|
||||
.settle_lease(&caller.caller_id, &grant.lease_id, usage)
|
||||
.map_err(|_| io::Error::other("ledger"))
|
||||
}
|
||||
}
|
||||
|
||||
/// The plan's windows as the cell holds them at `now_ms`. It takes the cell by
|
||||
/// reference so it cannot note a request, and never waits for a first read.
|
||||
fn readout(quota: &QuotaCell, now_ms: u64) -> LeaseMessage {
|
||||
LeaseMessage::ClaudeUsageReadout(UsageReadout::new(now_ms, quota.snapshot()))
|
||||
}
|
||||
|
||||
/// The longest a lease waits for the meter's first read of the week. A call
|
||||
/// takes a few seconds; the holder's own wait for the grant is far longer.
|
||||
const FIRST_READ_WAIT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// How often a held lease looks again at its holder's unit invocation.
|
||||
const HOLD_POLL_MS: u64 = 500;
|
||||
|
||||
fn refuse(stream: &mut UnixStream, kind: LeaseRefusalKind, detail: &str) -> io::Result<()> {
|
||||
stream.write_all(&encode_frame(&LeaseMessage::ClaudeLeaseRefusal(
|
||||
LeaseRefused {
|
||||
|
|
@ -622,12 +686,216 @@ fn refuse(stream: &mut UnixStream, kind: LeaseRefusalKind, detail: &str) -> io::
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A settle frame whose body is exactly `body_bytes` long.
|
||||
fn settle_frame_of(body_bytes: usize) -> Vec<u8> {
|
||||
struct NoTokens;
|
||||
impl TokenSource for NoTokens {
|
||||
fn read(&self) -> Option<zeroize::Zeroizing<String>> {
|
||||
panic!("a readout read the token")
|
||||
}
|
||||
}
|
||||
struct NoUnits;
|
||||
impl PeerUnits for NoUnits {
|
||||
fn invocation_in(&self, _: BorrowedFd<'_>, _: &str) -> Option<PeerUnit> {
|
||||
panic!("a readout looked up the peer's unit")
|
||||
}
|
||||
}
|
||||
|
||||
fn lender(
|
||||
quota: &Arc<QuotaCell>,
|
||||
dir: &std::path::Path,
|
||||
max_connections: usize,
|
||||
) -> (Arc<Mutex<TransportService>>, Lender) {
|
||||
let service = Arc::new(Mutex::new(
|
||||
TransportService::open(
|
||||
&dir.join("replay.cc"),
|
||||
"claude-code",
|
||||
[model_connector::CallerAdmission::new(
|
||||
"lease-test-caller",
|
||||
"lease-test-connection-key",
|
||||
1,
|
||||
["model".to_string()],
|
||||
1,
|
||||
65_536,
|
||||
32_768,
|
||||
)
|
||||
.unwrap()],
|
||||
300_000,
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let lender = Lender {
|
||||
callers: Vec::new(),
|
||||
limits: LeaseLimits {
|
||||
socket_timeout: Duration::from_secs(2),
|
||||
max_lease_ms: 3_600_000,
|
||||
max_connections,
|
||||
},
|
||||
service: service.clone(),
|
||||
quota: quota.clone(),
|
||||
tokens: Arc::new(NoTokens),
|
||||
units: Arc::new(NoUnits),
|
||||
leases: Arc::new(AtomicUsize::new(0)),
|
||||
readouts: Arc::new(AtomicUsize::new(0)),
|
||||
};
|
||||
(service, lender)
|
||||
}
|
||||
|
||||
/// Serves `lender`'s parts on a socket in `dir`; the path comes back.
|
||||
fn serve(lender: Lender, dir: &std::path::Path) -> std::path::PathBuf {
|
||||
let socket = dir.join("lease.sock");
|
||||
let listener = UnixListener::bind(&socket).unwrap();
|
||||
let (service, quota) = (lender.service.clone(), lender.quota.clone());
|
||||
thread::spawn(move || {
|
||||
let _ = serve_leases(
|
||||
&listener,
|
||||
lender.callers,
|
||||
lender.limits,
|
||||
service,
|
||||
quota,
|
||||
lender.tokens,
|
||||
lender.units,
|
||||
);
|
||||
});
|
||||
socket
|
||||
}
|
||||
|
||||
fn ask(socket: &std::path::Path, message: &LeaseMessage) -> Option<LeaseMessage> {
|
||||
let mut stream = UnixStream::connect(socket).ok()?;
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.unwrap();
|
||||
stream.write_all(&encode_frame(message)).ok()?;
|
||||
let mut raw = Vec::new();
|
||||
let _ = stream.read_to_end(&mut raw);
|
||||
decode_frame(&raw)
|
||||
}
|
||||
|
||||
fn readout_request() -> LeaseMessage {
|
||||
LeaseMessage::ClaudeUsageReadoutRequest(LeaseUsageReadoutRequest {})
|
||||
}
|
||||
|
||||
fn scratch(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("{name}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_socket_readout_never_asks_the_meter_waits_for_a_week_or_takes_the_service_lock() {
|
||||
let dir = scratch("readout-arm");
|
||||
let quota = Arc::new(QuotaCell::new());
|
||||
quota.attach_meter();
|
||||
let (service, lender) = lender("a, &dir, 8);
|
||||
let socket = serve(lender, &dir);
|
||||
// Held throughout: a readout that takes it hangs past the read timeout.
|
||||
let guard = service.lock().unwrap();
|
||||
for _ in 0..20 {
|
||||
let started = Instant::now();
|
||||
let Some(LeaseMessage::ClaudeUsageReadout(answer)) = ask(&socket, &readout_request())
|
||||
else {
|
||||
panic!("no readout");
|
||||
};
|
||||
assert!(started.elapsed() < Duration::from_secs(1));
|
||||
assert!(answer.plan_quota.is_empty());
|
||||
}
|
||||
drop(guard);
|
||||
assert_eq!(quota.asks_so_far(), 0);
|
||||
assert!(!quota.wanted_at(unix_ms(), Duration::from_secs(15 * 60)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flood_of_readouts_at_their_limit_leaves_every_lease_request_answered() {
|
||||
let dir = scratch("readout-flood");
|
||||
let quota = Arc::new(QuotaCell::new());
|
||||
// Fewer lease slots than flooding readers: the readers must not need them.
|
||||
let (_service, lender) = lender("a, &dir, 2);
|
||||
let socket = serve(lender, &dir);
|
||||
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let flood: Vec<_> = (0..READOUT_CONNECTIONS)
|
||||
.map(|_| {
|
||||
let (socket, stop) = (socket.clone(), stop.clone());
|
||||
thread::spawn(move || {
|
||||
while !stop.load(Ordering::Acquire) {
|
||||
let _ = ask(&socket, &readout_request());
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
// No caller is configured, so each lease is answered UnknownCaller:
|
||||
// an answer is all that is asked.
|
||||
let lease = LeaseMessage::ClaudeLeaseRequest(LeaseRequest {
|
||||
expires_at_unix_ms: unix_ms() + 60_000,
|
||||
});
|
||||
let unanswered = (0..40)
|
||||
.filter(|_| {
|
||||
!matches!(
|
||||
ask(&socket, &lease),
|
||||
Some(LeaseMessage::ClaudeLeaseRefusal(LeaseRefused {
|
||||
kind: LeaseRefusalKind::UnknownCaller,
|
||||
..
|
||||
}))
|
||||
)
|
||||
})
|
||||
.count();
|
||||
stop.store(true, Ordering::Release);
|
||||
for client in flood {
|
||||
client.join().unwrap();
|
||||
}
|
||||
assert_eq!(unanswered, 0);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_readout_over_the_readout_limit_is_refused_busy_not_dropped() {
|
||||
let dir = scratch("readout-limit");
|
||||
let quota = Arc::new(QuotaCell::new());
|
||||
let (_service, lender) = lender("a, &dir, 8);
|
||||
let held: Vec<_> = (0..READOUT_CONNECTIONS)
|
||||
.map(|_| Permit::acquire(&lender.readouts, READOUT_CONNECTIONS).unwrap())
|
||||
.collect();
|
||||
let (mut client, server) = UnixStream::pair().unwrap();
|
||||
client.write_all(&encode_frame(&readout_request())).unwrap();
|
||||
lender.serve_one(server).unwrap();
|
||||
let mut raw = Vec::new();
|
||||
client.read_to_end(&mut raw).unwrap();
|
||||
let Some(LeaseMessage::ClaudeLeaseRefusal(refusal)) = decode_frame(&raw) else {
|
||||
panic!("no refusal");
|
||||
};
|
||||
assert_eq!(refusal.kind, LeaseRefusalKind::Busy);
|
||||
drop(held);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_readout_of_an_empty_metered_cell_does_not_wait() {
|
||||
let quota = QuotaCell::new();
|
||||
quota.attach_meter();
|
||||
let started = Instant::now();
|
||||
let LeaseMessage::ClaudeUsageReadout(answer) = readout("a, 77) else {
|
||||
panic!("a readout answers with a readout");
|
||||
};
|
||||
assert!(started.elapsed() < Duration::from_secs(1));
|
||||
assert!(answer.plan_quota.is_empty());
|
||||
assert_eq!(answer.at_unix_ms, 77);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_readout_is_no_sign_of_life() {
|
||||
let quota = Arc::new(QuotaCell::new());
|
||||
let within = Duration::from_secs(15 * 60);
|
||||
let now = unix_ms();
|
||||
let _ = readout("a, now);
|
||||
assert!(!quota.wanted_at(now, within));
|
||||
let _asking = quota.asking();
|
||||
assert!(quota.wanted_at(now, within));
|
||||
}
|
||||
|
||||
/// A refusal frame whose body is exactly `body_bytes` long.
|
||||
fn frame_of(body_bytes: usize) -> Vec<u8> {
|
||||
let frame_with = |pad: usize| {
|
||||
encode_frame(&LeaseMessage::ClaudeLeaseSettle(LeaseSettle {
|
||||
lease_id: "x".repeat(pad),
|
||||
usage: Vec::new(),
|
||||
encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused {
|
||||
kind: LeaseRefusalKind::Busy,
|
||||
detail: "x".repeat(pad),
|
||||
}))
|
||||
};
|
||||
// The string header is the same width between 256 and 65535 bytes.
|
||||
|
|
@ -646,10 +914,10 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn a_frame_is_one_whole_message_within_the_bound() {
|
||||
let at_bound = settle_frame_of(MAX_LEASE_FRAME_BYTES);
|
||||
let at_bound = frame_of(MAX_LEASE_FRAME_BYTES);
|
||||
assert_eq!(at_bound.len(), 4 + MAX_LEASE_FRAME_BYTES);
|
||||
assert!(decode_frame(&at_bound).is_some());
|
||||
let past_bound = settle_frame_of(MAX_LEASE_FRAME_BYTES + 1);
|
||||
let past_bound = frame_of(MAX_LEASE_FRAME_BYTES + 1);
|
||||
assert!(decode_frame(&past_bound).is_none());
|
||||
let mut trailing = at_bound.clone();
|
||||
trailing.push(0);
|
||||
|
|
@ -661,9 +929,9 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn a_stream_frame_over_the_bound_is_refused_before_it_is_read() {
|
||||
let past_bound = settle_frame_of(MAX_LEASE_FRAME_BYTES + 1);
|
||||
let past_bound = frame_of(MAX_LEASE_FRAME_BYTES + 1);
|
||||
assert!(within(&past_bound).is_err());
|
||||
let at_bound = settle_frame_of(MAX_LEASE_FRAME_BYTES);
|
||||
let at_bound = frame_of(MAX_LEASE_FRAME_BYTES);
|
||||
assert!(within(&at_bound).is_ok());
|
||||
assert!(within(&[0_u8, 0, 0, 0]).is_err());
|
||||
// Short of the length it announced is end of file, not a message.
|
||||
|
|
@ -673,9 +941,9 @@ mod tests {
|
|||
#[test]
|
||||
fn a_frame_that_trickles_past_its_deadline_is_refused_however_small_each_read() {
|
||||
let (mut reader, mut writer) = UnixStream::pair().unwrap();
|
||||
let frame = encode_frame(&LeaseMessage::ClaudeLeaseSettle(LeaseSettle {
|
||||
lease_id: "lease:x".to_string(),
|
||||
usage: Vec::new(),
|
||||
let frame = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused {
|
||||
kind: LeaseRefusalKind::Busy,
|
||||
detail: "lease:x".to_string(),
|
||||
}));
|
||||
let trickle = thread::spawn(move || {
|
||||
for byte in frame {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
//! stream-json in and out, with every tool, MCP server, settings source and
|
||||
//! plugin switched off. A binary wires it to [`model_connector::serve`].
|
||||
|
||||
pub mod ask;
|
||||
mod backend;
|
||||
mod config;
|
||||
mod daemon;
|
||||
|
|
@ -10,6 +11,8 @@ mod handle;
|
|||
mod launch;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod lease;
|
||||
mod messages;
|
||||
mod meter;
|
||||
mod process;
|
||||
mod quota;
|
||||
mod stream;
|
||||
|
|
@ -17,18 +20,19 @@ mod stream;
|
|||
mod unit;
|
||||
|
||||
pub use backend::{ClaudeCodeBackend, CredentialTokenSource, StderrSink, TokenSource};
|
||||
pub use config::{ClaudeCodeConfig, ClaudeCodeLimits};
|
||||
pub use config::{ClaudeAuth, ClaudeCodeConfig, ClaudeCodeLimits};
|
||||
pub use daemon::{
|
||||
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, check_ready, load_config, write_config,
|
||||
};
|
||||
#[cfg(unix)]
|
||||
pub use daemon::{check_prompt_dir, serve_config};
|
||||
pub use messages::{MessagesBackend, MessagesConfig};
|
||||
pub use handle::{FsSessionStore, MIN_SECRET_BYTES, SessionStore};
|
||||
pub use launch::ChildEnv;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use lease::{
|
||||
LeaseCaller, LeaseGranted, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused,
|
||||
LeaseRequest, LeaseSettle, LeaseSettled, MAX_LEASE_FRAME_BYTES, PeerCredentials, PeerUnit,
|
||||
LeaseRequest, LeaseUsageReadoutRequest, MAX_LEASE_FRAME_BYTES, PeerCredentials, PeerUnit,
|
||||
PeerUnits, decode_frame, encode_frame, peer_credentials, serve_leases, user_uid,
|
||||
};
|
||||
#[cfg(unix)]
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
//! claude-connector config add-caller PATH.cc --caller-id ID --connection-key-file F ...
|
||||
//! claude-connector config add-lease-caller PATH.cc --lease-user U --caller-id ID ...
|
||||
//! claude-connector config check PATH.cc
|
||||
//! claude-connector ask --caller-id ID --connection-key-file F --model M (--system TEXT | --system-file F) < prompt
|
||||
//!
|
||||
//! `serve` takes its configuration from the typed document alone. The flags of
|
||||
//! `config init` exist only to author that document. No message here echoes a
|
||||
|
|
@ -14,11 +15,12 @@ use std::collections::BTreeMap;
|
|||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use claude_connector::ask::{self, AskArgs, AskError};
|
||||
use claude_connector::{
|
||||
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, MIN_SECRET_BYTES, check_ready,
|
||||
ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, MIN_SECRET_BYTES, check_ready,
|
||||
load_config, write_config,
|
||||
};
|
||||
use model_connector::{CallerConfig, LeaseTurn, ModelPrice, Rates, frame_bytes_for_payload};
|
||||
use model_connector::{CallerConfig, LeaseTurn, frame_bytes_for_payload};
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
|
|
@ -29,6 +31,7 @@ fn main() -> ExitCode {
|
|||
["config", "add-caller", path, flags @ ..] => add_caller(path, flags),
|
||||
["config", "add-lease-caller", path, flags @ ..] => add_lease_caller(path, flags),
|
||||
["config", "check", path] => check(path),
|
||||
["ask", flags @ ..] => run_ask(flags),
|
||||
_ => Err(Failure::Usage),
|
||||
};
|
||||
match result {
|
||||
|
|
@ -43,7 +46,7 @@ fn main() -> ExitCode {
|
|||
#[derive(Debug, thiserror::Error)]
|
||||
enum Failure {
|
||||
#[error(
|
||||
"usage: serve --config PATH | config init PATH --flag value ... | config add-caller PATH --flag value ... | config add-lease-caller PATH --flag value ... | config check PATH (check reads the credentials from the environment it runs in: run it in the unit's environment)"
|
||||
"usage: serve --config PATH | config init PATH --flag value ... | config add-caller PATH --flag value ... | config add-lease-caller PATH --flag value ... | config check PATH | ask --caller-id ID --connection-key-file FILE --model MODEL (--system TEXT | --system-file FILE) [--endpoint HOST:PORT] [--effort low|medium|high|max] [--max-output-tokens N] [--timeout-secs N] (prompt on stdin, answer on stdout) (check reads the credentials from the environment it runs in: run it in the unit's environment)"
|
||||
)]
|
||||
Usage,
|
||||
#[error(transparent)]
|
||||
|
|
@ -54,6 +57,8 @@ enum Failure {
|
|||
Malformed(&'static str),
|
||||
#[error("a flag is unknown, repeated or has no value")]
|
||||
Flags,
|
||||
#[error("{0}")]
|
||||
Ask(#[from] AskError),
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
|
|
@ -72,10 +77,71 @@ fn check(path: &str) -> Result<(), Failure> {
|
|||
println!("claude connector configuration is valid and ready to serve");
|
||||
println!("callers: {}", config.callers.len());
|
||||
println!("lease_callers: {}", config.lease_callers.len());
|
||||
println!("prices: {}", config.prices.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const ASK: [&str; 9] = [
|
||||
"--endpoint",
|
||||
"--caller-id",
|
||||
"--connection-key-file",
|
||||
"--model",
|
||||
"--system",
|
||||
"--system-file",
|
||||
"--effort",
|
||||
"--max-output-tokens",
|
||||
"--timeout-secs",
|
||||
];
|
||||
|
||||
/// One no-tools completion: the prompt is all of stdin, the answer is stdout.
|
||||
fn run_ask(args: &[&str]) -> Result<(), Failure> {
|
||||
use std::io::{Read, Write};
|
||||
|
||||
let flags = Flags::parse(args, &[&ASK], &[])?;
|
||||
let instructions = match (
|
||||
flags.single.get("--system"),
|
||||
flags.single.get("--system-file"),
|
||||
) {
|
||||
(Some(text), None) => text.clone(),
|
||||
(None, Some(path)) => ask::read_system_file(std::path::Path::new(path))?,
|
||||
_ => return Err(Failure::Missing("--system or --system-file (exactly one)")),
|
||||
};
|
||||
let effort = match flags.single.get("--effort").map(String::as_str) {
|
||||
None => None,
|
||||
Some("low") => Some(model_connector::ReasoningEffort::Low),
|
||||
Some("medium") => Some(model_connector::ReasoningEffort::Medium),
|
||||
Some("high") => Some(model_connector::ReasoningEffort::High),
|
||||
Some("max") => Some(model_connector::ReasoningEffort::Max),
|
||||
Some(_) => return Err(Failure::Malformed("--effort")),
|
||||
};
|
||||
let endpoint = flags
|
||||
.single
|
||||
.get("--endpoint")
|
||||
.map_or(ask::DEFAULT_ENDPOINT, String::as_str)
|
||||
.parse()
|
||||
.map_err(|_| Failure::Malformed("--endpoint"))?;
|
||||
let mut raw = Vec::new();
|
||||
std::io::stdin()
|
||||
.take(ask::PAYLOAD_BYTES as u64 + 1)
|
||||
.read_to_end(&mut raw)
|
||||
.map_err(|_| AskError::StdinRead)?;
|
||||
let prompt = String::from_utf8(raw).map_err(|_| AskError::StdinNotText)?;
|
||||
let answer = ask::ask(&AskArgs {
|
||||
endpoint,
|
||||
caller_id: flags.text("--caller-id")?,
|
||||
key_file: flags.path("--connection-key-file")?,
|
||||
model: flags.text("--model")?,
|
||||
instructions,
|
||||
effort,
|
||||
max_output_tokens: flags.number_or("--max-output-tokens", 8192)?,
|
||||
timeout: std::time::Duration::from_secs(flags.number_or("--timeout-secs", 300)?),
|
||||
prompt,
|
||||
})?;
|
||||
let mut out = std::io::stdout();
|
||||
out.write_all(answer.as_bytes())
|
||||
.and_then(|()| out.flush())
|
||||
.map_err(|_| AskError::StdoutWrite.into())
|
||||
}
|
||||
|
||||
/// The flags of one config verb: each single flag at most once, each list
|
||||
/// flag any number of times.
|
||||
struct Flags {
|
||||
|
|
@ -85,17 +151,16 @@ struct Flags {
|
|||
|
||||
/// The flags that describe one caller, shared by `config init` (which writes
|
||||
/// the first caller) and `config add-caller`.
|
||||
const CALLER: [&str; 7] = [
|
||||
const CALLER: [&str; 5] = [
|
||||
"--caller-id",
|
||||
"--connection-key-file",
|
||||
"--connection-key-epoch",
|
||||
"--spend-ceiling-micro-usd",
|
||||
"--spend-window-ms",
|
||||
"--max-concurrent-requests",
|
||||
"--max-output-tokens",
|
||||
];
|
||||
|
||||
const INIT: [&str; 22] = [
|
||||
"--auth",
|
||||
"--listen",
|
||||
"--replay-store",
|
||||
"--claude-binary",
|
||||
|
|
@ -117,15 +182,9 @@ const INIT: [&str; 22] = [
|
|||
"--lease-max-ms",
|
||||
"--turn",
|
||||
"--lease-unit-instance",
|
||||
"--lease-reservation-micro-usd",
|
||||
];
|
||||
|
||||
const LEASE_CALLER: [&str; 4] = [
|
||||
"--caller-id",
|
||||
"--turn",
|
||||
"--lease-unit-instance",
|
||||
"--lease-reservation-micro-usd",
|
||||
];
|
||||
const LEASE_CALLER: [&str; 3] = ["--caller-id", "--turn", "--lease-unit-instance"];
|
||||
|
||||
impl Flags {
|
||||
fn parse(
|
||||
|
|
@ -182,6 +241,15 @@ impl Flags {
|
|||
.map_err(|_| Failure::Malformed(name))
|
||||
}
|
||||
|
||||
/// Which credential `--token-credential` names: `oauth-token` (the default) or `api-key`.
|
||||
fn auth(&self) -> Result<ClaudeAuth, Failure> {
|
||||
match self.single.get("--auth").map(String::as_str) {
|
||||
None | Some("oauth-token") => Ok(ClaudeAuth::OAuthToken),
|
||||
Some("api-key") => Ok(ClaudeAuth::ApiKey),
|
||||
Some(_) => Err(Failure::Malformed("--auth")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of turn a leasing account serves: `self` or `persona`.
|
||||
fn turn(&self) -> Result<LeaseTurn, Failure> {
|
||||
match self.text("--turn")?.as_str() {
|
||||
|
|
@ -213,8 +281,6 @@ impl Flags {
|
|||
max_concurrent_requests: self.number_or("--max-concurrent-requests", 4)?,
|
||||
max_payload_bytes: self.number_or("--max-payload-bytes", 1 << 20)?,
|
||||
max_output_tokens: self.number_or("--max-output-tokens", 32_768)?,
|
||||
spend_ceiling_micro_usd: self.number("--spend-ceiling-micro-usd")?,
|
||||
spend_window_ms: self.number("--spend-window-ms")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -230,33 +296,6 @@ fn sha256(hex: &str) -> Option<[u8; 32]> {
|
|||
Some(digest)
|
||||
}
|
||||
|
||||
/// MODEL:INPUT:OUTPUT:CACHE_WRITE:CACHE_READ:OVERHEAD, rates in micro-USD per
|
||||
/// million tokens. The one cache-write rate prices both retentions.
|
||||
fn price(text: &str) -> Option<(String, ModelPrice)> {
|
||||
let mut parts = text.split(':');
|
||||
let model = parts.next()?.to_string();
|
||||
let mut next = || parts.next()?.parse::<u64>().ok();
|
||||
let (input, output, cache_write, cache_read, overhead_tokens) =
|
||||
(next()?, next()?, next()?, next()?, next()?);
|
||||
if parts.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
Some((
|
||||
model,
|
||||
ModelPrice {
|
||||
rates: Rates {
|
||||
input,
|
||||
cache_write_short: cache_write,
|
||||
cache_write_long: cache_write,
|
||||
cache_read,
|
||||
output,
|
||||
},
|
||||
long_context: None,
|
||||
overhead_tokens,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// Writes 32 random bytes as 64 hex characters, mode 0600, unless the file is
|
||||
/// already there: the secret is never read back or shown, and a file that
|
||||
/// exists is the secret handles already depend on, so it is kept as it is when
|
||||
|
|
@ -322,16 +361,9 @@ fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
|
|||
let flags = Flags::parse(
|
||||
args,
|
||||
&[&INIT, &CALLER],
|
||||
&["--allowed-model", "--price", "--lease-user"],
|
||||
&["--allowed-model", "--lease-user"],
|
||||
)?;
|
||||
let first = flags.caller()?;
|
||||
let mut prices = BTreeMap::new();
|
||||
for text in flags.list("--price") {
|
||||
let (model, price) = price(text).ok_or(Failure::Malformed("--price"))?;
|
||||
if prices.insert(model, price).is_some() {
|
||||
return Err(Failure::Malformed("--price"));
|
||||
}
|
||||
}
|
||||
let lease_callers = flags
|
||||
.list("--lease-user")
|
||||
.iter()
|
||||
|
|
@ -341,7 +373,6 @@ fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
|
|||
caller_id: first.caller_runtime_id.clone(),
|
||||
turn: flags.turn()?,
|
||||
unit_instance: flags.text("--lease-unit-instance")?,
|
||||
reservation_micro_usd: flags.number("--lease-reservation-micro-usd")?,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, Failure>>()?;
|
||||
|
|
@ -366,11 +397,11 @@ fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
|
|||
socket_timeout_ms: flags.number_or("--socket-timeout-ms", 10_000)?,
|
||||
max_expiry_skew_ms: 300_000,
|
||||
callers: vec![first],
|
||||
prices,
|
||||
lease_socket: flags.single.get("--lease-socket").map(PathBuf::from),
|
||||
lease_callers,
|
||||
lease_max_ms: flags.number_or("--lease-max-ms", 3_600_000)?,
|
||||
handle_secret_credential: flags.text("--handle-secret-credential")?,
|
||||
auth: flags.auth()?,
|
||||
};
|
||||
// Validate before the secret file exists: a refused document leaves nothing.
|
||||
config.validate()?;
|
||||
|
|
@ -412,7 +443,6 @@ fn add_lease_caller(path: &str, args: &[&str]) -> Result<(), Failure> {
|
|||
caller_id: flags.text("--caller-id")?,
|
||||
turn: flags.turn()?,
|
||||
unit_instance: flags.text("--lease-unit-instance")?,
|
||||
reservation_micro_usd: flags.number("--lease-reservation-micro-usd")?,
|
||||
});
|
||||
write_config(path.as_ref(), &config)?;
|
||||
Ok(())
|
||||
|
|
|
|||
626
crates/claude-connector/src/messages.rs
Normal file
626
crates/claude-connector/src/messages.rs
Normal file
|
|
@ -0,0 +1,626 @@
|
|||
//! The Messages API backend: one non-streaming `POST /v1/messages` per call,
|
||||
//! authenticated with an Anthropic API key. It is the backend of a connector
|
||||
//! whose document says `auth` is an API key; the `claude` CLI is never spawned
|
||||
//! for it. Tools, tool calls and results, thinking blocks, cache breakpoints
|
||||
//! and cache usage map natively; the contract's shapes are unchanged.
|
||||
//!
|
||||
//! API facts this module follows were read from the Claude API reference on
|
||||
//! 2026-11-29 (`anthropic-version: 2026-10-21`):
|
||||
//! - `claude-sonnet-5-5`, `claude-opus-5-5` and any model
|
||||
//! [`rejects_forced_tool_choice`] does not name answer a forced
|
||||
//! `tool_choice` (`any`, `tool`) with a 400. [`ToolChoice::Required`] is
|
||||
//! `tool_choice: any` on a model that accepts it and a typed refusal before
|
||||
//! sending on one that does not; the request's `system` never depends on it.
|
||||
//! Thinking is `{"type":"adaptive"}` with `output_config.effort`
|
||||
//! (`thinking.budget_tokens` is rejected), and a request's output schema is
|
||||
//! `output_config.format` (`json_schema`) instead of a forced tool.
|
||||
//! - A thinking block is replayed unchanged, in transcript order; the API
|
||||
//! drops one its model cannot read. Its `signature` is the provider's.
|
||||
//! - Usage reports thinking tokens in `output_tokens_details.thinking_tokens`
|
||||
//! (a detail of `output_tokens`) and `input_tokens` apart from `cache_read_input_tokens` and
|
||||
//! `cache_creation_input_tokens`.
|
||||
//!
|
||||
//! The key is read from the systemd credential at every call and reaches the
|
||||
//! HTTP client as the `x-api-key` header; it is in no environment, argument,
|
||||
//! log line or message. A failed call is never run again, and a redirect is
|
||||
//! never followed: it would carry the key to whatever host it names.
|
||||
//!
|
||||
//! Failures are typed as the Persona drain reads them: no answer could be had
|
||||
//! (connection, deadline, 5xx, 429, 402, 3xx) is an outage kind, and only a
|
||||
//! request or answer the provider refused is a strike. Two 400
|
||||
//! `invalid_request_error` answers are the exception: the provider reports a
|
||||
//! spent balance and the operator's Console spend limit as a 400 whose message
|
||||
//! begins with a fixed string (`SPEND_EXHAUSTED`), and only that string tells
|
||||
//! them from a bad request, so they are matched, as 402 is, to `Authentication`.
|
||||
//!
|
||||
//! The assistant turn is replayed from what the contract carries: thinking
|
||||
//! blocks as parsed, text by its text, tool calls by id, name and input. The
|
||||
//! contract has no shape for a block of another type or for a tool call's other
|
||||
//! fields, and the API rejects an empty text block, so those are not replayed;
|
||||
//! with no server tools sent, no response carries one.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use model_connector::{
|
||||
CacheRetention, FailureKind, InputItem, PlanQuotaSnapshot, ProviderBackend, ProviderCall,
|
||||
ProviderRequest, ReasoningEffort, StopReason, ToolChoice, TransportEvent,
|
||||
TransportEventPayload, TransportOutcome, TransportResult, Usage,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::backend::TokenSource;
|
||||
|
||||
/// The provider tag on every receipt and every reasoning block of this
|
||||
/// backend; distinct from the CLI backend's tag.
|
||||
pub(crate) const PROVIDER: &str = "anthropic-messages";
|
||||
const ENDPOINT: &str = "https://api.anthropic.com";
|
||||
const API_VERSION: &str = "2026-10-21";
|
||||
/// The longest provider message a receipt carries.
|
||||
const MESSAGE_BYTES: usize = 2048;
|
||||
|
||||
/// Whether the API answers `tool_choice: any` with a 400 for this model, by
|
||||
/// the table in the tool-use docs (read 2026-11-29). A model not named as
|
||||
/// accepting it is treated as rejecting it, so a new model is refused here
|
||||
/// until someone reads its row.
|
||||
fn rejects_forced_tool_choice(model: &str) -> bool {
|
||||
let base = match model.rsplit_once('-') {
|
||||
Some((base, date)) if date.len() == 8 && date.bytes().all(|b| b.is_ascii_digit()) => base,
|
||||
_ => model,
|
||||
};
|
||||
!matches!(
|
||||
base,
|
||||
"claude-opus-5"
|
||||
| "claude-sonnet-5"
|
||||
| "claude-haiku-5-5"
|
||||
| "claude-haiku-4-5"
|
||||
| "claude-opus-4-8"
|
||||
| "claude-opus-4-7"
|
||||
| "claude-opus-4-6"
|
||||
| "claude-opus-4-5"
|
||||
| "claude-sonnet-4-6"
|
||||
| "claude-sonnet-4-5"
|
||||
)
|
||||
}
|
||||
|
||||
/// What the connector's binary hands the backend.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MessagesConfig {
|
||||
/// The name of the systemd credential that holds the API key, under
|
||||
/// `$CREDENTIALS_DIRECTORY`.
|
||||
pub key_credential: String,
|
||||
/// The whole call, connect to the last byte of the response.
|
||||
pub deadline: Duration,
|
||||
/// The largest response body read.
|
||||
pub max_response_bytes: usize,
|
||||
}
|
||||
|
||||
/// Answers each call with one HTTP request to the Messages API.
|
||||
pub struct MessagesBackend {
|
||||
agent: ureq::Agent,
|
||||
endpoint: String,
|
||||
keys: Box<dyn TokenSource>,
|
||||
max_response_bytes: u64,
|
||||
}
|
||||
|
||||
impl MessagesBackend {
|
||||
/// The backend over the real API, with the key read from the credential
|
||||
/// `config.key_credential` names.
|
||||
pub fn new(config: MessagesConfig) -> Self {
|
||||
let keys = Box::new(crate::backend::CredentialTokenSource::from_environment(
|
||||
config.key_credential.clone(),
|
||||
));
|
||||
Self::with_parts(config, keys, ENDPOINT.to_string())
|
||||
}
|
||||
|
||||
pub(crate) fn with_parts(
|
||||
config: MessagesConfig,
|
||||
keys: Box<dyn TokenSource>,
|
||||
endpoint: String,
|
||||
) -> Self {
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||
.timeout_global(Some(config.deadline))
|
||||
.http_status_as_error(false)
|
||||
.max_redirects(0)
|
||||
.build()
|
||||
.into();
|
||||
Self {
|
||||
agent,
|
||||
endpoint,
|
||||
keys,
|
||||
max_response_bytes: config.max_response_bytes as u64,
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, request: &ProviderRequest) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
let Some(key) = self.keys.read() else {
|
||||
return failed(
|
||||
FailureKind::Authentication,
|
||||
"anthropic-messages: the connector has no API key".to_string(),
|
||||
Some(zero_usage()),
|
||||
);
|
||||
};
|
||||
let body = match render(request).and_then(|body| {
|
||||
serde_json::to_vec(&body).map_err(|_| "the request could not be encoded".to_string())
|
||||
}) {
|
||||
Ok(body) => body,
|
||||
Err(message) => {
|
||||
return failed(
|
||||
FailureKind::InvalidRequest,
|
||||
format!("anthropic-messages: {message}"),
|
||||
Some(zero_usage()),
|
||||
);
|
||||
}
|
||||
};
|
||||
let sent = self
|
||||
.agent
|
||||
.post(format!("{}/v1/messages", self.endpoint))
|
||||
.header("x-api-key", key.as_str())
|
||||
.header("anthropic-version", API_VERSION)
|
||||
.header("content-type", "application/json")
|
||||
.send(&body[..]);
|
||||
let mut response = match sent {
|
||||
Ok(response) => response,
|
||||
Err(error) => return transport_failure(&error),
|
||||
};
|
||||
let status = response.status().as_u16();
|
||||
let text = match response
|
||||
.body_mut()
|
||||
.with_config()
|
||||
.limit(self.max_response_bytes)
|
||||
.read_to_vec()
|
||||
{
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) => return transport_failure(&error),
|
||||
};
|
||||
if !(200..300).contains(&status) {
|
||||
return http_failure(status, &text);
|
||||
}
|
||||
let required = request.tool_choice == ToolChoice::Required && !request.tools.is_empty();
|
||||
match parse(&text, required) {
|
||||
Ok(done) => {
|
||||
let events = done
|
||||
.payloads
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(sequence, payload)| TransportEvent {
|
||||
sequence: sequence as u64,
|
||||
payload,
|
||||
})
|
||||
.collect();
|
||||
(
|
||||
events,
|
||||
TransportOutcome::Completed {
|
||||
provider_response_id: done.id,
|
||||
stop_reason: done.stop_reason,
|
||||
usage: done.usage,
|
||||
},
|
||||
)
|
||||
}
|
||||
Err(failure) => failed(failure.kind, failure.message, failure.usage),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ProviderBackend for MessagesBackend {
|
||||
fn ready(&self) -> Result<(), &'static str> {
|
||||
match self.keys.read() {
|
||||
Some(_) => Ok(()),
|
||||
None => Err(self.keys.missing()),
|
||||
}
|
||||
}
|
||||
|
||||
fn provider(&self) -> &str {
|
||||
PROVIDER
|
||||
}
|
||||
|
||||
fn plan_quota(&self) -> PlanQuotaSnapshot {
|
||||
PlanQuotaSnapshot::default()
|
||||
}
|
||||
|
||||
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
||||
let (events, outcome) = self.run(call.request());
|
||||
call.transported(events, outcome)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- request ----
|
||||
|
||||
/// The request body, or what is wrong with the request.
|
||||
fn render(request: &ProviderRequest) -> Result<Value, String> {
|
||||
let mut body = Map::new();
|
||||
body.insert("model".into(), json!(request.model));
|
||||
body.insert("max_tokens".into(), json!(request.max_output_tokens));
|
||||
|
||||
body.insert(
|
||||
"system".into(),
|
||||
json!([{"type": "text", "text": request.instructions}]),
|
||||
);
|
||||
|
||||
let mut messages = messages_of(&request.input)?;
|
||||
if let Some(retention) = request.cache_retention {
|
||||
mark_cache_breakpoint(&mut messages, retention);
|
||||
}
|
||||
body.insert("messages".into(), Value::Array(messages));
|
||||
|
||||
if !request.tools.is_empty() {
|
||||
let mut tools = Vec::with_capacity(request.tools.len());
|
||||
for tool in &request.tools {
|
||||
let schema: Value = serde_json::from_str(&tool.parameters_json)
|
||||
.map_err(|_| format!("tool {} has parameters that are not JSON", tool.name))?;
|
||||
tools.push(json!({
|
||||
"name": tool.name,
|
||||
"description": tool.description,
|
||||
"input_schema": schema,
|
||||
}));
|
||||
}
|
||||
body.insert("tools".into(), Value::Array(tools));
|
||||
let kind = if request.tool_choice == ToolChoice::Required {
|
||||
if rejects_forced_tool_choice(&request.model) {
|
||||
return Err(format!(
|
||||
"model {} does not accept a required tool choice",
|
||||
request.model
|
||||
));
|
||||
}
|
||||
Some("any")
|
||||
} else if !request.parallel_tool_calls {
|
||||
Some("auto")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(kind) = kind {
|
||||
let mut choice = json!({"type": kind});
|
||||
if !request.parallel_tool_calls {
|
||||
choice["disable_parallel_tool_use"] = json!(true);
|
||||
}
|
||||
body.insert("tool_choice".into(), choice);
|
||||
}
|
||||
}
|
||||
|
||||
let mut output = Map::new();
|
||||
if let Some(effort) = request.reasoning_effort {
|
||||
body.insert("thinking".into(), json!({"type": "adaptive"}));
|
||||
output.insert("effort".into(), json!(effort_name(effort)));
|
||||
}
|
||||
if let Some(schema) = &request.output_schema_json {
|
||||
let schema: Value = serde_json::from_str(schema)
|
||||
.map_err(|_| "the output schema is not JSON".to_string())?;
|
||||
output.insert(
|
||||
"format".into(),
|
||||
json!({"type": "json_schema", "schema": schema}),
|
||||
);
|
||||
}
|
||||
if !output.is_empty() {
|
||||
body.insert("output_config".into(), Value::Object(output));
|
||||
}
|
||||
Ok(Value::Object(body))
|
||||
}
|
||||
|
||||
fn effort_name(effort: ReasoningEffort) -> &'static str {
|
||||
match effort {
|
||||
ReasoningEffort::Low => "low",
|
||||
ReasoningEffort::Medium => "medium",
|
||||
ReasoningEffort::High => "high",
|
||||
ReasoningEffort::Max => "max",
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Role {
|
||||
User,
|
||||
Assistant,
|
||||
}
|
||||
|
||||
/// The transcript as alternating messages: consecutive assistant-side items
|
||||
/// (reasoning, text, tool calls) are one assistant message in their order,
|
||||
/// consecutive user-side items (text, tool results) one user message with its
|
||||
/// tool results first, as the API requires.
|
||||
fn messages_of(input: &[InputItem]) -> Result<Vec<Value>, String> {
|
||||
let mut messages: Vec<Value> = Vec::new();
|
||||
let mut open: Option<(Role, Vec<Value>)> = None;
|
||||
for item in input {
|
||||
let (role, block) = block_of(item)?;
|
||||
match &mut open {
|
||||
Some((current, blocks)) if *current == role => blocks.push(block),
|
||||
_ => {
|
||||
if let Some(done) = open.take() {
|
||||
messages.push(message_of(done));
|
||||
}
|
||||
open = Some((role, vec![block]));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(done) = open {
|
||||
messages.push(message_of(done));
|
||||
}
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
fn message_of((role, mut blocks): (Role, Vec<Value>)) -> Value {
|
||||
if role == Role::User {
|
||||
blocks.sort_by_key(|block| block["type"] != "tool_result");
|
||||
}
|
||||
json!({
|
||||
"role": if role == Role::User { "user" } else { "assistant" },
|
||||
"content": blocks,
|
||||
})
|
||||
}
|
||||
|
||||
fn block_of(item: &InputItem) -> Result<(Role, Value), String> {
|
||||
Ok(match item {
|
||||
InputItem::UserText { text } => (Role::User, json!({"type": "text", "text": text})),
|
||||
InputItem::AssistantText { text } => {
|
||||
(Role::Assistant, json!({"type": "text", "text": text}))
|
||||
}
|
||||
InputItem::ToolCall {
|
||||
call_id,
|
||||
name,
|
||||
arguments,
|
||||
} => {
|
||||
let input: Value = serde_json::from_str(arguments)
|
||||
.ok()
|
||||
.filter(Value::is_object)
|
||||
.ok_or_else(|| format!("the arguments of call {call_id} are not a JSON object"))?;
|
||||
(
|
||||
Role::Assistant,
|
||||
json!({"type": "tool_use", "id": call_id, "name": name, "input": input}),
|
||||
)
|
||||
}
|
||||
InputItem::ToolResult { call_id, output } => (
|
||||
Role::User,
|
||||
json!({"type": "tool_result", "tool_use_id": call_id, "content": output}),
|
||||
),
|
||||
InputItem::ReasoningState {
|
||||
provider, state, ..
|
||||
} => {
|
||||
let block: Value = serde_json::from_slice(state)
|
||||
.ok()
|
||||
.filter(|block: &Value| {
|
||||
provider == PROVIDER
|
||||
&& matches!(
|
||||
block["type"].as_str(),
|
||||
Some("thinking" | "redacted_thinking")
|
||||
)
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
"a reasoning state is not a thinking block of this provider".to_string()
|
||||
})?;
|
||||
(Role::Assistant, block)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Puts the one breakpoint on the last block of the last message that can
|
||||
/// carry it (a thinking block cannot).
|
||||
fn mark_cache_breakpoint(messages: &mut [Value], retention: CacheRetention) {
|
||||
let mark = match retention {
|
||||
CacheRetention::Short => json!({"type": "ephemeral"}),
|
||||
CacheRetention::Long => json!({"type": "ephemeral", "ttl": "1h"}),
|
||||
};
|
||||
let Some(blocks) = messages
|
||||
.last_mut()
|
||||
.and_then(|message| message["content"].as_array_mut())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if let Some(block) = blocks.iter_mut().rev().find(|block| {
|
||||
!matches!(
|
||||
block["type"].as_str(),
|
||||
Some("thinking" | "redacted_thinking")
|
||||
)
|
||||
}) {
|
||||
block["cache_control"] = mark;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- response ----
|
||||
|
||||
struct Done {
|
||||
id: Option<String>,
|
||||
payloads: Vec<TransportEventPayload>,
|
||||
stop_reason: StopReason,
|
||||
usage: Usage,
|
||||
}
|
||||
|
||||
struct Failure {
|
||||
kind: FailureKind,
|
||||
message: String,
|
||||
usage: Option<Usage>,
|
||||
}
|
||||
|
||||
/// `required`: the request forced a tool call, so an answer without one is a
|
||||
/// failure, never a completed turn.
|
||||
fn parse(bytes: &[u8], required: bool) -> Result<Done, Failure> {
|
||||
let provider_failure = |message: &str, usage: Option<Usage>| Failure {
|
||||
kind: FailureKind::Provider,
|
||||
message: format!("anthropic-messages: {message}"),
|
||||
usage,
|
||||
};
|
||||
let response: Value = serde_json::from_slice(bytes)
|
||||
.map_err(|_| provider_failure("the response is not JSON", None))?;
|
||||
let usage = usage_of(&response["usage"]);
|
||||
let blocks = response["content"]
|
||||
.as_array()
|
||||
.ok_or_else(|| provider_failure("the response has no content", usage.clone()))?;
|
||||
let mut payloads = Vec::new();
|
||||
for block in blocks {
|
||||
match block["type"].as_str() {
|
||||
Some("text") => {
|
||||
if let Some(text) = block["text"].as_str().filter(|text| !text.is_empty()) {
|
||||
payloads.push(TransportEventPayload::TextDelta {
|
||||
text: text.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Some("tool_use") => {
|
||||
let (Some(id), Some(name)) = (block["id"].as_str(), block["name"].as_str()) else {
|
||||
return Err(provider_failure("a tool call has no id or name", usage));
|
||||
};
|
||||
payloads.push(TransportEventPayload::ToolCall {
|
||||
call_id: id.to_string(),
|
||||
name: name.to_string(),
|
||||
arguments: serde_json::to_string(&block["input"]).unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
Some("thinking" | "redacted_thinking") => {
|
||||
payloads.push(TransportEventPayload::ReasoningState {
|
||||
state: serde_json::to_vec(block).unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if required
|
||||
&& !payloads
|
||||
.iter()
|
||||
.any(|payload| matches!(payload, TransportEventPayload::ToolCall { .. }))
|
||||
{
|
||||
return Err(provider_failure("a required tool call did not come", usage));
|
||||
}
|
||||
let stop_reason = match response["stop_reason"].as_str() {
|
||||
Some("end_turn") => StopReason::EndTurn,
|
||||
Some("tool_use") => StopReason::ToolUse,
|
||||
Some("max_tokens") => StopReason::MaxOutputTokens,
|
||||
Some("stop_sequence") => StopReason::StopSequence,
|
||||
Some("refusal") => StopReason::Refusal,
|
||||
Some("model_context_window_exceeded") => StopReason::ContextWindow,
|
||||
_ => {
|
||||
return Err(provider_failure(
|
||||
"the stop reason is not one this backend maps",
|
||||
usage,
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(Done {
|
||||
id: response["id"].as_str().map(str::to_string),
|
||||
payloads,
|
||||
stop_reason,
|
||||
usage: usage.unwrap_or_else(zero_usage),
|
||||
})
|
||||
}
|
||||
|
||||
fn usage_of(usage: &Value) -> Option<Usage> {
|
||||
usage.is_object().then(|| {
|
||||
let count = |name: &str| usage[name].as_u64().unwrap_or(0);
|
||||
Usage {
|
||||
input_tokens: count("input_tokens"),
|
||||
cache_read_tokens: count("cache_read_input_tokens"),
|
||||
cache_write_tokens: count("cache_creation_input_tokens"),
|
||||
output_tokens: count("output_tokens"),
|
||||
reasoning_tokens: usage["output_tokens_details"]["thinking_tokens"].as_u64(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ---- failures ----
|
||||
|
||||
/// The Persona drain treats `RateLimited`, `Unavailable`, `Timeout` and
|
||||
/// `Authentication` as outages and every other kind as a strike against the
|
||||
/// line the turn was waking on. A fault of the key's account or of the path to
|
||||
/// the API is never the line's.
|
||||
///
|
||||
/// 402 is a credential-level fault, not a transient one: the key's account
|
||||
/// cannot pay and only the operator fixes it, as with 401 and 403, so it is
|
||||
/// `Authentication`; `Unavailable` would promise that it heals itself.
|
||||
fn kind_of_status(status: u16) -> FailureKind {
|
||||
match status {
|
||||
401..=403 => FailureKind::Authentication,
|
||||
408 | 504 => FailureKind::Timeout,
|
||||
429 => FailureKind::RateLimited,
|
||||
300..=399 | 500..=599 => FailureKind::Unavailable,
|
||||
400 => FailureKind::InvalidRequest,
|
||||
_ => FailureKind::Provider,
|
||||
}
|
||||
}
|
||||
|
||||
/// The fixed beginnings of the provider's 400 messages for a spent balance
|
||||
/// and a reached Console spend limit, lower-cased.
|
||||
const SPEND_EXHAUSTED: [&str; 2] = [
|
||||
"your credit balance is too low",
|
||||
"you have reached your specified api usage limits",
|
||||
];
|
||||
|
||||
fn spend_exhausted(error: &Value) -> bool {
|
||||
error["type"].as_str() == Some("invalid_request_error")
|
||||
&& error["message"].as_str().is_some_and(|text| {
|
||||
let text = text.trim_start().to_lowercase();
|
||||
SPEND_EXHAUSTED.iter().any(|prefix| text.starts_with(prefix))
|
||||
})
|
||||
}
|
||||
|
||||
/// A failure the provider answered: its own type and message, bounded.
|
||||
fn http_failure(status: u16, body: &[u8]) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
let parsed: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
|
||||
let error = &parsed["error"];
|
||||
let mut message = format!("anthropic-messages: HTTP {status}");
|
||||
if let Some(kind) = error["type"].as_str() {
|
||||
message.push(' ');
|
||||
message.push_str(kind);
|
||||
}
|
||||
if let Some(text) = error["message"].as_str().filter(|text| !text.is_empty()) {
|
||||
message.push_str(": ");
|
||||
message.push_str(text);
|
||||
}
|
||||
let kind = if status == 400 && spend_exhausted(error) {
|
||||
FailureKind::Authentication
|
||||
} else {
|
||||
kind_of_status(status)
|
||||
};
|
||||
failed(kind, bounded(message), None)
|
||||
}
|
||||
|
||||
/// A failure before an answer: the deadline, the size cap, the connection.
|
||||
fn transport_failure(error: &ureq::Error) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
let (kind, what) = match error {
|
||||
ureq::Error::Timeout(_) => (
|
||||
FailureKind::Timeout,
|
||||
"the deadline passed before a response",
|
||||
),
|
||||
ureq::Error::BodyExceedsLimit(_) => {
|
||||
(FailureKind::Provider, "the response passed its size cap")
|
||||
}
|
||||
ureq::Error::BadUri(_) | ureq::Error::Http(_) | ureq::Error::InvalidProxyUrl => {
|
||||
(FailureKind::Provider, "the request could not be built")
|
||||
}
|
||||
_ => (FailureKind::Unavailable, "the API could not be reached"),
|
||||
};
|
||||
failed(kind, format!("anthropic-messages: {what}"), None)
|
||||
}
|
||||
|
||||
fn bounded(mut message: String) -> String {
|
||||
if message.len() > MESSAGE_BYTES {
|
||||
let mut end = MESSAGE_BYTES;
|
||||
while !message.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
message.truncate(end);
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
fn zero_usage() -> Usage {
|
||||
Usage {
|
||||
input_tokens: 0,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
output_tokens: 0,
|
||||
reasoning_tokens: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn failed(
|
||||
kind: FailureKind,
|
||||
message: String,
|
||||
usage: Option<Usage>,
|
||||
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
(
|
||||
Vec::new(),
|
||||
TransportOutcome::Failed {
|
||||
kind,
|
||||
message,
|
||||
usage,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
1095
crates/claude-connector/src/messages/tests.rs
Normal file
1095
crates/claude-connector/src/messages/tests.rs
Normal file
File diff suppressed because it is too large
Load diff
651
crates/claude-connector/src/meter.rs
Normal file
651
crates/claude-connector/src/meter.rs
Normal file
|
|
@ -0,0 +1,651 @@
|
|||
//! The meter: keeps the plan's weekly reading fresh while the swarm is
|
||||
//! working. The subscription reports its windows only inside the CLI's
|
||||
//! `rate_limit_event`, on a call the CLI makes, and Personas make theirs under
|
||||
//! leases that report nothing back. So when the `seven_day` reading in the
|
||||
//! [`QuotaCell`] is `STALE` old, the meter makes the smallest real call
|
||||
//! through the backend's own path (one `claude -p` on the cheapest model with
|
||||
//! a trivial prompt) and the stream fills the cell exactly as it does for any
|
||||
//! call. The meter holds no credential, speaks no protocol and writes nothing
|
||||
//! itself.
|
||||
//!
|
||||
//! The meter is driven by the connector's own lease state. It reads only
|
||||
//! while a lease is held or one was asked for less than `STALE` ago: a held
|
||||
//! swarm brake stops the units, they ask for nothing, and a braked or quiet
|
||||
//! swarm spends nothing. A call that fails, or completes without refreshing
|
||||
//! the reading, is not retried at the staleness period: the wait doubles per
|
||||
//! consecutive miss, up to `CEILING`.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use model_connector::{PlanQuota, Usage};
|
||||
|
||||
use crate::backend::ClaudeCodeBackend;
|
||||
use crate::quota::{EXPIRED, QuotaCell, WEEK};
|
||||
|
||||
/// A reading this old, or older, is stale; also the least gap between calls.
|
||||
const STALE: Duration = Duration::from_secs(15 * 60);
|
||||
/// The longest any backoff may wait; also how long an idle meter sleeps
|
||||
/// before looking again, since a lease request wakes it.
|
||||
const CEILING: Duration = Duration::from_secs(6 * 60 * 60);
|
||||
|
||||
/// The smallest real call, as the backend makes it.
|
||||
pub(crate) trait Probe: Send {
|
||||
/// What the call billed, or the failure's kind. Never a message: a
|
||||
/// provider's words do not enter the meter's log.
|
||||
fn call(&self) -> Result<Usage, String>;
|
||||
}
|
||||
|
||||
impl Probe for Arc<ClaudeCodeBackend> {
|
||||
fn call(&self) -> Result<Usage, String> {
|
||||
self.read_meter()
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the meter is waiting. A refresh is logged every time, with the reading
|
||||
/// it saw; the other states are logged once per change.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum State {
|
||||
/// The week window as the refresh left it; a window with no reading is
|
||||
/// `None`.
|
||||
Read {
|
||||
permille: Option<u32>,
|
||||
resets_at_unix_ms: u64,
|
||||
},
|
||||
Idle,
|
||||
/// The call failed; the kind is the failure's kind, never its message.
|
||||
Failed(String),
|
||||
Unread,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn line(&self) -> String {
|
||||
match self {
|
||||
Self::Read {
|
||||
permille,
|
||||
resets_at_unix_ms,
|
||||
} => {
|
||||
let permille = permille.map_or("unknown".to_string(), |p| p.to_string());
|
||||
format!(
|
||||
"meter: weekly reading refreshed, permille {permille} resets_at_unix_ms {resets_at_unix_ms}"
|
||||
)
|
||||
}
|
||||
Self::Idle => "meter: no lease asked lately, making no call".to_string(),
|
||||
Self::Failed(kind) => format!("meter: the call failed ({kind}), backing off"),
|
||||
Self::Unread => {
|
||||
"meter: the call completed without a weekly reading, backing off".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Meter {
|
||||
cell: Arc<QuotaCell>,
|
||||
probe: Box<dyn Probe>,
|
||||
log: Box<dyn FnMut(&str) + Send>,
|
||||
/// No call before this instant, unix ms.
|
||||
not_before_ms: u64,
|
||||
/// Consecutive calls that left the reading unrefreshed.
|
||||
misses: u32,
|
||||
last_state: Option<State>,
|
||||
}
|
||||
|
||||
impl Meter {
|
||||
fn new(cell: Arc<QuotaCell>, probe: Box<dyn Probe>, log: Box<dyn FnMut(&str) + Send>) -> Self {
|
||||
Self {
|
||||
cell,
|
||||
probe,
|
||||
log,
|
||||
not_before_ms: 0,
|
||||
misses: 0,
|
||||
last_state: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes the call if one is due at `now_ms`; returns how long to wait
|
||||
/// before looking again. Nothing is due while no lease is held or lately
|
||||
/// asked for, nor before the last miss's backoff has passed, nor while the
|
||||
/// weekly reading is younger than `STALE`.
|
||||
fn tick(&mut self, now_ms: u64) -> Duration {
|
||||
if !self.cell.wanted_at(now_ms, STALE) {
|
||||
self.report(State::Idle);
|
||||
return CEILING;
|
||||
}
|
||||
let due_at = self.due_at_ms();
|
||||
if now_ms < due_at {
|
||||
return Duration::from_millis(due_at - now_ms);
|
||||
}
|
||||
// A failed call may still have refreshed the reading: a rejected turn
|
||||
// reports its windows and then errors. Only the cell says whether the
|
||||
// week was read.
|
||||
let called = self.probe.call();
|
||||
let state = if let Some(week) = self.week_refreshed_since(now_ms) {
|
||||
self.misses = 0;
|
||||
State::Read {
|
||||
permille: week.utilization_permille,
|
||||
resets_at_unix_ms: week.resets_at_unix_ms,
|
||||
}
|
||||
} else {
|
||||
self.misses = self.misses.saturating_add(1);
|
||||
match called {
|
||||
Ok(_) => State::Unread,
|
||||
Err(kind) => State::Failed(kind),
|
||||
}
|
||||
};
|
||||
self.report(state);
|
||||
self.not_before_ms = now_ms.saturating_add(duration_ms(backoff(self.misses)));
|
||||
Duration::from_millis(self.due_at_ms().saturating_sub(now_ms))
|
||||
}
|
||||
|
||||
/// The earliest instant the next call may happen. A window past its reset
|
||||
/// described a week that is over, so it is due at once.
|
||||
fn due_at_ms(&self) -> u64 {
|
||||
let stale_at = self
|
||||
.cell
|
||||
.snapshot()
|
||||
.windows
|
||||
.iter()
|
||||
.find(|quota| quota.window == WEEK)
|
||||
.map_or(0, |quota| {
|
||||
if quota.status == EXPIRED {
|
||||
0
|
||||
} else {
|
||||
quota.observed_at_unix_ms.saturating_add(duration_ms(STALE))
|
||||
}
|
||||
});
|
||||
stale_at.max(self.not_before_ms)
|
||||
}
|
||||
|
||||
/// The week window if it was observed at or after `since_ms`, from one
|
||||
/// snapshot, so the logged value is the one that decided the refresh.
|
||||
fn week_refreshed_since(&self, since_ms: u64) -> Option<PlanQuota> {
|
||||
self.cell
|
||||
.snapshot()
|
||||
.windows
|
||||
.into_iter()
|
||||
.find(|quota| quota.window == WEEK && quota.observed_at_unix_ms >= since_ms)
|
||||
}
|
||||
|
||||
fn report(&mut self, state: State) {
|
||||
if matches!(state, State::Read { .. }) || self.last_state.as_ref() != Some(&state) {
|
||||
(self.log)(&state.line());
|
||||
self.last_state = Some(state);
|
||||
}
|
||||
}
|
||||
|
||||
fn run(mut self) {
|
||||
loop {
|
||||
let seen = self.cell.asks_so_far();
|
||||
let wait = self.tick(unix_ms());
|
||||
self.cell.sleep_until_asked(seen, wait);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The wait after `misses` consecutive unrefreshed calls: the staleness
|
||||
/// period, doubling per miss beyond the first, up to the ceiling.
|
||||
fn backoff(misses: u32) -> Duration {
|
||||
let doublings = misses.saturating_sub(1).min(16);
|
||||
STALE.saturating_mul(1 << doublings).min(CEILING)
|
||||
}
|
||||
|
||||
fn duration_ms(duration: Duration) -> u64 {
|
||||
u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
|
||||
}
|
||||
|
||||
fn unix_ms() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, duration_ms)
|
||||
}
|
||||
|
||||
/// Starts the meter thread. It writes only through the calls it makes, and
|
||||
/// logs one line to stderr per refresh of the weekly reading and one per
|
||||
/// change of any other state. From here a lease asked of
|
||||
/// a cell with no weekly reading waits for the meter's first read.
|
||||
pub(crate) fn start(
|
||||
cell: Arc<QuotaCell>,
|
||||
probe: Box<dyn Probe>,
|
||||
) -> std::io::Result<std::thread::JoinHandle<()>> {
|
||||
cell.attach_meter();
|
||||
let meter = Meter::new(
|
||||
cell,
|
||||
probe,
|
||||
Box::new(|line| eprintln!("claude-connector: {line}")),
|
||||
);
|
||||
std::thread::Builder::new()
|
||||
.name("claude-meter".to_string())
|
||||
.spawn(move || meter.run())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::quota::Asking;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
const MIN: u64 = 60_000;
|
||||
const NOW: u64 = 1_800_000_000_000;
|
||||
const RESET: u64 = 4_102_444_800_000;
|
||||
|
||||
fn reading(status: &str) -> Vec<PlanQuota> {
|
||||
vec![PlanQuota {
|
||||
window: WEEK.to_string(),
|
||||
utilization_permille: Some(60),
|
||||
resets_at_unix_ms: RESET,
|
||||
status: status.to_string(),
|
||||
observed_at_unix_ms: 0,
|
||||
}]
|
||||
}
|
||||
|
||||
/// What the next call does: the instant its stream stamps a weekly
|
||||
/// reading (if any) and the kind it then fails with (if any).
|
||||
#[derive(Clone, Default)]
|
||||
struct Script {
|
||||
reading_at: Option<u64>,
|
||||
status: String,
|
||||
fails_with: Option<String>,
|
||||
/// The used thousandths the reading reports; 60 when unset.
|
||||
permille: Option<u32>,
|
||||
/// The reset the reading reports; `RESET` when unset.
|
||||
resets_at: Option<u64>,
|
||||
}
|
||||
|
||||
/// A call that answers as scripted and feeds the cell the way the stream
|
||||
/// does, before it fails, as a rejected turn does.
|
||||
struct Calls {
|
||||
cell: Arc<QuotaCell>,
|
||||
made: Arc<AtomicUsize>,
|
||||
script: Arc<Mutex<Script>>,
|
||||
}
|
||||
|
||||
impl Probe for Calls {
|
||||
fn call(&self) -> Result<Usage, String> {
|
||||
self.made.fetch_add(1, Ordering::SeqCst);
|
||||
let script = self.script.lock().unwrap().clone();
|
||||
if let Some(at) = script.reading_at {
|
||||
let mut week = reading(&script.status);
|
||||
week[0].utilization_permille = Some(script.permille.unwrap_or(60));
|
||||
week[0].resets_at_unix_ms = script.resets_at.unwrap_or(RESET);
|
||||
self.cell.observe_at(at, week);
|
||||
}
|
||||
if let Some(kind) = script.fails_with {
|
||||
return Err(kind);
|
||||
}
|
||||
Ok(Usage {
|
||||
input_tokens: 385,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
output_tokens: 4,
|
||||
reasoning_tokens: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct Rig {
|
||||
meter: Meter,
|
||||
cell: Arc<QuotaCell>,
|
||||
made: Arc<AtomicUsize>,
|
||||
script: Arc<Mutex<Script>>,
|
||||
log: Arc<Mutex<Vec<String>>>,
|
||||
/// The lease the swarm holds until a test lets go of it.
|
||||
lease: Option<Asking>,
|
||||
}
|
||||
|
||||
fn rig() -> Rig {
|
||||
let cell = Arc::new(QuotaCell::new());
|
||||
let made = Arc::new(AtomicUsize::new(0));
|
||||
let script = Arc::new(Mutex::new(Script::default()));
|
||||
let log = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = log.clone();
|
||||
let meter = Meter::new(
|
||||
cell.clone(),
|
||||
Box::new(Calls {
|
||||
cell: cell.clone(),
|
||||
made: made.clone(),
|
||||
script: script.clone(),
|
||||
}),
|
||||
Box::new(move |line| sink.lock().unwrap().push(line.to_string())),
|
||||
);
|
||||
let lease = Some(cell.asking_at(NOW));
|
||||
Rig {
|
||||
meter,
|
||||
cell,
|
||||
made,
|
||||
script,
|
||||
log,
|
||||
lease,
|
||||
}
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn reads(&self, at: u64) {
|
||||
*self.script.lock().unwrap() = Script {
|
||||
reading_at: Some(at),
|
||||
status: "allowed".to_string(),
|
||||
fails_with: None,
|
||||
..Script::default()
|
||||
};
|
||||
}
|
||||
fn reads_nothing(&self) {
|
||||
*self.script.lock().unwrap() = Script::default();
|
||||
}
|
||||
fn fails(&self, kind: &str) {
|
||||
*self.script.lock().unwrap() = Script {
|
||||
fails_with: Some(kind.to_string()),
|
||||
..Script::default()
|
||||
};
|
||||
}
|
||||
fn calls(&self) -> usize {
|
||||
self.made.load(Ordering::SeqCst)
|
||||
}
|
||||
fn lines(&self) -> Vec<String> {
|
||||
self.log.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unread_week_triggers_one_call_and_the_fresh_reading_ends_the_asking() {
|
||||
let mut rig = rig();
|
||||
rig.reads(NOW);
|
||||
assert_eq!(rig.meter.tick(NOW), STALE, "fresh for the staleness period");
|
||||
assert_eq!(rig.calls(), 1);
|
||||
assert_eq!(
|
||||
rig.meter.tick(NOW + 5 * MIN),
|
||||
Duration::from_millis(10 * MIN)
|
||||
);
|
||||
assert_eq!(rig.calls(), 1, "a fresh reading makes no call");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_reading_triggers_a_call_at_the_period_and_not_before() {
|
||||
let mut rig = rig();
|
||||
rig.cell.observe_at(NOW, reading("allowed"));
|
||||
rig.reads(NOW + 15 * MIN);
|
||||
rig.meter.tick(NOW + 15 * MIN - 1);
|
||||
assert_eq!(rig.calls(), 0, "one millisecond short of stale");
|
||||
rig.meter.tick(NOW + 15 * MIN);
|
||||
assert_eq!(rig.calls(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_past_its_reset_is_read_at_once_not_after_the_period() {
|
||||
let mut rig = rig();
|
||||
let now = unix_ms();
|
||||
let mut over = reading("allowed").remove(0);
|
||||
over.resets_at_unix_ms = 1;
|
||||
rig.cell.observe_at(now, vec![over]);
|
||||
rig.reads(now);
|
||||
rig.meter.tick(now);
|
||||
assert_eq!(rig.calls(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swarm_that_asks_for_nothing_spends_nothing_however_stale_the_reading() {
|
||||
let mut rig = rig();
|
||||
drop(rig.lease.take());
|
||||
for step in 0..10 {
|
||||
let at = NOW + 15 * MIN + step * 60 * MIN;
|
||||
assert_eq!(rig.meter.tick(at), CEILING);
|
||||
}
|
||||
assert_eq!(rig.calls(), 0);
|
||||
assert_eq!(rig.lines(), vec![State::Idle.line()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lease_asked_for_wakes_the_meter_and_the_empty_cell_is_read() {
|
||||
let mut rig = rig();
|
||||
drop(rig.lease.take());
|
||||
rig.reads(NOW + 180 * MIN);
|
||||
rig.meter.tick(NOW + 180 * MIN);
|
||||
assert_eq!(rig.calls(), 0, "asked three hours ago and let go");
|
||||
let _later = rig.cell.asking_at(NOW + 180 * MIN);
|
||||
rig.meter.tick(NOW + 180 * MIN);
|
||||
assert_eq!(rig.calls(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lease_let_go_is_still_wanted_for_exactly_one_staleness_period() {
|
||||
let mut rig = rig();
|
||||
drop(rig.lease.take());
|
||||
rig.reads(NOW + 15 * MIN - 1);
|
||||
rig.meter.tick(NOW + 15 * MIN - 1);
|
||||
assert_eq!(rig.calls(), 1, "one millisecond inside the period");
|
||||
rig.reads(NOW + 30 * MIN);
|
||||
rig.meter.tick(NOW + 30 * MIN);
|
||||
assert_eq!(rig.calls(), 1, "a period after the last ask: unwanted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lease_held_for_four_hours_keeps_the_week_read_throughout() {
|
||||
let mut rig = rig();
|
||||
for step in 0..=16 {
|
||||
let at = NOW + step * 15 * MIN;
|
||||
rig.reads(at);
|
||||
rig.meter.tick(at);
|
||||
}
|
||||
assert_eq!(
|
||||
rig.calls(),
|
||||
17,
|
||||
"one read per period, the lease never lapsing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_call_leaves_the_cell_and_backs_off_instead_of_hammering() {
|
||||
let mut rig = rig();
|
||||
rig.cell.observe_at(NOW, reading("allowed"));
|
||||
let before = rig.cell.snapshot();
|
||||
rig.fails("Provider");
|
||||
let mut at = NOW + 15 * MIN;
|
||||
let mut waits = Vec::new();
|
||||
for _ in 0..4 {
|
||||
waits.push(rig.meter.tick(at));
|
||||
at += duration_ms(*waits.last().unwrap());
|
||||
}
|
||||
assert_eq!(rig.calls(), 4);
|
||||
assert_eq!(rig.cell.snapshot(), before, "the cell is untouched");
|
||||
assert_eq!(
|
||||
waits,
|
||||
[15, 30, 60, 120].map(|m| Duration::from_secs(m * 60)),
|
||||
"the wait doubles per consecutive miss"
|
||||
);
|
||||
rig.meter.tick(at - MIN);
|
||||
assert_eq!(rig.calls(), 4, "nothing is asked before the backoff ends");
|
||||
assert_eq!(
|
||||
rig.lines(),
|
||||
vec!["meter: the call failed (Provider), backing off"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_failure_kind_is_logged_again_when_it_changes_and_not_when_it_repeats() {
|
||||
let mut rig = rig();
|
||||
rig.fails("Authentication");
|
||||
rig.meter.tick(NOW);
|
||||
rig.meter.tick(NOW + 15 * MIN);
|
||||
rig.fails("InvalidRequest");
|
||||
rig.meter.tick(NOW + 45 * MIN);
|
||||
assert_eq!(
|
||||
rig.lines(),
|
||||
vec![
|
||||
"meter: the call failed (Authentication), backing off",
|
||||
"meter: the call failed (InvalidRequest), backing off",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backoff_stops_at_the_ceiling_and_one_good_reading_resets_it() {
|
||||
assert_eq!(backoff(0), STALE);
|
||||
assert_eq!(backoff(1), STALE);
|
||||
assert_eq!(backoff(u32::MAX), CEILING);
|
||||
let mut rig = rig();
|
||||
rig.fails("Provider");
|
||||
rig.meter.tick(NOW);
|
||||
rig.meter.tick(NOW + 15 * MIN);
|
||||
assert_eq!(rig.meter.misses, 2);
|
||||
rig.reads(NOW + 45 * MIN);
|
||||
rig.meter.tick(NOW + 45 * MIN);
|
||||
assert_eq!(rig.meter.misses, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_that_completes_without_a_weekly_reading_is_a_miss_too() {
|
||||
let mut rig = rig();
|
||||
rig.reads_nothing();
|
||||
assert_eq!(rig.meter.tick(NOW), STALE);
|
||||
assert_eq!(rig.meter.tick(NOW + 15 * MIN), 2 * STALE);
|
||||
assert_eq!(rig.calls(), 2);
|
||||
assert_eq!(rig.lines(), vec![State::Unread.line()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_turn_that_refreshed_the_reading_and_then_errored_is_no_miss() {
|
||||
let mut rig = rig();
|
||||
*rig.script.lock().unwrap() = Script {
|
||||
reading_at: Some(NOW),
|
||||
status: "rejected".to_string(),
|
||||
fails_with: Some("RateLimited".to_string()),
|
||||
..Script::default()
|
||||
};
|
||||
assert_eq!(rig.meter.tick(NOW), STALE, "the next read is a period away");
|
||||
assert_eq!(rig.meter.misses, 0);
|
||||
assert_eq!(
|
||||
rig.lines(),
|
||||
vec![format!(
|
||||
"meter: weekly reading refreshed, permille 60 resets_at_unix_ms {RESET}"
|
||||
)]
|
||||
);
|
||||
rig.reads(NOW + 15 * MIN);
|
||||
rig.meter.tick(NOW + 15 * MIN);
|
||||
assert_eq!(rig.calls(), 2, "a rejected reading is kept fresh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reading_from_before_the_call_does_not_count_as_its_answer() {
|
||||
let mut rig = rig();
|
||||
// A slow concurrent sensor stamped earlier than this call began.
|
||||
rig.reads(NOW - 1);
|
||||
rig.meter.tick(NOW);
|
||||
assert_eq!(rig.meter.misses, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refresh_logs_the_reading_and_an_unchanged_value_logs_again() {
|
||||
let mut rig = rig();
|
||||
rig.reads(NOW);
|
||||
rig.meter.tick(NOW);
|
||||
rig.reads(NOW + 15 * MIN);
|
||||
rig.meter.tick(NOW + 15 * MIN);
|
||||
let line =
|
||||
format!("meter: weekly reading refreshed, permille 60 resets_at_unix_ms {RESET}");
|
||||
assert_eq!(rig.lines(), vec![line.clone(), line]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_logged_value_follows_the_reading_and_an_expired_week_is_unknown() {
|
||||
let mut rig = rig();
|
||||
for (at, permille) in [(NOW, 60), (NOW + 15 * MIN, 75)] {
|
||||
*rig.script.lock().unwrap() = Script {
|
||||
reading_at: Some(at),
|
||||
status: "allowed".to_string(),
|
||||
permille: Some(permille),
|
||||
resets_at: Some(RESET + permille as u64),
|
||||
..Script::default()
|
||||
};
|
||||
rig.meter.tick(at);
|
||||
}
|
||||
let mut expired = self::rig();
|
||||
let now = unix_ms();
|
||||
*expired.script.lock().unwrap() = Script {
|
||||
reading_at: Some(now),
|
||||
status: "allowed".to_string(),
|
||||
resets_at: Some(1),
|
||||
..Script::default()
|
||||
};
|
||||
expired.meter.tick(now);
|
||||
assert_eq!(
|
||||
expired.lines(),
|
||||
vec!["meter: weekly reading refreshed, permille unknown resets_at_unix_ms 1"]
|
||||
);
|
||||
assert_eq!(
|
||||
rig.lines(),
|
||||
vec![
|
||||
format!(
|
||||
"meter: weekly reading refreshed, permille 60 resets_at_unix_ms {}",
|
||||
RESET + 60
|
||||
),
|
||||
format!(
|
||||
"meter: weekly reading refreshed, permille 75 resets_at_unix_ms {}",
|
||||
RESET + 75
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_logs_once_per_change_however_often_it_repeats() {
|
||||
let mut rig = rig();
|
||||
rig.lease = None;
|
||||
for step in 0..3 {
|
||||
rig.meter.tick(NOW + 60 * MIN * (step + 1));
|
||||
}
|
||||
assert_eq!(rig.lines(), vec![State::Idle.line()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_log_says_what_the_meter_is_doing_in_words() {
|
||||
assert_eq!(
|
||||
State::Idle.line(),
|
||||
"meter: no lease asked lately, making no call"
|
||||
);
|
||||
assert_eq!(
|
||||
State::Read {
|
||||
permille: None,
|
||||
resets_at_unix_ms: 7
|
||||
}
|
||||
.line(),
|
||||
"meter: weekly reading refreshed, permille unknown resets_at_unix_ms 7"
|
||||
);
|
||||
assert_eq!(
|
||||
State::Unread.line(),
|
||||
"meter: the call completed without a weekly reading, backing off"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clock_is_the_system_clock_in_unix_milliseconds() {
|
||||
let before = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
|
||||
let read = unix_ms();
|
||||
let after = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
|
||||
assert!((before.as_millis() as u64..=after.as_millis() as u64).contains(&read));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_started_meter_sleeps_until_a_lease_asks_and_then_reads() {
|
||||
let cell = Arc::new(QuotaCell::new());
|
||||
let made = Arc::new(AtomicUsize::new(0));
|
||||
let probe = Calls {
|
||||
cell: cell.clone(),
|
||||
made: made.clone(),
|
||||
script: Arc::new(Mutex::new(Script {
|
||||
reading_at: Some(unix_ms() + 60 * MIN),
|
||||
status: "allowed".to_string(),
|
||||
fails_with: None,
|
||||
..Script::default()
|
||||
})),
|
||||
};
|
||||
start(cell.clone(), Box::new(probe)).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
assert_eq!(made.load(Ordering::SeqCst), 0, "no lease, no call");
|
||||
let _lease = cell.asking();
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(10);
|
||||
while made.load(Ordering::SeqCst) == 0 {
|
||||
assert!(std::time::Instant::now() < deadline, "the ask woke nobody");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert_eq!(cell.snapshot_with_week(Duration::ZERO).windows.len(), 1);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,38 +1,150 @@
|
|||
//! The plan's own usage windows, as the CLI reports them. The subscription
|
||||
//! decides how much a plan may burn; the CLI's `rate_limit_event` is the only
|
||||
//! place that number appears, so the latest observation of each window is kept
|
||||
//! here and read out beside the connector's own spend ledger.
|
||||
//! The plan's own usage windows, as the subscription reports them. The
|
||||
//! subscription decides how much a plan may burn, and one sensor observes it:
|
||||
//! the CLI's `rate_limit_event` on the connector's own calls, which the
|
||||
//! `meter` makes when the week's reading goes stale. The latest observation of
|
||||
//! each window is kept here and published as the usage readout and lent with
|
||||
//! each lease.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use model_connector::{PlanQuota, PlanQuotaSnapshot};
|
||||
|
||||
/// The window the weekly pacing reads, and the one the meter keeps fresh.
|
||||
pub(crate) const WEEK: &str = "seven_day";
|
||||
/// The windows the pacing reads, and so the only ones the cell keeps.
|
||||
pub(crate) const PACED: [&str; 2] = ["five_hour", WEEK];
|
||||
|
||||
/// How often a lease waiting for its first reading looks at the cell again.
|
||||
const FIRST_READ_POLL: Duration = Duration::from_millis(50);
|
||||
|
||||
/// The latest observation of each plan window, shared by the backend that
|
||||
/// feeds it and whatever reads it out. Each window carries the time of its
|
||||
/// own observation: an event that names one window says nothing about the
|
||||
/// others.
|
||||
///
|
||||
/// It also keeps who is asking: a lease request is the swarm's only sign of
|
||||
/// life the connector sees, and the meter reads the plan only while someone
|
||||
/// asks.
|
||||
#[derive(Default)]
|
||||
pub struct QuotaCell(Mutex<BTreeMap<String, PlanQuota>>);
|
||||
pub struct QuotaCell {
|
||||
windows: Mutex<BTreeMap<String, PlanQuota>>,
|
||||
asks: Mutex<Asks>,
|
||||
asked: Condvar,
|
||||
metered: AtomicBool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Asks {
|
||||
/// Lease requests in flight or held.
|
||||
live: usize,
|
||||
/// Requests ever made; the meter sleeps until it changes.
|
||||
count: u64,
|
||||
/// When the latest request came, unix ms.
|
||||
last_ms: Option<u64>,
|
||||
}
|
||||
|
||||
/// A lease request while it is in flight or held. Dropping it is the lease
|
||||
/// ending, by whatever road.
|
||||
pub(crate) struct Asking(Arc<QuotaCell>);
|
||||
|
||||
impl Drop for Asking {
|
||||
fn drop(&mut self) {
|
||||
let mut asks = self.0.asks.lock().unwrap_or_else(|e| e.into_inner());
|
||||
asks.live = asks.live.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
|
||||
impl QuotaCell {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Records the windows one event reported, stamping each with now. Each
|
||||
/// replaces that window's earlier observation, and windows the event did
|
||||
/// not mention stay as they were, stamp included.
|
||||
/// Notes a lease request, now, and wakes the meter.
|
||||
pub(crate) fn asking(self: &Arc<Self>) -> Asking {
|
||||
self.asking_at(unix_ms())
|
||||
}
|
||||
|
||||
pub(crate) fn asking_at(self: &Arc<Self>, now: u64) -> Asking {
|
||||
{
|
||||
let mut asks = self.asks.lock().unwrap_or_else(|e| e.into_inner());
|
||||
asks.live += 1;
|
||||
asks.count += 1;
|
||||
asks.last_ms = Some(now);
|
||||
}
|
||||
self.asked.notify_all();
|
||||
Asking(self.clone())
|
||||
}
|
||||
|
||||
/// Whether a lease is held, or one was asked for less than `within` ago.
|
||||
pub(crate) fn wanted_at(&self, now: u64, within: Duration) -> bool {
|
||||
let asks = self.asks.lock().unwrap_or_else(|e| e.into_inner());
|
||||
asks.live > 0
|
||||
|| asks.last_ms.is_some_and(|last| {
|
||||
now < last.saturating_add(u64::try_from(within.as_millis()).unwrap_or(u64::MAX))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn asks_so_far(&self) -> u64 {
|
||||
self.asks.lock().unwrap_or_else(|e| e.into_inner()).count
|
||||
}
|
||||
|
||||
/// Sleeps up to `limit`, or until a request beyond the first `seen` comes.
|
||||
pub(crate) fn sleep_until_asked(&self, seen: u64, limit: Duration) {
|
||||
let asks = self.asks.lock().unwrap_or_else(|e| e.into_inner());
|
||||
drop(
|
||||
self.asked
|
||||
.wait_timeout_while(asks, limit, |asks| asks.count == seen)
|
||||
.unwrap_or_else(|e| e.into_inner()),
|
||||
);
|
||||
}
|
||||
|
||||
/// Declares that a meter reads this cell, so a first lease may wait for it.
|
||||
pub(crate) fn attach_meter(&self) {
|
||||
self.metered.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// The windows as they stand, but with no weekly reading yet (a restart
|
||||
/// leaves the cell empty) a metered cell is given up to `within` to get
|
||||
/// one, so a lease is not lent "unobserved" for want of a few seconds.
|
||||
pub(crate) fn snapshot_with_week(&self, within: Duration) -> PlanQuotaSnapshot {
|
||||
let deadline = Instant::now() + within;
|
||||
loop {
|
||||
let snapshot = self.snapshot();
|
||||
let read = snapshot
|
||||
.windows
|
||||
.iter()
|
||||
.any(|quota| quota.window == WEEK && quota.status != EXPIRED);
|
||||
let now = Instant::now();
|
||||
if read || !self.metered.load(Ordering::SeqCst) || now >= deadline {
|
||||
return snapshot;
|
||||
}
|
||||
std::thread::sleep(FIRST_READ_POLL.min(deadline - now));
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the windows one event reported, stamping each with now. See
|
||||
/// [`QuotaCell::observe_at`] for how a reading combines with what is held.
|
||||
pub fn observe(&self, windows: impl IntoIterator<Item = PlanQuota>) {
|
||||
self.observe_at(unix_ms(), windows);
|
||||
}
|
||||
|
||||
fn observe_at(&self, now: u64, windows: impl IntoIterator<Item = PlanQuota>) {
|
||||
let mut held = self.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
/// Records readings taken at `at` (unix ms). A reading older than the
|
||||
/// held one is dropped, so a slow call cannot replace what a faster one
|
||||
/// saw meanwhile. Windows the readings did not mention stay as they were,
|
||||
/// stamp included.
|
||||
pub fn observe_at(&self, at: u64, windows: impl IntoIterator<Item = PlanQuota>) {
|
||||
let mut held = self.windows.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for mut quota in windows {
|
||||
quota.observed_at_unix_ms = now;
|
||||
held.insert(quota.window.clone(), quota);
|
||||
quota.observed_at_unix_ms = at;
|
||||
if held
|
||||
.get("a.window)
|
||||
.is_none_or(|current| quota.observed_at_unix_ms >= current.observed_at_unix_ms)
|
||||
{
|
||||
held.insert(quota.window.clone(), quota);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -43,8 +155,8 @@ impl QuotaCell {
|
|||
/// The windows as of `now`. One whose reset time has passed is reported
|
||||
/// `expired` with no utilization: the reading described a window that no
|
||||
/// longer exists.
|
||||
fn snapshot_at(&self, now: u64) -> PlanQuotaSnapshot {
|
||||
let held = self.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
pub(crate) fn snapshot_at(&self, now: u64) -> PlanQuotaSnapshot {
|
||||
let held = self.windows.lock().unwrap_or_else(|e| e.into_inner());
|
||||
PlanQuotaSnapshot {
|
||||
windows: held
|
||||
.values()
|
||||
|
|
@ -62,7 +174,7 @@ impl QuotaCell {
|
|||
}
|
||||
|
||||
/// The status of a window whose reset has passed since it was observed.
|
||||
const EXPIRED: &str = "expired";
|
||||
pub(crate) const EXPIRED: &str = "expired";
|
||||
|
||||
fn unix_ms() -> u64 {
|
||||
SystemTime::now()
|
||||
|
|
@ -133,6 +245,38 @@ mod tests {
|
|||
assert_eq!(expired[0].resets_at_unix_ms, RESET);
|
||||
}
|
||||
|
||||
fn with_status(mut quota: PlanQuota, status: &str) -> PlanQuota {
|
||||
quota.status = status.to_string();
|
||||
quota
|
||||
}
|
||||
|
||||
fn held(cell: &QuotaCell) -> (String, Option<u32>, u64) {
|
||||
let window = cell.snapshot_at(250).windows.remove(0);
|
||||
(
|
||||
window.status,
|
||||
window.utilization_permille,
|
||||
window.observed_at_unix_ms,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reading_older_than_the_held_one_is_dropped_and_an_equal_one_replaces() {
|
||||
let cell = QuotaCell::new();
|
||||
cell.observe_at(200, [quota("five_hour", 80, 0)]);
|
||||
cell.observe_at(100, [quota("five_hour", 10, 0)]);
|
||||
assert_eq!(held(&cell), ("allowed".to_string(), Some(80), 200));
|
||||
cell.observe_at(200, [quota("five_hour", 90, 0)]);
|
||||
assert_eq!(held(&cell), ("allowed".to_string(), Some(90), 200));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newer_reading_lifts_a_rejection() {
|
||||
let cell = QuotaCell::new();
|
||||
cell.observe_at(100, [with_status(quota("five_hour", 1000, 0), "rejected")]);
|
||||
cell.observe_at(200, [quota("five_hour", 300, 0)]);
|
||||
assert_eq!(held(&cell), ("allowed".to_string(), Some(300), 200));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_live_clock_stamps_and_expires() {
|
||||
let cell = QuotaCell::new();
|
||||
|
|
@ -148,4 +292,114 @@ mod tests {
|
|||
assert_eq!(windows[0].utilization_permille, Some(80));
|
||||
assert_eq!(windows[1].status, "expired");
|
||||
}
|
||||
|
||||
const HOUR: u64 = 3_600_000;
|
||||
|
||||
#[test]
|
||||
fn nobody_wants_the_plan_before_anyone_asks() {
|
||||
let cell = Arc::new(QuotaCell::new());
|
||||
assert!(!cell.wanted_at(0, Duration::from_secs(900)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lease_in_flight_or_held_is_wanted_for_as_long_as_it_lives() {
|
||||
let cell = Arc::new(QuotaCell::new());
|
||||
let lease = cell.asking_at(1_000);
|
||||
let other = cell.asking_at(2_000);
|
||||
let day = Duration::from_secs(86_400);
|
||||
assert!(cell.wanted_at(1_000 + 4 * HOUR, Duration::from_secs(1)));
|
||||
drop(lease);
|
||||
assert!(cell.wanted_at(1_000 + 4 * HOUR, Duration::from_secs(1)), "one lease still lives");
|
||||
drop(other);
|
||||
assert!(!cell.wanted_at(1_000 + 4 * HOUR, Duration::from_secs(1)));
|
||||
assert!(cell.wanted_at(2_000 + 4 * HOUR, day), "within the window of the last ask");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lease_let_go_is_wanted_until_exactly_the_period_after_its_ask() {
|
||||
let cell = Arc::new(QuotaCell::new());
|
||||
drop(cell.asking_at(10_000));
|
||||
let period = Duration::from_millis(900);
|
||||
assert!(cell.wanted_at(10_899, period));
|
||||
assert!(!cell.wanted_at(10_900, period));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_ask_is_counted_and_wakes_a_sleeper_at_once() {
|
||||
let cell = Arc::new(QuotaCell::new());
|
||||
assert_eq!(cell.asks_so_far(), 0);
|
||||
let sleeper = {
|
||||
let cell = cell.clone();
|
||||
std::thread::spawn(move || {
|
||||
let started = Instant::now();
|
||||
cell.sleep_until_asked(0, Duration::from_secs(30));
|
||||
started.elapsed()
|
||||
})
|
||||
};
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
drop(cell.asking());
|
||||
assert!(sleeper.join().unwrap() < Duration::from_secs(10), "woken, not timed out");
|
||||
assert_eq!(cell.asks_so_far(), 1);
|
||||
// An ask that came after `seen` was read ends the sleep before it starts.
|
||||
let started = Instant::now();
|
||||
cell.sleep_until_asked(0, Duration::from_secs(30));
|
||||
assert!(started.elapsed() < Duration::from_secs(10));
|
||||
// Nothing new: the sleep is the whole limit.
|
||||
let started = Instant::now();
|
||||
cell.sleep_until_asked(1, Duration::from_millis(200));
|
||||
assert!(started.elapsed() >= Duration::from_millis(200));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_metered_cell_with_no_week_gives_a_first_lease_the_reading_when_it_lands() {
|
||||
let cell = Arc::new(QuotaCell::new());
|
||||
cell.attach_meter();
|
||||
let feeder = {
|
||||
let cell = cell.clone();
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
cell.observe([quota(WEEK, 60, 0)]);
|
||||
})
|
||||
};
|
||||
let plan = cell.snapshot_with_week(Duration::from_secs(20));
|
||||
feeder.join().unwrap();
|
||||
assert_eq!(plan.windows.len(), 1, "the lease waited for the week");
|
||||
assert_eq!(plan.windows[0].window, WEEK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_wait_for_the_first_reading_is_bounded() {
|
||||
let cell = Arc::new(QuotaCell::new());
|
||||
cell.attach_meter();
|
||||
let started = Instant::now();
|
||||
let plan = cell.snapshot_with_week(Duration::from_millis(300));
|
||||
let waited = started.elapsed();
|
||||
assert!(plan.windows.is_empty(), "no reading came: unobserved, not hung");
|
||||
assert!(waited >= Duration::from_millis(300), "{waited:?}");
|
||||
assert!(waited < Duration::from_secs(10), "{waited:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cell_nobody_meters_or_that_holds_the_week_is_never_waited_on() {
|
||||
let bare = QuotaCell::new();
|
||||
let started = Instant::now();
|
||||
assert!(bare.snapshot_with_week(Duration::from_secs(20)).windows.is_empty());
|
||||
let held = QuotaCell::new();
|
||||
held.attach_meter();
|
||||
held.observe([quota(WEEK, 60, 0)]);
|
||||
assert_eq!(held.snapshot_with_week(Duration::from_secs(20)).windows.len(), 1);
|
||||
assert!(started.elapsed() < Duration::from_secs(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_week_past_its_reset_is_waited_on_like_no_week() {
|
||||
let cell = QuotaCell::new();
|
||||
cell.attach_meter();
|
||||
let mut over = quota(WEEK, 60, 0);
|
||||
over.resets_at_unix_ms = 1;
|
||||
cell.observe([over]);
|
||||
let started = Instant::now();
|
||||
cell.snapshot_with_week(Duration::from_millis(300));
|
||||
assert!(started.elapsed() >= Duration::from_millis(300));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,14 +7,14 @@ use model_connector::{FailureKind, PlanQuota, StopReason, Usage};
|
|||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::quota::QuotaCell;
|
||||
use crate::quota::{PACED, QuotaCell};
|
||||
|
||||
/// The tool the CLI gives the model to deliver an answer that must match a
|
||||
/// `--json-schema`. Its call is the structured output, not a tool exchange.
|
||||
const STRUCTURED_OUTPUT_TOOL: &str = "StructuredOutput";
|
||||
|
||||
/// A call that cannot complete, with the stage that failed. `usage` is `None`
|
||||
/// (the kit bills its reservation) unless a result event reported it or the
|
||||
/// (unknown) unless a result event reported it or the
|
||||
/// call never reached the provider (zero).
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Failure {
|
||||
|
|
@ -25,7 +25,7 @@ pub(crate) struct Failure {
|
|||
|
||||
impl Failure {
|
||||
/// A failure after the child ran: what the provider billed is unknown, so
|
||||
/// the kit bills its reservation.
|
||||
/// the usage is unknown.
|
||||
pub(crate) fn cost_unknown(kind: FailureKind, message: &'static str) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
|
|
@ -121,7 +121,7 @@ pub(crate) struct StreamState<'a> {
|
|||
/// Whether that schema's top type admits an object (absent counts): the
|
||||
/// structured output must be an object, never a bare scalar or array.
|
||||
schema_top_is_object: bool,
|
||||
quota: &'a QuotaCell,
|
||||
quota: Option<&'a QuotaCell>,
|
||||
session_id: Option<String>,
|
||||
texts: Vec<String>,
|
||||
message_id: Option<String>,
|
||||
|
|
@ -130,7 +130,7 @@ pub(crate) struct StreamState<'a> {
|
|||
|
||||
impl<'a> StreamState<'a> {
|
||||
/// `schema` is the request's output schema text, when it carried one.
|
||||
pub(crate) fn new(model: &'a str, schema: Option<&str>, quota: &'a QuotaCell) -> Self {
|
||||
pub(crate) fn new(model: &'a str, schema: Option<&str>, quota: Option<&'a QuotaCell>) -> Self {
|
||||
let top = schema
|
||||
.and_then(|text| serde_json::from_str::<Value>(text).ok())
|
||||
.and_then(|schema| schema.get("type").cloned());
|
||||
|
|
@ -176,7 +176,9 @@ impl<'a> StreamState<'a> {
|
|||
if let Some(info) = &line.rate_limit_info {
|
||||
self.plan_rejected |=
|
||||
info.get("status").and_then(Value::as_str) == Some("rejected");
|
||||
self.quota.observe(plan_windows(info));
|
||||
if let Some(quota) = self.quota {
|
||||
quota.observe(plan_windows(info));
|
||||
}
|
||||
}
|
||||
Step::More
|
||||
}
|
||||
|
|
@ -320,12 +322,16 @@ impl<'a> StreamState<'a> {
|
|||
/// `rate_limit_info.unifiedWindows`: utilization as a fraction of the window,
|
||||
/// reset as unix seconds. A window missing any of its three fields is skipped;
|
||||
/// an unknown reading is never zero.
|
||||
/// Only the windows pacing reads are taken ([`PACED`]): the event also names
|
||||
/// per-model buckets, and one of those reading `rejected` must not close every
|
||||
/// lease.
|
||||
fn plan_windows(info: &Value) -> Vec<PlanQuota> {
|
||||
let Some(windows) = info.get("unifiedWindows").and_then(Value::as_object) else {
|
||||
return Vec::new();
|
||||
};
|
||||
windows
|
||||
.iter()
|
||||
.filter(|(window, _)| PACED.contains(&window.as_str()))
|
||||
.filter_map(|(window, reading)| {
|
||||
let utilization = reading.get("utilization")?.as_f64()?;
|
||||
let resets_at = reading.get("resetsAt")?.as_u64()?;
|
||||
|
|
@ -356,7 +362,7 @@ fn fail(kind: FailureKind, message: &'static str) -> Step {
|
|||
/// provider cannot have billed (`empty_is_zero`: a refusal at the door, 401,
|
||||
/// 403 or 429, or a call never made); elsewhere the CLI also zeroes usage on
|
||||
/// crashes after real work. A call never made (`absent_is_zero`) may also
|
||||
/// omit the field. `None` is billed the reservation by the kit.
|
||||
/// omit the field. `None` is unknown usage.
|
||||
fn read_usage(reported: Option<Value>, empty_is_zero: bool, absent_is_zero: bool) -> Option<Usage> {
|
||||
let Some(reported) = reported else {
|
||||
return absent_is_zero.then(|| sum_usage(std::iter::empty()));
|
||||
|
|
@ -392,3 +398,50 @@ fn sum_usage(models: impl Iterator<Item = ModelUsage>) -> Usage {
|
|||
}
|
||||
usage
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn windows(body: &str) -> Vec<(String, Option<u32>, u64)> {
|
||||
let info: Value = serde_json::from_str(&format!(r#"{{"unifiedWindows":{body}}}"#)).unwrap();
|
||||
plan_windows(&info)
|
||||
.into_iter()
|
||||
.map(|q| (q.window, q.utilization_permille, q.resets_at_unix_ms))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_five_hour_and_seven_day_windows_are_taken() {
|
||||
let taken = windows(
|
||||
r#"{"five_hour":{"utilization":0.5,"resetsAt":2,"status":"allowed"},
|
||||
"seven_day":{"utilization":0.25,"resetsAt":3,"status":"allowed"},
|
||||
"seven_day_opus":{"utilization":0.1,"resetsAt":4,"status":"allowed"},
|
||||
"seven_day_overage_included":{"utilization":1,"resetsAt":5,"status":"rejected"}}"#,
|
||||
);
|
||||
assert_eq!(
|
||||
taken,
|
||||
vec![
|
||||
("five_hour".to_string(), Some(500), 2000),
|
||||
("seven_day".to_string(), Some(250), 3000),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_missing_a_field_or_of_the_wrong_type_costs_only_itself() {
|
||||
// Unknown is never zero: such a window is skipped, not read as empty.
|
||||
for broken in [
|
||||
r#"{"resetsAt":2,"status":"allowed"}"#,
|
||||
r#"{"utilization":0.5,"status":"allowed"}"#,
|
||||
r#"{"utilization":0.5,"resetsAt":2}"#,
|
||||
r#"{"utilization":"high","resetsAt":2,"status":"allowed"}"#,
|
||||
r#"{"utilization":-0.5,"resetsAt":2,"status":"allowed"}"#,
|
||||
] {
|
||||
let both = windows(&format!(
|
||||
r#"{{"five_hour":{broken},"seven_day":{{"utilization":0,"resetsAt":3,"status":"allowed"}}}}"#
|
||||
));
|
||||
assert_eq!(both, vec![("seven_day".to_string(), Some(0), 3000)], "{broken}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
769
crates/claude-connector/tests/ask.rs
Normal file
769
crates/claude-connector/tests/ask.rs
Normal file
|
|
@ -0,0 +1,769 @@
|
|||
//! `claude-connector ask` against a real serve loop on loopback with a scripted
|
||||
//! backend: the consumer side of the no-tools completion.
|
||||
|
||||
use std::net::{SocketAddr, TcpListener};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use claude_connector::ask::{AskArgs, AskError, ask, build_invocation};
|
||||
use model_connector::*;
|
||||
|
||||
const CALLER: &str = "ask-caller";
|
||||
const KEY: &str = "ask-test-key-0123456789-abcdefghijklmnop";
|
||||
const MODEL: &str = "claude-haiku-5-5";
|
||||
const FRAME: usize = 4 << 20;
|
||||
|
||||
/// What the scripted backend does with each call.
|
||||
#[derive(Clone)]
|
||||
enum Script {
|
||||
Text(&'static str),
|
||||
Empty,
|
||||
Failed(&'static str),
|
||||
Sleep(Duration),
|
||||
ToolCall,
|
||||
Stop(StopReason),
|
||||
}
|
||||
|
||||
struct Backend {
|
||||
script: Script,
|
||||
seen: Mutex<Vec<ProviderRequest>>,
|
||||
}
|
||||
|
||||
impl ProviderBackend for Backend {
|
||||
fn ready(&self) -> Result<(), &'static str> {
|
||||
Ok(())
|
||||
}
|
||||
fn provider(&self) -> &str {
|
||||
"claude-code"
|
||||
}
|
||||
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
||||
self.seen.lock().unwrap().push(call.request().clone());
|
||||
let usage = Usage {
|
||||
input_tokens: 1,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
output_tokens: 1,
|
||||
reasoning_tokens: None,
|
||||
};
|
||||
let text = |t: &str| {
|
||||
vec![TransportEvent {
|
||||
sequence: 0,
|
||||
payload: TransportEventPayload::TextDelta { text: t.into() },
|
||||
}]
|
||||
};
|
||||
let stop = match &self.script {
|
||||
Script::Stop(reason) => *reason,
|
||||
_ => StopReason::EndTurn,
|
||||
};
|
||||
let completed = TransportOutcome::Completed {
|
||||
provider_response_id: None,
|
||||
stop_reason: stop,
|
||||
usage: usage.clone(),
|
||||
};
|
||||
match &self.script {
|
||||
Script::Text(t) => call.transported(text(t), completed),
|
||||
Script::Empty => call.transported(Vec::new(), completed),
|
||||
Script::Failed(message) => call.transported(
|
||||
Vec::new(),
|
||||
TransportOutcome::Failed {
|
||||
kind: FailureKind::Provider,
|
||||
message: message.to_string(),
|
||||
usage: None,
|
||||
},
|
||||
),
|
||||
Script::Stop(_) => call.transported(text("cut off"), completed),
|
||||
Script::ToolCall => call.transported(
|
||||
vec![TransportEvent {
|
||||
sequence: 0,
|
||||
payload: TransportEventPayload::ToolCall {
|
||||
call_id: "c".into(),
|
||||
name: "n".into(),
|
||||
arguments: "{}".into(),
|
||||
},
|
||||
}],
|
||||
completed,
|
||||
),
|
||||
Script::Sleep(d) => {
|
||||
thread::sleep(*d);
|
||||
call.transported(text("late"), completed)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_key(path: &std::path::Path, bytes: &[u8], mode: u32) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::write(path, bytes).unwrap();
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
|
||||
}
|
||||
|
||||
struct Rig {
|
||||
endpoint: SocketAddr,
|
||||
dir: PathBuf,
|
||||
key_file: PathBuf,
|
||||
backend: Arc<Backend>,
|
||||
}
|
||||
|
||||
fn rig(script: Script) -> Rig {
|
||||
static SEQ: AtomicUsize = AtomicUsize::new(0);
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"claude-connector-ask-{}-{}",
|
||||
std::process::id(),
|
||||
SEQ.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let key_file = dir.join("caller.key");
|
||||
write_key(&key_file, format!("{KEY}\n").as_bytes(), 0o600);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let endpoint = listener.local_addr().unwrap();
|
||||
let admission =
|
||||
CallerAdmission::new(CALLER, KEY, 1, [MODEL.to_string()], 4, 1 << 20, 4_096).unwrap();
|
||||
let limits = ServeLimits {
|
||||
max_frame_bytes: FRAME,
|
||||
max_connections: 8,
|
||||
socket_timeout_ms: 5_000,
|
||||
max_expiry_skew_ms: 300_000,
|
||||
};
|
||||
let backend = Arc::new(Backend {
|
||||
script,
|
||||
seen: Mutex::new(Vec::new()),
|
||||
});
|
||||
let served = backend.clone();
|
||||
let store = dir.join("replay.cc");
|
||||
thread::spawn(move || serve(listener, limits, vec![admission], &store, served));
|
||||
Rig {
|
||||
endpoint,
|
||||
dir,
|
||||
key_file,
|
||||
backend,
|
||||
}
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn args(&self) -> AskArgs {
|
||||
AskArgs {
|
||||
endpoint: self.endpoint,
|
||||
caller_id: CALLER.into(),
|
||||
key_file: self.key_file.clone(),
|
||||
model: MODEL.into(),
|
||||
instructions: "Answer briefly.".into(),
|
||||
effort: Some(ReasoningEffort::Low),
|
||||
max_output_tokens: 1_024,
|
||||
timeout: Duration::from_secs(5),
|
||||
prompt: "SECRET-PROMPT-TEXT".into(),
|
||||
}
|
||||
}
|
||||
fn seen(&self) -> Vec<ProviderRequest> {
|
||||
self.backend.seen.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn message(error: &AskError) -> String {
|
||||
error.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn success_returns_the_answer_text_and_the_backend_saw_a_toolless_request() {
|
||||
let rig = rig(Script::Text("four"));
|
||||
assert_eq!(ask(&rig.args()).unwrap(), "four");
|
||||
let seen = rig.seen();
|
||||
assert_eq!(seen.len(), 1);
|
||||
assert!(seen[0].tools.is_empty());
|
||||
assert_eq!(seen[0].model, MODEL);
|
||||
assert_eq!(seen[0].instructions, "Answer briefly.");
|
||||
assert_eq!(seen[0].reasoning_effort, Some(ReasoningEffort::Low));
|
||||
assert_eq!(seen[0].max_output_tokens, 1_024);
|
||||
assert_eq!(
|
||||
seen[0].input,
|
||||
vec![InputItem::UserText {
|
||||
text: "SECRET-PROMPT-TEXT".into()
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_run_uses_a_fresh_request_id_so_replay_never_answers_a_new_question() {
|
||||
let rig = rig(Script::Text("again"));
|
||||
ask(&rig.args()).unwrap();
|
||||
ask(&rig.args()).unwrap();
|
||||
let seen = rig.seen();
|
||||
assert_eq!(seen.len(), 2, "the provider ran once per run");
|
||||
assert_ne!(seen[0].request_id, seen[1].request_id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cli_cannot_construct_a_request_with_tools() {
|
||||
let rig = rig(Script::Text("x"));
|
||||
let invocation = build_invocation(&rig.args()).unwrap();
|
||||
assert!(invocation.request.tools.is_empty());
|
||||
assert_eq!(invocation.request.tool_choice, ToolChoice::Auto);
|
||||
assert!(
|
||||
invocation
|
||||
.request
|
||||
.input
|
||||
.iter()
|
||||
.all(|item| matches!(item, InputItem::UserText { .. }))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_model_outside_allowed_models_is_refused_loudly() {
|
||||
let rig = rig(Script::Text("x"));
|
||||
let mut args = rig.args();
|
||||
args.model = "claude-opus-5".into();
|
||||
let error = ask(&args).unwrap_err();
|
||||
assert!(
|
||||
matches!(error, AskError::Refused(Refusal::ModelNotAllowed)),
|
||||
"{error}"
|
||||
);
|
||||
assert!(rig.seen().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_output_bound_over_the_callers_cap_is_refused() {
|
||||
let rig = rig(Script::Text("x"));
|
||||
let mut args = rig.args();
|
||||
args.max_output_tokens = 4_097;
|
||||
assert!(matches!(
|
||||
ask(&args).unwrap_err(),
|
||||
AskError::Refused(Refusal::OutputBound)
|
||||
));
|
||||
assert!(rig.seen().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_key_or_caller_is_an_error_and_never_reaches_the_provider() {
|
||||
let rig = rig(Script::Text("x"));
|
||||
let mut wrong_key = rig.args();
|
||||
let other = rig.dir.join("other.key");
|
||||
write_key(&other, b"some-other-connection-key-0123456789", 0o600);
|
||||
wrong_key.key_file = other;
|
||||
let error = ask(&wrong_key).unwrap_err();
|
||||
assert!(!message(&error).contains("some-other"), "{error}");
|
||||
let mut wrong_caller = rig.args();
|
||||
wrong_caller.caller_id = "someone-else".into();
|
||||
ask(&wrong_caller).unwrap_err();
|
||||
assert!(rig.seen().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unusable_key_file_errors_without_echoing_its_contents() {
|
||||
let rig = rig(Script::Text("x"));
|
||||
let cases: Vec<(&str, Vec<u8>)> = vec![
|
||||
("empty", b"\n".to_vec()),
|
||||
("long", vec![b'k'; 2_000]),
|
||||
("binary", vec![0xff, 0xfe, 0xfd, 0x41]),
|
||||
("padded", b" spaced-secret-value-padded ".to_vec()),
|
||||
];
|
||||
for (name, bytes) in cases {
|
||||
let path = rig.dir.join(format!("{name}.key"));
|
||||
write_key(&path, &bytes, 0o600);
|
||||
let mut args = rig.args();
|
||||
args.key_file = path;
|
||||
let text = message(&ask(&args).unwrap_err());
|
||||
assert!(!text.contains("spaced-secret"), "{name}: {text}");
|
||||
assert!(!text.contains("kkkk"), "{name}: {text}");
|
||||
}
|
||||
let mut missing = rig.args();
|
||||
missing.key_file = rig.dir.join("absent.key");
|
||||
assert!(matches!(
|
||||
ask(&missing).unwrap_err(),
|
||||
AskError::KeyUnreadable
|
||||
));
|
||||
let mut directory = rig.args();
|
||||
directory.key_file = rig.dir.clone();
|
||||
assert!(matches!(
|
||||
ask(&directory).unwrap_err(),
|
||||
AskError::KeyNotRegular
|
||||
));
|
||||
assert!(rig.seen().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_answer_is_an_error() {
|
||||
for script in [Script::Empty, Script::Text(" \n")] {
|
||||
let rig = rig(script);
|
||||
assert!(matches!(
|
||||
ask(&rig.args()).unwrap_err(),
|
||||
AskError::EmptyAnswer
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_prompt_is_an_error_before_any_connection() {
|
||||
let rig = rig(Script::Text("x"));
|
||||
let mut args = rig.args();
|
||||
args.prompt = " \n\t".into();
|
||||
assert!(matches!(ask(&args).unwrap_err(), AskError::EmptyPrompt));
|
||||
assert!(rig.seen().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_provider_failure_names_its_kind_and_not_its_message() {
|
||||
let rig = rig(Script::Failed("stderr tail with SECRET-PROMPT-TEXT"));
|
||||
let error = ask(&rig.args()).unwrap_err();
|
||||
assert!(matches!(error, AskError::Failed(FailureKind::Provider)));
|
||||
assert!(!message(&error).contains("SECRET"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connector_that_does_not_answer_in_time_is_a_timeout() {
|
||||
let rig = rig(Script::Sleep(Duration::from_secs(3)));
|
||||
let mut args = rig.args();
|
||||
args.timeout = Duration::from_millis(300);
|
||||
assert!(matches!(ask(&args).unwrap_err(), AskError::Timeout));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dead_endpoint_is_a_connection_error() {
|
||||
let rig = rig(Script::Text("x"));
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let mut args = rig.args();
|
||||
args.endpoint = listener.local_addr().unwrap();
|
||||
drop(listener);
|
||||
assert!(matches!(ask(&args).unwrap_err(), AskError::NotListening));
|
||||
}
|
||||
|
||||
fn run_binary(rig: &Rig, stdin: &str, extra: &[&str]) -> std::process::Output {
|
||||
run_binary_with_key(rig, &rig.key_file, stdin, extra)
|
||||
}
|
||||
|
||||
fn run_binary_with_key(
|
||||
rig: &Rig,
|
||||
key_file: &std::path::Path,
|
||||
stdin: &str,
|
||||
extra: &[&str],
|
||||
) -> std::process::Output {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_claude-connector"))
|
||||
.args(["ask", "--endpoint", &rig.endpoint.to_string()])
|
||||
.args([
|
||||
"--caller-id",
|
||||
CALLER,
|
||||
"--model",
|
||||
MODEL,
|
||||
"--system",
|
||||
"Be brief.",
|
||||
])
|
||||
.args(["--connection-key-file", key_file.to_str().unwrap()])
|
||||
.args(extra)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
{
|
||||
use std::io::Write;
|
||||
let _ = child.stdin.take().unwrap().write_all(stdin.as_bytes());
|
||||
}
|
||||
child.wait_with_output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_toolcall_in_the_answer_is_an_error() {
|
||||
let rig = rig(Script::ToolCall);
|
||||
assert!(matches!(ask(&rig.args()).unwrap_err(), AskError::ToolCall));
|
||||
}
|
||||
|
||||
/// The rule: only a turn that ended (end of turn or a stop sequence) is an
|
||||
/// answer; a truncated, refused or context-limited turn is an error even when
|
||||
/// it carries text.
|
||||
#[test]
|
||||
fn a_turn_that_did_not_end_is_an_error() {
|
||||
for reason in [
|
||||
StopReason::MaxOutputTokens,
|
||||
StopReason::Refusal,
|
||||
StopReason::ContextWindow,
|
||||
StopReason::ToolUse,
|
||||
] {
|
||||
let rig = rig(Script::Stop(reason));
|
||||
assert!(
|
||||
matches!(ask(&rig.args()).unwrap_err(), AskError::NotCompleted(r) if r == reason),
|
||||
"{reason:?}"
|
||||
);
|
||||
}
|
||||
let rig = rig(Script::Stop(StopReason::StopSequence));
|
||||
assert_eq!(ask(&rig.args()).unwrap(), "cut off");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fifo_key_file_errors_promptly_instead_of_hanging() {
|
||||
let rig = rig(Script::Text("x"));
|
||||
let fifo = rig.dir.join("fifo.key");
|
||||
let path = std::ffi::CString::new(fifo.to_str().unwrap()).unwrap();
|
||||
assert_eq!(unsafe { libc::mkfifo(path.as_ptr(), 0o600) }, 0);
|
||||
let mut args = rig.args();
|
||||
args.key_file = fifo;
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
thread::spawn(move || tx.send(ask(&args)).unwrap());
|
||||
let error = rx
|
||||
.recv_timeout(Duration::from_secs(3))
|
||||
.expect("reading a FIFO key file must not hang")
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, AskError::KeyNotRegular), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_file_readable_by_group_or_world_is_refused_and_a_private_one_accepted() {
|
||||
let rig = rig(Script::Text("fine"));
|
||||
for mode in [0o644, 0o640, 0o604] {
|
||||
let path = rig.dir.join(format!("mode-{mode:o}.key"));
|
||||
write_key(&path, KEY.as_bytes(), mode);
|
||||
let mut args = rig.args();
|
||||
args.key_file = path;
|
||||
let error = ask(&args).unwrap_err();
|
||||
assert!(matches!(error, AskError::KeyExposed), "{mode:o}: {error}");
|
||||
assert!(!message(&error).contains(KEY));
|
||||
}
|
||||
assert!(rig.seen().is_empty());
|
||||
assert_eq!(ask(&rig.args()).unwrap(), "fine");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symlinked_key_is_judged_by_its_target() {
|
||||
let rig = rig(Script::Text("linked"));
|
||||
let link = rig.dir.join("link.key");
|
||||
std::os::unix::fs::symlink(&rig.key_file, &link).unwrap();
|
||||
let mut args = rig.args();
|
||||
args.key_file = link;
|
||||
assert_eq!(ask(&args).unwrap(), "linked");
|
||||
let dir_link = rig.dir.join("dir.key");
|
||||
std::os::unix::fs::symlink(&rig.dir, &dir_link).unwrap();
|
||||
args.key_file = dir_link;
|
||||
assert!(matches!(ask(&args).unwrap_err(), AskError::KeyNotRegular));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_key_read_is_bounded_at_1024_bytes() {
|
||||
let rig = rig(Script::Text("x"));
|
||||
let path = rig.dir.join("big.key");
|
||||
write_key(&path, &vec![b'k'; 1_025], 0o600);
|
||||
assert!(matches!(
|
||||
claude_connector::ask::read_key(&path).unwrap_err(),
|
||||
AskError::KeyLength
|
||||
));
|
||||
write_key(&path, &vec![b'k'; 1_024], 0o600);
|
||||
assert!(claude_connector::ask::read_key(&path).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_instructions_file_is_capped_and_must_be_a_regular_file() {
|
||||
use claude_connector::ask::{MAX_SYSTEM_BYTES, read_system_file};
|
||||
let rig = rig(Script::Text("x"));
|
||||
let path = rig.dir.join("system.txt");
|
||||
std::fs::write(&path, vec![b's'; MAX_SYSTEM_BYTES]).unwrap();
|
||||
assert_eq!(read_system_file(&path).unwrap().len(), MAX_SYSTEM_BYTES);
|
||||
std::fs::write(&path, vec![b's'; MAX_SYSTEM_BYTES + 1]).unwrap();
|
||||
assert!(matches!(
|
||||
read_system_file(&path).unwrap_err(),
|
||||
AskError::SystemTooLarge
|
||||
));
|
||||
assert!(matches!(
|
||||
read_system_file(&rig.dir).unwrap_err(),
|
||||
AskError::SystemUnreadable
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_binary_never_prints_key_bytes_for_a_bad_key_file() {
|
||||
let rig = rig(Script::Text("x"));
|
||||
let cases: [(&str, &[u8], u32); 3] = [
|
||||
("exposed", b"exposed-key-bytes-0123456789", 0o644),
|
||||
("padded", b" padded-key-bytes-0123456789 ", 0o600),
|
||||
("wrong", b"wrong-but-wellformed-key-0123456789", 0o600),
|
||||
];
|
||||
for (name, bytes, mode) in cases {
|
||||
let path = rig.dir.join(format!("bin-{name}.key"));
|
||||
write_key(&path, bytes, mode);
|
||||
let out = run_binary_with_key(&rig, &path, "q", &[]);
|
||||
assert!(!out.status.success(), "{name}");
|
||||
let shown = [out.stdout.clone(), out.stderr.clone()].concat();
|
||||
let shown = String::from_utf8_lossy(&shown);
|
||||
assert!(
|
||||
!shown.contains("key-bytes") && !shown.contains("wellformed"),
|
||||
"{name}: {shown}"
|
||||
);
|
||||
assert!(out.stdout.is_empty());
|
||||
}
|
||||
let out = run_binary(&rig, "q", &["--system-file", "/nonexistent"]);
|
||||
assert!(!out.status.success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_and_stdout_failures_have_their_own_wording() {
|
||||
let rig = rig(Script::Text("x"));
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_claude-connector"))
|
||||
.args(["ask", "--endpoint", &rig.endpoint.to_string()])
|
||||
.args(["--caller-id", CALLER, "--model", MODEL, "--system", "s"])
|
||||
.args(["--connection-key-file", rig.key_file.to_str().unwrap()])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
{
|
||||
use std::io::Write;
|
||||
child
|
||||
.stdin
|
||||
.take()
|
||||
.unwrap()
|
||||
.write_all(&[0xff, 0xfe])
|
||||
.unwrap();
|
||||
}
|
||||
let out = child.wait_with_output().unwrap();
|
||||
let err = String::from_utf8(out.stderr).unwrap();
|
||||
assert!(err.contains("not UTF-8"), "{err}");
|
||||
assert!(!err.contains("flag"), "{err}");
|
||||
}
|
||||
|
||||
/// What the wire returns for a tools-bearing request that gets past the CLI's
|
||||
/// own construction (here forced by hand) when the real claude backend sits
|
||||
/// behind the real serve loop: the service admits it, the backend's planner
|
||||
/// refuses it, the caller receives a transported `Failed(InvalidRequest)`
|
||||
/// result, and the claude child is never started.
|
||||
#[test]
|
||||
fn t_c0_oauth_still_cli_a_tools_request_is_refused_and_no_child_starts() {
|
||||
use claude_connector::{
|
||||
ChildEnv, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, ProcessPort, RunningChild,
|
||||
SessionStore, StderrSink, TokenSource,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
struct CountingPort(Arc<AtomicUsize>);
|
||||
impl ProcessPort for CountingPort {
|
||||
fn spawn(
|
||||
&self,
|
||||
_: &[String],
|
||||
_: &ChildEnv,
|
||||
_: &std::path::Path,
|
||||
_: Vec<u8>,
|
||||
_: &str,
|
||||
) -> std::io::Result<Box<dyn RunningChild>> {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
Err(std::io::Error::other("no child in this test"))
|
||||
}
|
||||
}
|
||||
struct Fixed(&'static str);
|
||||
impl TokenSource for Fixed {
|
||||
fn read(&self) -> Option<Zeroizing<String>> {
|
||||
Some(Zeroizing::new(self.0.to_string()))
|
||||
}
|
||||
}
|
||||
struct NoSessions;
|
||||
impl SessionStore for NoSessions {
|
||||
fn exists(&self, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
struct Quiet;
|
||||
impl StderrSink for Quiet {
|
||||
fn stderr_tail(&self, _: &[u8]) {}
|
||||
}
|
||||
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("claude-connector-ask-tools-{}", std::process::id()));
|
||||
for sub in ["work", "config", "prompt"] {
|
||||
std::fs::create_dir_all(dir.join(sub)).unwrap();
|
||||
}
|
||||
let binary = dir.join("claude");
|
||||
std::fs::write(&binary, b"pretend claude").unwrap();
|
||||
let spawns = Arc::new(AtomicUsize::new(0));
|
||||
let backend = ClaudeCodeBackend::with_ports(
|
||||
ClaudeCodeConfig {
|
||||
claude_binary: binary,
|
||||
claude_binary_sha256: Sha256::digest(b"pretend claude").into(),
|
||||
work_dir: dir.join("work"),
|
||||
config_dir: dir.join("config"),
|
||||
prompt_dir: dir.join("prompt"),
|
||||
token_credential: "t".into(),
|
||||
handle_secret_credential: "h".into(),
|
||||
instance: "i".into(),
|
||||
limits: ClaudeCodeLimits {
|
||||
deadline: Duration::from_secs(5),
|
||||
max_line_bytes: 1 << 16,
|
||||
max_total_bytes: 1 << 20,
|
||||
stderr_tail_bytes: 64,
|
||||
},
|
||||
},
|
||||
Box::new(CountingPort(spawns.clone())),
|
||||
Box::new(NoSessions),
|
||||
Box::new(Quiet),
|
||||
Box::new(Fixed("token")),
|
||||
Box::new(Fixed(
|
||||
"handle-secret-0000000000000000000000000000000000000000",
|
||||
)),
|
||||
);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let endpoint = listener.local_addr().unwrap();
|
||||
let admission =
|
||||
CallerAdmission::new(CALLER, KEY, 1, [MODEL.to_string()], 4, 1 << 20, 4_096).unwrap();
|
||||
let limits = ServeLimits {
|
||||
max_frame_bytes: FRAME,
|
||||
max_connections: 8,
|
||||
socket_timeout_ms: 5_000,
|
||||
max_expiry_skew_ms: 300_000,
|
||||
};
|
||||
let store = dir.join("replay.cc");
|
||||
thread::spawn(move || serve(listener, limits, vec![admission], &store, Arc::new(backend)));
|
||||
|
||||
let mut args = AskArgs {
|
||||
endpoint,
|
||||
caller_id: CALLER.into(),
|
||||
key_file: dir.join("unused"),
|
||||
model: MODEL.into(),
|
||||
instructions: "i".into(),
|
||||
effort: None,
|
||||
max_output_tokens: 64,
|
||||
timeout: Duration::from_secs(5),
|
||||
prompt: "p".into(),
|
||||
};
|
||||
let mut forced = build_invocation(&args).unwrap().request;
|
||||
forced.tools.push(ToolDefinition {
|
||||
name: "lookup".into(),
|
||||
description: "d".into(),
|
||||
parameters_json: "{}".into(),
|
||||
});
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis() as u64;
|
||||
let invocation = TransportInvocation::new(
|
||||
CALLER,
|
||||
now + 60_000,
|
||||
provider_request_sha256(&forced).unwrap(),
|
||||
forced,
|
||||
)
|
||||
.unwrap();
|
||||
let client = ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap();
|
||||
let result = client.execute(&invocation).unwrap();
|
||||
let TransportDisposition::Transported { receipt, .. } = &result.disposition else {
|
||||
panic!(
|
||||
"expected the planner's failed result, got {:?}",
|
||||
result.disposition
|
||||
);
|
||||
};
|
||||
assert!(matches!(
|
||||
receipt.outcome,
|
||||
TransportOutcome::Failed {
|
||||
kind: FailureKind::InvalidRequest,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert_eq!(
|
||||
spawns.load(Ordering::SeqCst),
|
||||
0,
|
||||
"the claude child must never start"
|
||||
);
|
||||
// The same CLI path with no tools would have reached the spawn.
|
||||
args.key_file = dir.join("unused");
|
||||
let clean = client.execute(&build_invocation(&args).unwrap()).unwrap();
|
||||
assert!(matches!(
|
||||
clean.disposition,
|
||||
TransportDisposition::Transported { .. }
|
||||
));
|
||||
assert_eq!(spawns.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_binary_prints_the_answer_on_success() {
|
||||
let rig = rig(Script::Text("pong"));
|
||||
let out = run_binary(
|
||||
&rig,
|
||||
"ping",
|
||||
&["--effort", "low", "--max-output-tokens", "1024"],
|
||||
);
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
assert_eq!(String::from_utf8(out.stdout).unwrap(), "pong");
|
||||
assert!(out.stderr.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_binary_fails_loudly_with_one_stderr_line_and_empty_stdout() {
|
||||
let rig = rig(Script::Text("x"));
|
||||
let out = run_binary(&rig, "", &[]);
|
||||
assert!(!out.status.success());
|
||||
assert!(out.stdout.is_empty());
|
||||
let err = String::from_utf8(out.stderr).unwrap();
|
||||
assert_eq!(err.trim_end().lines().count(), 1, "{err}");
|
||||
assert!(err.starts_with("claude-connector: "));
|
||||
assert!(!err.contains(KEY));
|
||||
// Tools, a working directory and a second endpoint are not flags.
|
||||
for flag in ["--tools", "--cwd", "--work-dir"] {
|
||||
let out = run_binary(&rig, "q", &[flag, "x"]);
|
||||
assert!(!out.status.success());
|
||||
assert!(out.stdout.is_empty());
|
||||
}
|
||||
assert!(rig.seen().is_empty());
|
||||
}
|
||||
|
||||
/// Runs the binary with `--system-file` instead of `--system`, killing it if it
|
||||
/// has not exited within five seconds (a hang is a failure, not a stuck suite).
|
||||
fn run_with_system_file(rig: &Rig, file: &std::path::Path) -> std::process::Output {
|
||||
use std::io::Write;
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_claude-connector"))
|
||||
.args(["ask", "--endpoint", &rig.endpoint.to_string()])
|
||||
.args(["--caller-id", CALLER, "--model", MODEL])
|
||||
.args(["--max-output-tokens", "1024"])
|
||||
.args(["--connection-key-file", rig.key_file.to_str().unwrap()])
|
||||
.args(["--system-file", file.to_str().unwrap()])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let _ = child.stdin.take().unwrap().write_all(b"question");
|
||||
let started = std::time::Instant::now();
|
||||
while child.try_wait().unwrap().is_none() {
|
||||
if started.elapsed() > Duration::from_secs(5) {
|
||||
child.kill().unwrap();
|
||||
let _ = child.wait();
|
||||
panic!("the binary hung on its --system-file");
|
||||
}
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
child.wait_with_output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_binary_bounds_and_guards_its_system_file() {
|
||||
use claude_connector::ask::MAX_SYSTEM_BYTES;
|
||||
let rig = rig(Script::Text("accepted"));
|
||||
|
||||
let fifo = rig.dir.join("system.fifo");
|
||||
let path = std::ffi::CString::new(fifo.to_str().unwrap()).unwrap();
|
||||
assert_eq!(unsafe { libc::mkfifo(path.as_ptr(), 0o600) }, 0);
|
||||
let out = run_with_system_file(&rig, &fifo);
|
||||
assert!(!out.status.success());
|
||||
assert!(out.stdout.is_empty());
|
||||
|
||||
let zero = run_with_system_file(&rig, std::path::Path::new("/dev/zero"));
|
||||
assert!(!zero.status.success());
|
||||
assert!(zero.stdout.is_empty());
|
||||
|
||||
let file = rig.dir.join("system.txt");
|
||||
std::fs::write(&file, vec![b's'; MAX_SYSTEM_BYTES + 1]).unwrap();
|
||||
let over = run_with_system_file(&rig, &file);
|
||||
assert!(!over.status.success());
|
||||
assert!(over.stdout.is_empty());
|
||||
assert!(String::from_utf8_lossy(&over.stderr).contains("larger than"));
|
||||
assert!(rig.seen().is_empty());
|
||||
|
||||
std::fs::write(&file, vec![b's'; MAX_SYSTEM_BYTES]).unwrap();
|
||||
let exact = run_with_system_file(&rig, &file);
|
||||
assert!(
|
||||
exact.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&exact.stderr)
|
||||
);
|
||||
assert_eq!(String::from_utf8(exact.stdout).unwrap(), "accepted");
|
||||
assert_eq!(rig.seen()[0].instructions.len(), MAX_SYSTEM_BYTES);
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
4
crates/claude-connector/tests/fixtures/claude-2.1.312-meter-call.jsonl
vendored
Normal file
4
crates/claude-connector/tests/fixtures/claude-2.1.312-meter-call.jsonl
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{"type":"system","subtype":"init","cwd":"/tmp/meter-probe.Ye68uq/work","session_id":"1c3d29e9-8277-4ee0-86df-efc86d994f01","tools":[],"mcp_servers":[],"model":"claude-haiku-5-5","permissionMode":"bypassPermissions","slash_commands":[],"apiKeySource":"none","claude_code_version":"2.1.312","output_style":"default","agents":["claude","Explore","general-purpose","Plan","statusline-setup"],"skills":[],"plugins":[{"name":"cc-plugin-sec-default","path":"builtin","source":"cc-plugin-sec-default@builtin"},{"name":"cc-plugin-agents-md","path":"builtin","source":"cc-plugin-agents-md@builtin"},{"name":"cc-plugin-telemetry","path":"builtin","source":"cc-plugin-telemetry@builtin"},{"name":"cc-plugin-plugin-authoring","path":"builtin","source":"cc-plugin-plugin-authoring@builtin"}],"capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"analytics_disabled":false,"product_feedback_disabled":false,"uuid":"8ad7f8d7-2831-43f2-a221-8af6323dcbd9","memory_paths":{"auto":"/tmp/meter-probe.Ye68uq/home/projects/-tmp-meter-probe-Ye68uq-work/memory/"},"original_cwd":"/tmp/meter-probe.Ye68uq/work","additional_directories":[],"messaging_socket_path":"/tmp/cc-socks/2838104.sock","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","per_turn_effort_active":true,"view_mode":"default"}
|
||||
{"type":"assistant","message":{"model":"claude-haiku-5-5","id":"msg_011Cgfu1sQvRAVmjwWNHc58s","type":"message","role":"assistant","content":[{"type":"text","text":"ok"}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":384,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":4,"service_tier":"standard","inference_geo":"global","speed":"standard"},"input_transformations":[],"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"1c3d29e9-8277-4ee0-86df-efc86d994f01","uuid":"f80db687-b098-415c-ac44-51c40a6cb63a","timestamp":"2026-11-03T11:14:35.024Z","request_id":"req_011Cgfu1sCXBsDrfz8a1LoMd"}
|
||||
{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","resetsAt":1794261600,"rateLimitType":"seven_day","overageStatus":"rejected","overageDisabledReason":"org_level_disabled","isUsingOverage":false,"unifiedWindows":{"seven_day":{"utilization":0.06,"resetsAt":1794261600,"status":"allowed"}}},"uuid":"acb3b364-a218-4965-b967-f73028254f8b","session_id":"1c3d29e9-8277-4ee0-86df-efc86d994f01"}
|
||||
{"duration_api_ms":995,"stop_reason":"end_turn","session_id":"1c3d29e9-8277-4ee0-86df-efc86d994f01","total_cost_usd":0.000040400000000000006,"usage":{"input_tokens":384,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":4,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"global","iterations":[{"input_tokens":384,"output_tokens":4,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard","fallback_credit":null},"modelUsage":{"claude-haiku-5-5":{"inputTokens":384,"outputTokens":4,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.000040400000000000006,"contextWindow":1000000,"maxOutputTokens":128000,"thinkingTokens":0,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationEphemeral1hInputTokens":0,"canonicalModel":"claude-haiku-5-5","provider":"firstParty","costBasis":"list"}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subagent_stats":{"spawned":0,"requested":{"background":0,"foreground":0,"unset":0},"started_in_background":0,"max_depth":0,"spawned_by_subagents":0,"completed":0,"failed":0,"killed":{"parent":0,"user":0,"system":0},"refused":{"depth_limit":0,"concurrency_limit":0,"budget":0},"by_type":{}},"safety_stops":0,"is_error":false,"num_turns":1,"subtype":"success","api_error_status":null,"result":"ok","ttft_ms":1210,"type":"result","duration_ms":1228,"uuid":"d0b1b31b-1428-45aa-b90e-d35903c9b91b","ttft_stream_ms":1209,"time_to_request_ms":232,"first_content_frame_ms":1209,"queued_turn_count":0,"result_index":0,"model_usage_since_last_result":{"claude-haiku-5-5":{"inputTokens":384,"outputTokens":4,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.000040400000000000006,"contextWindow":1000000,"maxOutputTokens":128000,"thinkingTokens":0,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationEphemeral1hInputTokens":0,"canonicalModel":"claude-haiku-5-5","provider":"firstParty","costBasis":"list"}}}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
20
crates/claude-connector/tests/fixtures/lease_v2/README.md
vendored
Normal file
20
crates/claude-connector/tests/fixtures/lease_v2/README.md
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
# lease_v2 fixtures
|
||||
|
||||
The exact bytes of the claude lease protocol v2: each file is one whole frame (a u32
|
||||
big-endian length, then the named-MessagePack map `{kind, value}`).
|
||||
|
||||
- `request.bin`: `claude_lease_request`.
|
||||
- `refusal_unknown_caller.bin`, `refusal_expired.bin`, `refusal_busy.bin`,
|
||||
`refusal_provider_rejected.bin`: `claude_lease_refusal`; `kind` is the variant name as a
|
||||
PascalCase string.
|
||||
- `grant.bin`: `claude_lease_grant` with `lease_id` and `plan_quota` carrying `five_hour` and
|
||||
`seven_day` windows (utilization_permille, resets_at_unix_ms, status, observed_at_unix_ms).
|
||||
On the wire the grant travels with one SCM_RIGHTS fd; the file holds the frame only.
|
||||
|
||||
- `usage_readout_request.bin`: `claude_usage_readout_request`, an empty map; opens no lease.
|
||||
- `usage_readout.bin`: `claude_usage_readout`, the kit's `UsageReadout` (`schema_id`, `at_unix_ms`,
|
||||
`plan_quota` with `five_hour` and `seven_day` windows); no fd travels with it.
|
||||
|
||||
Huginn's lease client vendors these files from this repository and tests against the same
|
||||
bytes. Generator: `tests/lease_wire_golden.rs`; run it with `LEASE_V2_REGENERATE=1`, then
|
||||
review the diff: a changed byte is a wire change.
|
||||
BIN
crates/claude-connector/tests/fixtures/lease_v2/grant.bin
vendored
Normal file
BIN
crates/claude-connector/tests/fixtures/lease_v2/grant.bin
vendored
Normal file
Binary file not shown.
BIN
crates/claude-connector/tests/fixtures/lease_v2/refusal_busy.bin
vendored
Normal file
BIN
crates/claude-connector/tests/fixtures/lease_v2/refusal_busy.bin
vendored
Normal file
Binary file not shown.
BIN
crates/claude-connector/tests/fixtures/lease_v2/refusal_expired.bin
vendored
Normal file
BIN
crates/claude-connector/tests/fixtures/lease_v2/refusal_expired.bin
vendored
Normal file
Binary file not shown.
BIN
crates/claude-connector/tests/fixtures/lease_v2/refusal_provider_rejected.bin
vendored
Normal file
BIN
crates/claude-connector/tests/fixtures/lease_v2/refusal_provider_rejected.bin
vendored
Normal file
Binary file not shown.
BIN
crates/claude-connector/tests/fixtures/lease_v2/refusal_unknown_caller.bin
vendored
Normal file
BIN
crates/claude-connector/tests/fixtures/lease_v2/refusal_unknown_caller.bin
vendored
Normal file
Binary file not shown.
BIN
crates/claude-connector/tests/fixtures/lease_v2/usage_readout.bin
vendored
Normal file
BIN
crates/claude-connector/tests/fixtures/lease_v2/usage_readout.bin
vendored
Normal file
Binary file not shown.
BIN
crates/claude-connector/tests/fixtures/lease_v2/usage_readout_request.bin
vendored
Normal file
BIN
crates/claude-connector/tests/fixtures/lease_v2/usage_readout_request.bin
vendored
Normal file
Binary file not shown.
File diff suppressed because it is too large
Load diff
134
crates/claude-connector/tests/lease_wire_golden.rs
Normal file
134
crates/claude-connector/tests/lease_wire_golden.rs
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
//! Pins the bytes of the lease protocol v2: every frame a lease client sends
|
||||
//! or receives. The fixtures in `fixtures/lease_v2` are the contract's bytes
|
||||
//! for other implementations (Huginn's lease client vendors them and tests
|
||||
//! against the same bytes); the types in `claude_connector::lease` own the
|
||||
//! shape. Regenerate with `LEASE_V2_REGENERATE=1`, then review the diff.
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use claude_connector::{
|
||||
LeaseGranted, LeaseMessage, LeaseRefusalKind, LeaseRefused, LeaseRequest,
|
||||
LeaseUsageReadoutRequest, decode_frame, encode_frame,
|
||||
};
|
||||
use model_connector::{PlanQuota, PlanQuotaSnapshot, UsageReadout};
|
||||
|
||||
const REGENERATE: &str = "LEASE_V2_REGENERATE";
|
||||
|
||||
fn fixtures() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/lease_v2")
|
||||
}
|
||||
|
||||
fn assert_frame(name: &str, message: &LeaseMessage) {
|
||||
let path = fixtures().join(name);
|
||||
let bytes = encode_frame(message);
|
||||
if std::env::var_os(REGENERATE).is_some() {
|
||||
std::fs::create_dir_all(fixtures()).unwrap();
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
}
|
||||
let committed = std::fs::read(&path).unwrap_or_else(|_| panic!("{name} is missing"));
|
||||
assert_eq!(committed, bytes, "{name} is not what the types encode");
|
||||
assert_eq!(decode_frame(&committed).as_ref(), Some(message), "{name}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_request_frame_is_pinned() {
|
||||
assert_frame(
|
||||
"request.bin",
|
||||
&LeaseMessage::ClaudeLeaseRequest(LeaseRequest {
|
||||
expires_at_unix_ms: 1_793_307_000_000,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_refusal_frame_is_pinned_with_its_kind_as_a_pascal_case_string() {
|
||||
let kinds = [
|
||||
(
|
||||
"refusal_unknown_caller.bin",
|
||||
LeaseRefusalKind::UnknownCaller,
|
||||
"UnknownCaller",
|
||||
),
|
||||
("refusal_expired.bin", LeaseRefusalKind::Expired, "Expired"),
|
||||
("refusal_busy.bin", LeaseRefusalKind::Busy, "Busy"),
|
||||
(
|
||||
"refusal_provider_rejected.bin",
|
||||
LeaseRefusalKind::ProviderRejected,
|
||||
"ProviderRejected",
|
||||
),
|
||||
];
|
||||
for (name, kind, spelled) in kinds {
|
||||
let message = LeaseMessage::ClaudeLeaseRefusal(LeaseRefused {
|
||||
kind,
|
||||
detail: "the reason".to_string(),
|
||||
});
|
||||
assert_frame(name, &message);
|
||||
// The kind travels as the variant's name, which other runtimes read.
|
||||
let bytes = encode_frame(&message);
|
||||
let value: rmpv::Value = rmp_serde::from_slice(&bytes[4..]).unwrap();
|
||||
let rmpv::Value::Map(outer) = value else {
|
||||
panic!("a frame is a map")
|
||||
};
|
||||
let rmpv::Value::Map(inner) = &outer[1].1 else {
|
||||
panic!("the value is a map")
|
||||
};
|
||||
assert_eq!(inner[0].0.as_str(), Some("kind"));
|
||||
assert_eq!(inner[0].1.as_str(), Some(spelled));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grant_with_both_usage_windows_is_pinned() {
|
||||
let window = |name: &str, permille, status: &str, resets| PlanQuota {
|
||||
window: name.to_string(),
|
||||
utilization_permille: Some(permille),
|
||||
resets_at_unix_ms: resets,
|
||||
status: status.to_string(),
|
||||
observed_at_unix_ms: 1_793_300_000_000,
|
||||
};
|
||||
assert_frame(
|
||||
"grant.bin",
|
||||
&LeaseMessage::ClaudeLeaseGrant(LeaseGranted {
|
||||
lease_id: "lease:0123456789abcdef0123456789abcdef".to_string(),
|
||||
plan_quota: vec![
|
||||
window("five_hour", 420, "allowed", 1_793_307_000_000),
|
||||
window("seven_day", 999, "allowed_warning", 1_793_800_000_000),
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_usage_readout_frames_are_pinned() {
|
||||
let window = |name: &str, permille, status: &str, resets| PlanQuota {
|
||||
window: name.to_string(),
|
||||
utilization_permille: Some(permille),
|
||||
resets_at_unix_ms: resets,
|
||||
status: status.to_string(),
|
||||
observed_at_unix_ms: 1_793_300_000_000,
|
||||
};
|
||||
let request = LeaseMessage::ClaudeUsageReadoutRequest(LeaseUsageReadoutRequest {});
|
||||
let answer = LeaseMessage::ClaudeUsageReadout(UsageReadout::new(
|
||||
1_793_300_100_000,
|
||||
PlanQuotaSnapshot {
|
||||
windows: vec![
|
||||
window("five_hour", 420, "allowed", 1_793_307_000_000),
|
||||
window("seven_day", 999, "allowed_warning", 1_793_800_000_000),
|
||||
],
|
||||
},
|
||||
));
|
||||
assert_frame("usage_readout_request.bin", &request);
|
||||
assert_frame("usage_readout.bin", &answer);
|
||||
for (message, spelled) in [
|
||||
(&request, "claude_usage_readout_request"),
|
||||
(&answer, "claude_usage_readout"),
|
||||
] {
|
||||
let bytes = encode_frame(message);
|
||||
let value: rmpv::Value = rmp_serde::from_slice(&bytes[4..]).unwrap();
|
||||
let rmpv::Value::Map(outer) = value else {
|
||||
panic!("a frame is a map")
|
||||
};
|
||||
assert_eq!(outer[0].0.as_str(), Some("kind"));
|
||||
assert_eq!(outer[0].1.as_str(), Some(spelled));
|
||||
}
|
||||
}
|
||||
|
|
@ -9,11 +9,11 @@ use rand_core::{OsRng, RngCore};
|
|||
use crate::contract::{TransportInvocation, TransportKey, TransportResult};
|
||||
use crate::envelope::{
|
||||
MAX_IDENTITY_BYTES, ServiceError, TransportFrameError, decode_result_frame,
|
||||
decode_spend_readout_response_frame, decrypt_result, decrypt_spend_readout,
|
||||
encode_invocation_frame, encode_spend_readout_request_frame, encrypt_invocation,
|
||||
encrypt_spend_readout_request, read_transport_frame, write_transport_frame,
|
||||
decode_usage_readout_response_frame, decrypt_result, decrypt_usage_readout,
|
||||
encode_invocation_frame, encode_usage_readout_request_frame, encrypt_invocation,
|
||||
encrypt_usage_readout_request, read_transport_frame, write_transport_frame,
|
||||
};
|
||||
use crate::readout::SpendReadout;
|
||||
use crate::readout::UsageReadout;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ConnectorClient {
|
||||
|
|
@ -62,25 +62,25 @@ impl ConnectorClient {
|
|||
decrypt_result(&envelope, &self.security, invocation).map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Reads the connector's spend ledger and plan quota as `caller_runtime_id`,
|
||||
/// Reads the plan's usage windows as `caller_runtime_id`,
|
||||
/// which must be a caller whose connection key this client holds.
|
||||
pub fn spend_readout(
|
||||
pub fn usage_readout(
|
||||
&self,
|
||||
caller_runtime_id: &str,
|
||||
) -> Result<SpendReadout, ConnectorClientError> {
|
||||
) -> Result<UsageReadout, ConnectorClientError> {
|
||||
let mut nonce = [0_u8; 16];
|
||||
OsRng.fill_bytes(&mut nonce);
|
||||
let request_id = format!(
|
||||
"spend-readout-{}",
|
||||
"usage-readout-{}",
|
||||
nonce.iter().map(|b| format!("{b:02x}")).collect::<String>()
|
||||
);
|
||||
let sealed = encrypt_spend_readout_request(caller_runtime_id, &request_id, &self.security)?;
|
||||
let response = self.exchange(&encode_spend_readout_request_frame(&sealed)?)?;
|
||||
let envelope = decode_spend_readout_response_frame(&response)?;
|
||||
let sealed = encrypt_usage_readout_request(caller_runtime_id, &request_id, &self.security)?;
|
||||
let response = self.exchange(&encode_usage_readout_request_frame(&sealed)?)?;
|
||||
let envelope = decode_usage_readout_response_frame(&response)?;
|
||||
if envelope.caller_runtime_id != caller_runtime_id || envelope.request_id != request_id {
|
||||
return Err(ServiceError::OuterIdentity.into());
|
||||
}
|
||||
decrypt_spend_readout(&envelope, &self.security).map_err(Into::into)
|
||||
decrypt_usage_readout(&envelope, &self.security).map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Sends one frame on a fresh connection and reads the one answer.
|
||||
|
|
@ -274,17 +274,17 @@ mod fixture_tests {
|
|||
let server = std::thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let request = read_transport_frame(&mut stream, 64 * 1024).unwrap();
|
||||
let RequestFrame::SpendReadout(asked) = decode_request_frame(&request).unwrap()
|
||||
let RequestFrame::UsageReadout(asked) = decode_request_frame(&request).unwrap()
|
||||
else {
|
||||
panic!("the client sent something other than a readout request");
|
||||
};
|
||||
let request_id = answer_request.unwrap_or(&asked.request_id);
|
||||
let readout = SpendReadout::new(1, Vec::new(), PlanQuotaSnapshot::default());
|
||||
let readout = UsageReadout::new(1, PlanQuotaSnapshot::default());
|
||||
let sealed =
|
||||
encrypt_spend_readout(answer_caller, request_id, &readout, &key).unwrap();
|
||||
encrypt_usage_readout(answer_caller, request_id, &readout, &key).unwrap();
|
||||
write_transport_frame(
|
||||
&mut stream,
|
||||
&encode_spend_readout_response_frame(&sealed).unwrap(),
|
||||
&encode_usage_readout_response_frame(&sealed).unwrap(),
|
||||
64 * 1024,
|
||||
)
|
||||
.unwrap();
|
||||
|
|
@ -296,7 +296,7 @@ mod fixture_tests {
|
|||
Some(Duration::from_secs(1)),
|
||||
)
|
||||
.unwrap();
|
||||
let answer = client.spend_readout("caller-1");
|
||||
let answer = client.usage_readout("caller-1");
|
||||
if accepted {
|
||||
assert_eq!(answer.unwrap().at_unix_ms, 1);
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -9,11 +9,11 @@ use zeroize::Zeroize;
|
|||
|
||||
use crate::envelope::{ServiceError, binary_schema};
|
||||
|
||||
pub const PROVIDER_REQUEST_SCHEMA_ID: &str = "gamecult.model.provider_request.v3";
|
||||
pub const INVOCATION_SCHEMA_ID: &str = "gamecult.model.transport_invocation.v3";
|
||||
pub const RESULT_SCHEMA_ID: &str = "gamecult.model.transport_result.v3";
|
||||
pub const RECEIPT_SCHEMA_ID: &str = "gamecult.model.transport_receipt.v3";
|
||||
pub const ENVELOPE_SCHEMA_ID: &str = "gamecult.model.transport_envelope.v3";
|
||||
pub const PROVIDER_REQUEST_SCHEMA_ID: &str = "gamecult.model.provider_request.v4";
|
||||
pub const INVOCATION_SCHEMA_ID: &str = "gamecult.model.transport_invocation.v4";
|
||||
pub const RESULT_SCHEMA_ID: &str = "gamecult.model.transport_result.v4";
|
||||
pub const RECEIPT_SCHEMA_ID: &str = "gamecult.model.transport_receipt.v4";
|
||||
pub const ENVELOPE_SCHEMA_ID: &str = "gamecult.model.transport_envelope.v4";
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct TransportKey(pub(crate) [u8; 32]);
|
||||
|
|
@ -190,10 +190,10 @@ pub enum FailureKind {
|
|||
Provider,
|
||||
}
|
||||
|
||||
/// Token accounting for one request, as the backend reports it; the service
|
||||
/// prices it. Cache reads and writes are counted apart from plain input.
|
||||
/// Token accounting for one request, as the backend reports it. Cache reads
|
||||
/// and writes are counted apart from plain input.
|
||||
/// `output_tokens` includes reasoning tokens: `reasoning_tokens` is a detail
|
||||
/// (absent when the provider does not report it) and is never priced apart.
|
||||
/// (absent when the provider does not report it) and is never counted apart.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Usage {
|
||||
|
|
@ -252,10 +252,6 @@ pub struct TransportInvocation {
|
|||
pub expires_at_unix_ms: u64,
|
||||
pub native_request_sha256: [u8; 32],
|
||||
pub provider_request_sha256: [u8; 32],
|
||||
/// The most this request may cost, in micro-USD: the caller's own bound
|
||||
/// on it. Required nonzero. It is part of the invocation's identity, so a
|
||||
/// changed budget under a recorded request id is a `ReplayConflict`.
|
||||
pub max_cost_micro_usd: u64,
|
||||
pub request: ProviderRequest,
|
||||
}
|
||||
|
||||
|
|
@ -264,7 +260,6 @@ impl TransportInvocation {
|
|||
caller_runtime_id: impl Into<String>,
|
||||
expires_at_unix_ms: u64,
|
||||
native_request_sha256: [u8; 32],
|
||||
max_cost_micro_usd: u64,
|
||||
request: ProviderRequest,
|
||||
) -> Result<Self, ContractError> {
|
||||
let provider_request_sha256 = provider_request_sha256(&request)?;
|
||||
|
|
@ -274,7 +269,6 @@ impl TransportInvocation {
|
|||
expires_at_unix_ms,
|
||||
native_request_sha256,
|
||||
provider_request_sha256,
|
||||
max_cost_micro_usd,
|
||||
request,
|
||||
})
|
||||
}
|
||||
|
|
@ -287,9 +281,6 @@ impl TransportInvocation {
|
|||
if self.native_request_sha256 == [0; 32] {
|
||||
return Err(ContractError::Invalid("native_request_sha256"));
|
||||
}
|
||||
if self.max_cost_micro_usd == 0 {
|
||||
return Err(ContractError::Invalid("max_cost_micro_usd"));
|
||||
}
|
||||
self.request.validate()?;
|
||||
if self.provider_request_sha256 != provider_request_sha256(&self.request)? {
|
||||
return Err(ContractError::ProviderDigest);
|
||||
|
|
@ -485,15 +476,6 @@ pub struct TransportReceipt {
|
|||
/// How many foreign `ReasoningState` items the service removed from the
|
||||
/// request before the backend saw it.
|
||||
pub foreign_reasoning_dropped: u32,
|
||||
/// What the request cost, in micro-USD. The service derives it from the
|
||||
/// outcome's usage and its price table; a backend never writes it.
|
||||
pub cost_micro_usd: u64,
|
||||
/// How far `cost_micro_usd` exceeds what the service reserved for the
|
||||
/// request: zero unless the backend reported usage above the worst case
|
||||
/// the request allowed, which is a breach of the backend's contract. The
|
||||
/// cost is still the true one and the caller's window is charged all of
|
||||
/// it. The service derives this; a backend never writes it.
|
||||
pub overrun_micro_usd: u64,
|
||||
pub outcome: TransportOutcome,
|
||||
}
|
||||
|
||||
|
|
@ -558,12 +540,6 @@ pub enum Refusal {
|
|||
ModelNotAllowed,
|
||||
OutputBound,
|
||||
PayloadBound,
|
||||
// The worst case of the request exceeds the invocation's own
|
||||
// `max_cost_micro_usd`. Plain comments: a doc comment would split the
|
||||
// published schema into a union.
|
||||
CostBound,
|
||||
// The caller's spend window cannot hold the request's reservation.
|
||||
SpendCeiling,
|
||||
Capacity,
|
||||
InFlight,
|
||||
Indeterminate,
|
||||
|
|
@ -573,15 +549,12 @@ pub enum Refusal {
|
|||
// exchange, where dropping it would break the provider's own rules. A plain
|
||||
// comment: a doc comment would split the published schema into a union.
|
||||
ForeignReasoningState,
|
||||
// The caller's newest admission window starts after the clock's reading,
|
||||
// and the request does not fit what that window holds: the host's clock
|
||||
// is behind the window and the caller stays refused until it catches up.
|
||||
// A plain comment: a doc comment would split the published schema into a
|
||||
// union.
|
||||
ClockBehindAdmissionWindow,
|
||||
// The provider itself is refusing right now: a plan window it reported
|
||||
// `rejected` has not reached its own reset. Plain comments, as above.
|
||||
ProviderRejected,
|
||||
}
|
||||
|
||||
/// The one wire codec of every v3 document: named MessagePack (struct fields
|
||||
/// The one wire codec of every v4 document: named MessagePack (struct fields
|
||||
/// are keyed by name), with unknown fields refused by the types themselves.
|
||||
pub(crate) fn wire_encode<T: Serialize + ?Sized>(document: &T) -> Result<Vec<u8>, ContractError> {
|
||||
rmp_serde::to_vec_named(document).map_err(|_| ContractError::Encoding)
|
||||
|
|
@ -787,28 +760,23 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn max_cost_zero_is_malformed() {
|
||||
let mut invocation = invocation();
|
||||
invocation.max_cost_micro_usd = 0;
|
||||
assert_eq!(
|
||||
invocation.validate(1_000, 2_000),
|
||||
Err(ContractError::Invalid("max_cost_micro_usd"))
|
||||
);
|
||||
invocation.max_cost_micro_usd = 1;
|
||||
assert_eq!(invocation.validate(1_000, 2_000), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_cost_is_part_of_the_invocations_identity() {
|
||||
fn the_invocations_identity_covers_its_request() {
|
||||
let one = invocation();
|
||||
let mut other = one.clone();
|
||||
other.max_cost_micro_usd += 1;
|
||||
let mut request = one.request.clone();
|
||||
request.max_output_tokens += 1;
|
||||
let other = TransportInvocation::new(
|
||||
one.caller_runtime_id.clone(),
|
||||
one.expires_at_unix_ms,
|
||||
one.native_request_sha256,
|
||||
request,
|
||||
)
|
||||
.unwrap();
|
||||
assert_ne!(
|
||||
canonical_invocation_bytes(&one).unwrap(),
|
||||
canonical_invocation_bytes(&other).unwrap()
|
||||
);
|
||||
let decoded: TransportInvocation = wire_decode(&wire_encode(&one).unwrap()).unwrap();
|
||||
assert_eq!(decoded.max_cost_micro_usd, one.max_cost_micro_usd);
|
||||
assert_eq!(decoded, one);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -869,7 +837,7 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn v3_documents_carry_their_v3_ids() {
|
||||
fn v4_documents_carry_their_v4_ids() {
|
||||
assert_eq!(
|
||||
[
|
||||
PROVIDER_REQUEST_SCHEMA_ID,
|
||||
|
|
@ -879,11 +847,11 @@ mod tests {
|
|||
ENVELOPE_SCHEMA_ID
|
||||
],
|
||||
[
|
||||
"gamecult.model.provider_request.v3",
|
||||
"gamecult.model.transport_invocation.v3",
|
||||
"gamecult.model.transport_result.v3",
|
||||
"gamecult.model.transport_receipt.v3",
|
||||
"gamecult.model.transport_envelope.v3"
|
||||
"gamecult.model.provider_request.v4",
|
||||
"gamecult.model.transport_invocation.v4",
|
||||
"gamecult.model.transport_result.v4",
|
||||
"gamecult.model.transport_receipt.v4",
|
||||
"gamecult.model.transport_envelope.v4"
|
||||
]
|
||||
);
|
||||
let invocation = invocation();
|
||||
|
|
@ -922,7 +890,7 @@ mod tests {
|
|||
let bytes = wire_encode(document).unwrap();
|
||||
let mut value = rmpv::decode::read_value(&mut bytes.as_slice()).unwrap();
|
||||
let rmpv::Value::Map(entries) = &mut value else {
|
||||
panic!("a v3 document is a named map");
|
||||
panic!("a v4 document is a named map");
|
||||
};
|
||||
entries.push((rmpv::Value::from("unexpected_field"), rmpv::Value::from(1)));
|
||||
let mut out = Vec::new();
|
||||
|
|
|
|||
|
|
@ -17,14 +17,14 @@ use crate::contract::{
|
|||
ContractError, ENVELOPE_SCHEMA_ID, TransportInvocation, TransportKey, TransportResult,
|
||||
canonical_invocation_bytes, require_id, wire_decode, wire_encode,
|
||||
};
|
||||
use crate::readout::SpendReadout;
|
||||
use crate::readout::UsageReadout;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub enum EnvelopeKind {
|
||||
Invocation,
|
||||
Result,
|
||||
SpendReadoutRequest,
|
||||
SpendReadoutResult,
|
||||
UsageReadoutRequest,
|
||||
UsageReadoutResult,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
|
|
@ -54,8 +54,8 @@ pub(crate) fn binary_schema(_: &mut schemars::SchemaGenerator) -> schemars::Sche
|
|||
pub const CONNECTOR_SERVICE_ID: &str = "gamecult.model.connector";
|
||||
/// The operation that runs one sealed invocation.
|
||||
pub const INVOKE_OPERATION: &str = "invoke";
|
||||
/// The operation that reads the spend ledger and the plan's quota.
|
||||
pub const SPEND_READOUT_OPERATION: &str = "spend_readout";
|
||||
/// The operation that reads the plan's usage.
|
||||
pub const USAGE_READOUT_OPERATION: &str = "usage_readout";
|
||||
|
||||
const PAYLOAD_ENCODING: &str = "messagepack-base64";
|
||||
const OK_STATUS: &str = "ok";
|
||||
|
|
@ -78,19 +78,19 @@ fn seal_payload(envelope: &TransportEnvelope) -> Result<String, ServiceError> {
|
|||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Operation {
|
||||
Invoke,
|
||||
SpendReadout,
|
||||
UsageReadout,
|
||||
}
|
||||
|
||||
impl Operation {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Operation::Invoke => INVOKE_OPERATION,
|
||||
Operation::SpendReadout => SPEND_READOUT_OPERATION,
|
||||
Operation::UsageReadout => USAGE_READOUT_OPERATION,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_name(name: &str) -> Option<Self> {
|
||||
[Operation::Invoke, Operation::SpendReadout]
|
||||
pub(crate) fn from_name(name: &str) -> Option<Self> {
|
||||
[Operation::Invoke, Operation::UsageReadout]
|
||||
.into_iter()
|
||||
.find(|operation| operation.name() == name)
|
||||
}
|
||||
|
|
@ -141,10 +141,10 @@ pub(crate) fn encode_invocation_frame(
|
|||
request_frame(Operation::Invoke, envelope)
|
||||
}
|
||||
|
||||
pub(crate) fn encode_spend_readout_request_frame(
|
||||
pub(crate) fn encode_usage_readout_request_frame(
|
||||
envelope: &TransportEnvelope,
|
||||
) -> Result<Vec<u8>, ServiceError> {
|
||||
request_frame(Operation::SpendReadout, envelope)
|
||||
request_frame(Operation::UsageReadout, envelope)
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "daemon", test))]
|
||||
|
|
@ -153,10 +153,10 @@ pub(crate) fn encode_result_frame(envelope: &TransportEnvelope) -> Result<Vec<u8
|
|||
}
|
||||
|
||||
#[cfg(feature = "daemon")]
|
||||
pub(crate) fn encode_spend_readout_response_frame(
|
||||
pub(crate) fn encode_usage_readout_response_frame(
|
||||
envelope: &TransportEnvelope,
|
||||
) -> Result<Vec<u8>, ServiceError> {
|
||||
response_frame(Operation::SpendReadout, envelope)
|
||||
response_frame(Operation::UsageReadout, envelope)
|
||||
}
|
||||
|
||||
/// Opens the carriage of one frame. Everything the carriage says is checked
|
||||
|
|
@ -193,7 +193,7 @@ fn read_carriage(bytes: &[u8]) -> Result<CultNetMessage, ServiceError> {
|
|||
#[cfg(any(feature = "daemon", test))]
|
||||
pub(crate) enum RequestFrame {
|
||||
Invoke(TransportEnvelope),
|
||||
SpendReadout(TransportEnvelope),
|
||||
UsageReadout(TransportEnvelope),
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "daemon", test))]
|
||||
|
|
@ -215,7 +215,7 @@ pub(crate) fn decode_request_frame(bytes: &[u8]) -> Result<RequestFrame, Service
|
|||
&payload,
|
||||
)? {
|
||||
(Operation::Invoke, envelope) => Ok(RequestFrame::Invoke(envelope)),
|
||||
(Operation::SpendReadout, envelope) => Ok(RequestFrame::SpendReadout(envelope)),
|
||||
(Operation::UsageReadout, envelope) => Ok(RequestFrame::UsageReadout(envelope)),
|
||||
}
|
||||
}
|
||||
_ => Err(ServiceError::Carriage),
|
||||
|
|
@ -226,7 +226,7 @@ pub(crate) fn decode_request_frame(bytes: &[u8]) -> Result<RequestFrame, Service
|
|||
pub(crate) fn decode_invocation_frame(bytes: &[u8]) -> Result<TransportEnvelope, ServiceError> {
|
||||
match decode_request_frame(bytes)? {
|
||||
RequestFrame::Invoke(envelope) => Ok(envelope),
|
||||
RequestFrame::SpendReadout(_) => Err(ServiceError::Carriage),
|
||||
RequestFrame::UsageReadout(_) => Err(ServiceError::Carriage),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -263,10 +263,10 @@ pub(crate) fn decode_result_frame(bytes: &[u8]) -> Result<TransportEnvelope, Ser
|
|||
decode_response_frame(bytes, Operation::Invoke)
|
||||
}
|
||||
|
||||
pub(crate) fn decode_spend_readout_response_frame(
|
||||
pub(crate) fn decode_usage_readout_response_frame(
|
||||
bytes: &[u8],
|
||||
) -> Result<TransportEnvelope, ServiceError> {
|
||||
decode_response_frame(bytes, Operation::SpendReadout)
|
||||
decode_response_frame(bytes, Operation::UsageReadout)
|
||||
}
|
||||
|
||||
/// The most bytes one frame holding a sealed envelope of `ciphertext_len`
|
||||
|
|
@ -416,9 +416,9 @@ pub fn decrypt_result(
|
|||
Ok(result)
|
||||
}
|
||||
|
||||
/// A spend readout request carries no content: the sealed envelope's
|
||||
/// A usage readout request carries no content: the sealed envelope's
|
||||
/// authenticated identity and kind are the whole request.
|
||||
pub(crate) fn encrypt_spend_readout_request(
|
||||
pub(crate) fn encrypt_usage_readout_request(
|
||||
caller_runtime_id: &str,
|
||||
request_id: &str,
|
||||
security: &TransportKey,
|
||||
|
|
@ -426,45 +426,45 @@ pub(crate) fn encrypt_spend_readout_request(
|
|||
encrypt_message(
|
||||
caller_runtime_id,
|
||||
request_id,
|
||||
EnvelopeKind::SpendReadoutRequest,
|
||||
EnvelopeKind::UsageReadoutRequest,
|
||||
&[],
|
||||
security,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "daemon", test))]
|
||||
pub(crate) fn decrypt_spend_readout_request(
|
||||
pub(crate) fn decrypt_usage_readout_request(
|
||||
envelope: &TransportEnvelope,
|
||||
security: &TransportKey,
|
||||
) -> Result<(), ServiceError> {
|
||||
validate_envelope(envelope, EnvelopeKind::SpendReadoutRequest)?;
|
||||
validate_envelope(envelope, EnvelopeKind::UsageReadoutRequest)?;
|
||||
decrypt_message(envelope, security).map(drop)
|
||||
}
|
||||
|
||||
#[cfg(feature = "daemon")]
|
||||
pub(crate) fn encrypt_spend_readout(
|
||||
pub(crate) fn encrypt_usage_readout(
|
||||
caller_runtime_id: &str,
|
||||
request_id: &str,
|
||||
readout: &SpendReadout,
|
||||
readout: &UsageReadout,
|
||||
security: &TransportKey,
|
||||
) -> Result<TransportEnvelope, ServiceError> {
|
||||
let plaintext = wire_encode(readout).map_err(|_| ServiceError::Encoding)?;
|
||||
encrypt_message(
|
||||
caller_runtime_id,
|
||||
request_id,
|
||||
EnvelopeKind::SpendReadoutResult,
|
||||
EnvelopeKind::UsageReadoutResult,
|
||||
&plaintext,
|
||||
security,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn decrypt_spend_readout(
|
||||
pub(crate) fn decrypt_usage_readout(
|
||||
envelope: &TransportEnvelope,
|
||||
security: &TransportKey,
|
||||
) -> Result<SpendReadout, ServiceError> {
|
||||
validate_envelope(envelope, EnvelopeKind::SpendReadoutResult)?;
|
||||
) -> Result<UsageReadout, ServiceError> {
|
||||
validate_envelope(envelope, EnvelopeKind::UsageReadoutResult)?;
|
||||
let plaintext = decrypt_message(envelope, security)?;
|
||||
let readout: SpendReadout = wire_decode(&plaintext).map_err(|_| ServiceError::Encoding)?;
|
||||
let readout: UsageReadout = wire_decode(&plaintext).map_err(|_| ServiceError::Encoding)?;
|
||||
readout.validate()?;
|
||||
Ok(readout)
|
||||
}
|
||||
|
|
@ -607,8 +607,6 @@ pub enum ServiceError {
|
|||
SharedCallerKey,
|
||||
#[error("connector replay store failed: {0}")]
|
||||
ReplayStore(String),
|
||||
#[error("an allowed model has no price: {0}")]
|
||||
UnpricedModel(String),
|
||||
#[error("connector replay record is malformed")]
|
||||
InvalidReplayRecord,
|
||||
#[error("caller key changed while durable replay records still exist")]
|
||||
|
|
@ -1072,7 +1070,7 @@ mod tests {
|
|||
fn golden_frame() -> Vec<u8> {
|
||||
std::fs::read(
|
||||
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/fixtures/wire_v3/carriage_invocation.frame"),
|
||||
.join("tests/fixtures/wire_v4/carriage_invocation.frame"),
|
||||
)
|
||||
.expect("carriage_invocation.frame is committed")
|
||||
}
|
||||
|
|
@ -1109,7 +1107,7 @@ mod tests {
|
|||
assert_eq!(text(&request, "operation"), "invoke");
|
||||
assert_eq!(
|
||||
text(&request, "payloadSchema"),
|
||||
"gamecult.model.transport_envelope.v3"
|
||||
"gamecult.model.transport_envelope.v4"
|
||||
);
|
||||
assert_eq!(text(&request, "payloadEncoding"), "messagepack-base64");
|
||||
assert_eq!(text(&request, "messageId"), envelope.request_id);
|
||||
|
|
@ -1123,7 +1121,7 @@ mod tests {
|
|||
assert_eq!(text(&response, "status"), "ok");
|
||||
assert_eq!(
|
||||
text(&response, "payloadSchema"),
|
||||
"gamecult.model.transport_envelope.v3"
|
||||
"gamecult.model.transport_envelope.v4"
|
||||
);
|
||||
assert_eq!(text(&response, "payloadEncoding"), "messagepack-base64");
|
||||
assert_eq!(text(&response, "messageId"), envelope.request_id);
|
||||
|
|
@ -1287,23 +1285,23 @@ mod tests {
|
|||
#[test]
|
||||
fn a_readout_request_is_not_an_invocation_and_names_its_own_operation() {
|
||||
let key = TransportKey::from_connection_secret("readout-test-key").unwrap();
|
||||
let sealed = encrypt_spend_readout_request("caller-1", "readout-1", &key).unwrap();
|
||||
let frame = encode_spend_readout_request_frame(&sealed).unwrap();
|
||||
let sealed = encrypt_usage_readout_request("caller-1", "readout-1", &key).unwrap();
|
||||
let frame = encode_usage_readout_request_frame(&sealed).unwrap();
|
||||
assert!(matches!(
|
||||
decode_request_frame(&frame),
|
||||
Ok(RequestFrame::SpendReadout(found)) if found == sealed
|
||||
Ok(RequestFrame::UsageReadout(found)) if found == sealed
|
||||
));
|
||||
assert_eq!(decode_invocation_frame(&frame), Err(ServiceError::Carriage));
|
||||
// Sealed as one kind, the authenticated data refuses it as another.
|
||||
assert!(decrypt_spend_readout_request(&sealed, &key).is_ok());
|
||||
assert!(decrypt_usage_readout_request(&sealed, &key).is_ok());
|
||||
assert_eq!(
|
||||
decrypt_spend_readout(&sealed, &key).unwrap_err(),
|
||||
decrypt_usage_readout(&sealed, &key).unwrap_err(),
|
||||
ServiceError::Envelope
|
||||
);
|
||||
let mut relabelled = sealed.clone();
|
||||
relabelled.message_kind = EnvelopeKind::SpendReadoutResult;
|
||||
relabelled.message_kind = EnvelopeKind::UsageReadoutResult;
|
||||
assert_eq!(
|
||||
decrypt_spend_readout(&relabelled, &key).unwrap_err(),
|
||||
decrypt_usage_readout(&relabelled, &key).unwrap_err(),
|
||||
ServiceError::Encryption
|
||||
);
|
||||
}
|
||||
|
|
@ -1313,12 +1311,12 @@ mod tests {
|
|||
fn a_response_is_read_as_its_own_operation_only() {
|
||||
use crate::readout::PlanQuotaSnapshot;
|
||||
let key = TransportKey::from_connection_secret("readout-test-key").unwrap();
|
||||
let readout = SpendReadout::new(1, Vec::new(), PlanQuotaSnapshot::default());
|
||||
let sealed = encrypt_spend_readout("caller-1", "readout-1", &readout, &key).unwrap();
|
||||
let readout_frame = encode_spend_readout_response_frame(&sealed).unwrap();
|
||||
let readout = UsageReadout::new(1, PlanQuotaSnapshot::default());
|
||||
let sealed = encrypt_usage_readout("caller-1", "readout-1", &readout, &key).unwrap();
|
||||
let readout_frame = encode_usage_readout_response_frame(&sealed).unwrap();
|
||||
let invoke_frame = encode_result_frame(&sealed).unwrap();
|
||||
assert_eq!(
|
||||
decode_spend_readout_response_frame(&readout_frame).unwrap(),
|
||||
decode_usage_readout_response_frame(&readout_frame).unwrap(),
|
||||
sealed
|
||||
);
|
||||
assert_eq!(decode_result_frame(&invoke_frame).unwrap(), sealed);
|
||||
|
|
@ -1327,9 +1325,9 @@ mod tests {
|
|||
Err(ServiceError::Carriage)
|
||||
);
|
||||
assert_eq!(
|
||||
decode_spend_readout_response_frame(&invoke_frame),
|
||||
decode_usage_readout_response_frame(&invoke_frame),
|
||||
Err(ServiceError::Carriage)
|
||||
);
|
||||
assert_eq!(decrypt_spend_readout(&sealed, &key).unwrap(), readout);
|
||||
assert_eq!(decrypt_usage_readout(&sealed, &key).unwrap(), readout);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -67,14 +67,6 @@ impl FlakyStore {
|
|||
pub(crate) fn allowance(&self) -> Arc<AtomicUsize> {
|
||||
self.pushes_allowed.clone()
|
||||
}
|
||||
|
||||
/// A store over the same records that accepts `pushes_allowed` more writes.
|
||||
pub(crate) fn reopened(&self, pushes_allowed: usize) -> Self {
|
||||
Self {
|
||||
held: self.held.clone(),
|
||||
pushes_allowed: Arc::new(AtomicUsize::new(pushes_allowed)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "daemon")]
|
||||
|
|
@ -133,16 +125,8 @@ pub(crate) fn request() -> ProviderRequest {
|
|||
request
|
||||
}
|
||||
|
||||
/// Generous next to the fixture request's worst case (about 64,000), so it
|
||||
/// binds only in the tests that are about spend.
|
||||
pub(crate) const MAX_COST: u64 = 10_000_000;
|
||||
|
||||
/// What the fixture usage (10 input and 3 output tokens) costs under
|
||||
/// [`fixture_price`]: 10 x 3,000,000 + 3 x 15,000,000 = 75,000,000 / 1e6.
|
||||
pub(crate) const FIXTURE_USAGE_COST: u64 = 75;
|
||||
|
||||
pub(crate) fn invocation() -> TransportInvocation {
|
||||
TransportInvocation::new("epiphany-yggdrasil", 2_000, [7; 32], MAX_COST, request()).unwrap()
|
||||
TransportInvocation::new("epiphany-yggdrasil", 2_000, [7; 32], request()).unwrap()
|
||||
}
|
||||
|
||||
pub(crate) fn receipt(invocation: &TransportInvocation) -> TransportReceipt {
|
||||
|
|
@ -155,8 +139,6 @@ pub(crate) fn receipt(invocation: &TransportInvocation) -> TransportReceipt {
|
|||
model: invocation.request.model.clone(),
|
||||
provider: "fixture-sse".to_string(),
|
||||
foreign_reasoning_dropped: 0,
|
||||
cost_micro_usd: FIXTURE_USAGE_COST,
|
||||
overrun_micro_usd: 0,
|
||||
outcome: TransportOutcome::Completed {
|
||||
provider_response_id: Some("response-1".to_string()),
|
||||
stop_reason: StopReason::EndTurn,
|
||||
|
|
@ -170,33 +152,6 @@ pub(crate) fn receipt(invocation: &TransportInvocation) -> TransportReceipt {
|
|||
},
|
||||
}
|
||||
}
|
||||
/// A price with a distinct nonzero rate per class, so a swapped rate changes a cost.
|
||||
#[cfg(feature = "daemon")]
|
||||
pub(crate) fn fixture_price() -> ModelPrice {
|
||||
ModelPrice {
|
||||
rates: Rates {
|
||||
input: 3_000_000,
|
||||
cache_write_short: 3_750_000,
|
||||
cache_write_long: 6_000_000,
|
||||
cache_read: 300_000,
|
||||
output: 15_000_000,
|
||||
},
|
||||
long_context: None,
|
||||
overhead_tokens: 100,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "daemon")]
|
||||
pub(crate) fn fixture_prices() -> PriceTable {
|
||||
PriceTable::from([("gpt-5.4".to_string(), fixture_price())])
|
||||
}
|
||||
|
||||
/// Far above anything a fixture request reserves: the ceiling binds only in
|
||||
/// the tests that are about it.
|
||||
#[cfg(feature = "daemon")]
|
||||
pub(crate) const CEILING: u64 = 1 << 40;
|
||||
#[cfg(feature = "daemon")]
|
||||
pub(crate) const WINDOW_MS: u64 = 3_600_000;
|
||||
|
||||
#[cfg(feature = "daemon")]
|
||||
pub(crate) fn caller(
|
||||
|
|
@ -212,8 +167,6 @@ pub(crate) fn caller(
|
|||
max_concurrent_requests,
|
||||
64 * 1024,
|
||||
32_768,
|
||||
SpendCeiling(CEILING),
|
||||
SpendWindowMs(WINDOW_MS),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
|
@ -223,7 +176,6 @@ pub(crate) fn open_service(store: &TestStore, max_concurrent_requests: usize) ->
|
|||
TransportService::open(
|
||||
&store.path,
|
||||
"fixture-sse",
|
||||
fixture_prices(),
|
||||
[
|
||||
caller(
|
||||
"epiphany-yggdrasil",
|
||||
|
|
@ -249,5 +201,5 @@ pub(crate) fn security(key: &str) -> TransportKey {
|
|||
pub(crate) fn invocation_for(caller_runtime_id: &str, request_id: &str) -> TransportInvocation {
|
||||
let mut request = request();
|
||||
request.request_id = request_id.to_string();
|
||||
TransportInvocation::new(caller_runtime_id, 2_000, [7; 32], MAX_COST, request).unwrap()
|
||||
TransportInvocation::new(caller_runtime_id, 2_000, [7; 32], request).unwrap()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
//! The spend readout: what each caller has spent and holds in its current
|
||||
//! window, and the plan's own usage as the backend last saw it. The ledger is
|
||||
//! the replay store's; a readout only reads it.
|
||||
//! The usage readout: the subscription plan's own usage windows as the backend
|
||||
//! last saw them. The connector meters nothing in dollars; it publishes what
|
||||
//! the provider reports, and the minds read it and decide their own burn.
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::contract::ContractError;
|
||||
|
||||
pub const SPEND_READOUT_SCHEMA_ID: &str = "gamecult.model.spend_readout.v1";
|
||||
pub const USAGE_READOUT_SCHEMA_ID: &str = "gamecult.model.usage_readout.v1";
|
||||
|
||||
/// One window of the subscription plan, as the provider reported it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
|
|
@ -32,40 +32,25 @@ pub struct PlanQuotaSnapshot {
|
|||
pub windows: Vec<PlanQuota>,
|
||||
}
|
||||
|
||||
/// One caller's current spend window in micro-USD. `spent` is settled charges
|
||||
/// plus what a crash left counted at its full reservation; `reserved` is what
|
||||
/// calls in flight hold, and both count against the ceiling.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CallerSpend {
|
||||
pub caller_id: String,
|
||||
pub window_ms: u64,
|
||||
pub ceiling_micro_usd: u64,
|
||||
pub spent_micro_usd: u64,
|
||||
pub reserved_micro_usd: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SpendReadout {
|
||||
pub struct UsageReadout {
|
||||
pub schema_id: String,
|
||||
pub at_unix_ms: u64,
|
||||
pub callers: Vec<CallerSpend>,
|
||||
pub plan_quota: Vec<PlanQuota>,
|
||||
}
|
||||
|
||||
impl SpendReadout {
|
||||
pub fn new(at_unix_ms: u64, callers: Vec<CallerSpend>, plan: PlanQuotaSnapshot) -> Self {
|
||||
impl UsageReadout {
|
||||
pub fn new(at_unix_ms: u64, plan: PlanQuotaSnapshot) -> Self {
|
||||
Self {
|
||||
schema_id: SPEND_READOUT_SCHEMA_ID.to_string(),
|
||||
schema_id: USAGE_READOUT_SCHEMA_ID.to_string(),
|
||||
at_unix_ms,
|
||||
callers,
|
||||
plan_quota: plan.windows,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate(&self) -> Result<(), ContractError> {
|
||||
if self.schema_id != SPEND_READOUT_SCHEMA_ID {
|
||||
if self.schema_id != USAGE_READOUT_SCHEMA_ID {
|
||||
return Err(ContractError::Schema);
|
||||
}
|
||||
Ok(())
|
||||
|
|
@ -77,16 +62,9 @@ mod tests {
|
|||
use super::*;
|
||||
use crate::contract::{wire_decode, wire_encode};
|
||||
|
||||
fn readout() -> SpendReadout {
|
||||
SpendReadout::new(
|
||||
fn readout() -> UsageReadout {
|
||||
UsageReadout::new(
|
||||
1_000,
|
||||
vec![CallerSpend {
|
||||
caller_id: "eureka".into(),
|
||||
window_ms: 3_600_000,
|
||||
ceiling_micro_usd: 50_000_000,
|
||||
spent_micro_usd: 7,
|
||||
reserved_micro_usd: 3,
|
||||
}],
|
||||
PlanQuotaSnapshot {
|
||||
windows: vec![PlanQuota {
|
||||
window: "five_hour".into(),
|
||||
|
|
@ -107,21 +85,21 @@ mod tests {
|
|||
panic!("a readout is a map, not a positional array");
|
||||
};
|
||||
let names: Vec<&str> = fields.iter().filter_map(|(k, _)| k.as_str()).collect();
|
||||
assert_eq!(names, ["schema_id", "at_unix_ms", "callers", "plan_quota"]);
|
||||
assert_eq!(wire_decode::<SpendReadout>(&bytes).unwrap(), readout());
|
||||
assert_eq!(names, ["schema_id", "at_unix_ms", "plan_quota"]);
|
||||
assert_eq!(wire_decode::<UsageReadout>(&bytes).unwrap(), readout());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unobserved_plan_is_none_not_zero() {
|
||||
let bare = SpendReadout::new(1, Vec::new(), PlanQuotaSnapshot::default());
|
||||
let decoded: SpendReadout = wire_decode(&wire_encode(&bare).unwrap()).unwrap();
|
||||
let bare = UsageReadout::new(1, PlanQuotaSnapshot::default());
|
||||
let decoded: UsageReadout = wire_decode(&wire_encode(&bare).unwrap()).unwrap();
|
||||
assert!(decoded.plan_quota.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_readout_of_another_schema_is_refused() {
|
||||
let mut other = readout();
|
||||
other.schema_id = "gamecult.model.spend_readout.v2".into();
|
||||
other.schema_id = "gamecult.model.usage_readout.v2".into();
|
||||
assert!(other.validate().is_err());
|
||||
assert!(readout().validate().is_ok());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,13 +13,12 @@ use zeroize::Zeroizing;
|
|||
use crate::contract::TransportResult;
|
||||
use crate::envelope::{
|
||||
RequestFrame, ServiceError, TransportFrameError, decode_request_frame, encode_result_frame,
|
||||
encode_spend_readout_response_frame, frame_bytes_for_payload, read_transport_frame,
|
||||
encode_usage_readout_response_frame, frame_bytes_for_payload, read_transport_frame,
|
||||
write_transport_frame,
|
||||
};
|
||||
use crate::readout::PlanQuotaSnapshot;
|
||||
use crate::service::{
|
||||
CallerAdmission, PriceTable, ProviderCall, SpendCeiling, SpendWindowMs, TransportAdmission,
|
||||
TransportService, distinct_admissions,
|
||||
CallerAdmission, ProviderCall, TransportAdmission, TransportService, distinct_admissions,
|
||||
};
|
||||
|
||||
/// The only provider seam of the connector kit. A connector binary implements
|
||||
|
|
@ -34,8 +33,9 @@ pub trait ProviderBackend: Send + Sync {
|
|||
/// `serve` on: it names the provider on every receipt and decides which
|
||||
/// reasoning state is foreign.
|
||||
fn provider(&self) -> &str;
|
||||
/// What the provider's own plan allows and has used, for the spend
|
||||
/// readout. A provider with no plan to report keeps the default.
|
||||
/// What the provider's own plan allows and has used, for the usage
|
||||
/// readout and the provider's own refusals. A provider with no plan to report
|
||||
/// keeps the default.
|
||||
fn plan_quota(&self) -> PlanQuotaSnapshot {
|
||||
PlanQuotaSnapshot::default()
|
||||
}
|
||||
|
|
@ -123,12 +123,6 @@ pub struct CallerConfig {
|
|||
pub max_concurrent_requests: usize,
|
||||
pub max_payload_bytes: usize,
|
||||
pub max_output_tokens: u32,
|
||||
/// The most the caller may spend in one window, in micro-USD. Required
|
||||
/// nonzero. A fuse set once, generously above what the dial allows.
|
||||
pub spend_ceiling_micro_usd: u64,
|
||||
/// The length of the caller's spend window, in milliseconds. Windows are
|
||||
/// fixed and aligned to the unix epoch. Required nonzero.
|
||||
pub spend_window_ms: u64,
|
||||
}
|
||||
|
||||
pub fn load_admissions(callers: &[CallerConfig]) -> Result<Vec<CallerAdmission>, ServeError> {
|
||||
|
|
@ -149,8 +143,6 @@ pub fn load_admissions(callers: &[CallerConfig]) -> Result<Vec<CallerAdmission>,
|
|||
caller.max_concurrent_requests,
|
||||
caller.max_payload_bytes,
|
||||
caller.max_output_tokens,
|
||||
SpendCeiling(caller.spend_ceiling_micro_usd),
|
||||
SpendWindowMs(caller.spend_window_ms),
|
||||
)
|
||||
.map_err(ServeError::Service)?,
|
||||
);
|
||||
|
|
@ -159,15 +151,12 @@ pub fn load_admissions(callers: &[CallerConfig]) -> Result<Vec<CallerAdmission>,
|
|||
}
|
||||
|
||||
/// Serves admitted callers on a loopback listener until the listener fails.
|
||||
/// `prices` is the connector binary's config document's table of what every
|
||||
/// allowed model costs (B4 owns that document).
|
||||
/// The caller binds; a listener that is not bound to loopback is refused, and
|
||||
/// peers that are not loopback are dropped.
|
||||
pub fn serve(
|
||||
listener: TcpListener,
|
||||
limits: ServeLimits,
|
||||
admissions: Vec<CallerAdmission>,
|
||||
prices: PriceTable,
|
||||
replay_store: &Path,
|
||||
backend: Arc<dyn ProviderBackend>,
|
||||
) -> Result<(), ServeError> {
|
||||
|
|
@ -176,7 +165,6 @@ pub fn serve(
|
|||
let service = Arc::new(Mutex::new(TransportService::open(
|
||||
replay_store,
|
||||
backend.provider(),
|
||||
prices,
|
||||
admissions,
|
||||
limits.max_expiry_skew_ms,
|
||||
)?));
|
||||
|
|
@ -184,8 +172,8 @@ pub fn serve(
|
|||
}
|
||||
|
||||
/// `serve` over a service the caller opened and keeps a handle to, so another
|
||||
/// front of the same ledger (the Self-run credential lease) reserves in the
|
||||
/// same windows. The limits must already have been validated against the
|
||||
/// front of the same service (the Self-run credential lease) shares its
|
||||
/// replay store and plan. The limits must already have been validated against the
|
||||
/// service's admissions.
|
||||
pub fn serve_service(
|
||||
listener: TcpListener,
|
||||
|
|
@ -197,7 +185,7 @@ pub fn serve_service(
|
|||
accept_loop(|| listener.accept(), limits, service, backend)
|
||||
}
|
||||
|
||||
/// What must be true before a serve loop touches the ledger: the listener is
|
||||
/// What must be true before a serve loop touches the store: the listener is
|
||||
/// on loopback and the backend can take work.
|
||||
fn admit_listener(listener: &TcpListener, backend: &dyn ProviderBackend) -> Result<(), ServeError> {
|
||||
if !listener
|
||||
|
|
@ -272,20 +260,25 @@ fn answer_frame(
|
|||
) -> Result<Vec<u8>, ServeError> {
|
||||
let envelope = match decode_request_frame(request).map_err(|_| ServeError::FrameEncoding)? {
|
||||
RequestFrame::Invoke(envelope) => envelope,
|
||||
RequestFrame::SpendReadout(envelope) => {
|
||||
RequestFrame::UsageReadout(envelope) => {
|
||||
let plan = backend.plan_quota();
|
||||
let response = service
|
||||
.lock()
|
||||
.map_err(|_| ServeError::ServicePoisoned)?
|
||||
.spend_readout(&envelope, unix_ms()?, plan, limits.max_frame_bytes)?;
|
||||
return encode_spend_readout_response_frame(&response)
|
||||
.usage_readout(&envelope, unix_ms()?, plan, limits.max_frame_bytes)?;
|
||||
return encode_usage_readout_response_frame(&response)
|
||||
.map_err(|_| ServeError::FrameEncoding);
|
||||
}
|
||||
};
|
||||
let admission = service
|
||||
.lock()
|
||||
.map_err(|_| ServeError::ServicePoisoned)?
|
||||
.begin(&envelope, unix_ms()?, limits.max_frame_bytes)?;
|
||||
.begin(
|
||||
&envelope,
|
||||
unix_ms()?,
|
||||
&backend.plan_quota(),
|
||||
limits.max_frame_bytes,
|
||||
)?;
|
||||
let response = match admission {
|
||||
TransportAdmission::Reply(response) => response,
|
||||
TransportAdmission::Execute(claim) => {
|
||||
|
|
@ -389,10 +382,7 @@ mod tests {
|
|||
FailureKind, Refusal, TransportDisposition, TransportEvent, TransportEventPayload,
|
||||
TransportInvocation, TransportOutcome, TransportResult,
|
||||
};
|
||||
use crate::fixtures::{
|
||||
CEILING, MAX_COST, TestStore, WINDOW_MS, caller, fixture_prices, invocation_for, receipt,
|
||||
request,
|
||||
};
|
||||
use crate::fixtures::{TestStore, caller, invocation_for, receipt, request};
|
||||
|
||||
const CALLER: &str = "epiphany-yggdrasil";
|
||||
const KEY: &str = "epiphany-distinct-test-key";
|
||||
|
|
@ -468,14 +458,7 @@ mod tests {
|
|||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let path = path.to_path_buf();
|
||||
thread::spawn(move || {
|
||||
let _ = sender.send(serve(
|
||||
listener,
|
||||
limits,
|
||||
admissions,
|
||||
fixture_prices(),
|
||||
&path,
|
||||
backend,
|
||||
));
|
||||
let _ = sender.send(serve(listener, limits, admissions, &path, backend));
|
||||
});
|
||||
receiver.recv_timeout(Duration::from_secs(2)).ok()
|
||||
}
|
||||
|
|
@ -501,16 +484,7 @@ mod tests {
|
|||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let endpoint = listener.local_addr().unwrap();
|
||||
let path = store.path.clone();
|
||||
thread::spawn(move || {
|
||||
serve(
|
||||
listener,
|
||||
limits(),
|
||||
admissions,
|
||||
fixture_prices(),
|
||||
&path,
|
||||
backend,
|
||||
)
|
||||
});
|
||||
thread::spawn(move || serve(listener, limits(), admissions, &path, backend));
|
||||
let client =
|
||||
ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap();
|
||||
(client, endpoint)
|
||||
|
|
@ -528,8 +502,6 @@ mod tests {
|
|||
max_concurrent_requests: *capacity,
|
||||
max_payload_bytes: 1_048_576,
|
||||
max_output_tokens: 16_384,
|
||||
spend_ceiling_micro_usd: CEILING,
|
||||
spend_window_ms: WINDOW_MS,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
|
@ -559,7 +531,7 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn serve_reads_out_spend_and_plan_quota_without_executing_anything() {
|
||||
fn serve_reads_out_plan_usage_without_executing_anything() {
|
||||
let store = TestStore::new();
|
||||
let inner = CountingBackend::new(true);
|
||||
let plan = PlanQuotaSnapshot {
|
||||
|
|
@ -580,16 +552,9 @@ mod tests {
|
|||
assert_eq!(inner.executions.load(Ordering::SeqCst), 1);
|
||||
|
||||
let before = now_ms();
|
||||
let readout = client.spend_readout(CALLER).unwrap();
|
||||
let readout = client.usage_readout(CALLER).unwrap();
|
||||
assert!(readout.at_unix_ms >= before && readout.at_unix_ms <= now_ms());
|
||||
assert_eq!(readout.plan_quota, plan.windows);
|
||||
let [row] = readout.callers.as_slice() else {
|
||||
panic!("one admitted caller");
|
||||
};
|
||||
assert_eq!(row.caller_id, CALLER);
|
||||
assert_eq!((row.ceiling_micro_usd, row.window_ms), (CEILING, WINDOW_MS));
|
||||
assert!(row.spent_micro_usd > 0, "the settled call was charged");
|
||||
assert_eq!(row.reserved_micro_usd, 0);
|
||||
assert_eq!(
|
||||
inner.executions.load(Ordering::SeqCst),
|
||||
1,
|
||||
|
|
@ -604,40 +569,61 @@ mod tests {
|
|||
Some(Duration::from_secs(5)),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(stranger.spend_readout(CALLER).is_err());
|
||||
assert!(stranger.usage_readout(CALLER).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_backend_with_no_plan_reads_out_none() {
|
||||
let store = TestStore::new();
|
||||
let (client, _) = start(CountingBackend::new(true), &store);
|
||||
let readout = client.spend_readout(CALLER).unwrap();
|
||||
let readout = client.usage_readout(CALLER).unwrap();
|
||||
assert!(readout.plan_quota.is_empty());
|
||||
}
|
||||
|
||||
fn window_plan(permille: u32, status: &str, resets_at_unix_ms: u64) -> PlanQuotaSnapshot {
|
||||
PlanQuotaSnapshot {
|
||||
windows: vec![crate::readout::PlanQuota {
|
||||
window: "five_hour".into(),
|
||||
utilization_permille: Some(permille),
|
||||
resets_at_unix_ms,
|
||||
status: status.into(),
|
||||
observed_at_unix_ms: 1,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_refuses_a_request_over_its_max_cost_without_executing_it() {
|
||||
fn serve_repeats_the_providers_rejection_and_executes_nothing_while_it_stands() {
|
||||
let store = TestStore::new();
|
||||
let backend = CountingBackend::new(true);
|
||||
let (client, _) = start(backend.clone(), &store);
|
||||
let mut invocation = fresh("request-costly");
|
||||
invocation.max_cost_micro_usd = 1;
|
||||
let refused = client.execute(&invocation).unwrap();
|
||||
let inner = CountingBackend::new(true);
|
||||
let backend = Arc::new(PlanBackend {
|
||||
inner: inner.clone(),
|
||||
plan: window_plan(1_000, "rejected", now_ms() + 3_600_000),
|
||||
});
|
||||
let (client, _) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]);
|
||||
let refused = client.execute(&fresh("request-rejected")).unwrap();
|
||||
assert_eq!(
|
||||
refused.disposition,
|
||||
TransportDisposition::Refused(Refusal::CostBound)
|
||||
TransportDisposition::Refused(Refusal::ProviderRejected)
|
||||
);
|
||||
assert_eq!(backend.executions.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(inner.executions.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
// The refusal was not recorded: the same id with a budget that holds
|
||||
// the worst case is admitted and executed.
|
||||
invocation.max_cost_micro_usd = MAX_COST;
|
||||
let admitted = client.execute(&invocation).unwrap();
|
||||
#[test]
|
||||
fn serve_admits_a_full_window_the_provider_still_allows() {
|
||||
let store = TestStore::new();
|
||||
let inner = CountingBackend::new(true);
|
||||
let backend = Arc::new(PlanBackend {
|
||||
inner: inner.clone(),
|
||||
plan: window_plan(999, "allowed", now_ms() + 3_600_000),
|
||||
});
|
||||
let (client, _) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]);
|
||||
let admitted = client.execute(&fresh("request-full")).unwrap();
|
||||
assert!(matches!(
|
||||
admitted.disposition,
|
||||
TransportDisposition::Transported { .. }
|
||||
));
|
||||
assert_eq!(backend.executions.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(inner.executions.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -676,7 +662,6 @@ mod tests {
|
|||
CALLER,
|
||||
invocation.expires_at_unix_ms,
|
||||
[7; 32],
|
||||
MAX_COST,
|
||||
conflicting_request,
|
||||
)
|
||||
.unwrap();
|
||||
|
|
@ -761,7 +746,6 @@ mod tests {
|
|||
let mut service = TransportService::open(
|
||||
&store.path,
|
||||
"fixture-sse",
|
||||
fixture_prices(),
|
||||
vec![caller(CALLER, KEY, 4)],
|
||||
300_000,
|
||||
)
|
||||
|
|
@ -769,8 +753,9 @@ mod tests {
|
|||
let envelope =
|
||||
crate::envelope::encrypt_invocation(&invocation, &crate::fixtures::security(KEY))
|
||||
.unwrap();
|
||||
let TransportAdmission::Execute(claim) =
|
||||
service.begin(&envelope, now_ms(), 1 << 20).unwrap()
|
||||
let TransportAdmission::Execute(claim) = service
|
||||
.begin(&envelope, now_ms(), &PlanQuotaSnapshot::default(), 1 << 20)
|
||||
.unwrap()
|
||||
else {
|
||||
panic!("a fresh request must execute");
|
||||
};
|
||||
|
|
@ -793,7 +778,6 @@ mod tests {
|
|||
listener,
|
||||
narrowed,
|
||||
vec![caller(CALLER, KEY, 4)],
|
||||
fixture_prices(),
|
||||
&path,
|
||||
served,
|
||||
)
|
||||
|
|
@ -879,13 +863,7 @@ mod tests {
|
|||
fn the_smallest_frame_also_carries_the_failure_that_stands_in_for_a_result() {
|
||||
let long = "x".repeat(crate::envelope::MAX_IDENTITY_BYTES);
|
||||
let plaintext = crate::contract::wire_encode(&crate::service::result_size_failure(
|
||||
&long,
|
||||
&long,
|
||||
&long,
|
||||
[0xff; 32],
|
||||
[0xff; 32],
|
||||
0,
|
||||
u64::MAX,
|
||||
&long, &long, &long, [0xff; 32], [0xff; 32], 0,
|
||||
))
|
||||
.unwrap()
|
||||
.len();
|
||||
|
|
@ -993,18 +971,7 @@ mod tests {
|
|||
}
|
||||
|
||||
fn admission(id: &str, key: &str, slots: usize, payload: usize) -> CallerAdmission {
|
||||
CallerAdmission::new(
|
||||
id,
|
||||
key,
|
||||
1,
|
||||
["gpt-5.4".to_string()],
|
||||
slots,
|
||||
payload,
|
||||
32_768,
|
||||
SpendCeiling(CEILING),
|
||||
SpendWindowMs(WINDOW_MS),
|
||||
)
|
||||
.unwrap()
|
||||
CallerAdmission::new(id, key, 1, ["gpt-5.4".to_string()], slots, payload, 32_768).unwrap()
|
||||
}
|
||||
|
||||
/// `Some(field)` when serve refused the configuration, `None` while it serves.
|
||||
|
|
@ -1110,7 +1077,7 @@ mod tests {
|
|||
..limits()
|
||||
};
|
||||
let admissions = vec![admission(CALLER, KEY, 4, bound)];
|
||||
thread::spawn(move || serve(listener, tight, admissions, fixture_prices(), &path, served));
|
||||
thread::spawn(move || serve(listener, tight, admissions, &path, served));
|
||||
let client =
|
||||
ConnectorClient::new(endpoint, KEY, frame, Some(Duration::from_secs(5))).unwrap();
|
||||
let reply = client.execute(&invocation).unwrap();
|
||||
|
|
@ -1225,7 +1192,6 @@ mod tests {
|
|||
let mut service = TransportService::open(
|
||||
&store.path,
|
||||
"fixture-sse",
|
||||
fixture_prices(),
|
||||
vec![caller(CALLER, KEY, 4)],
|
||||
300_000,
|
||||
)
|
||||
|
|
@ -1235,8 +1201,9 @@ mod tests {
|
|||
&crate::fixtures::security(KEY),
|
||||
)
|
||||
.unwrap();
|
||||
let TransportAdmission::Execute(claim) =
|
||||
service.begin(&envelope, now_ms(), 1 << 20).unwrap()
|
||||
let TransportAdmission::Execute(claim) = service
|
||||
.begin(&envelope, now_ms(), &PlanQuotaSnapshot::default(), 1 << 20)
|
||||
.unwrap()
|
||||
else {
|
||||
panic!("a fresh request must execute");
|
||||
};
|
||||
|
|
@ -1328,7 +1295,6 @@ mod tests {
|
|||
TransportService::open(
|
||||
&store.path,
|
||||
"fixture-sse",
|
||||
fixture_prices(),
|
||||
vec![caller(CALLER, KEY, 4)],
|
||||
300_000,
|
||||
)
|
||||
|
|
@ -1386,16 +1352,7 @@ mod tests {
|
|||
let backend = CountingBackend::new(true);
|
||||
let path = store.path.clone();
|
||||
let served = backend.clone();
|
||||
thread::spawn(move || {
|
||||
serve(
|
||||
listener,
|
||||
limits(),
|
||||
admissions,
|
||||
fixture_prices(),
|
||||
&path,
|
||||
served,
|
||||
)
|
||||
});
|
||||
thread::spawn(move || serve(listener, limits(), admissions, &path, served));
|
||||
let client =
|
||||
ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap();
|
||||
client.execute(&fresh("request-key")).unwrap();
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1 +0,0 @@
|
|||
<EFBFBD>messageIdョgolden-requestゥoperationヲinvokeァpayloadレDhqlzY2hlbWFfaWTZJGdhbWVjdWx0Lm1vZGVsLnRyYW5zcG9ydF9lbnZlbG9wZS52M7FjYWxsZXJfcnVudGltZV9pZK1nb2xkZW4tY2FsbGVyqnJlcXVlc3RfaWSuZ29sZGVuLXJlcXVlc3SsbWVzc2FnZV9raW5kqkludm9jYXRpb26lbm9uY2WczO7MxRrMxw7MhTh7SMzwzNB2qmNpcGhlcnRleHTFA0d65EskLG6kIwJ/G+XDK03gZOGtLFi6vZHJbI+/KpRLwnLT0TPF7RQa0KD98CrW+VwkKY3sRa4+Z9+/5OdPq1YmDFwbxvMVjZsFjXXw84tzvuLKHsb/3kQSEvAlFE4K6FXHvznLcMo4CnGUzoXwNGALf+xDTqFG0aFbdG4xGynV/kttsL6f34F4+l6xiXMUy87Q8/1UyOK/YaVxMMmlT3tdTllhq8YU8Dvfq0KuMaj/f9Anya8A5bJwlxafZPtc53RoH1/oNjLdaDqvwrTEnTB9TvKlnEOxKyyKhmmwGaC03qqPJXRaj8cDQO6EHDbML4J0zMN8TvssQISd5UCeVMkvDGjmvEOmRUoPk1/SnSrIHdha4+6rU4lUSumloLmlx5vv++Mq4AqzOdd/vPB6Ov/AoF32X27o4RI6H3xCKKHjKC4m3+cVjXCrOcGojuRf9yeDFkgbiPaC31hmSc8rAm6HO/NcaIHvx+G+6AaurAEhDLdF6DdrXb4xwjuv6yWQKihNvLXpnwmhRFkSeD5lS6FHW+CoOIdq/RBnFFyDrboTPWFoxQYIrBuqFoHDOajIz7dXYif0sf9sB9JBrDhlcbTpiGcyURfzDhW55NOPqKFGi6ropaJ1/SyLP3f7E57kA22aQ2Op7o36Tu06Pnzo2wI7UsL/Qz27F+AGAukQCvTJyjxARiGr3TRpChjVXx6GXhLrG1T9P+Mrhyrt9vwwhboN8qz1uvDZwKhGWBKXPXkxluq/NY1DwB3JTCCZfEwukWjMZbqiINLEKvW9BStcBR1kfXcK6sQvn/F0g9r81e9brbe+w3U24GERnHwgruOqytTeax/xPbQ7uISV48g5L8DAYf788KhUXwI43QDHNBdBUyo0rCsgoWJKeO05fcAgKgYYGsyLtMW10Vstw3q4POyn3o7rrBz4S2cnl2iZgr0ixg/KgF0V+loEVuj/6rYrcW0SLCHwV1+w1ClFMn0ZPsrz28EoZMA617G0Rrch66cS5uI9/Zf/wLX3z6n7xoPLNXk51ZsLSZ2bqEQkcBJbW/dT5MdH6anWVogRDvIW1coUbkIq9l+pkQSuelWsfakX4UQwYuUD0UwNbqxHiGwlEFj0f1bdhEj26Q==ッpayloadEncodingイmessagepack-base64ュpayloadSchemaル$gamecult.model.transport_envelope.v3ュschemaVersionシcultnet.operation_request.v0ゥserviceIdクgamecult.model.connector
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -1,6 +1,6 @@
|
|||
# wire_v3 fixtures
|
||||
# wire_v4 fixtures
|
||||
|
||||
The named-MessagePack bytes of the v3 documents and one sealed carriage frame,
|
||||
The named-MessagePack bytes of the v4 documents and one sealed carriage frame,
|
||||
produced by the kit at the revision that added them. They pin drift; the types in
|
||||
`src/contract.rs` own the shape, and `schemas/` publishes it.
|
||||
|
||||
|
|
@ -10,7 +10,7 @@ produced by the kit at the revision that added them. They pin drift; the types i
|
|||
the plaintext documents.
|
||||
- `carriage_invocation.frame`: a `cultnet.operation_request.v0` for service
|
||||
`gamecult.model.connector`, operation `invoke`, whose payload is the base64 of an envelope
|
||||
sealed under the fixed test key in `tests/wire_golden_v3.rs`.
|
||||
sealed under the fixed test key in `tests/wire_golden_v4.rs`.
|
||||
|
||||
Generator: `tests/wire_golden_v3.rs` itself. Run it with `WIRE_V3_REGENERATE=1` to rewrite
|
||||
Generator: `tests/wire_golden_v4.rs` itself. Run it with `WIRE_V4_REGENERATE=1` to rewrite
|
||||
the files from the kit, then review the diff: a changed byte is a wire change.
|
||||
1
crates/model-connector/tests/fixtures/wire_v4/carriage_invocation.frame
vendored
Normal file
1
crates/model-connector/tests/fixtures/wire_v4/carriage_invocation.frame
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
<EFBFBD>messageIdョgolden-requestゥoperationヲinvokeァpayloadレ(hqlzY2hlbWFfaWTZJGdhbWVjdWx0Lm1vZGVsLnRyYW5zcG9ydF9lbnZlbG9wZS52NLFjYWxsZXJfcnVudGltZV9pZK1nb2xkZW4tY2FsbGVyqnJlcXVlc3RfaWSuZ29sZGVuLXJlcXVlc3SsbWVzc2FnZV9raW5kqkludm9jYXRpb26lbm9uY2WcXSbMzU3MhsyCzLAtzKLMhcy8zMSqY2lwaGVydGV4dMUDMY816tn0FGQ9jqxE+KyDVcxmhufaQI7vzEXO8NXTQPOYpRuMcRDM/j/QzNF2Lb3Fak0G+hHRKrXDxJ3MeKpoELNYOEyxbKfxn88mjAyyc7BVPM7+0Bk9ye3m5oBF6hoyCgOHSTwESIfq0bim+9oQh1IDp+HdFjztK/XjM731GRzKJmGgxsKqQsz42zq8y9mjAXl3V1RR9ssdKvk2k5U56/3liOeHDU96kOa7IlVCBm6qnn06hg2DTtnBF4xGj6PihHj4KufVkAcuQhRCZWOKsploToXo7wy+jcQDrnhHIUCMN6sk3P9YJh1ejuleDM9rp3RYiXcnzRwMNXK1AGpNraTgWn91d6L/1Ff+gaQBgPxSjW6FATshJf9Iqk9pEhT8xeCQMmNj40CdlVFYNz/TsRJYW45BXm8g83Jnh3Wj0Z90WJ80bwwgZbjPWx6wCOCID6Jo8wiubF6411ygi+GUHTR9rZFhrsGo6TSmsbvIAuabUJcskqKHW7tqVkfpz5JdjyeSSDvKcZ3PQyVne7Lyo8nzNh0g06a7CEUvq9kvr4zfTCfwk/1YVSrZ+7U8ePGj27V3D8+BH/pafiLR5FxxBKWBTYe7n5irVP5gLw4WlzOrSriXpolmaPWujCm3apml45mhlYARdfJJbpQxnQGb6cI3D/vAxxI50BPLB82JqCjNFex9xwfP5jSRDYah9wLm4yVymBqZ8Wvn0maLz4OvF2EonJBwEtN73UBULkdeX6g9GTiu2MKtCjSMm33SkwiHfvDdwMDS11sINK+YQLF/3HobbnAk2n963JahlddNRg79T96GksjN0br8u1PNMC+/uBUHEQvUBfRnR4tKp+SeLF6zMn228orgHgWr7sxilMwTOP1DgXpbEE19M0P8XC0CA/pTeHr4eFHzakPLotxF8avQfPKAXbXWgNGK6uWj1NGPshD6EN3pLvePOc4uObqHMKz/dg52/7m1VTHhYMivSRenG6H/BrWfUXQvcgCPalg7C4KCPYINb3nnRxP0NIOBP+KJ4S2haU94ZNHVr2HB038xNzUm2HrONVBsxuuTckYDmHfCa6FmvVJv4she5wyuPHk=ッpayloadEncodingイmessagepack-base64ュpayloadSchemaル$gamecult.model.transport_envelope.v4ュschemaVersionシcultnet.operation_request.v0ゥserviceIdクgamecult.model.connector
|
||||
Binary file not shown.
Binary file not shown.
BIN
crates/model-connector/tests/fixtures/wire_v4/transport_invocation.mp
vendored
Normal file
BIN
crates/model-connector/tests/fixtures/wire_v4/transport_invocation.mp
vendored
Normal file
Binary file not shown.
BIN
crates/model-connector/tests/fixtures/wire_v4/transport_receipt_failed.mp
vendored
Normal file
BIN
crates/model-connector/tests/fixtures/wire_v4/transport_receipt_failed.mp
vendored
Normal file
Binary file not shown.
|
|
@ -1 +1 @@
|
|||
„©schema_idÙ"gamecult.model.transport_result.v3ªrequest_id®golden-request±caller_runtime_idgolden-caller«disposition<6F>§Refused«OutputBound
|
||||
„©schema_idÙ"gamecult.model.transport_result.v4ªrequest_id®golden-request±caller_runtime_idgolden-caller«disposition<6F>§Refused«OutputBound
|
||||
BIN
crates/model-connector/tests/fixtures/wire_v4/transport_result_transported.mp
vendored
Normal file
BIN
crates/model-connector/tests/fixtures/wire_v4/transport_result_transported.mp
vendored
Normal file
Binary file not shown.
|
|
@ -1,4 +1,4 @@
|
|||
//! `schemas/` at the repository root publishes one JSON Schema per v3 document,
|
||||
//! `schemas/` at the repository root publishes one JSON Schema per v4 document,
|
||||
//! generated from the types. This test regenerates them and fails on any
|
||||
//! difference; run it with `MODEL_CONNECTOR_REGENERATE_SCHEMAS=1` to rewrite the
|
||||
//! files from the types.
|
||||
|
|
@ -28,7 +28,7 @@ fn published_schemas_are_the_types() {
|
|||
("transport_result", render::<TransportResult>()),
|
||||
("transport_receipt", render::<TransportReceipt>()),
|
||||
("transport_envelope", render::<TransportEnvelope>()),
|
||||
("spend_readout", render::<SpendReadout>()),
|
||||
("usage_readout", render::<UsageReadout>()),
|
||||
];
|
||||
let dir = schemas_dir();
|
||||
if std::env::var_os(REGENERATE).is_some() {
|
||||
|
|
@ -80,7 +80,7 @@ fn the_published_ciphertext_is_what_the_wire_sends() {
|
|||
assert_eq!(&published["properties"]["ciphertext"], ciphertext);
|
||||
|
||||
let envelope = TransportEnvelope {
|
||||
schema_id: "gamecult.model.transport_envelope.v3".to_string(),
|
||||
schema_id: "gamecult.model.transport_envelope.v4".to_string(),
|
||||
caller_runtime_id: "caller".to_string(),
|
||||
request_id: "request".to_string(),
|
||||
message_kind: EnvelopeKind::Invocation,
|
||||
|
|
@ -111,9 +111,7 @@ fn the_refusal_schema_is_one_flat_string_enum() {
|
|||
.iter()
|
||||
.map(|value| value.as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(variants.len(), 15);
|
||||
assert!(variants.contains(&"ClockBehindAdmissionWindow"));
|
||||
assert_eq!(variants.len(), 13);
|
||||
assert!(variants.contains(&"ForeignReasoningState"));
|
||||
assert!(variants.contains(&"CostBound"));
|
||||
assert!(variants.contains(&"SpendCeiling"));
|
||||
assert!(variants.contains(&"ProviderRejected"));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -106,8 +106,6 @@ fn start_with(backend: Arc<dyn ProviderBackend>, max_concurrent: usize) -> Conne
|
|||
max_concurrent,
|
||||
64 * 1024,
|
||||
32_768,
|
||||
SpendCeiling(1 << 40),
|
||||
SpendWindowMs(3_600_000),
|
||||
)
|
||||
.unwrap();
|
||||
let limits = ServeLimits {
|
||||
|
|
@ -116,21 +114,7 @@ fn start_with(backend: Arc<dyn ProviderBackend>, max_concurrent: usize) -> Conne
|
|||
socket_timeout_ms: 5_000,
|
||||
max_expiry_skew_ms: 300_000,
|
||||
};
|
||||
let prices = PriceTable::from([(
|
||||
"claude-opus-4-5".to_string(),
|
||||
ModelPrice {
|
||||
rates: Rates {
|
||||
input: 5_000_000,
|
||||
cache_write_short: 6_250_000,
|
||||
cache_write_long: 10_000_000,
|
||||
cache_read: 500_000,
|
||||
output: 25_000_000,
|
||||
},
|
||||
long_context: None,
|
||||
overhead_tokens: 100,
|
||||
},
|
||||
)]);
|
||||
thread::spawn(move || serve(listener, limits, vec![admission], prices, &store, backend));
|
||||
thread::spawn(move || serve(listener, limits, vec![admission], &store, backend));
|
||||
ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap()
|
||||
}
|
||||
|
||||
|
|
@ -143,7 +127,7 @@ fn invocation(request_id: &str, input: Vec<InputItem>) -> TransportInvocation {
|
|||
4_096,
|
||||
);
|
||||
request.input = input;
|
||||
TransportInvocation::new(CALLER, now_ms() + 60_000, [7; 32], 10_000_000, request).unwrap()
|
||||
TransportInvocation::new(CALLER, now_ms() + 60_000, [7; 32], request).unwrap()
|
||||
}
|
||||
|
||||
fn user(text: &str) -> InputItem {
|
||||
|
|
@ -332,7 +316,7 @@ fn a_refused_completion_reaches_the_caller_as_a_typed_failure_and_frees_the_slot
|
|||
let edits: [fn(&mut TransportReceipt); 3] = [
|
||||
|receipt| receipt.provider = "another-provider".to_string(),
|
||||
|receipt| receipt.foreign_reasoning_dropped += 1,
|
||||
|receipt| receipt.cost_micro_usd += 1,
|
||||
|receipt| receipt.request_id = "another-request".to_string(),
|
||||
];
|
||||
for edit in edits {
|
||||
// One concurrent request: a wedged slot would refuse the next id.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
//! Pins the bytes of the v3 wire so a drift is a failing test. The fixtures in
|
||||
//! `fixtures/wire_v3` are produced by this file (see its README); they pin the
|
||||
//! Pins the bytes of the v4 wire so a drift is a failing test. The fixtures in
|
||||
//! `fixtures/wire_v4` are produced by this file (see its README); they pin the
|
||||
//! kit against itself and are not a second contract: the types in
|
||||
//! `model_connector::contract` own the shape.
|
||||
|
||||
|
|
@ -17,10 +17,10 @@ use serde::de::DeserializeOwned;
|
|||
|
||||
const KEY: &str = "golden-distinct-test-key";
|
||||
const CALLER: &str = "golden-caller";
|
||||
const REGENERATE: &str = "WIRE_V3_REGENERATE";
|
||||
const REGENERATE: &str = "WIRE_V4_REGENERATE";
|
||||
|
||||
fn fixtures() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/wire_v3")
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/wire_v4")
|
||||
}
|
||||
|
||||
fn named<T: Serialize>(value: &T) -> Vec<u8> {
|
||||
|
|
@ -28,7 +28,7 @@ fn named<T: Serialize>(value: &T) -> Vec<u8> {
|
|||
}
|
||||
|
||||
/// The value serializes to the committed bytes and the committed bytes decode
|
||||
/// back to it. With `WIRE_V3_REGENERATE` set, the committed bytes are rewritten
|
||||
/// back to it. With `WIRE_V4_REGENERATE` set, the committed bytes are rewritten
|
||||
/// from the value first.
|
||||
fn assert_wire<T: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug>(
|
||||
name: &str,
|
||||
|
|
@ -81,7 +81,7 @@ fn request() -> ProviderRequest {
|
|||
}
|
||||
|
||||
fn invocation() -> TransportInvocation {
|
||||
TransportInvocation::new(CALLER, 1_800_000_000_000, [7; 32], 5_000_000, request()).unwrap()
|
||||
TransportInvocation::new(CALLER, 1_800_000_000_000, [7; 32], request()).unwrap()
|
||||
}
|
||||
|
||||
fn receipt(outcome: TransportOutcome) -> TransportReceipt {
|
||||
|
|
@ -95,8 +95,6 @@ fn receipt(outcome: TransportOutcome) -> TransportReceipt {
|
|||
model: invocation.request.model.clone(),
|
||||
provider: "anthropic-messages".to_string(),
|
||||
foreign_reasoning_dropped: 2,
|
||||
cost_micro_usd: 1_234_567,
|
||||
overrun_micro_usd: 89,
|
||||
outcome,
|
||||
}
|
||||
}
|
||||
|
|
@ -116,7 +114,7 @@ fn completed() -> TransportOutcome {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn wire_golden_v3() {
|
||||
fn wire_golden_v4() {
|
||||
let invocation = invocation();
|
||||
assert_wire("provider_request.mp", &invocation.request);
|
||||
assert_wire("transport_invocation.mp", &invocation);
|
||||
|
|
@ -233,7 +231,7 @@ fn the_golden_carriage_frame_decrypts_and_validates_under_the_fixed_key() {
|
|||
};
|
||||
assert_eq!(service_id, "gamecult.model.connector");
|
||||
assert_eq!(operation, "invoke");
|
||||
assert_eq!(payload_schema, "gamecult.model.transport_envelope.v3");
|
||||
assert_eq!(payload_schema, "gamecult.model.transport_envelope.v4");
|
||||
assert_eq!(message_id, invocation.request_id());
|
||||
let envelope: TransportEnvelope =
|
||||
rmp_serde::from_slice(&STANDARD.decode(payload).unwrap()).unwrap();
|
||||
|
|
@ -47,8 +47,8 @@
|
|||
"enum": [
|
||||
"Invocation",
|
||||
"Result",
|
||||
"SpendReadoutRequest",
|
||||
"SpendReadoutResult"
|
||||
"UsageReadoutRequest",
|
||||
"UsageReadoutResult"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,12 +11,6 @@
|
|||
"format": "uint64",
|
||||
"minimum": 0
|
||||
},
|
||||
"max_cost_micro_usd": {
|
||||
"description": "The most this request may cost, in micro-USD: the caller's own bound\non it. Required nonzero. It is part of the invocation's identity, so a\nchanged budget under a recorded request id is a `ReplayConflict`.",
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0
|
||||
},
|
||||
"native_request_sha256": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
|
|
@ -53,7 +47,6 @@
|
|||
"expires_at_unix_ms",
|
||||
"native_request_sha256",
|
||||
"provider_request_sha256",
|
||||
"max_cost_micro_usd",
|
||||
"request"
|
||||
],
|
||||
"$defs": {
|
||||
|
|
|
|||
|
|
@ -6,12 +6,6 @@
|
|||
"caller_runtime_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"cost_micro_usd": {
|
||||
"description": "What the request cost, in micro-USD. The service derives it from the\noutcome's usage and its price table; a backend never writes it.",
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0
|
||||
},
|
||||
"foreign_reasoning_dropped": {
|
||||
"description": "How many foreign `ReasoningState` items the service removed from the\nrequest before the backend saw it.",
|
||||
"type": "integer",
|
||||
|
|
@ -35,12 +29,6 @@
|
|||
"outcome": {
|
||||
"$ref": "#/$defs/TransportOutcome"
|
||||
},
|
||||
"overrun_micro_usd": {
|
||||
"description": "How far `cost_micro_usd` exceeds what the service reserved for the\nrequest: zero unless the backend reported usage above the worst case\nthe request allowed, which is a breach of the backend's contract. The\ncost is still the true one and the caller's window is charged all of\nit. The service derives this; a backend never writes it.",
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0
|
||||
},
|
||||
"provider": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -72,8 +60,6 @@
|
|||
"model",
|
||||
"provider",
|
||||
"foreign_reasoning_dropped",
|
||||
"cost_micro_usd",
|
||||
"overrun_micro_usd",
|
||||
"outcome"
|
||||
],
|
||||
"$defs": {
|
||||
|
|
@ -174,7 +160,7 @@
|
|||
]
|
||||
},
|
||||
"Usage": {
|
||||
"description": "Token accounting for one request, as the backend reports it; the service\nprices it. Cache reads and writes are counted apart from plain input.\n`output_tokens` includes reasoning tokens: `reasoning_tokens` is a detail\n(absent when the provider does not report it) and is never priced apart.",
|
||||
"description": "Token accounting for one request, as the backend reports it. Cache reads\nand writes are counted apart from plain input.\n`output_tokens` includes reasoning tokens: `reasoning_tokens` is a detail\n(absent when the provider does not report it) and is never counted apart.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"cache_read_tokens": {
|
||||
|
|
|
|||
|
|
@ -46,15 +46,13 @@
|
|||
"ModelNotAllowed",
|
||||
"OutputBound",
|
||||
"PayloadBound",
|
||||
"CostBound",
|
||||
"SpendCeiling",
|
||||
"Capacity",
|
||||
"InFlight",
|
||||
"Indeterminate",
|
||||
"ReplayConflict",
|
||||
"Malformed",
|
||||
"ForeignReasoningState",
|
||||
"ClockBehindAdmissionWindow"
|
||||
"ProviderRejected"
|
||||
]
|
||||
},
|
||||
"StopReason": {
|
||||
|
|
@ -286,12 +284,6 @@
|
|||
"caller_runtime_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"cost_micro_usd": {
|
||||
"description": "What the request cost, in micro-USD. The service derives it from the\noutcome's usage and its price table; a backend never writes it.",
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0
|
||||
},
|
||||
"foreign_reasoning_dropped": {
|
||||
"description": "How many foreign `ReasoningState` items the service removed from the\nrequest before the backend saw it.",
|
||||
"type": "integer",
|
||||
|
|
@ -315,12 +307,6 @@
|
|||
"outcome": {
|
||||
"$ref": "#/$defs/TransportOutcome"
|
||||
},
|
||||
"overrun_micro_usd": {
|
||||
"description": "How far `cost_micro_usd` exceeds what the service reserved for the\nrequest: zero unless the backend reported usage above the worst case\nthe request allowed, which is a breach of the backend's contract. The\ncost is still the true one and the caller's window is charged all of\nit. The service derives this; a backend never writes it.",
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0
|
||||
},
|
||||
"provider": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -352,13 +338,11 @@
|
|||
"model",
|
||||
"provider",
|
||||
"foreign_reasoning_dropped",
|
||||
"cost_micro_usd",
|
||||
"overrun_micro_usd",
|
||||
"outcome"
|
||||
]
|
||||
},
|
||||
"Usage": {
|
||||
"description": "Token accounting for one request, as the backend reports it; the service\nprices it. Cache reads and writes are counted apart from plain input.\n`output_tokens` includes reasoning tokens: `reasoning_tokens` is a detail\n(absent when the provider does not report it) and is never priced apart.",
|
||||
"description": "Token accounting for one request, as the backend reports it. Cache reads\nand writes are counted apart from plain input.\n`output_tokens` includes reasoning tokens: `reasoning_tokens` is a detail\n(absent when the provider does not report it) and is never counted apart.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"cache_read_tokens": {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "SpendReadout",
|
||||
"title": "UsageReadout",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"at_unix_ms": {
|
||||
|
|
@ -8,12 +8,6 @@
|
|||
"format": "uint64",
|
||||
"minimum": 0
|
||||
},
|
||||
"callers": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/CallerSpend"
|
||||
}
|
||||
},
|
||||
"plan_quota": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
|
|
@ -28,47 +22,9 @@
|
|||
"required": [
|
||||
"schema_id",
|
||||
"at_unix_ms",
|
||||
"callers",
|
||||
"plan_quota"
|
||||
],
|
||||
"$defs": {
|
||||
"CallerSpend": {
|
||||
"description": "One caller's current spend window in micro-USD. `spent` is settled charges\nplus what a crash left counted at its full reservation; `reserved` is what\ncalls in flight hold, and both count against the ceiling.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"caller_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"ceiling_micro_usd": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0
|
||||
},
|
||||
"reserved_micro_usd": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0
|
||||
},
|
||||
"spent_micro_usd": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0
|
||||
},
|
||||
"window_ms": {
|
||||
"type": "integer",
|
||||
"format": "uint64",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"caller_id",
|
||||
"window_ms",
|
||||
"ceiling_micro_usd",
|
||||
"spent_micro_usd",
|
||||
"reserved_micro_usd"
|
||||
]
|
||||
},
|
||||
"PlanQuota": {
|
||||
"description": "One window of the subscription plan, as the provider reported it.",
|
||||
"type": "object",
|
||||
Loading…
Reference in a new issue