feat(claude-connector): wire connector_config.v4 ModelRow.price, CLI flags, and lock-free SpendSnapshot readout

- Bump ClaudeConnectorConfig CultCache type from connector_config.v3 to
  connector_config.v4 and add ModelRow.price: Option<PriceRow>, validated
  solely through PriceRow::validate() in ClaudeConnectorConfig::validate().
- Wire ModelRow.price into ProviderRoutes::with_prices in routes_for and
  extract opened.spend_snapshot() before Mutex wrapping in serve_bound_with
  so start_leases -> serve_leases -> Lender -> lease::readout publishes
  live communal monthly spend without taking service.lock().
- Add --price-input, --price-cache-read, --price-cache-write, --price-output,
  and repeated --price-band flags to config init and add-model, requiring all
  four base rate flags whenever pricing or band flags are given and never
  echoing input values on error.
- Remove obsolete --price refusal from config_document::the_dollar_flags_are_not_flags,
  add v3 refusal / v4 price / PriceRow / CLI / lease / E2E tests, and update README.md.
This commit is contained in:
Meta Vens 2026-12-06 05:50:58 +01:00
commit fcad6ed3f7
12 changed files with 1347 additions and 95 deletions

View file

@ -4,10 +4,7 @@ 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.
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.
The connector gates nothing in dollars. It holds the provider credentials and subscription token, lends leases, derives optional per-call micro-USD visibility on receipts, and publishes communal monthly caller/model spend alongside 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.
@ -16,8 +13,8 @@ Status: the `model-connector` crate and the `claude-connector` backend crate and
Crate `crates/model-connector`:
- `src/contract.rs` - the v4 wire contract (`gamecult.model.*.v4`): `ProviderRequest`, `TransportInvocation`,
`TransportResult`, `TransportReceipt`, the typed `StopReason`, `FailureKind` and `Refusal`,
- `src/contract.rs` - the v5 wire contract (`gamecult.model.*.v5`): `ProviderRequest`, `TransportInvocation`,
`TransportResult`, `TransportReceipt` (with optional `cost_micro_usd` visibility), 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
state in the in-flight tool exchange and drops it from earlier turns),
@ -28,13 +25,16 @@ Crate `crates/model-connector`:
`cultnet.operation_request.v0` / `operation_response.v0` for service
`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;
`UsageReadout` (`gamecult.model.usage_readout.v2`): communal monthly `CallerModelSpend` rows
and 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.
- `schemas/` - one JSON Schema per v5 document, generated from the types.
- `src/client.rs` - `ConnectorClient`, the one-request caller side.
- `src/price.rs` - pure-integer UTC `PriceRow` (`base` plus ordered `PriceBand` overrides) and
`TokenRates` cost calculation for non-gating visibility.
- `src/service.rs` (feature `daemon`) - `TransportService`: caller admission, durable
replay (a retried request is answered byte-identically and the provider runs once),
per-call `cost_micro_usd` derivation, lock-free `SpendSnapshot` projection,
in-flight and capacity refusals.
- `src/serve.rs` (feature `daemon`) - `serve()`, the loopback accept loop, over the
`ProviderBackend` trait. A connector binary implements `ProviderBackend` for its
@ -42,7 +42,11 @@ Crate `crates/model-connector`:
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
- `RouterBackend` routes each configured `ModelRow` in the CultCache `gamecult.model_connector.connector_config.v4`
document to its configured `ProviderEntry` (`ProviderWire::AnthropicMessages`, `ProviderWire::OpenAiChat`, or
`ProviderWire::ClaudeCodeCli`), enforces per-model `ModelRow` policies (`upstream`, `efforts`, `unset_effort`,
`forced_tool_choice`, `output_schema`, `strict_tools`), and isolates `ReasoningState` by provider entry id.
- `ClaudeCodeBackend` implements `ProviderBackend` for `ProviderWire::ClaudeCodeCli` by driving the
unmodified `claude` binary, one child per call, in print stream-json mode with no tools, no MCP
servers, no settings sources and the system prompt replaced. Tool-less turns only: a request
with tools or a final tool result is refused before any spawn. A request's output schema goes
@ -50,12 +54,23 @@ Crate `crates/claude-connector` (library and the `claude-connector` binary that
- 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.
- `MessagesBackend` implements `ProviderBackend` for `ProviderWire::AnthropicMessages` (one
non-streaming `POST /v1/messages` per call: tools, tool calls and results, thinking blocks,
`cache_control`, and cache read/write usage; optional `x-api-key` credential). `OpenAiChatBackend`
implements `ProviderBackend` for `ProviderWire::OpenAiChat` (non-streaming chat completions with
`reasoning_content` replay and `Bearer` credential when configured). Neither HTTP wire has a
plan: `plan_quota` comes only from a `ClaudeCodeCli` meter, and only a config with a `ClaudeCodeCli`
provider lends token leases.
- `config init` and `config add-model` accept optional per-model pricing flags (`--price-input`,
`--price-cache-read`, `--price-cache-write`, `--price-output`, and repeated
`--price-band WEEKDAYS:UTC_HOURS:INPUT:CACHE_READ:CACHE_WRITE:OUTPUT`) populating `ModelRow.price`
for non-gating receipt and readout visibility only.
- `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 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.
plan windows the CLI's `rate_limit_event`s report, served alongside `SpendSnapshot` in `usage_readout`
and `ClaudeUsageReadout` without taking the `TransportService` lock.
## Asking for one no-tools completion
@ -82,8 +97,8 @@ 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 v4
only: a v2 frame gets no answer.
The default feature set compiles contract, envelope and client only. The kit speaks v5
only: a v4 frame gets no answer.
## Verify
@ -92,9 +107,9 @@ cargo test --locked --workspace
cargo test --locked --workspace --features model-connector/daemon
```
`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/wire_golden_v5.rs` pins the v5 documents and one sealed carriage
frame to the fixtures in `crates/model-connector/tests/fixtures/wire_v5` (regenerate with
`WIRE_V5_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).

View file

@ -342,6 +342,7 @@ fn default_row(id: &str) -> ModelRow {
forced_tool_choice: ForcedToolChoice::Never,
output_schema: OutputSchemaSupport::Native,
strict_tools: false,
price: None,
}
}
@ -675,6 +676,7 @@ fn cli_parameterized_id_efforts_output_schema_and_meter_model() {
forced_tool_choice: ForcedToolChoice::Never,
output_schema: OutputSchemaSupport::None,
strict_tools: false,
price: None,
};
let backend = ClaudeCodeBackend::with_ports(

View file

@ -1,10 +1,10 @@
use std::path::PathBuf;
use std::time::Duration;
use model_connector::ReasoningEffort;
use model_connector::{PriceRow, ReasoningEffort};
use serde::{Deserialize, Serialize};
/// One configured provider entry in the connector's v3 config document.
/// One configured provider entry in the connector's v4 config document.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProviderEntry {
/// Provider tag written on receipts and reasoning state items.
@ -59,6 +59,7 @@ pub struct ModelRow {
pub forced_tool_choice: ForcedToolChoice,
pub output_schema: OutputSchemaSupport,
pub strict_tools: bool,
pub price: Option<PriceRow>,
}
impl ModelRow {

View file

@ -51,7 +51,7 @@ pub struct LeaseHolderConfig {
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "gamecult.model_connector.connector_config.v3")]
#[cultcache(type = "gamecult.model_connector.connector_config.v4")]
pub struct ClaudeConnectorConfig {
/// A loopback socket address.
#[cultcache(key = 0)]
@ -304,6 +304,11 @@ impl ClaudeConnectorConfig {
{
return Err(ConfigError::Invalid("unset_effort"));
}
if let Some(price) = &model.price
&& price.validate().is_err()
{
return Err(ConfigError::Invalid("price"));
}
}
if self.callers.is_empty() {
@ -794,6 +799,7 @@ fn start_leases(
config: &ClaudeConnectorConfig,
socket: &Path,
service: Arc<Mutex<TransportService>>,
spend: model_connector::SpendSnapshot,
quota: Arc<crate::QuotaCell>,
) -> Result<(), ConfigError> {
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
@ -825,6 +831,7 @@ fn start_leases(
holders,
limits,
service,
spend,
quota,
tokens,
Arc::new(SystemdUnits::system()),
@ -847,15 +854,16 @@ pub fn serve_config(path: &Path) -> Result<(), ConfigError> {
serve_config_with(path, |_| ())
}
/// Maps every configured model to its configured provider entry id.
/// Maps every configured model to its configured provider entry id and optional price.
#[cfg(any(unix, test))]
fn routes_for(config: &ClaudeConnectorConfig) -> Result<ProviderRoutes, ConfigError> {
ProviderRoutes::new(
config
.models
.iter()
.map(|model| (model.id.clone(), model.provider.clone())),
)
ProviderRoutes::with_prices(config.models.iter().map(|model| {
(
model.id.clone(),
model.provider.clone(),
model.price.clone(),
)
}))
.map_err(|error| ConfigError::from(ServeError::Service(error)))
}
@ -885,15 +893,16 @@ fn serve_bound_with(
)?);
let listener = TcpListener::bind(listen).map_err(|_| ConfigError::Listen)?;
bound(listener.local_addr().map_err(|_| ConfigError::Listen)?);
let service = Arc::new(Mutex::new(
TransportService::open(
&config.replay_store,
routes,
admissions,
config.max_expiry_skew_ms,
)
.map_err(|error| ConfigError::from(ServeError::Service(error)))?,
));
let opened = TransportService::open(
&config.replay_store,
routes,
admissions,
config.max_expiry_skew_ms,
)
.map_err(|error| ConfigError::from(ServeError::Service(error)))?;
#[cfg(target_os = "linux")]
let spend = opened.spend_snapshot();
let service = Arc::new(Mutex::new(opened));
// The meter is running before the first lease can ask, so that lease can
// wait for its first read. When no ClaudeCodeCli entry is configured, no
// meter runs and the cell stays empty.
@ -907,7 +916,7 @@ fn serve_bound_with(
started(&quota);
#[cfg(target_os = "linux")]
if let Some(socket) = &config.lease_socket {
start_leases(&config, socket, service.clone(), quota.clone())?;
start_leases(&config, socket, service.clone(), spend, quota.clone())?;
}
serve_service(listener, config.serve_limits(), service, router)?;
Ok(())
@ -937,6 +946,7 @@ mod tests {
forced_tool_choice: ForcedToolChoice::Never,
output_schema: OutputSchemaSupport::Native,
strict_tools: false,
price: None,
}
}
@ -1937,6 +1947,27 @@ mod tests {
max_payload_bytes: MIN_PAYLOAD_BYTES,
max_output_tokens: 4_096,
};
let haiku_price = model_connector::PriceRow {
base: model_connector::TokenRates {
input: 1_000_000,
cache_read: 100_000,
cache_write: 1_250_000,
output: 5_000_000,
},
bands: vec![model_connector::PriceBand {
weekdays: vec![model_connector::Weekday::Mon],
utc_hours: vec![1, 2],
rates: model_connector::TokenRates {
input: 500_000,
cache_read: 50_000,
cache_write: 625_000,
output: 2_500_000,
},
}],
};
let mut priced_haiku = test_model("claude-haiku-5-5", "anthropic-primary");
priced_haiku.price = Some(haiku_price.clone());
let config = ClaudeConnectorConfig {
listen: "127.0.0.1:0".to_string(),
replay_store: PathBuf::from("/tmp/replay.cc"),
@ -1965,7 +1996,7 @@ mod tests {
},
],
models: vec![
test_model("claude-haiku-5-5", "anthropic-primary"),
priced_haiku,
test_model("claude-sonnet-5-5", "anthropic-primary"),
test_model("custom-model", "local-stub"),
],
@ -1983,14 +2014,299 @@ mod tests {
routes.provider_for("claude-haiku-5-5"),
Some("anthropic-primary")
);
assert_eq!(routes.price_for("claude-haiku-5-5"), Some(&haiku_price));
assert_eq!(
routes.provider_for("claude-sonnet-5-5"),
Some("anthropic-primary")
);
assert_eq!(routes.price_for("claude-sonnet-5-5"), None);
assert_eq!(routes.provider_for("custom-model"), Some("local-stub"));
assert_eq!(routes.price_for("custom-model"), None);
assert_eq!(routes.provider_for("unlisted-model"), None);
}
#[cfg(target_os = "linux")]
#[test]
fn priced_serve_records_receipt_cost_and_publishes_communal_spend_on_tcp_and_lease_socket() {
use std::io::{Read, Write};
use std::os::unix::fs::PermissionsExt;
use std::os::unix::net::UnixStream;
let _env_guard = CREDENTIALS_ENV_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let dir = std::env::temp_dir().join(format!(
"claude-connector-priced-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();
let script = "#!/bin/sh\ncat > /dev/null\n";
std::fs::write(at("claude"), script).unwrap();
std::fs::set_permissions(at("claude"), std::fs::Permissions::from_mode(0o755)).unwrap();
let secret_a = "a".repeat(48);
let secret_b = "b".repeat(48);
std::fs::write(at("caller-a.key"), &secret_a).unwrap();
std::fs::write(at("caller-b.key"), &secret_b).unwrap();
std::fs::write(at("credentials/cli-token"), "sk-ant-oat01-fake-token").unwrap();
std::fs::write(at("credentials/cli-handle-secret"), "s".repeat(48)).unwrap();
std::fs::write(at("credentials/msg-key"), "sk-msg-priced-key").unwrap();
let reply = |id: &str, input_tokens: u64, output_tokens: u64| {
serde_json::json!({
"id": id,
"content": [{"type": "text", "text": "ok"}],
"stop_reason": "end_turn",
"usage": {
"input_tokens": input_tokens,
"output_tokens": output_tokens
}
})
};
let (msg_url, seen_http) = spawn_http_mock(vec![
reply("m1", 1_000_000, 1_000_000),
reply("m2", 500_000, 500_000),
reply("m3", 100_000, 50_000),
]);
// Extreme rates ($500,000 per million tokens) prove pricing is visibility-only and never gates.
let extreme_price = model_connector::PriceRow {
base: model_connector::TokenRates {
input: 500_000_000_000,
cache_read: 0,
cache_write: 0,
output: 500_000_000_000,
},
bands: Vec::new(),
};
let mut priced_model = test_model("m-priced", "msg-entry");
priced_model.price = Some(extreme_price);
let unpriced_model = test_model("m-unpriced", "msg-entry");
let lease_sock = at("lease.sock");
let config = ClaudeConnectorConfig {
listen: "127.0.0.1:0".to_string(),
replay_store: at("replay.cc"),
max_frame_bytes: 2 << 20,
max_connections: 8,
socket_timeout_ms: 10_000,
max_expiry_skew_ms: 300_000,
providers: vec![
ProviderEntry {
id: "cli-main".to_string(),
credential: Some("cli-token".to_string()),
wire: ProviderWire::ClaudeCodeCli {
binary: at("claude"),
binary_sha256: sha2::Sha256::digest(script.as_bytes()).into(),
work_dir: at("work"),
config_dir: at("home"),
prompt_dir: at("prompts"),
handle_secret_credential: "cli-handle-secret".to_string(),
instance: "priced-inst".to_string(),
deadline_ms: 600_000,
max_line_bytes: 4 << 20,
max_total_bytes: 64 << 20,
stderr_tail_bytes: 8192,
meter_model: Some("m-priced".to_string()),
},
},
ProviderEntry {
id: "msg-entry".to_string(),
credential: Some("msg-key".to_string()),
wire: ProviderWire::AnthropicMessages {
base_url: msg_url,
deadline_ms: 60_000,
max_response_bytes: 16 << 20,
},
},
],
models: vec![priced_model, unpriced_model],
callers: vec![
CallerConfig {
caller_runtime_id: "caller-a".to_string(),
connection_key_file: at("caller-a.key"),
connection_key_epoch: 1,
allowed_models: vec!["m-priced".to_string()],
max_concurrent_requests: 4,
max_payload_bytes: 1 << 20,
max_output_tokens: 32_768,
},
CallerConfig {
caller_runtime_id: "caller-b".to_string(),
connection_key_file: at("caller-b.key"),
connection_key_epoch: 1,
allowed_models: vec!["m-unpriced".to_string()],
max_concurrent_requests: 4,
max_payload_bytes: 1 << 20,
max_output_tokens: 32_768,
},
],
lease_socket: Some(lease_sock.clone()),
lease_holders: vec![LeaseHolderConfig {
unix_user: "root".to_string(),
caller_id: "caller-a".to_string(),
provider: "cli-main".to_string(),
unit: "agent@alice.service".to_string(),
scope: LeaseScope::PerCaller,
}],
lease_max_ms: 3_600_000,
};
let cfg_path = at("connector.cc");
write_config(&cfg_path, &config).unwrap();
// SAFETY: guarded by CREDENTIALS_ENV_LOCK across all in-process tests touching CREDENTIALS_DIRECTORY.
unsafe { std::env::set_var("CREDENTIALS_DIRECTORY", at("credentials")) };
let (addr_tx, addr_rx) = std::sync::mpsc::channel();
let cfg_thread = cfg_path.clone();
std::thread::spawn(move || {
let _ = serve_bound_with(
&cfg_thread,
|addr| {
let _ = addr_tx.send(addr);
},
|_| (),
);
});
let endpoint = addr_rx.recv_timeout(Duration::from_secs(10)).unwrap();
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while !lease_sock.exists() {
assert!(
std::time::Instant::now() < deadline,
"lease socket never bound"
);
std::thread::sleep(Duration::from_millis(20));
}
let client_a = model_connector::ConnectorClient::new(
endpoint,
&secret_a,
2 << 20,
Some(Duration::from_secs(5)),
)
.unwrap();
let client_b = model_connector::ConnectorClient::new(
endpoint,
&secret_b,
2 << 20,
Some(Duration::from_secs(5)),
)
.unwrap();
let user_msg = vec![model_connector::InputItem::UserText {
text: "hi".to_string(),
}];
// Call 1: priced request records 1_000_000_000_000 micro-USD on receipt.
let r1 = invoke(
&client_a,
"caller-a",
"req-priced-1",
"m-priced",
user_msg.clone(),
);
let model_connector::TransportDisposition::Transported { receipt: rec1, .. } =
&r1.disposition
else {
panic!("expected transported r1: {r1:?}");
};
assert_eq!(rec1.cost_micro_usd, Some(1_000_000_000_000));
// Replay of req-priced-1 must not hit the backend or double-count monthly spend.
let r1_replay = invoke(
&client_a,
"caller-a",
"req-priced-1",
"m-priced",
user_msg.clone(),
);
assert_eq!(r1_replay, r1);
// Call 2: even at $1,000,000 accumulated spend, a second priced call proceeds without gating.
let r2 = invoke(
&client_a,
"caller-a",
"req-priced-2",
"m-priced",
user_msg.clone(),
);
let model_connector::TransportDisposition::Transported { receipt: rec2, .. } =
&r2.disposition
else {
panic!("expected transported r2: {r2:?}");
};
assert_eq!(rec2.cost_micro_usd, Some(500_000_000_000));
// Call 3: unpriced model call for caller-b leaves receipt cost None and increments calls_without_price.
let r3 = invoke(
&client_b,
"caller-b",
"req-unpriced-1",
"m-unpriced",
user_msg,
);
let model_connector::TransportDisposition::Transported { receipt: rec3, .. } =
&r3.disposition
else {
panic!("expected transported r3: {r3:?}");
};
assert_eq!(rec3.cost_micro_usd, None);
assert_eq!(seen_http.lock().unwrap().len(), 3);
// Both callers see identical communal monthly spend rows over TCP usage_readout.
let tcp_a = client_a.usage_readout("caller-a").unwrap();
let tcp_b = client_b.usage_readout("caller-b").unwrap();
assert_eq!(tcp_a.spend, tcp_b.spend);
assert_eq!(tcp_a.spend.len(), 2);
let row_a = tcp_a
.spend
.iter()
.find(|r| r.caller == "caller-a")
.expect("caller-a spend row");
assert_eq!(row_a.model, "m-priced");
assert_eq!(row_a.calls, 2);
assert_eq!(row_a.cost_micro_usd, 1_500_000_000_000);
assert_eq!(row_a.calls_without_price, 0);
let row_b = tcp_a
.spend
.iter()
.find(|r| r.caller == "caller-b")
.expect("caller-b spend row");
assert_eq!(row_b.model, "m-unpriced");
assert_eq!(row_b.calls, 1);
assert_eq!(row_b.cost_micro_usd, 0);
assert_eq!(row_b.calls_without_price, 1);
// Unix lease socket ClaudeUsageReadout matches TCP usage_readout.spend.
let mut lease_stream = UnixStream::connect(&lease_sock).unwrap();
lease_stream
.set_read_timeout(Some(Duration::from_secs(3)))
.unwrap();
lease_stream
.write_all(&crate::lease::encode_frame(
&crate::lease::LeaseMessage::ClaudeUsageReadoutRequest(
crate::lease::LeaseUsageReadoutRequest {},
),
))
.unwrap();
let mut raw = Vec::new();
lease_stream.read_to_end(&mut raw).unwrap();
let Some(crate::lease::LeaseMessage::ClaudeUsageReadout(lease_readout)) =
crate::lease::decode_frame(&raw)
else {
panic!("expected ClaudeUsageReadout on lease socket");
};
assert_eq!(lease_readout.spend, tcp_a.spend);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn readiness_of_in_checks_every_entry_and_names_failing_id_without_leaking_secret() {
const SECRET_A: &str = "canary-secret-alpha-91c2";

View file

@ -30,7 +30,8 @@ use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use model_connector::{
LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseScope, PlanQuota, TransportService, UsageReadout,
LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseScope, PlanQuota, SpendSnapshot,
TransportService, UsageReadout,
};
use serde::{Deserialize, Serialize};
@ -379,6 +380,7 @@ struct Lender {
holders: Vec<LeaseHolder>,
limits: LeaseLimits,
service: Arc<Mutex<TransportService>>,
spend: SpendSnapshot,
quota: Arc<QuotaCell>,
tokens: Arc<dyn TokenSource>,
units: Arc<dyn PeerUnits>,
@ -406,6 +408,7 @@ pub fn serve_leases(
holders: Vec<LeaseHolder>,
limits: LeaseLimits,
service: Arc<Mutex<TransportService>>,
spend: SpendSnapshot,
quota: Arc<QuotaCell>,
tokens: Arc<dyn TokenSource>,
units: Arc<dyn PeerUnits>,
@ -414,6 +417,7 @@ pub fn serve_leases(
holders,
limits,
service,
spend,
quota,
tokens,
units,
@ -461,7 +465,7 @@ impl Lender {
"too many usage readouts at once",
);
};
stream.write_all(&encode_frame(&readout(&self.quota, unix_ms())))
stream.write_all(&encode_frame(&readout(&self.quota, &self.spend, unix_ms())))
}
_ => Err(io::Error::from(io::ErrorKind::InvalidData)),
}
@ -646,10 +650,15 @@ impl Lender {
}
}
/// 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, Vec::new(), quota.snapshot()))
/// The plan's windows and committed monthly spend rows as they stand at `now_ms`.
/// Takes both by reference so it cannot note a request, wait for a first read,
/// or acquire the service mutex.
fn readout(quota: &QuotaCell, spend: &SpendSnapshot, now_ms: u64) -> LeaseMessage {
LeaseMessage::ClaudeUsageReadout(UsageReadout::new(
now_ms,
spend.snapshot(),
quota.snapshot(),
))
}
/// The longest a lease waits for the meter's first read of the week. A call
@ -690,28 +699,38 @@ mod tests {
dir: &std::path::Path,
max_connections: usize,
) -> (Arc<Mutex<TransportService>>, Lender) {
let service = Arc::new(Mutex::new(
TransportService::open(
&dir.join("replay.cc"),
model_connector::ProviderRoutes::new([(
"model".to_string(),
"claude-code".to_string(),
)])
.unwrap(),
[model_connector::CallerAdmission::new(
"lease-test-caller",
"lease-test-connection-key",
1,
["model".to_string()],
1,
65_536,
32_768,
)
.unwrap()],
300_000,
)
let price = model_connector::PriceRow {
base: model_connector::TokenRates {
input: 1_000_000,
cache_read: 0,
cache_write: 0,
output: 2_000_000,
},
bands: Vec::new(),
};
let opened = TransportService::open(
&dir.join("replay.cc"),
model_connector::ProviderRoutes::with_prices([(
"model".to_string(),
"claude-code".to_string(),
Some(price),
)])
.unwrap(),
));
[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 spend = opened.spend_snapshot();
let service = Arc::new(Mutex::new(opened));
let lender = Lender {
holders: Vec::new(),
limits: LeaseLimits {
@ -720,6 +739,7 @@ mod tests {
max_connections,
},
service: service.clone(),
spend,
quota: quota.clone(),
tokens: Arc::new(NoTokens),
units: Arc::new(NoUnits),
@ -733,13 +753,18 @@ mod tests {
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());
let (service, spend, quota) = (
lender.service.clone(),
lender.spend.clone(),
lender.quota.clone(),
);
thread::spawn(move || {
let _ = serve_leases(
&listener,
lender.holders,
lender.limits,
service,
spend,
quota,
lender.tokens,
lender.units,
@ -772,10 +797,60 @@ mod tests {
#[test]
fn a_socket_readout_never_asks_the_meter_waits_for_a_week_or_takes_the_service_lock() {
let dir = scratch("readout-arm");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let quota = Arc::new(QuotaCell::new());
quota.attach_meter();
let (service, lender) = lender(&quota, &dir, 8);
let socket = serve(lender, &dir);
// Commit one priced model call before taking the lock so the readout
// proves live SpendSnapshot rows are served without service.lock().
{
let now = unix_ms();
let req = model_connector::ProviderRequest::new(
"lease-readout-req-1",
"conv-lease",
"model",
"Be brief.",
100,
);
let hash = model_connector::provider_request_sha256(&req).unwrap();
let inv = model_connector::TransportInvocation::new(
"lease-test-caller",
now + 60_000,
hash,
req,
)
.unwrap();
let key =
model_connector::TransportKey::from_connection_secret("lease-test-connection-key")
.unwrap();
let env = model_connector::encrypt_invocation(&inv, &key).unwrap();
let mut locked = service.lock().unwrap();
let model_connector::TransportAdmission::Execute(claim) =
locked.begin(&env, now, None, 65_536).unwrap()
else {
panic!("expected execute claim");
};
let result = claim.call().transported(
Vec::new(),
model_connector::TransportOutcome::Succeeded {
text: "ok".to_string(),
tool_calls: Vec::new(),
stop_reason: model_connector::StopReason::EndTurn,
usage: Some(model_connector::Usage {
input_tokens: 1_000_000,
cache_read_tokens: 0,
cache_write_tokens: 0,
output_tokens: 500_000,
reasoning_tokens: 0,
}),
},
);
locked.complete(*claim, result, 65_536).unwrap();
}
// Held throughout: a readout that takes it hangs past the read timeout.
let guard = service.lock().unwrap();
for _ in 0..20 {
@ -786,6 +861,12 @@ mod tests {
};
assert!(started.elapsed() < Duration::from_secs(1));
assert!(answer.plan_quota.is_empty());
assert_eq!(answer.spend.len(), 1);
assert_eq!(answer.spend[0].caller, "lease-test-caller");
assert_eq!(answer.spend[0].model, "model");
assert_eq!(answer.spend[0].calls, 1);
assert_eq!(answer.spend[0].cost_micro_usd, 2_000_000);
assert_eq!(answer.spend[0].calls_without_price, 0);
}
drop(guard);
assert_eq!(quota.asks_so_far(), 0);
@ -860,21 +941,24 @@ mod tests {
fn a_readout_of_an_empty_metered_cell_does_not_wait() {
let quota = QuotaCell::new();
quota.attach_meter();
let spend = SpendSnapshot::default();
let started = Instant::now();
let LeaseMessage::ClaudeUsageReadout(answer) = readout(&quota, 77) else {
let LeaseMessage::ClaudeUsageReadout(answer) = readout(&quota, &spend, 77) else {
panic!("a readout answers with a readout");
};
assert!(started.elapsed() < Duration::from_secs(1));
assert!(answer.plan_quota.is_empty());
assert!(answer.spend.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 spend = SpendSnapshot::default();
let within = Duration::from_secs(15 * 60);
let now = unix_ms();
let _ = readout(&quota, now);
let _ = readout(&quota, &spend, now);
assert!(!quota.wanted_at(now, within));
let _asking = quota.asking();
assert!(quota.wanted_at(now, within));

View file

@ -24,7 +24,9 @@ use claude_connector::{
MIN_SECRET_BYTES, ModelRow, OutputSchemaSupport, ProviderEntry, ProviderWire, check_ready,
load_config, write_config,
};
use model_connector::{CallerConfig, LeaseScope, frame_bytes_for_payload};
use model_connector::{
CallerConfig, LeaseScope, PriceBand, PriceRow, TokenRates, Weekday, frame_bytes_for_payload,
};
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
@ -213,7 +215,7 @@ const PROVIDER: [&str; 18] = [
"--meter-model",
];
const MODEL: [&str; 11] = [
const MODEL: [&str; 15] = [
"--model",
"--provider",
"--upstream",
@ -225,6 +227,10 @@ const MODEL: [&str; 11] = [
"--forced-tool-choice",
"--output-schema",
"--strict-tools",
"--price-input",
"--price-cache-read",
"--price-cache-write",
"--price-output",
];
const LEASE_HOLDER: [&str; 4] = ["--caller-id", "--provider", "--unit", "--scope"];
@ -401,6 +407,32 @@ impl Flags {
}
fn model_row(&self, provider_id: &str) -> Result<ModelRow, Failure> {
const PRICE_RATES: [&str; 4] = [
"--price-input",
"--price-cache-read",
"--price-cache-write",
"--price-output",
];
let raw_bands = self.list("--price-band");
let has_price = PRICE_RATES
.iter()
.any(|flag| self.single.contains_key(flag))
|| !raw_bands.is_empty();
let price = if has_price {
let base = TokenRates {
input: self.number("--price-input")?,
cache_read: self.number("--price-cache-read")?,
cache_write: self.number("--price-cache-write")?,
output: self.number("--price-output")?,
};
let bands = raw_bands
.iter()
.map(|raw| parse_price_band(raw))
.collect::<Result<Vec<_>, _>>()?;
Some(PriceRow { base, bands })
} else {
None
};
Ok(ModelRow {
id: self.text("--model")?,
provider: provider_id.to_string(),
@ -415,6 +447,7 @@ impl Flags {
forced_tool_choice: self.forced_tool_choice()?,
output_schema: self.output_schema()?,
strict_tools: self.bool_flag("--strict-tools")?,
price,
})
}
@ -453,6 +486,71 @@ impl Flags {
}
}
fn parse_weekday(raw: &str) -> Option<Weekday> {
if raw.eq_ignore_ascii_case("mon") {
Some(Weekday::Mon)
} else if raw.eq_ignore_ascii_case("tue") {
Some(Weekday::Tue)
} else if raw.eq_ignore_ascii_case("wed") {
Some(Weekday::Wed)
} else if raw.eq_ignore_ascii_case("thu") {
Some(Weekday::Thu)
} else if raw.eq_ignore_ascii_case("fri") {
Some(Weekday::Fri)
} else if raw.eq_ignore_ascii_case("sat") {
Some(Weekday::Sat)
} else if raw.eq_ignore_ascii_case("sun") {
Some(Weekday::Sun)
} else {
None
}
}
fn parse_price_band(raw: &str) -> Result<PriceBand, Failure> {
let parts: Vec<&str> = raw.split(':').collect();
let [
days_raw,
hours_raw,
input_raw,
cache_read_raw,
cache_write_raw,
output_raw,
] = parts.as_slice()
else {
return Err(Failure::Malformed("--price-band"));
};
let weekdays = days_raw
.split(',')
.map(|day| parse_weekday(day).ok_or(Failure::Malformed("--price-band")))
.collect::<Result<Vec<_>, _>>()?;
let utc_hours = hours_raw
.split(',')
.map(|hour| {
hour.parse::<u8>()
.map_err(|_| Failure::Malformed("--price-band"))
})
.collect::<Result<Vec<_>, _>>()?;
let rates = TokenRates {
input: input_raw
.parse::<u64>()
.map_err(|_| Failure::Malformed("--price-band"))?,
cache_read: cache_read_raw
.parse::<u64>()
.map_err(|_| Failure::Malformed("--price-band"))?,
cache_write: cache_write_raw
.parse::<u64>()
.map_err(|_| Failure::Malformed("--price-band"))?,
output: output_raw
.parse::<u64>()
.map_err(|_| Failure::Malformed("--price-band"))?,
};
Ok(PriceBand {
weekdays,
utc_hours,
rates,
})
}
fn sha256(hex: &str) -> Option<[u8; 32]> {
if hex.len() != 64 || !hex.is_ascii() {
return None;
@ -529,7 +627,12 @@ fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
let flags = Flags::parse(
args,
&[&INIT, &PROVIDER, &MODEL, &CALLER],
&["--allowed-model", "--lease-user", "--strict-unsupported"],
&[
"--allowed-model",
"--lease-user",
"--strict-unsupported",
"--price-band",
],
)?;
let provider_id = flags.text("--provider")?;
let provider = flags.provider_entry(&provider_id)?;
@ -594,7 +697,7 @@ fn add_provider(path: &str, args: &[&str]) -> Result<(), Failure> {
/// Appends one model row to an existing document.
fn add_model(path: &str, args: &[&str]) -> Result<(), Failure> {
let flags = Flags::parse(args, &[&MODEL], &[])?;
let flags = Flags::parse(args, &[&MODEL], &["--price-band"])?;
let provider_id = flags.text("--provider")?;
let model = flags.model_row(&provider_id)?;
let mut config = load_config(path.as_ref())?;

View file

@ -29,6 +29,7 @@ fn default_row(model: &str) -> ModelRow {
forced_tool_choice: ForcedToolChoice::Always,
output_schema: OutputSchemaSupport::Native,
strict_tools: false,
price: None,
}
}

View file

@ -156,6 +156,7 @@ fn deepseek_row() -> ModelRow {
forced_tool_choice: ForcedToolChoice::WithoutThinking,
output_schema: OutputSchemaSupport::None,
strict_tools: true,
price: None,
}
}
@ -174,6 +175,7 @@ fn openai_row() -> ModelRow {
forced_tool_choice: ForcedToolChoice::Never,
output_schema: OutputSchemaSupport::Native,
strict_tools: true,
price: None,
}
}

View file

@ -262,6 +262,7 @@ mod tests {
forced_tool_choice: ForcedToolChoice::Never,
output_schema: OutputSchemaSupport::Native,
strict_tools: false,
price: None,
}
}

View file

@ -612,6 +612,7 @@ fn t_c0_oauth_still_cli_a_tools_request_is_refused_and_no_child_starts() {
forced_tool_choice: ForcedToolChoice::Never,
output_schema: OutputSchemaSupport::Native,
strict_tools: false,
price: None,
}],
)
.unwrap();

View file

@ -11,7 +11,10 @@ use claude_connector::{
OutputSchemaSupport, ProviderEntry, ProviderWire, load_config, write_config,
};
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
use model_connector::{CallerConfig, LeaseScope, MAX_IDENTITY_BYTES, ReasoningEffort};
use model_connector::{
CallerConfig, LeaseScope, MAX_IDENTITY_BYTES, PriceBand, PriceRow, ReasoningEffort, TokenRates,
Weekday,
};
const OPUS: &str = "claude-opus-5-1";
const HAIKU: &str = "claude-haiku-5-5";
@ -90,6 +93,7 @@ fn model_row(id: &str, provider: &str) -> ModelRow {
forced_tool_choice: ForcedToolChoice::Never,
output_schema: OutputSchemaSupport::Native,
strict_tools: false,
price: None,
}
}
@ -181,6 +185,64 @@ fn a_dollar_era_config_is_refused_at_load() {
assert!(matches!(load_config(&path), Err(ConfigError::Store)));
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "gamecult.model_connector.connector_config.v3")]
struct V3Config {
#[cultcache(key = 0)]
listen: String,
}
#[test]
fn v3_config_is_refused_at_load() {
let scratch = Scratch::new();
let v3_path = scratch.path("v3.cc");
{
let mut cache = CultCache::new();
cache.register_entry_type::<V3Config>().unwrap();
cache
.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&v3_path))
.unwrap();
cache
.put(
"runtime".to_string(),
&V3Config {
listen: "127.0.0.1:7443".to_string(),
},
)
.unwrap();
}
assert!(matches!(load_config(&v3_path), Err(ConfigError::Store)));
let v4_path = scratch.path("v4.cc");
let mut config = valid();
config.models[0].price = Some(PriceRow {
base: TokenRates {
input: 270_000,
cache_read: 27_000,
cache_write: 0,
output: 1_100_000,
},
bands: vec![PriceBand {
weekdays: vec![
Weekday::Mon,
Weekday::Tue,
Weekday::Wed,
Weekday::Thu,
Weekday::Fri,
],
utc_hours: vec![1, 2, 3, 6, 7, 8, 9],
rates: TokenRates {
input: 540_000,
cache_read: 54_000,
cache_write: 0,
output: 2_200_000,
},
}],
});
write_config(&v4_path, &config).unwrap();
assert_eq!(load_config(&v4_path).unwrap(), config);
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "gamecult.model_connector.claude_connector_config.v2")]
struct V2Config {
@ -210,6 +272,64 @@ fn v2_config_is_refused_at_load() {
assert!(matches!(load_config(&path), Err(ConfigError::Store)));
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "gamecult.model_connector.connector_config.v3")]
struct V3Config {
#[cultcache(key = 0)]
listen: String,
}
#[test]
fn v3_config_is_refused_at_load() {
let scratch = Scratch::new();
let v3_path = scratch.path("v3.cc");
{
let mut cache = CultCache::new();
cache.register_entry_type::<V3Config>().unwrap();
cache
.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&v3_path))
.unwrap();
cache
.put(
"runtime".to_string(),
&V3Config {
listen: "127.0.0.1:7443".to_string(),
},
)
.unwrap();
}
assert!(matches!(load_config(&v3_path), Err(ConfigError::Store)));
let v4_path = scratch.path("v4.cc");
let mut config = valid();
config.models[0].price = Some(PriceRow {
base: TokenRates {
input: 270_000,
cache_read: 27_000,
cache_write: 0,
output: 1_100_000,
},
bands: vec![PriceBand {
weekdays: vec![
Weekday::Mon,
Weekday::Tue,
Weekday::Wed,
Weekday::Thu,
Weekday::Fri,
],
utc_hours: vec![1, 2, 3, 6, 7, 8, 9],
rates: TokenRates {
input: 540_000,
cache_read: 54_000,
cache_write: 0,
output: 2_200_000,
},
}],
});
write_config(&v4_path, &config).unwrap();
assert_eq!(load_config(&v4_path).unwrap(), config);
}
#[test]
fn allowed_models_must_be_subset_of_configured_models() {
for good in [
@ -238,7 +358,7 @@ fn allowed_models_must_be_subset_of_configured_models() {
}
#[test]
fn v3_validation_refuses_invalid_providers_models_and_urls() {
fn v4_validation_refuses_invalid_providers_models_and_urls() {
// Valid HTTPS and loopback HTTP URLs (with and without credential).
for (url, cred) in [
("https://api.example.com", Some("k1")),
@ -518,6 +638,90 @@ fn v3_validation_refuses_invalid_providers_models_and_urls() {
assert_eq!(refused(&untrimmed_effort), "efforts");
}
// Valid PriceRow with base + overlapping bands validates (first-match-wins).
let mut priced = valid();
priced.models[0].price = Some(PriceRow {
base: TokenRates {
input: 270_000,
cache_read: 27_000,
cache_write: 0,
output: 1_100_000,
},
bands: vec![
PriceBand {
weekdays: vec![Weekday::Mon, Weekday::Tue],
utc_hours: vec![1, 2],
rates: TokenRates {
input: 540_000,
cache_read: 54_000,
cache_write: 0,
output: 2_200_000,
},
},
PriceBand {
weekdays: vec![Weekday::Mon],
utc_hours: vec![1, 3],
rates: TokenRates {
input: 999_999,
cache_read: 99_999,
cache_write: 0,
output: 4_444_444,
},
},
],
});
assert!(priced.validate().is_ok());
let rate = TokenRates {
input: 123_456,
cache_read: 0,
cache_write: 0,
output: 654_321,
};
for bad_band in [
PriceBand {
weekdays: Vec::new(),
utc_hours: vec![0],
rates: rate.clone(),
},
PriceBand {
weekdays: vec![Weekday::Mon, Weekday::Mon],
utc_hours: vec![0],
rates: rate.clone(),
},
PriceBand {
weekdays: vec![Weekday::Mon],
utc_hours: Vec::new(),
rates: rate.clone(),
},
PriceBand {
weekdays: vec![Weekday::Mon],
utc_hours: vec![5, 5],
rates: rate.clone(),
},
PriceBand {
weekdays: vec![Weekday::Mon],
utc_hours: vec![24],
rates: rate.clone(),
},
PriceBand {
weekdays: vec![Weekday::Sat],
utc_hours: vec![255],
rates: rate.clone(),
},
] {
let mut bad = valid();
bad.models[0].price = Some(PriceRow {
base: rate.clone(),
bands: vec![bad_band],
});
let err = bad.validate().unwrap_err();
let rendered = format!("{err} {err:?}");
assert!(matches!(err, ConfigError::Invalid("price")), "{rendered}");
assert!(!rendered.contains("123456"), "{rendered}");
assert!(!rendered.contains("654321"), "{rendered}");
}
let mut with_meter_model = valid();
with_meter_model.providers.push(http_provider(
"remote",
@ -1111,6 +1315,404 @@ fn config_add_provider_and_add_model_append_and_validate() {
}
}
#[test]
fn config_init_and_add_model_price_flags() {
let scratch = Scratch::new();
let config_path = scratch.path("connector.cc");
let p = config_path.to_str().unwrap();
// 1. `config init` persists --price-* and repeated --price-band (covering all 7 weekdays, mixed case).
let made = init(
&scratch,
&http_init_flags(
&scratch,
&[
"--price-input",
"100000",
"--price-cache-read",
"10000",
"--price-cache-write",
"125000",
"--price-output",
"500000",
"--price-band",
"MON,tue,Wed:0,1:200000:20000:250000:1000000",
"--price-band",
"Thu,FRI,sat,SuN:22,23:150000:15000:0:750000",
],
),
);
assert!(made.status.success(), "{made:?}");
let loaded = load_config(&config_path).unwrap();
assert_eq!(
loaded.models[0].price,
Some(PriceRow {
base: TokenRates {
input: 100_000,
cache_read: 10_000,
cache_write: 125_000,
output: 500_000,
},
bands: vec![
PriceBand {
weekdays: vec![Weekday::Mon, Weekday::Tue, Weekday::Wed],
utc_hours: vec![0, 1],
rates: TokenRates {
input: 200_000,
cache_read: 20_000,
cache_write: 250_000,
output: 1_000_000,
},
},
PriceBand {
weekdays: vec![Weekday::Thu, Weekday::Fri, Weekday::Sat, Weekday::Sun],
utc_hours: vec![22, 23],
rates: TokenRates {
input: 150_000,
cache_read: 15_000,
cache_write: 0,
output: 750_000,
},
},
],
})
);
// 2. `config add-model` persists DeepSeek off-peak base + peak band.
let added = run(&[
"config",
"add-model",
p,
"--model",
"deepseek-v3",
"--provider",
"anthropic-a",
"--upstream",
"deepseek-chat",
"--forced-tool-choice",
"without-thinking",
"--output-schema",
"none",
"--strict-tools",
"true",
"--price-input",
"270000",
"--price-cache-read",
"27000",
"--price-cache-write",
"0",
"--price-output",
"1100000",
"--price-band",
"mon,tue,wed,thu,fri:1,2,3,6,7,8,9:540000:54000:0:2200000",
]);
assert!(added.status.success(), "{added:?}");
let loaded = load_config(&config_path).unwrap();
assert_eq!(loaded.models.len(), 2);
assert_eq!(
loaded.models[1].price,
Some(PriceRow {
base: TokenRates {
input: 270_000,
cache_read: 27_000,
cache_write: 0,
output: 1_100_000,
},
bands: vec![PriceBand {
weekdays: vec![
Weekday::Mon,
Weekday::Tue,
Weekday::Wed,
Weekday::Thu,
Weekday::Fri,
],
utc_hours: vec![1, 2, 3, 6, 7, 8, 9],
rates: TokenRates {
input: 540_000,
cache_read: 54_000,
cache_write: 0,
output: 2_200_000,
},
}],
})
);
// 3. Partial --price-*, malformed --price-band, and invalid band bounds are refused
// without modifying the existing document and without echoing input values.
let before = std::fs::read(&config_path).unwrap();
let base_model_args = [
"config",
"add-model",
p,
"--model",
"bad-price-model",
"--provider",
"anthropic-a",
"--upstream",
"u",
"--forced-tool-choice",
"never",
"--output-schema",
"native",
"--strict-tools",
"false",
];
let bad_cases: &[(&[&str], &str)] = &[
// Partial base rates (each of the 4 missing or --price-band alone).
(
&[
"--price-cache-read",
"11",
"--price-cache-write",
"22",
"--price-output",
"33",
],
"11",
),
(
&[
"--price-input",
"11",
"--price-cache-write",
"22",
"--price-output",
"33",
],
"22",
),
(
&[
"--price-input",
"11",
"--price-cache-read",
"22",
"--price-output",
"33",
],
"33",
),
(
&[
"--price-input",
"11",
"--price-cache-read",
"22",
"--price-cache-write",
"33",
],
"33",
),
(&["--price-band", "mon:1:100:200:300:400"], "100"),
// Non-numeric base rate.
(
&[
"--price-input",
"canary-bad-rate",
"--price-cache-read",
"0",
"--price-cache-write",
"0",
"--price-output",
"10",
],
"canary-bad-rate",
),
// Malformed --price-band (wrong field count, bad day, bad hour, bad rate fields).
(
&[
"--price-input",
"1",
"--price-cache-read",
"1",
"--price-cache-write",
"1",
"--price-output",
"1",
"--price-band",
"canary-only-five:1:2:3:4",
],
"canary-only-five",
),
(
&[
"--price-input",
"1",
"--price-cache-read",
"1",
"--price-cache-write",
"1",
"--price-output",
"1",
"--price-band",
"monday:1:2:3:4:5",
],
"monday",
),
(
&[
"--price-input",
"1",
"--price-cache-read",
"1",
"--price-cache-write",
"1",
"--price-output",
"1",
"--price-band",
":1:2:3:4:5",
],
"2:3:4:5",
),
(
&[
"--price-input",
"1",
"--price-cache-read",
"1",
"--price-cache-write",
"1",
"--price-output",
"1",
"--price-band",
"mon:canary-hour:2:3:4:5",
],
"canary-hour",
),
(
&[
"--price-input",
"1",
"--price-cache-read",
"1",
"--price-cache-write",
"1",
"--price-output",
"1",
"--price-band",
"mon:1:canary-in:3:4:5",
],
"canary-in",
),
(
&[
"--price-input",
"1",
"--price-cache-read",
"1",
"--price-cache-write",
"1",
"--price-output",
"1",
"--price-band",
"mon:1:2:canary-cr:4:5",
],
"canary-cr",
),
(
&[
"--price-input",
"1",
"--price-cache-read",
"1",
"--price-cache-write",
"1",
"--price-output",
"1",
"--price-band",
"mon:1:2:3:canary-cw:5",
],
"canary-cw",
),
(
&[
"--price-input",
"1",
"--price-cache-read",
"1",
"--price-cache-write",
"1",
"--price-output",
"1",
"--price-band",
"mon:1:2:3:4:canary-out",
],
"canary-out",
),
// Invalid band bounds (duplicate day, hour >= 24, duplicate hour) caught by PriceRow::validate.
(
&[
"--price-input",
"1",
"--price-cache-read",
"1",
"--price-cache-write",
"1",
"--price-output",
"1",
"--price-band",
"mon,mon:1:987654:3:4:5",
],
"987654",
),
(
&[
"--price-input",
"1",
"--price-cache-read",
"1",
"--price-cache-write",
"1",
"--price-output",
"1",
"--price-band",
"mon:24:987654:3:4:5",
],
"987654",
),
(
&[
"--price-input",
"1",
"--price-cache-read",
"1",
"--price-cache-write",
"1",
"--price-output",
"1",
"--price-band",
"mon:5,5:987654:3:4:5",
],
"987654",
),
];
for &(extra, secret_canary) in bad_cases {
let mut args = base_model_args.to_vec();
args.extend_from_slice(extra);
let out = run(&args);
assert!(!out.status.success(), "{extra:?} unexpectedly succeeded");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains(secret_canary),
"error echoed input {secret_canary:?}: {stderr}"
);
assert_eq!(
std::fs::read(&config_path).unwrap(),
before,
"{extra:?} modified config"
);
}
// Also verify init refuses partial price flags without writing config.
let init_scratch = Scratch::new();
let init_bad = init(
&init_scratch,
&http_init_flags(&init_scratch, &["--price-input", "12345"]),
);
assert!(!init_bad.status.success());
assert!(!init_scratch.path("connector.cc").exists());
}
#[test]
fn readiness_names_failing_entry_id_and_never_leaks_secret() {
const SECRET_1: &str = "canary-secret-value-one-73a9";
@ -1170,10 +1772,9 @@ fn readiness_names_failing_entry_id_and_never_leaks_secret() {
#[test]
fn the_dollar_flags_are_not_flags() {
let dollar_flags: [&[&str]; 4] = [
let dollar_flags: [&[&str]; 3] = [
&["--spend-ceiling-micro-usd", "50000000"],
&["--spend-window-ms", "3600000"],
&["--price", "claude-haiku-5-5:1:1:1:1:1"],
&["--lease-reservation-micro-usd", "5000000"],
];
for extra in dollar_flags {

View file

@ -19,7 +19,9 @@ use claude_connector::{
decode_frame, encode_frame, serve_leases,
};
use model_connector::{
CallerAdmission, LeaseScope, PlanQuota, ProviderRoutes, TransportService, UsageReadout,
CallerAdmission, LeaseScope, PlanQuota, PriceRow, ProviderRequest, ProviderRoutes, StopReason,
TokenRates, TransportAdmission, TransportInvocation, TransportKey, TransportOutcome,
TransportService, Usage, UsageReadout, encrypt_invocation, provider_request_sha256,
};
use zeroize::Zeroizing;
@ -244,6 +246,25 @@ fn setup() -> Setup {
/// A listener serving `uid` as the caller `eureka`. Peers start in invocation
/// 1 of the configured unit.
fn start(setup: Setup) -> Harness {
start_with(
setup,
ProviderRoutes::new([(MODEL.to_string(), "claude-code".to_string())]).unwrap(),
vec![
CallerAdmission::new(
CALLER,
"lease-test-connection-key",
1,
[MODEL.to_string()],
1,
65_536,
32_768,
)
.unwrap(),
],
)
}
fn start_with(setup: Setup, routes: ProviderRoutes, admissions: Vec<CallerAdmission>) -> Harness {
let units = Arc::new(FakeUnits {
peer: Mutex::new(None),
asked_about: Mutex::new(Vec::new()),
@ -255,24 +276,10 @@ fn start(setup: Setup) -> Harness {
));
std::fs::create_dir_all(&dir).unwrap();
let socket = dir.join("lease.sock");
let service = Arc::new(Mutex::new(
TransportService::open(
&dir.join("replay.cc"),
ProviderRoutes::new([(MODEL.to_string(), "claude-code".to_string())]).unwrap(),
[CallerAdmission::new(
CALLER,
"lease-test-connection-key",
1,
[MODEL.to_string()],
1,
65_536,
32_768,
)
.unwrap()],
300_000,
)
.unwrap(),
));
let opened =
TransportService::open(&dir.join("replay.cc"), routes, admissions, 300_000).unwrap();
let spend = opened.spend_snapshot();
let service = Arc::new(Mutex::new(opened));
let tokens = Arc::new(FakeTokens {
token: setup.token,
reads: AtomicUsize::new(0),
@ -282,6 +289,7 @@ fn start(setup: Setup) -> Harness {
let listener = UnixListener::bind(&socket).unwrap();
let serving = (
service.clone(),
spend,
quota.clone(),
tokens.clone(),
units.clone(),
@ -306,6 +314,7 @@ fn start(setup: Setup) -> Harness {
serving.1,
serving.2,
serving.3,
serving.4,
);
});
let harness = Harness {
@ -682,6 +691,122 @@ fn usage_of(answer: &Answer) -> UsageReadout {
}
}
#[test]
fn a_readout_returns_live_communal_spend_rows_across_callers() {
let price = PriceRow {
base: TokenRates {
input: 3_000_000,
cache_read: 300_000,
cache_write: 3_750_000,
output: 15_000_000,
},
bands: Vec::new(),
};
let routes = ProviderRoutes::with_prices([
(MODEL.to_string(), "claude-code".to_string(), Some(price)),
(
"unpriced-model".to_string(),
"claude-code".to_string(),
None,
),
])
.unwrap();
let admissions = vec![
CallerAdmission::new(
CALLER,
"lease-test-connection-key",
1,
[MODEL.to_string()],
1,
65_536,
32_768,
)
.unwrap(),
CallerAdmission::new(
"peer-caller",
"peer-test-connection-key",
1,
["unpriced-model".to_string()],
1,
65_536,
32_768,
)
.unwrap(),
];
let harness = start_with(setup(), routes, admissions);
let commit_call = |caller: &str, secret: &str, req_id: &str, model: &str| {
let now = now_ms();
let req = ProviderRequest::new(req_id, "conv-communal", model, "Be brief.", 100);
let hash = provider_request_sha256(&req).unwrap();
let inv = TransportInvocation::new(caller, now + 60_000, hash, req).unwrap();
let key = TransportKey::from_connection_secret(secret).unwrap();
let env = encrypt_invocation(&inv, &key).unwrap();
let mut service = harness._service.lock().unwrap();
let TransportAdmission::Execute(claim) = service.begin(&env, now, None, 65_536).unwrap()
else {
panic!("expected execute claim for {req_id}");
};
let result = claim.call().transported(
Vec::new(),
TransportOutcome::Succeeded {
text: "ok".to_string(),
tool_calls: Vec::new(),
stop_reason: StopReason::EndTurn,
usage: Some(Usage {
input_tokens: 1_000_000,
cache_read_tokens: 0,
cache_write_tokens: 0,
output_tokens: 200_000,
reasoning_tokens: 0,
}),
},
);
service.complete(*claim, result, 65_536).unwrap();
};
commit_call(CALLER, "lease-test-connection-key", "req-communal-1", MODEL);
commit_call(
"peer-caller",
"peer-test-connection-key",
"req-communal-2",
"unpriced-model",
);
let reset = now_ms() + 3_600_000;
harness
.quota
.observe([window("five_hour", 310, "allowed", reset)]);
let answer = read_usage(&harness);
assert!(answer.fds.is_empty());
let readout = usage_of(&answer);
assert_eq!(readout.plan_quota, harness.quota.snapshot().windows);
assert_eq!(readout.spend.len(), 2);
let eureka_row = readout
.spend
.iter()
.find(|row| row.caller == CALLER)
.expect("eureka row");
assert_eq!(eureka_row.model, MODEL);
assert_eq!(eureka_row.calls, 1);
// 1M * 3_000_000 / 1M + 200k * 15_000_000 / 1M = 3_000_000 + 3_000_000 = 6_000_000
assert_eq!(eureka_row.cost_micro_usd, 6_000_000);
assert_eq!(eureka_row.calls_without_price, 0);
let peer_row = readout
.spend
.iter()
.find(|row| row.caller == "peer-caller")
.expect("peer row");
assert_eq!(peer_row.model, "unpriced-model");
assert_eq!(peer_row.calls, 1);
assert_eq!(peer_row.cost_micro_usd, 0);
assert_eq!(peer_row.calls_without_price, 1);
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
}
#[test]
fn a_readout_answers_the_cells_windows_and_lends_nothing() {
let harness = start(setup());