connector-usage-only: delete the dollar authorities (WIP, does not yet build)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-31 04:43:18 +01:00
commit 06a47bb13f
39 changed files with 1243 additions and 6010 deletions

View file

@ -5,8 +5,7 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use model_connector::{
CallerAdmission, ModelPrice, PriceTable, Rates, ReasoningEffort, SpendCeiling, SpendWindowMs,
StopReason, ToolDefinition, TransportAdmission, TransportDisposition, TransportInvocation,
CallerAdmission, PlanQuotaSnapshot, ReasoningEffort, StopReason, ToolDefinition, TransportAdmission, TransportDisposition, TransportInvocation,
TransportKey, TransportReceipt, TransportService, decrypt_result, encrypt_invocation,
};
@ -460,25 +459,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,13 +476,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)
TransportService::open(&dir.join("replay.cc"), PROVIDER, callers, 5_000)
.unwrap();
Self { dir, service }
}
@ -521,9 +499,12 @@ impl Door {
) -> (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();
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"),
}
@ -1458,11 +1439,6 @@ fn usage_sums_model_usage_across_models() {
};
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
);
// 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 +1575,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 +1582,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 +1681,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"
@ -1743,8 +1704,6 @@ fn backend_end_to_end_through_the_service() {
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);
assert_eq!(events.len(), 2);
let items = opened.transcript_items();
assert_eq!(items[0], assistant("hello back"));
@ -1757,13 +1716,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 +1740,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 +1787,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,7 +1798,6 @@ 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}");
}
}
@ -1865,7 +1812,6 @@ fn door_set_is_exactly_401_403_429() {
// 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 +1850,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 +1923,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 +1939,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());
@ -2695,7 +2633,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)
@ -2723,10 +2660,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}");
}
}
}

View file

@ -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,7 +11,7 @@ use std::time::Duration;
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
use model_connector::{
CallerAdmission, CallerConfig, LeaseTurn, MIN_PAYLOAD_BYTES, ModelPrice, ProviderBackend,
CallerAdmission, CallerConfig, LeaseTurn, MIN_PAYLOAD_BYTES, ProviderBackend,
ServeError, ServeLimits, ServiceError, TransportService, load_admissions, serve_service,
};
use serde::{Deserialize, Serialize};
@ -31,8 +31,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 +41,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 +85,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)]
@ -143,7 +138,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 +222,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"));
}
@ -240,19 +232,11 @@ impl ClaudeConnectorConfig {
for model in &caller.allowed_models {
if !has_model_id_form(model)
|| !seen.insert(model.as_str())
|| !self.prices.contains_key(model)
{
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)
}
@ -278,11 +262,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())
})
@ -336,8 +316,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,25 +344,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 {
@ -509,7 +469,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 +490,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 +519,7 @@ fn start_leases(
callers,
limits,
service,
quota,
tokens,
Arc::new(SystemdUnits::system()),
);
@ -589,7 +550,6 @@ pub fn serve_config(path: &Path) -> Result<(), ConfigError> {
TransportService::open(
&config.replay_store,
backend.provider(),
config.prices.clone(),
admissions,
config.max_expiry_skew_ms,
)
@ -597,7 +557,7 @@ pub fn serve_config(path: &Path) -> Result<(), ConfigError> {
));
#[cfg(target_os = "linux")]
if let Some(socket) = &config.lease_socket {
start_leases(&config, socket, service.clone())?;
start_leases(&config, socket, service.clone(), backend.quota())?;
}
serve_service(listener, config.serve_limits(), service, backend)?;
Ok(())
@ -643,10 +603,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",

View file

@ -1,15 +1,14 @@
//! 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 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 +27,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,
};
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,12 +48,9 @@ pub enum LeaseMessage {
/// holds the token, its write end closed.
ClaudeLeaseGrant(LeaseGranted),
ClaudeLeaseRefusal(LeaseRefused),
ClaudeLeaseSettle(LeaseSettle),
ClaudeLeaseSettled(LeaseSettled),
}
/// 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,
@ -64,16 +59,17 @@ pub struct LeaseRequest {
#[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 +78,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 +162,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 +173,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,6 +380,7 @@ struct Lender {
callers: Vec<LeaseCaller>,
limits: LeaseLimits,
service: Arc<Mutex<TransportService>>,
quota: Arc<QuotaCell>,
tokens: Arc<dyn TokenSource>,
units: Arc<dyn PeerUnits>,
}
@ -415,6 +396,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,6 +404,7 @@ pub fn serve_leases(
callers,
limits,
service,
quota,
tokens,
units,
});
@ -484,9 +467,9 @@ 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.
let plan = self.quota.snapshot();
let admission = self
.service
.lock()
@ -495,120 +478,134 @@ 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"))
}
}
/// 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 +619,12 @@ 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> {
/// 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 +643,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 +658,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,10 +670,10 @@ 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 {
if writer.write_all(&[byte]).is_err() {

View file

@ -28,7 +28,7 @@ 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, MAX_LEASE_FRAME_BYTES, PeerCredentials, PeerUnit,
PeerUnits, decode_frame, encode_frame, peer_credentials, serve_leases, user_uid,
};
#[cfg(unix)]

View file

@ -18,7 +18,7 @@ use claude_connector::{
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();
@ -72,7 +72,6 @@ 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(())
}
@ -85,17 +84,15 @@ 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] = [
const INIT: [&str; 21] = [
"--listen",
"--replay-store",
"--claude-binary",
@ -117,15 +114,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(
@ -213,8 +204,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 +219,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 +284,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 +296,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,7 +320,6 @@ 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)?,
@ -412,7 +365,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(())

View file

@ -1,7 +1,7 @@
//! 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.
//! here and published as the usage readout and lent with each lease.
use std::collections::BTreeMap;
use std::sync::Mutex;

View file

@ -14,7 +14,7 @@ use crate::quota::QuotaCell;
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,
@ -356,7 +356,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()));