feat(model-connector): v5 wire contract, PriceRow math, and atomic monthly spend totals
Delete v4 golden suite/fixtures, bump contract schemas to v5 and usage_readout to v2, add pure-integer PriceRow cost math, persist MonthlySpendRecord atomically with ReplayRecord via put_prepared_batch, and keep all dollar/cost figures non-gating.
This commit is contained in:
parent
4dc182facf
commit
38699f3d3b
25 changed files with 1463 additions and 147 deletions
|
|
@ -649,7 +649,7 @@ 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, quota.snapshot()))
|
||||
LeaseMessage::ClaudeUsageReadout(UsageReadout::new(now_ms, Vec::new(), quota.snapshot()))
|
||||
}
|
||||
|
||||
/// The longest a lease waits for the meter's first read of the week. A call
|
||||
|
|
|
|||
|
|
@ -12,8 +12,9 @@ big-endian length, then the named-MessagePack map `{kind, value}`).
|
|||
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.
|
||||
- `usage_readout.bin`: `claude_usage_readout`, the kit's `UsageReadout` v2 (`schema_id`,
|
||||
`at_unix_ms`, `spend` rows of `CallerModelSpend`, and `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
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ use claude_connector::{
|
|||
LeaseGranted, LeaseMessage, LeaseRefusalKind, LeaseRefused, LeaseRequest,
|
||||
LeaseUsageReadoutRequest, decode_frame, encode_frame,
|
||||
};
|
||||
use model_connector::{PlanQuota, PlanQuotaSnapshot, UsageReadout};
|
||||
use model_connector::{CallerModelSpend, PlanQuota, PlanQuotaSnapshot, UsageReadout};
|
||||
|
||||
const REGENERATE: &str = "LEASE_V2_REGENERATE";
|
||||
|
||||
|
|
@ -110,6 +110,14 @@ fn the_usage_readout_frames_are_pinned() {
|
|||
let request = LeaseMessage::ClaudeUsageReadoutRequest(LeaseUsageReadoutRequest {});
|
||||
let answer = LeaseMessage::ClaudeUsageReadout(UsageReadout::new(
|
||||
1_793_300_100_000,
|
||||
vec![CallerModelSpend {
|
||||
caller: "mind-self".to_string(),
|
||||
model: "deepseek/deepseek-flash".to_string(),
|
||||
month: "2026-12".to_string(),
|
||||
calls: 42,
|
||||
cost_micro_usd: 12_345,
|
||||
calls_without_price: 0,
|
||||
}],
|
||||
PlanQuotaSnapshot {
|
||||
windows: vec![
|
||||
window("five_hour", 420, "allowed", 1_793_307_000_000),
|
||||
|
|
|
|||
|
|
@ -62,8 +62,10 @@ impl ConnectorClient {
|
|||
decrypt_result(&envelope, &self.security, invocation).map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Reads the plan's usage windows as `caller_runtime_id`,
|
||||
/// which must be a caller whose connection key this client holds.
|
||||
/// Reads the connector's usage readout (`UsageReadout` v2: monthly
|
||||
/// caller/model spend rows and the subscription plan's usage windows) as
|
||||
/// `caller_runtime_id`, which must be a caller whose connection key this
|
||||
/// client holds.
|
||||
pub fn usage_readout(
|
||||
&self,
|
||||
caller_runtime_id: &str,
|
||||
|
|
@ -279,7 +281,7 @@ mod fixture_tests {
|
|||
panic!("the client sent something other than a readout request");
|
||||
};
|
||||
let request_id = answer_request.unwrap_or(&asked.request_id);
|
||||
let readout = UsageReadout::new(1, PlanQuotaSnapshot::default());
|
||||
let readout = UsageReadout::new(1, Vec::new(), PlanQuotaSnapshot::default());
|
||||
let sealed =
|
||||
encrypt_usage_readout(answer_caller, request_id, &readout, &key).unwrap();
|
||||
write_transport_frame(
|
||||
|
|
|
|||
|
|
@ -9,11 +9,11 @@ use zeroize::Zeroize;
|
|||
|
||||
use crate::envelope::{ServiceError, binary_schema};
|
||||
|
||||
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";
|
||||
pub const PROVIDER_REQUEST_SCHEMA_ID: &str = "gamecult.model.provider_request.v5";
|
||||
pub const INVOCATION_SCHEMA_ID: &str = "gamecult.model.transport_invocation.v5";
|
||||
pub const RESULT_SCHEMA_ID: &str = "gamecult.model.transport_result.v5";
|
||||
pub const RECEIPT_SCHEMA_ID: &str = "gamecult.model.transport_receipt.v5";
|
||||
pub const ENVELOPE_SCHEMA_ID: &str = "gamecult.model.transport_envelope.v5";
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct TransportKey(pub(crate) [u8; 32]);
|
||||
|
|
@ -476,6 +476,7 @@ pub struct TransportReceipt {
|
|||
/// How many foreign `ReasoningState` items the service removed from the
|
||||
/// request before the backend saw it.
|
||||
pub foreign_reasoning_dropped: u32,
|
||||
pub cost_micro_usd: Option<u64>,
|
||||
pub outcome: TransportOutcome,
|
||||
}
|
||||
|
||||
|
|
@ -497,6 +498,9 @@ impl TransportReceipt {
|
|||
return Err(ContractError::NativeDigest);
|
||||
}
|
||||
require_id(&self.provider, "receipt.provider")?;
|
||||
if self.outcome.usage().is_none() && self.cost_micro_usd.is_some() {
|
||||
return Err(ContractError::Invalid("receipt.cost_micro_usd"));
|
||||
}
|
||||
match &self.outcome {
|
||||
TransportOutcome::Completed {
|
||||
provider_response_id: Some(value),
|
||||
|
|
@ -532,6 +536,15 @@ pub enum TransportOutcome {
|
|||
},
|
||||
}
|
||||
|
||||
impl TransportOutcome {
|
||||
pub(crate) fn usage(&self) -> Option<&Usage> {
|
||||
match self {
|
||||
TransportOutcome::Completed { usage, .. } => Some(usage),
|
||||
TransportOutcome::Failed { usage, .. } => usage.as_ref(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub enum Refusal {
|
||||
Expired,
|
||||
|
|
@ -554,7 +567,7 @@ pub enum Refusal {
|
|||
ProviderRejected,
|
||||
}
|
||||
|
||||
/// The one wire codec of every v4 document: named MessagePack (struct fields
|
||||
/// The one wire codec of every v5 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)
|
||||
|
|
@ -837,7 +850,7 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn v4_documents_carry_their_v4_ids() {
|
||||
fn v5_documents_carry_their_v5_ids() {
|
||||
assert_eq!(
|
||||
[
|
||||
PROVIDER_REQUEST_SCHEMA_ID,
|
||||
|
|
@ -847,11 +860,11 @@ mod tests {
|
|||
ENVELOPE_SCHEMA_ID
|
||||
],
|
||||
[
|
||||
"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"
|
||||
"gamecult.model.provider_request.v5",
|
||||
"gamecult.model.transport_invocation.v5",
|
||||
"gamecult.model.transport_result.v5",
|
||||
"gamecult.model.transport_receipt.v5",
|
||||
"gamecult.model.transport_envelope.v5"
|
||||
]
|
||||
);
|
||||
let invocation = invocation();
|
||||
|
|
@ -865,24 +878,27 @@ mod tests {
|
|||
assert_eq!(sent.schema_id, RECEIPT_SCHEMA_ID);
|
||||
|
||||
let v2 = |name: &str| format!("{}{name}.v2", concat!("gamecult.", "codex."));
|
||||
let mut request = invocation.request.clone();
|
||||
request.schema_id = v2("provider_request");
|
||||
assert_eq!(request.validate(), Err(ContractError::Schema));
|
||||
let mut stale = invocation.clone();
|
||||
stale.schema_id = v2("transport_invocation");
|
||||
assert_eq!(stale.validate(1_000, 2_000), Err(ContractError::Schema));
|
||||
let mut stale = result.clone();
|
||||
stale.schema_id = v2("transport_result");
|
||||
assert_eq!(
|
||||
stale.validate_against(&invocation),
|
||||
Err(ContractError::Schema)
|
||||
);
|
||||
let mut stale = (**sent).clone();
|
||||
stale.schema_id = v2("transport_receipt");
|
||||
assert_eq!(
|
||||
stale.validate_against(&invocation),
|
||||
Err(ContractError::Schema)
|
||||
);
|
||||
let v4 = |name: &str| format!("gamecult.model.{name}.v4");
|
||||
for old_id in [v2, v4] {
|
||||
let mut request = invocation.request.clone();
|
||||
request.schema_id = old_id("provider_request");
|
||||
assert_eq!(request.validate(), Err(ContractError::Schema));
|
||||
let mut stale = invocation.clone();
|
||||
stale.schema_id = old_id("transport_invocation");
|
||||
assert_eq!(stale.validate(1_000, 2_000), Err(ContractError::Schema));
|
||||
let mut stale = result.clone();
|
||||
stale.schema_id = old_id("transport_result");
|
||||
assert_eq!(
|
||||
stale.validate_against(&invocation),
|
||||
Err(ContractError::Schema)
|
||||
);
|
||||
let mut stale = (**sent).clone();
|
||||
stale.schema_id = old_id("transport_receipt");
|
||||
assert_eq!(
|
||||
stale.validate_against(&invocation),
|
||||
Err(ContractError::Schema)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `document` re-encoded as a named map with one more key at its top level.
|
||||
|
|
@ -890,7 +906,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 v4 document is a named map");
|
||||
panic!("a v5 document is a named map");
|
||||
};
|
||||
entries.push((rmpv::Value::from("unexpected_field"), rmpv::Value::from(1)));
|
||||
let mut out = Vec::new();
|
||||
|
|
@ -1069,6 +1085,32 @@ mod tests {
|
|||
blank_response.validate_against(&invocation),
|
||||
Err(ContractError::Invalid("receipt.provider_response_id"))
|
||||
);
|
||||
let mut cost_without_usage = good.clone();
|
||||
cost_without_usage.outcome = TransportOutcome::Failed {
|
||||
kind: FailureKind::Provider,
|
||||
message: "failed".to_string(),
|
||||
usage: None,
|
||||
};
|
||||
cost_without_usage.cost_micro_usd = Some(0);
|
||||
assert_eq!(
|
||||
cost_without_usage.validate_against(&invocation),
|
||||
Err(ContractError::Invalid("receipt.cost_micro_usd"))
|
||||
);
|
||||
cost_without_usage.cost_micro_usd = None;
|
||||
assert_eq!(cost_without_usage.validate_against(&invocation), Ok(()));
|
||||
cost_without_usage.outcome = TransportOutcome::Failed {
|
||||
kind: FailureKind::RateLimited,
|
||||
message: "limited".to_string(),
|
||||
usage: Some(Usage {
|
||||
input_tokens: 0,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
output_tokens: 0,
|
||||
reasoning_tokens: None,
|
||||
}),
|
||||
};
|
||||
cost_without_usage.cost_micro_usd = Some(0);
|
||||
assert_eq!(cost_without_usage.validate_against(&invocation), Ok(()));
|
||||
}
|
||||
|
||||
fn reasoning(state: &[u8]) -> TransportEventPayload {
|
||||
|
|
|
|||
|
|
@ -1070,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_v4/carriage_invocation.frame"),
|
||||
.join("tests/fixtures/wire_v5/carriage_invocation.frame"),
|
||||
)
|
||||
.expect("carriage_invocation.frame is committed")
|
||||
}
|
||||
|
|
@ -1107,7 +1107,7 @@ mod tests {
|
|||
assert_eq!(text(&request, "operation"), "invoke");
|
||||
assert_eq!(
|
||||
text(&request, "payloadSchema"),
|
||||
"gamecult.model.transport_envelope.v4"
|
||||
"gamecult.model.transport_envelope.v5"
|
||||
);
|
||||
assert_eq!(text(&request, "payloadEncoding"), "messagepack-base64");
|
||||
assert_eq!(text(&request, "messageId"), envelope.request_id);
|
||||
|
|
@ -1121,7 +1121,7 @@ mod tests {
|
|||
assert_eq!(text(&response, "status"), "ok");
|
||||
assert_eq!(
|
||||
text(&response, "payloadSchema"),
|
||||
"gamecult.model.transport_envelope.v4"
|
||||
"gamecult.model.transport_envelope.v5"
|
||||
);
|
||||
assert_eq!(text(&response, "payloadEncoding"), "messagepack-base64");
|
||||
assert_eq!(text(&response, "messageId"), envelope.request_id);
|
||||
|
|
@ -1309,9 +1309,20 @@ mod tests {
|
|||
#[cfg(feature = "daemon")]
|
||||
#[test]
|
||||
fn a_response_is_read_as_its_own_operation_only() {
|
||||
use crate::readout::PlanQuotaSnapshot;
|
||||
use crate::readout::{CallerModelSpend, PlanQuotaSnapshot};
|
||||
let key = TransportKey::from_connection_secret("readout-test-key").unwrap();
|
||||
let readout = UsageReadout::new(1, PlanQuotaSnapshot::default());
|
||||
let readout = UsageReadout::new(
|
||||
1,
|
||||
vec![CallerModelSpend {
|
||||
caller: "caller-1".into(),
|
||||
model: "gpt-5.4".into(),
|
||||
month: "2026-12".into(),
|
||||
calls: 2,
|
||||
cost_micro_usd: 150,
|
||||
calls_without_price: 0,
|
||||
}],
|
||||
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();
|
||||
|
|
|
|||
|
|
@ -48,8 +48,9 @@ impl Drop for TestStore {
|
|||
/// every one, so a test can make the replay store fail where it chooses. A
|
||||
/// store reopened from it sees what was written, like a restart.
|
||||
#[cfg(feature = "daemon")]
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct FlakyStore {
|
||||
held: Arc<Mutex<BTreeMap<String, CultCacheEnvelope>>>,
|
||||
held: Arc<Mutex<BTreeMap<(String, String), CultCacheEnvelope>>>,
|
||||
pushes_allowed: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
|
|
@ -76,20 +77,27 @@ impl CacheBackingStore for FlakyStore {
|
|||
}
|
||||
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> anyhow::Result<()> {
|
||||
let allowed = self.pushes_allowed.load(Ordering::SeqCst);
|
||||
if allowed == 0 {
|
||||
if self
|
||||
.pushes_allowed
|
||||
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |allowed| {
|
||||
allowed.checked_sub(1)
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
return Err(anyhow::anyhow!("ledger write refused"));
|
||||
}
|
||||
self.pushes_allowed.store(allowed - 1, Ordering::SeqCst);
|
||||
self.held
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(entry.key.clone(), entry.clone());
|
||||
.insert((entry.r#type.clone(), entry.key.clone()), entry.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete(&mut self, entry: &CultCacheEnvelope) -> anyhow::Result<()> {
|
||||
self.held.lock().unwrap().remove(&entry.key);
|
||||
self.held
|
||||
.lock()
|
||||
.unwrap()
|
||||
.remove(&(entry.r#type.clone(), entry.key.clone()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -98,9 +106,18 @@ impl CacheBackingStore for FlakyStore {
|
|||
entries: &[CultCacheEnvelope],
|
||||
_options: PushAllOptions,
|
||||
) -> anyhow::Result<()> {
|
||||
if self
|
||||
.pushes_allowed
|
||||
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |allowed| {
|
||||
allowed.checked_sub(1)
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
return Err(anyhow::anyhow!("ledger write refused"));
|
||||
}
|
||||
*self.held.lock().unwrap() = entries
|
||||
.iter()
|
||||
.map(|entry| (entry.key.clone(), entry.clone()))
|
||||
.map(|entry| ((entry.r#type.clone(), entry.key.clone()), entry.clone()))
|
||||
.collect();
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -139,6 +156,7 @@ pub(crate) fn receipt(invocation: &TransportInvocation) -> TransportReceipt {
|
|||
model: invocation.request.model.clone(),
|
||||
provider: "fixture-sse".to_string(),
|
||||
foreign_reasoning_dropped: 0,
|
||||
cost_micro_usd: None,
|
||||
outcome: TransportOutcome::Completed {
|
||||
provider_response_id: Some("response-1".to_string()),
|
||||
stop_reason: StopReason::EndTurn,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
mod client;
|
||||
mod contract;
|
||||
mod envelope;
|
||||
mod price;
|
||||
mod readout;
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -14,6 +15,7 @@ mod service;
|
|||
pub use client::*;
|
||||
pub use contract::*;
|
||||
pub use envelope::*;
|
||||
pub use price::*;
|
||||
pub use readout::*;
|
||||
|
||||
#[cfg(feature = "daemon")]
|
||||
|
|
|
|||
379
crates/model-connector/src/price.rs
Normal file
379
crates/model-connector/src/price.rs
Normal file
|
|
@ -0,0 +1,379 @@
|
|||
//! Per-model token pricing in micro-USD per million tokens, plus pure-integer
|
||||
//! UTC calendar math for banded rates and monthly spend keys.
|
||||
//!
|
||||
//! Pricing exists solely for cost visibility on receipts and the communal usage
|
||||
//! readout (`Q4`). Nothing in the connector compares a cost or monthly total
|
||||
//! to refuse, delay, retry, or reorder a request.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::contract::{ContractError, Usage};
|
||||
|
||||
const MICRO_USD_SCALE: u128 = 1_000_000;
|
||||
const SECS_PER_DAY: u64 = 86_400;
|
||||
const SECS_PER_HOUR: u64 = 3_600;
|
||||
|
||||
/// Day of week in UTC.
|
||||
#[derive(
|
||||
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
|
||||
)]
|
||||
pub enum Weekday {
|
||||
Mon,
|
||||
Tue,
|
||||
Wed,
|
||||
Thu,
|
||||
Fri,
|
||||
Sat,
|
||||
Sun,
|
||||
}
|
||||
|
||||
/// Decomposed UTC calendar fields for a `unix_ms` timestamp.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct UtcParts {
|
||||
pub year: i64,
|
||||
pub month: u8,
|
||||
pub day: u8,
|
||||
pub weekday: Weekday,
|
||||
pub hour: u8,
|
||||
}
|
||||
|
||||
/// Pure-integer UTC calendar decomposition from Unix milliseconds (proleptic
|
||||
/// Gregorian calendar, no external date crate).
|
||||
pub fn utc_parts(unix_ms: u64) -> UtcParts {
|
||||
let total_secs = unix_ms / 1_000;
|
||||
let total_days = total_secs / SECS_PER_DAY;
|
||||
let sec_of_day = total_secs % SECS_PER_DAY;
|
||||
let hour = (sec_of_day / SECS_PER_HOUR) as u8;
|
||||
// 1970-01-01 was a Thursday (index 3 when Mon=0..Sun=6).
|
||||
let weekday = match (total_days + 3) % 7 {
|
||||
0 => Weekday::Mon,
|
||||
1 => Weekday::Tue,
|
||||
2 => Weekday::Wed,
|
||||
3 => Weekday::Thu,
|
||||
4 => Weekday::Fri,
|
||||
5 => Weekday::Sat,
|
||||
_ => Weekday::Sun,
|
||||
};
|
||||
|
||||
// Howard Hinnant's `civil_from_days` algorithm.
|
||||
let z = (total_days as i64) + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z.rem_euclid(146_097);
|
||||
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let y = yoe + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let day = (doy - (153 * mp + 2) / 5 + 1) as u8;
|
||||
let month = (mp + if mp < 10 { 3 } else { -9 }) as u8;
|
||||
let year = y + if month <= 2 { 1 } else { 0 };
|
||||
|
||||
UtcParts {
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
weekday,
|
||||
hour,
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats the UTC calendar month of `unix_ms` as `YYYY-MM`.
|
||||
pub fn utc_month_string(unix_ms: u64) -> String {
|
||||
let parts = utc_parts(unix_ms);
|
||||
format!("{:04}-{:02}", parts.year, parts.month)
|
||||
}
|
||||
|
||||
/// Per-million-token rates in micro-USD (`1 USD = 1_000_000 micro-USD`).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TokenRates {
|
||||
pub input: u64,
|
||||
pub cache_read: u64,
|
||||
pub cache_write: u64,
|
||||
pub output: u64,
|
||||
}
|
||||
|
||||
impl TokenRates {
|
||||
/// Computes `ceil(sum(tokens * rate) / 1_000_000)` in `u128`, clamping at
|
||||
/// `u64::MAX`. `reasoning_tokens` is already included in `output_tokens`
|
||||
/// and is never double-counted.
|
||||
pub fn cost_micro_usd(&self, usage: &Usage) -> u64 {
|
||||
let weighted = (u128::from(usage.input_tokens) * u128::from(self.input))
|
||||
.saturating_add(u128::from(usage.cache_read_tokens) * u128::from(self.cache_read))
|
||||
.saturating_add(u128::from(usage.cache_write_tokens) * u128::from(self.cache_write))
|
||||
.saturating_add(u128::from(usage.output_tokens) * u128::from(self.output));
|
||||
let micro_usd = weighted.div_ceil(MICRO_USD_SCALE);
|
||||
u64::try_from(micro_usd).unwrap_or(u64::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
/// Time-of-week UTC pricing band overriding [`PriceRow::base`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PriceBand {
|
||||
pub weekdays: Vec<Weekday>,
|
||||
pub utc_hours: Vec<u8>,
|
||||
pub rates: TokenRates,
|
||||
}
|
||||
|
||||
/// Per-model pricing table entry: base rates plus ordered UTC time bands
|
||||
/// (first matching band wins, otherwise `base`).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PriceRow {
|
||||
pub base: TokenRates,
|
||||
pub bands: Vec<PriceBand>,
|
||||
}
|
||||
|
||||
impl PriceRow {
|
||||
pub fn validate(&self) -> Result<(), ContractError> {
|
||||
for band in &self.bands {
|
||||
if band.weekdays.is_empty() {
|
||||
return Err(ContractError::Invalid("price.band.weekdays"));
|
||||
}
|
||||
let mut seen_days = HashSet::with_capacity(band.weekdays.len());
|
||||
for day in &band.weekdays {
|
||||
if !seen_days.insert(*day) {
|
||||
return Err(ContractError::Invalid("price.band.weekdays"));
|
||||
}
|
||||
}
|
||||
if band.utc_hours.is_empty() {
|
||||
return Err(ContractError::Invalid("price.band.utc_hours"));
|
||||
}
|
||||
let mut seen_hours = HashSet::with_capacity(band.utc_hours.len());
|
||||
for &hour in &band.utc_hours {
|
||||
if hour >= 24 || !seen_hours.insert(hour) {
|
||||
return Err(ContractError::Invalid("price.band.utc_hours"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn rates_at(&self, unix_ms: u64) -> &TokenRates {
|
||||
let parts = utc_parts(unix_ms);
|
||||
self.bands
|
||||
.iter()
|
||||
.find(|band| {
|
||||
band.weekdays.contains(&parts.weekday) && band.utc_hours.contains(&parts.hour)
|
||||
})
|
||||
.map_or(&self.base, |band| &band.rates)
|
||||
}
|
||||
|
||||
pub fn cost_micro_usd(&self, usage: &Usage, unix_ms: u64) -> u64 {
|
||||
self.rates_at(unix_ms).cost_micro_usd(usage)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn deepseek_price() -> PriceRow {
|
||||
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,
|
||||
},
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peak_and_off_peak_and_utc_calendar_math() {
|
||||
assert_eq!(
|
||||
utc_parts(0),
|
||||
UtcParts {
|
||||
year: 1970,
|
||||
month: 1,
|
||||
day: 1,
|
||||
weekday: Weekday::Thu,
|
||||
hour: 0,
|
||||
}
|
||||
);
|
||||
assert_eq!(utc_month_string(0), "1970-01");
|
||||
|
||||
// 2024-02-29T23:59:59Z (leap day, Thursday)
|
||||
let leap_day_ms = (19_782 * 86_400 + 23 * 3_600 + 59 * 60 + 59) * 1_000;
|
||||
assert_eq!(
|
||||
utc_parts(leap_day_ms),
|
||||
UtcParts {
|
||||
year: 2024,
|
||||
month: 2,
|
||||
day: 29,
|
||||
weekday: Weekday::Thu,
|
||||
hour: 23,
|
||||
}
|
||||
);
|
||||
assert_eq!(utc_month_string(leap_day_ms), "2024-02");
|
||||
|
||||
// 2026-12-08T02:30:00Z (Tuesday 02:30 UTC -> peak band)
|
||||
let tue_peak_ms = (20_795 * 86_400 + 2 * 3_600 + 30 * 60) * 1_000;
|
||||
assert_eq!(
|
||||
utc_parts(tue_peak_ms),
|
||||
UtcParts {
|
||||
year: 2026,
|
||||
month: 12,
|
||||
day: 8,
|
||||
weekday: Weekday::Tue,
|
||||
hour: 2,
|
||||
}
|
||||
);
|
||||
assert_eq!(utc_month_string(tue_peak_ms), "2026-12");
|
||||
|
||||
// 2026-12-08T12:00:00Z (Tuesday 12:00 UTC -> off-peak base)
|
||||
let tue_off_peak_ms = (20_795 * 86_400 + 12 * 3_600) * 1_000;
|
||||
assert_eq!(
|
||||
utc_parts(tue_off_peak_ms),
|
||||
UtcParts {
|
||||
year: 2026,
|
||||
month: 12,
|
||||
day: 8,
|
||||
weekday: Weekday::Tue,
|
||||
hour: 12,
|
||||
}
|
||||
);
|
||||
|
||||
// 2026-12-12T02:30:00Z (Saturday 02:30 UTC -> off-peak base despite peak hour)
|
||||
let sat_ms = (20_799 * 86_400 + 2 * 3_600 + 30 * 60) * 1_000;
|
||||
assert_eq!(utc_parts(sat_ms).weekday, Weekday::Sat);
|
||||
|
||||
let price = deepseek_price();
|
||||
assert_eq!(price.validate(), Ok(()));
|
||||
|
||||
let usage = Usage {
|
||||
input_tokens: 1_500,
|
||||
cache_read_tokens: 4_000,
|
||||
cache_write_tokens: 0,
|
||||
output_tokens: 750,
|
||||
reasoning_tokens: Some(300),
|
||||
};
|
||||
// Peak: (1500*540_000 + 4000*54_000 + 750*2_200_000) / 1_000_000
|
||||
// = (810_000_000 + 216_000_000 + 1_650_000_000) / 1_000_000
|
||||
// = 2_676_000_000 / 1_000_000 = 2_676 micro-USD.
|
||||
assert_eq!(price.cost_micro_usd(&usage, tue_peak_ms), 2_676);
|
||||
|
||||
// Off-peak (half rates): 1_338 micro-USD.
|
||||
assert_eq!(price.cost_micro_usd(&usage, tue_off_peak_ms), 1_338);
|
||||
assert_eq!(price.cost_micro_usd(&usage, sat_ms), 1_338);
|
||||
|
||||
// reasoning_tokens is a detail inside output_tokens and never double-counted.
|
||||
let without_detail = Usage {
|
||||
reasoning_tokens: None,
|
||||
..usage.clone()
|
||||
};
|
||||
assert_eq!(
|
||||
price.cost_micro_usd(&without_detail, tue_peak_ms),
|
||||
price.cost_micro_usd(&usage, tue_peak_ms)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ceiling_rounding_saturation_and_band_validation() {
|
||||
let unit = TokenRates {
|
||||
input: 1,
|
||||
cache_read: 0,
|
||||
cache_write: 0,
|
||||
output: 0,
|
||||
};
|
||||
let usage_for = |input_tokens| Usage {
|
||||
input_tokens,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
output_tokens: 0,
|
||||
reasoning_tokens: None,
|
||||
};
|
||||
assert_eq!(unit.cost_micro_usd(&usage_for(0)), 0);
|
||||
assert_eq!(unit.cost_micro_usd(&usage_for(1)), 1);
|
||||
assert_eq!(unit.cost_micro_usd(&usage_for(1_000_000)), 1);
|
||||
assert_eq!(unit.cost_micro_usd(&usage_for(1_000_001)), 2);
|
||||
|
||||
let huge_rates = TokenRates {
|
||||
input: u64::MAX,
|
||||
cache_read: u64::MAX,
|
||||
cache_write: u64::MAX,
|
||||
output: u64::MAX,
|
||||
};
|
||||
let huge_usage = Usage {
|
||||
input_tokens: u64::MAX,
|
||||
cache_read_tokens: u64::MAX,
|
||||
cache_write_tokens: u64::MAX,
|
||||
output_tokens: u64::MAX,
|
||||
reasoning_tokens: Some(u64::MAX),
|
||||
};
|
||||
assert_eq!(huge_rates.cost_micro_usd(&huge_usage), u64::MAX);
|
||||
|
||||
// First matching band wins.
|
||||
let base_rates = TokenRates {
|
||||
input: 100,
|
||||
cache_read: 0,
|
||||
cache_write: 0,
|
||||
output: 0,
|
||||
};
|
||||
let first_rates = TokenRates {
|
||||
input: 200,
|
||||
..base_rates.clone()
|
||||
};
|
||||
let second_rates = TokenRates {
|
||||
input: 300,
|
||||
..base_rates.clone()
|
||||
};
|
||||
let overlapping = PriceRow {
|
||||
base: base_rates,
|
||||
bands: vec![
|
||||
PriceBand {
|
||||
weekdays: vec![Weekday::Thu],
|
||||
utc_hours: vec![0],
|
||||
rates: first_rates.clone(),
|
||||
},
|
||||
PriceBand {
|
||||
weekdays: vec![Weekday::Thu],
|
||||
utc_hours: vec![0],
|
||||
rates: second_rates,
|
||||
},
|
||||
],
|
||||
};
|
||||
assert_eq!(overlapping.validate(), Ok(()));
|
||||
assert_eq!(overlapping.rates_at(0), &first_rates);
|
||||
|
||||
// Validation failures.
|
||||
let mut bad = deepseek_price();
|
||||
bad.bands[0].weekdays.clear();
|
||||
assert_eq!(bad.validate(), Err(ContractError::Invalid("price.band.weekdays")));
|
||||
|
||||
let mut bad = deepseek_price();
|
||||
bad.bands[0].weekdays = vec![Weekday::Mon, Weekday::Mon];
|
||||
assert_eq!(bad.validate(), Err(ContractError::Invalid("price.band.weekdays")));
|
||||
|
||||
let mut bad = deepseek_price();
|
||||
bad.bands[0].utc_hours.clear();
|
||||
assert_eq!(bad.validate(), Err(ContractError::Invalid("price.band.utc_hours")));
|
||||
|
||||
let mut bad = deepseek_price();
|
||||
bad.bands[0].utc_hours = vec![24];
|
||||
assert_eq!(bad.validate(), Err(ContractError::Invalid("price.band.utc_hours")));
|
||||
|
||||
let mut bad = deepseek_price();
|
||||
bad.bands[0].utc_hours = vec![1, 1];
|
||||
assert_eq!(bad.validate(), Err(ContractError::Invalid("price.band.utc_hours")));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,13 +1,26 @@
|
|||
//! 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.
|
||||
//! The usage readout: monthly caller/model spend visibility alongside the
|
||||
//! subscription plan's own usage windows as the backend last saw them. The
|
||||
//! connector gates nothing on cost; it publishes what it observed, and the
|
||||
//! callers monitor their own quota.
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::contract::ContractError;
|
||||
|
||||
pub const USAGE_READOUT_SCHEMA_ID: &str = "gamecult.model.usage_readout.v1";
|
||||
pub const USAGE_READOUT_SCHEMA_ID: &str = "gamecult.model.usage_readout.v2";
|
||||
|
||||
/// One caller's committed monthly usage row for a single model in UTC `YYYY-MM`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CallerModelSpend {
|
||||
pub caller: String,
|
||||
pub model: String,
|
||||
pub month: String,
|
||||
pub calls: u64,
|
||||
pub cost_micro_usd: u64,
|
||||
pub calls_without_price: u64,
|
||||
}
|
||||
|
||||
/// One window of the subscription plan, as the provider reported it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
|
|
@ -37,14 +50,20 @@ pub struct PlanQuotaSnapshot {
|
|||
pub struct UsageReadout {
|
||||
pub schema_id: String,
|
||||
pub at_unix_ms: u64,
|
||||
pub spend: Vec<CallerModelSpend>,
|
||||
pub plan_quota: Vec<PlanQuota>,
|
||||
}
|
||||
|
||||
impl UsageReadout {
|
||||
pub fn new(at_unix_ms: u64, plan: PlanQuotaSnapshot) -> Self {
|
||||
pub fn new(
|
||||
at_unix_ms: u64,
|
||||
spend: Vec<CallerModelSpend>,
|
||||
plan: PlanQuotaSnapshot,
|
||||
) -> Self {
|
||||
Self {
|
||||
schema_id: USAGE_READOUT_SCHEMA_ID.to_string(),
|
||||
at_unix_ms,
|
||||
spend,
|
||||
plan_quota: plan.windows,
|
||||
}
|
||||
}
|
||||
|
|
@ -65,6 +84,14 @@ mod tests {
|
|||
fn readout() -> UsageReadout {
|
||||
UsageReadout::new(
|
||||
1_000,
|
||||
vec![CallerModelSpend {
|
||||
caller: "caller-1".into(),
|
||||
model: "deepseek/deepseek-flash".into(),
|
||||
month: "2026-12".into(),
|
||||
calls: 3,
|
||||
cost_micro_usd: 4_014,
|
||||
calls_without_price: 1,
|
||||
}],
|
||||
PlanQuotaSnapshot {
|
||||
windows: vec![PlanQuota {
|
||||
window: "five_hour".into(),
|
||||
|
|
@ -85,21 +112,22 @@ 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", "plan_quota"]);
|
||||
assert_eq!(names, ["schema_id", "at_unix_ms", "spend", "plan_quota"]);
|
||||
assert_eq!(wire_decode::<UsageReadout>(&bytes).unwrap(), readout());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unobserved_plan_is_none_not_zero() {
|
||||
let bare = UsageReadout::new(1, PlanQuotaSnapshot::default());
|
||||
let bare = UsageReadout::new(1, Vec::new(), PlanQuotaSnapshot::default());
|
||||
let decoded: UsageReadout = wire_decode(&wire_encode(&bare).unwrap()).unwrap();
|
||||
assert!(decoded.spend.is_empty());
|
||||
assert!(decoded.plan_quota.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_readout_of_another_schema_is_refused() {
|
||||
let mut other = readout();
|
||||
other.schema_id = "gamecult.model.usage_readout.v2".into();
|
||||
other.schema_id = "gamecult.model.usage_readout.v1".into();
|
||||
assert!(other.validate().is_err());
|
||||
assert!(readout().validate().is_ok());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -588,6 +588,104 @@ mod tests {
|
|||
let (client, _) = start(CountingBackend::new(true), &store);
|
||||
let readout = client.usage_readout(CALLER).unwrap();
|
||||
assert!(readout.plan_quota.is_empty());
|
||||
assert!(readout.spend.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_usage_readout_includes_monthly_spend_communally() {
|
||||
use crate::price::{PriceRow, TokenRates, utc_month_string};
|
||||
use crate::readout::CallerModelSpend;
|
||||
|
||||
let store = TestStore::new();
|
||||
let now = now_ms();
|
||||
let month = utc_month_string(now);
|
||||
let priced_routes = ProviderRoutes::with_prices([(
|
||||
"gpt-5.4".to_string(),
|
||||
"fixture-sse".to_string(),
|
||||
Some(PriceRow {
|
||||
base: TokenRates {
|
||||
input: 1_000_000,
|
||||
cache_read: 0,
|
||||
cache_write: 0,
|
||||
output: 1_000_000,
|
||||
},
|
||||
bands: Vec::new(),
|
||||
}),
|
||||
)])
|
||||
.unwrap();
|
||||
let backend = CountingBackend::new(true);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let endpoint = listener.local_addr().unwrap();
|
||||
let path = store.path.clone();
|
||||
let backend_handle = backend.clone();
|
||||
thread::spawn(move || {
|
||||
serve(
|
||||
listener,
|
||||
limits(),
|
||||
vec![
|
||||
caller(CALLER, KEY, 4),
|
||||
caller("ghostlight-yggdrasil", "ghostlight-distinct-test-key", 4),
|
||||
],
|
||||
&path,
|
||||
priced_routes,
|
||||
backend_handle,
|
||||
)
|
||||
});
|
||||
|
||||
let client_a =
|
||||
ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap();
|
||||
let client_b = ConnectorClient::new(
|
||||
endpoint,
|
||||
"ghostlight-distinct-test-key",
|
||||
FRAME,
|
||||
Some(Duration::from_secs(5)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let inv_a = fresh("spend-a-1");
|
||||
let res_a = client_a.execute(&inv_a).unwrap();
|
||||
let TransportDisposition::Transported { receipt: rc_a, .. } = &res_a.disposition else {
|
||||
panic!("expected transported result");
|
||||
};
|
||||
assert_eq!(rc_a.cost_micro_usd, Some(13));
|
||||
// Replay must not double-count.
|
||||
assert_eq!(client_a.execute(&inv_a).unwrap(), res_a);
|
||||
assert_eq!(backend.executions.load(Ordering::SeqCst), 1);
|
||||
|
||||
let mut inv_b = invocation_for("ghostlight-yggdrasil", "spend-b-1");
|
||||
inv_b.expires_at_unix_ms = now_ms() + 60_000;
|
||||
let res_b = client_b.execute(&inv_b).unwrap();
|
||||
let TransportDisposition::Transported { receipt: rc_b, .. } = &res_b.disposition else {
|
||||
panic!("expected transported result");
|
||||
};
|
||||
assert_eq!(rc_b.cost_micro_usd, Some(13));
|
||||
|
||||
let expected = vec![
|
||||
CallerModelSpend {
|
||||
caller: CALLER.to_string(),
|
||||
model: "gpt-5.4".to_string(),
|
||||
month: month.clone(),
|
||||
calls: 1,
|
||||
cost_micro_usd: 13,
|
||||
calls_without_price: 0,
|
||||
},
|
||||
CallerModelSpend {
|
||||
caller: "ghostlight-yggdrasil".to_string(),
|
||||
model: "gpt-5.4".to_string(),
|
||||
month,
|
||||
calls: 1,
|
||||
cost_micro_usd: 13,
|
||||
calls_without_price: 0,
|
||||
},
|
||||
];
|
||||
assert_eq!(client_a.usage_readout(CALLER).unwrap().spend, expected);
|
||||
assert_eq!(
|
||||
client_b
|
||||
.usage_readout("ghostlight-yggdrasil")
|
||||
.unwrap()
|
||||
.spend,
|
||||
expected
|
||||
);
|
||||
}
|
||||
|
||||
fn window_plan(permille: u32, status: &str, resets_at_unix_ms: u64) -> PlanQuotaSnapshot {
|
||||
|
|
@ -1398,11 +1496,54 @@ mod tests {
|
|||
Err(TransportFrameError::Connection(_))
|
||||
));
|
||||
assert_eq!(backend.executions.load(Ordering::SeqCst), 0);
|
||||
// The loop survives the v2 peer and serves a v3 one.
|
||||
// The loop survives the v2 peer and serves a v5 one.
|
||||
client.execute(&fresh("request-after-v2")).unwrap();
|
||||
assert_eq!(backend.executions.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_v4_frame_gets_no_answer() {
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use cultnet_rs::{CultNetMessage, CultNetWireContract, encode_cultnet_message_to_vec};
|
||||
|
||||
let store = TestStore::new();
|
||||
let backend = CountingBackend::new(true);
|
||||
let (client, endpoint) = start(backend.clone(), &store);
|
||||
let v4_envelope = crate::envelope::TransportEnvelope {
|
||||
schema_id: format!("{}{}", "gamecult.model.transport_envelope.", "v4"),
|
||||
caller_runtime_id: CALLER.to_string(),
|
||||
request_id: "request-v4".to_string(),
|
||||
message_kind: crate::envelope::EnvelopeKind::Invocation,
|
||||
nonce: [0_u8; 12],
|
||||
ciphertext: vec![1_u8; 40],
|
||||
};
|
||||
let v4_frame = encode_cultnet_message_to_vec(
|
||||
&CultNetMessage::OperationRequest {
|
||||
message_id: "request-v4".to_string(),
|
||||
service_id: crate::envelope::CONNECTOR_SERVICE_ID.to_string(),
|
||||
operation: crate::envelope::INVOKE_OPERATION.to_string(),
|
||||
payload_schema: v4_envelope.schema_id.clone(),
|
||||
payload_encoding: "messagepack-base64".to_string(),
|
||||
payload: STANDARD.encode(crate::contract::wire_encode(&v4_envelope).unwrap()),
|
||||
source_runtime_id: None,
|
||||
target_runtime_id: None,
|
||||
},
|
||||
CultNetWireContract::CultNetSchemaV0,
|
||||
)
|
||||
.unwrap();
|
||||
let mut stream = TcpStream::connect(endpoint).unwrap();
|
||||
write_transport_frame(&mut stream, &v4_frame, FRAME).unwrap();
|
||||
assert!(matches!(
|
||||
read_transport_frame(&mut stream, FRAME),
|
||||
Err(TransportFrameError::Connection(_))
|
||||
));
|
||||
assert_eq!(backend.executions.load(Ordering::SeqCst), 0);
|
||||
// The loop survives the v4 peer and serves a v5 one.
|
||||
client.execute(&fresh("request-after-v4")).unwrap();
|
||||
assert_eq!(backend.executions.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reply_echoes_the_request_id() {
|
||||
use cultnet_rs::{CultNetMessage, CultNetWireContract, decode_cultnet_message_from_slice};
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,16 +0,0 @@
|
|||
# wire_v4 fixtures
|
||||
|
||||
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.
|
||||
|
||||
- `provider_request.mp`, `transport_invocation.mp`, `transport_result_transported.mp`,
|
||||
`transport_result_refused.mp`, `transport_receipt_failed.mp`, `transport_envelope.mp`,
|
||||
`input_reasoning_state.mp` (an `InputItem::ReasoningState`, its state as MessagePack `bin`):
|
||||
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_v4.rs`.
|
||||
|
||||
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 +0,0 @@
|
|||
<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
|
||||
|
|
@ -1 +0,0 @@
|
|||
<EFBFBD>ReasoningState<EFBFBD>provider淮nthropic-messages叮odel畚laude-opus-4-5叫tate<74><65><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>﹜ㄓ它夾帚型陋秣捲陷絮溢劃遞蝨螃謝藥齪ヌ圴佮迓玿旂衲欶趹欹詘棰葮摵蜠樉賥濋錎膼瀔嚦黀蘜蠲╭帉爎<E5B889>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -1 +0,0 @@
|
|||
„©schema_idÙ"gamecult.model.transport_result.v4ªrequest_id®golden-request±caller_runtime_idgolden-caller«disposition<6F>§Refused«OutputBound
|
||||
Binary file not shown.
16
crates/model-connector/tests/fixtures/wire_v5/README.md
vendored
Normal file
16
crates/model-connector/tests/fixtures/wire_v5/README.md
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
# wire_v5 fixtures
|
||||
|
||||
The named-MessagePack bytes of the v5 documents and one sealed carriage frame,
|
||||
kept so a format drift breaks a test instead of passing silently:
|
||||
|
||||
- `provider_request.mp`: `ProviderRequest`.
|
||||
- `transport_invocation.mp`: `TransportInvocation` over the same request.
|
||||
- `input_reasoning_state.mp`: `InputItem::ReasoningState` carrying bytes `0x80..=0xff`.
|
||||
- `transport_result_transported.mp`: `TransportResult` with `Transported` disposition and priced `cost_micro_usd`.
|
||||
- `transport_result_refused.mp`: `TransportResult` with `Refused` disposition.
|
||||
- `transport_receipt_failed.mp`: `TransportReceipt` with `Failed` outcome, usage, and `cost_micro_usd: Some(0)`.
|
||||
- `transport_receipt_failed_no_usage.mp`: `TransportReceipt` with `Failed` outcome, `usage: None`, and `cost_micro_usd: None`.
|
||||
- `transport_envelope.mp`: `TransportEnvelope` with non-ASCII nonce and ciphertext.
|
||||
- `carriage_invocation.frame`: `cultnet.operation_request.v0` wrapping the v5 envelope sealed under the fixed test key in `tests/wire_golden_v5.rs`.
|
||||
|
||||
Generator: `tests/wire_golden_v5.rs` itself. Run it with `WIRE_V5_REGENERATE=1` to rewrite the files from the types, then review the diff: a changed byte is a wire change.
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
//! `schemas/` at the repository root publishes one JSON Schema per v4 document,
|
||||
//! `schemas/` at the repository root publishes one JSON Schema per v5 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.
|
||||
|
|
@ -64,6 +64,17 @@ fn a_published_schema_refuses_an_unknown_field() {
|
|||
assert_eq!(schema["additionalProperties"], serde_json::json!(false));
|
||||
let required = schema["required"].as_array().unwrap();
|
||||
assert!(required.contains(&serde_json::json!("max_output_tokens")));
|
||||
|
||||
let receipt: serde_json::Value =
|
||||
serde_json::from_str(&std::fs::read_to_string(schemas_dir().join("transport_receipt.json")).unwrap())
|
||||
.unwrap();
|
||||
assert!(receipt["properties"].get("cost_micro_usd").is_some());
|
||||
|
||||
let readout: serde_json::Value =
|
||||
serde_json::from_str(&std::fs::read_to_string(schemas_dir().join("usage_readout.json")).unwrap())
|
||||
.unwrap();
|
||||
assert!(readout["properties"].get("spend").is_some());
|
||||
assert!(readout["$defs"].get("CallerModelSpend").is_some());
|
||||
}
|
||||
|
||||
/// The schema and the wire agree on the ciphertext: the schema says binary, not
|
||||
|
|
@ -80,7 +91,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.v4".to_string(),
|
||||
schema_id: "gamecult.model.transport_envelope.v5".to_string(),
|
||||
caller_runtime_id: "caller".to_string(),
|
||||
request_id: "request".to_string(),
|
||||
message_kind: EnvelopeKind::Invocation,
|
||||
|
|
|
|||
|
|
@ -307,10 +307,11 @@ impl ProviderBackend for TamperingBackend {
|
|||
|
||||
#[test]
|
||||
fn a_refused_completion_reaches_the_caller_as_a_typed_failure_and_frees_the_slot() {
|
||||
let edits: [fn(&mut TransportReceipt); 3] = [
|
||||
let edits: [fn(&mut TransportReceipt); 4] = [
|
||||
|receipt| receipt.provider = "another-provider".to_string(),
|
||||
|receipt| receipt.foreign_reasoning_dropped += 1,
|
||||
|receipt| receipt.request_id = "another-request".to_string(),
|
||||
|receipt| receipt.cost_micro_usd = Some(999),
|
||||
];
|
||||
for edit in edits {
|
||||
// One concurrent request: a wedged slot would refuse the next id.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
//! 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
|
||||
//! Pins the bytes of the v5 wire so a drift is a failing test. The fixtures in
|
||||
//! `fixtures/wire_v5` 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_V4_REGENERATE";
|
||||
const REGENERATE: &str = "WIRE_V5_REGENERATE";
|
||||
|
||||
fn fixtures() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/wire_v4")
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/wire_v5")
|
||||
}
|
||||
|
||||
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_V4_REGENERATE` set, the committed bytes are rewritten
|
||||
/// back to it. With `WIRE_V5_REGENERATE` set, the committed bytes are rewritten
|
||||
/// from the value first.
|
||||
fn assert_wire<T: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug>(
|
||||
name: &str,
|
||||
|
|
@ -84,7 +84,7 @@ fn invocation() -> TransportInvocation {
|
|||
TransportInvocation::new(CALLER, 1_800_000_000_000, [7; 32], request()).unwrap()
|
||||
}
|
||||
|
||||
fn receipt(outcome: TransportOutcome) -> TransportReceipt {
|
||||
fn receipt(cost_micro_usd: Option<u64>, outcome: TransportOutcome) -> TransportReceipt {
|
||||
let invocation = invocation();
|
||||
TransportReceipt {
|
||||
schema_id: RECEIPT_SCHEMA_ID.to_string(),
|
||||
|
|
@ -95,6 +95,7 @@ fn receipt(outcome: TransportOutcome) -> TransportReceipt {
|
|||
model: invocation.request.model.clone(),
|
||||
provider: "anthropic-messages".to_string(),
|
||||
foreign_reasoning_dropped: 2,
|
||||
cost_micro_usd,
|
||||
outcome,
|
||||
}
|
||||
}
|
||||
|
|
@ -114,7 +115,7 @@ fn completed() -> TransportOutcome {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn wire_golden_v4() {
|
||||
fn wire_golden_v5() {
|
||||
let invocation = invocation();
|
||||
assert_wire("provider_request.mp", &invocation.request);
|
||||
assert_wire("transport_invocation.mp", &invocation);
|
||||
|
|
@ -156,7 +157,7 @@ fn wire_golden_v4() {
|
|||
},
|
||||
},
|
||||
],
|
||||
receipt: Box::new(receipt(completed())),
|
||||
receipt: Box::new(receipt(Some(1_420), completed())),
|
||||
},
|
||||
};
|
||||
assert_eq!(transported.validate_against(&invocation), Ok(()));
|
||||
|
|
@ -165,19 +166,36 @@ fn wire_golden_v4() {
|
|||
let refused = TransportResult::refused(&invocation, Refusal::OutputBound);
|
||||
assert_wire("transport_result_refused.mp", &refused);
|
||||
|
||||
let failed = receipt(TransportOutcome::Failed {
|
||||
kind: FailureKind::RateLimited,
|
||||
message: "provider asked to slow down".to_string(),
|
||||
usage: Some(Usage {
|
||||
input_tokens: 120,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
output_tokens: 0,
|
||||
reasoning_tokens: None,
|
||||
}),
|
||||
});
|
||||
assert_eq!(failed.validate_against(&invocation), Ok(()));
|
||||
assert_wire("transport_receipt_failed.mp", &failed);
|
||||
let failed_with_usage = receipt(
|
||||
Some(0),
|
||||
TransportOutcome::Failed {
|
||||
kind: FailureKind::RateLimited,
|
||||
message: "provider asked to slow down".to_string(),
|
||||
usage: Some(Usage {
|
||||
input_tokens: 120,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
output_tokens: 0,
|
||||
reasoning_tokens: None,
|
||||
}),
|
||||
},
|
||||
);
|
||||
assert_eq!(failed_with_usage.validate_against(&invocation), Ok(()));
|
||||
assert_wire("transport_receipt_failed.mp", &failed_with_usage);
|
||||
|
||||
let failed_without_usage = receipt(
|
||||
None,
|
||||
TransportOutcome::Failed {
|
||||
kind: FailureKind::Unavailable,
|
||||
message: "provider unavailable".to_string(),
|
||||
usage: None,
|
||||
},
|
||||
);
|
||||
assert_eq!(failed_without_usage.validate_against(&invocation), Ok(()));
|
||||
assert_wire(
|
||||
"transport_receipt_failed_no_usage.mp",
|
||||
&failed_without_usage,
|
||||
);
|
||||
|
||||
let envelope = TransportEnvelope {
|
||||
schema_id: ENVELOPE_SCHEMA_ID.to_string(),
|
||||
|
|
@ -231,7 +249,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.v4");
|
||||
assert_eq!(payload_schema, "gamecult.model.transport_envelope.v5");
|
||||
assert_eq!(message_id, invocation.request_id());
|
||||
let envelope: TransportEnvelope =
|
||||
rmp_serde::from_slice(&STANDARD.decode(payload).unwrap()).unwrap();
|
||||
Loading…
Reference in a new issue