agent: a settle names its call row by the row's place in her trace; a call that reports no token is charged the worst case

A retried wake reuses its wake id, so keying settle rows by call id let a retry's
settle price an orphan reservation. Ledger::append answers the row's seq, the call
row's place is echoed as the settle's reserved, and the day sum pairs by it. A usage
that parses with all-zero tokens is charged the wake cap, as missing usage is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-29 23:56:38 +01:00
commit 5a9c851890
3 changed files with 67 additions and 21 deletions

View file

@ -136,7 +136,8 @@ pub trait Executor {
pub trait Ledger {
/// Every agent row, oldest first.
fn rows(&self) -> Result<Vec<Value>>;
fn append(&self, row: Value) -> Result<()>;
/// Writes `row`, stamping it with its place (`seq`), and answers that place: a place is never held by two rows, so it can name one.
fn append(&self, row: Value) -> Result<u64>;
}
/// The agent's rows in her trace: each is a record with an `agent` field naming its kind (`call`, `receipt`,
@ -158,10 +159,11 @@ impl Ledger for TraceLedger<'_> {
Ok(self.trace.records()?.into_iter().filter(|record| record.get("agent").is_some()).collect())
}
fn append(&self, mut row: Value) -> Result<()> {
let place = self.trace.records()?.len();
fn append(&self, mut row: Value) -> Result<u64> {
let place = self.trace.records()?.len() as u64;
row["seq"] = json!(place);
self.trace.record(&format!("{}-g{place}", self.stem), &row)
self.trace.record(&format!("{}-g{place}", self.stem), &row)?;
Ok(place)
}
}
@ -372,23 +374,23 @@ fn drive(run: &mut Run<'_>, tools: &[ToolDefinition], owners: &[(String, usize)]
}
let request_id = format!("{}-m{}", wake.id, run.model_calls + 1);
// The row comes first: it holds the call's place in the day's spend at the worst case, and a trace that cannot take it is a call not made.
run.record(json!({ "agent": "call", "at": (agent.clock)().to_rfc3339(), "wake": wake.id, "call": request_id, "model": bounds.model }))?;
let reserved = run.record(json!({ "agent": "call", "at": (agent.clock)().to_rfc3339(), "wake": wake.id, "call": request_id, "model": bounds.model }))?;
let answer = agent.model.step(StepRequest { request_id: &request_id, conversation_id: &conversation, model: &bounds.model, instructions: wake.instructions, tools, input: items.clone(), retention: Some(bounds.retention), schema: None });
let stepped = match answer {
Ok(stepped) => stepped,
Err(failed) => {
// A failure that reports no usage is charged at the worst case, never at nothing.
let usd = failed.usage.as_ref().map_or_else(|| unmetered_usd(bounds), |usage| price(bounds, usage));
let usd = failed.usage.as_ref().map_or_else(|| unmetered_usd(bounds), |usage| charge(bounds, usage));
run.usd += usd;
run.record(json!({ "agent": "settle", "at": (agent.clock)().to_rfc3339(), "wake": wake.id, "call": request_id, "usage": failed.usage, "usd": usd, "failed": failed.reason }))?;
run.record(json!({ "agent": "settle", "at": (agent.clock)().to_rfc3339(), "wake": wake.id, "call": request_id, "reserved": reserved, "usage": failed.usage, "usd": usd, "failed": failed.reason }))?;
return Ok(Ended::Failed(failed));
}
};
run.model_calls += 1;
let cost = price(bounds, &stepped.usage);
let cost = charge(bounds, &stepped.usage);
run.usd += cost;
let at = (agent.clock)();
run.record(json!({ "agent": "settle", "at": at.to_rfc3339(), "wake": wake.id, "call": request_id, "usage": stepped.usage, "usd": cost, "stop": format!("{:?}", stepped.stop) }))?;
run.record(json!({ "agent": "settle", "at": at.to_rfc3339(), "wake": wake.id, "call": request_id, "reserved": reserved, "usage": stepped.usage, "usd": cost, "stop": format!("{:?}", stepped.stop) }))?;
// Observed: a prefix the provider should hold was read as nothing, so the cache is gone. The wake finishes on what it has.
if warm_prefix >= bounds.cache_min_tokens && stepped.usage.cache_read_tokens == 0 {
cold = true;
@ -450,7 +452,7 @@ struct Run<'a> {
impl Run<'_> {
/// One row in her trace; a trace that cannot take it is the turn's failure.
fn record(&self, row: Value) -> std::result::Result<(), Failed> {
fn record(&self, row: Value) -> std::result::Result<u64, Failed> {
self.agent.ledger.append(row).map_err(|fault| ledger_failed(&fault))
}
@ -470,7 +472,7 @@ impl Run<'_> {
/// Forget the session, and say why in her trace.
fn discard(&mut self, why: &str) -> std::result::Result<(), Failed> {
self.agent.session.discard().map_err(|fault| ledger_failed(&fault))?;
self.record(json!({ "agent": "session_discarded", "at": (self.agent.clock)().to_rfc3339(), "wake": self.wake.id, "why": why }))
self.record(json!({ "agent": "session_discarded", "at": (self.agent.clock)().to_rfc3339(), "wake": self.wake.id, "why": why })).map(drop)
}
fn turn(self, ended: Ended) -> Turn {
@ -501,17 +503,24 @@ fn unmetered_usd(bounds: &AgentTuning) -> f64 {
bounds.wake_usd
}
/// What a call that reported `usage` is charged: its price, or `unmetered_usd` when it reports no token at all. A call that
/// was paid for never reports zero, so a zero is a count that cannot be believed, and a call is never free.
fn charge(bounds: &AgentTuning, usage: &Spent) -> f64 {
if prompt_tokens(usage) + usage.output_tokens == 0 { unmetered_usd(bounds) } else { price(bounds, usage) }
}
/// The UTC day's spend so far, from the `call` rows of her trace dated `now`'s day. A call row is priced by its own usage, or by
/// the `settle` row that answers it; a call with neither, or with a usage that does not read, is `unmetered_usd`. A row whose
/// time does not read counts as today's.
/// the `settle` row that names it: the settle's `reserved` is the call row's `seq`, its place in her trace, which no other row
/// holds, where a call id repeats when a wake is retried under its id. A call with neither, or with a usage that does not
/// read or counts no token, is `unmetered_usd`. A row whose time does not read counts as today's.
fn day_usd(rows: &[Value], now: DateTime<Utc>, bounds: &AgentTuning) -> f64 {
let settled: BTreeMap<&str, &Value> = rows.iter().filter(|row| row["agent"] == "settle").filter_map(|row| Some((row["call"].as_str()?, row))).collect();
let settled: BTreeMap<u64, &Value> = rows.iter().filter(|row| row["agent"] == "settle").filter_map(|row| Some((row["reserved"].as_u64()?, row))).collect();
rows.iter()
.filter(|row| row["agent"] == "call")
.filter(|row| row["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).is_none_or(|at| at.with_timezone(&Utc).date_naive() == now.date_naive()))
.map(|row| {
let usage = if row.get("usage").is_some() { &row["usage"] } else { row["call"].as_str().and_then(|id| settled.get(id)).map_or(&Value::Null, |settle| &settle["usage"]) };
serde_json::from_value::<Spent>(usage.clone()).map_or_else(|_| unmetered_usd(bounds), |usage| price(bounds, &usage))
let usage = if row.get("usage").is_some() { &row["usage"] } else { row["seq"].as_u64().and_then(|place| settled.get(&place)).map_or(&Value::Null, |settle| &settle["usage"]) };
serde_json::from_value::<Spent>(usage.clone()).map_or_else(|_| unmetered_usd(bounds), |usage| charge(bounds, &usage))
})
.sum()
}

View file

@ -98,12 +98,14 @@ impl Ledger for Memory {
Ok(self.rows.borrow().clone())
}
fn append(&self, row: Value) -> Result<()> {
fn append(&self, mut row: Value) -> Result<u64> {
if self.refuses.borrow().iter().any(|kind| row["agent"] == *kind) {
bail!("the trace cannot be written");
}
let place = self.rows.borrow().len() as u64;
row["seq"] = json!(place);
self.rows.borrow_mut().push(row);
Ok(())
Ok(place)
}
}
@ -530,8 +532,8 @@ fn t_a1_a_call_that_was_never_settled_stands_at_the_worst_case() {
assert!(model.seen.borrow().is_empty());
// A settle row prices its call; a usage that does not read, and a time that does not read, fail high.
let rig = Rig::new();
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "call": "a" })).unwrap();
rig.ledger.append(json!({ "agent": "settle", "at": noon().to_rfc3339(), "call": "a", "usage": usage(1000, 0, 0, 0) })).unwrap();
let place = rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "call": "a" })).unwrap();
rig.ledger.append(json!({ "agent": "settle", "at": noon().to_rfc3339(), "call": "a", "reserved": place, "usage": usage(1000, 0, 0, 0) })).unwrap();
assert!(near(day_of(&rig), 0.002));
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "usage": "garbage" })).unwrap();
assert!(near(day_of(&rig), 0.002 + 0.40));
@ -712,3 +714,38 @@ fn a_session_store_that_cannot_be_forgotten_is_an_error_and_one_already_gone_is_
std::fs::create_dir(&blocked).unwrap();
assert!(FileSession::new(&blocked).discard().is_err());
}
#[test]
fn t_a1_a_retried_wake_does_not_settle_the_orphan_it_reuses_the_name_of() {
// A start killed after its call row left `w1-m1` with no settle row. The retry runs under the same wake id and so asks
// for `w1-m1` again; its settle row is the retry's, and the orphan stays at the wake cap.
let rig = Rig::new();
rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "wake": "w1", "call": "w1-m1", "model": MODEL })).unwrap();
let turn = rig.run(&Script::new(vec![ends("Ok.", small())]), "x");
assert_eq!(turn.ended, Ended::EndTurn);
assert!(near(day_of(&rig), 0.40 + 0.0004), "{}", day_of(&rig));
// And the other way about: the retry's own call row is not priced by a settle that names an earlier place.
let rows = rig.ledger.rows.borrow();
let settle = rows.iter().find(|row| row["agent"] == "settle").unwrap();
assert_eq!(settle["reserved"], 1, "the retry's call row, not the orphan at place 0");
}
#[test]
fn t_a1_a_call_that_reports_no_token_is_charged_the_worst_case() {
let rig = Rig::new();
let turn = rig.run(&Script::new(vec![ends("Ok.", usage(0, 0, 0, 0))]), "x");
assert_eq!(turn.ended, Ended::EndTurn);
assert!(near(turn.usd, rig.bounds.wake_usd) && near(day_of(&rig), rig.bounds.wake_usd), "{} {}", turn.usd, day_of(&rig));
// A failed call that reports a usage of nothing.
let rig = Rig::new();
let nothing = Failed { reason: "cut".into(), outage: true, usage: Some(usage(0, 0, 0, 0)) };
let turn = rig.run(&Script::new(vec![Err(nothing.clone())]), "x");
assert_eq!(turn.ended, Ended::Failed(nothing));
assert!(near(turn.usd, rig.bounds.wake_usd) && near(day_of(&rig), rig.bounds.wake_usd), "{} {}", turn.usd, day_of(&rig));
// One token of anything is a count: it is priced.
for one in [usage(1, 0, 0, 0), usage(0, 1, 0, 0), usage(0, 0, 1, 0), usage(0, 0, 0, 1)] {
let rig = Rig::new();
rig.run(&Script::new(vec![ends("Ok.", one)]), "x");
assert!(day_of(&rig) < 1e-4, "{}", day_of(&rig));
}
}

View file

@ -290,7 +290,7 @@ mind_body::projection::agent: impl Steps for KitModel
mind_body::projection::agent: impl TraceLedger < 'a >: fn new (trace : & 'a dyn Trace , stem : impl Into < String >) -> Self
mind_body::projection::agent: impl< 'a > TraceLedger < 'a >
mind_body::projection::agent: pub trait Executor { fn definitions (& self) -> Vec < ToolDefinition > ; fn run (& self , call : & ToolCall) -> Receipt ; }
mind_body::projection::agent: pub trait Ledger { fn rows (& self) -> Result < Vec < Value > > ; fn append (& self , row : Value) -> Result < () > ; }
mind_body::projection::agent: pub trait Ledger { fn rows (& self) -> Result < Vec < Value > > ; fn append (& self , row : Value) -> Result < u64 > ; }
mind_body::projection::agent: pub trait Steps { fn step (& self , request : StepRequest < '_ >) -> std :: result :: Result < Stepped , Failed > ; }
mind_body::projection::agent: struct Agent< 'a > pub-fields[model: & 'a dyn Steps, session: & 'a FileSession, executors: & 'a [& 'a dyn Executor], ledger: & 'a dyn Ledger, bounds: & 'a AgentTuning, clock: & 'a dyn Fn () -> DateTime < Utc >]
mind_body::projection::agent: struct FileSession pub-fields[]