Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(pricing): account for cache writes separately

Rach Pradhan2bf45f17c9fd
diff --git a/src/agent_context.zig b/src/agent_context.zig
index 7d232c84..619cfd8d 100644
--- a/src/agent_context.zig
+++ b/src/agent_context.zig
@@ -131,9 +131,9 @@ pub fn recordUsage(self: *Agent, root: std.json.ObjectMap, req_body_len: usize)
floorContextTokens(self, fallback);
self.last_usage_includes_output = total > 0 and if (u.get("output_tokens")) |v| v == .integer and v.integer >= 0 else false;
const cache = usageInt(u, "cache_read_input_tokens");
+ const cache_write = usageInt(u, "cache_creation_input_tokens");
if (cache > 0) self.last_cache_read = @intCast(cache);
- // cache writes bill ~like input; fold them into uncached input.
- self.recordCost(usageInt(u, "input_tokens") +| usageInt(u, "cache_creation_input_tokens"), cache, usageInt(u, "output_tokens"));
+ self.recordCost(usageInt(u, "input_tokens"), cache, cache_write, usageInt(u, "output_tokens"));
},
.openai => {
const total = usageInt(u, "total_tokens");
@@ -148,11 +148,13 @@ pub fn recordUsage(self: *Agent, root: std.json.ObjectMap, req_body_len: usize)
// deepseek reports prompt_cache_hit_tokens; the OpenAI shape
// nests cached_tokens under prompt_tokens_details.
var cache = usageInt(u, "prompt_cache_hit_tokens");
- if (cache == 0) if (u.get("prompt_tokens_details")) |d| if (d == .object) {
- cache = usageInt(d.object, "cached_tokens");
+ var cache_write: i64 = 0;
+ if (u.get("prompt_tokens_details")) |d| if (d == .object) {
+ if (cache == 0) cache = usageInt(d.object, "cached_tokens");
+ cache_write = usageInt(d.object, "cache_write_tokens");
};
if (cache > 0) self.last_cache_read = @intCast(cache);
- self.recordCost(@max(usageInt(u, "prompt_tokens") - cache, 0), cache, usageInt(u, "completion_tokens"));
+ self.recordCost(@max(usageInt(u, "prompt_tokens") - cache - cache_write, 0), cache, cache_write, usageInt(u, "completion_tokens"));
},
// codex uses recordUsageResponses on its own path.
.responses => {},
@@ -188,8 +190,8 @@ pub fn usageInt(obj: std.json.ObjectMap, name: []const u8) i64 {
/// #471: the seat is classified from the provider AND how its credential was
/// obtained — a flat-rate login (codex/kimi/xai) tallies as sub_calls and adds
/// $0, while an env key on that same provider is metered like any other.
-pub fn recordCost(self: *Agent, uncached_in: i64, cache_in: i64, out: i64) void {
- g_cost.add(self.io, billing.forProvider(self.provider), self.provider.model, uncached_in, cache_in, out);
+pub fn recordCost(self: *Agent, ordinary_in: i64, cache_in: i64, cache_write_in: i64, out: i64) void {
+ g_cost.add(self.io, billing.forProvider(self.provider), self.provider.model, ordinary_in, cache_in, cache_write_in, out);
}
/// #174: ~4-bytes/token estimate of the FULL history serialized as Responses
@@ -477,11 +479,13 @@ pub fn recordUsageResponses(self: *Agent, response: std.json.ObjectMap, req_body
// backend rejects the resend for exceeding the window, and auto-compaction
// (gated on this meter) never rescues it.
var cached: i64 = 0;
+ var cache_write: i64 = 0;
if (u.get("input_tokens_details")) |d| if (d == .object) {
cached = usageInt(d.object, "cached_tokens");
+ cache_write = usageInt(d.object, "cache_write_tokens");
if (cached > 0) self.last_cache_read = @intCast(cached);
};
- self.recordCost(@max(in_tokens - cached, 0), cached, out_tokens);
+ self.recordCost(@max(in_tokens - cached - cache_write, 0), cached, cache_write, out_tokens);
}
test "recordUsageResponses: usage fallbacks never lower an authoritative meter" {
diff --git a/src/obs_cost_test.zig b/src/obs_cost_test.zig
index 6de78cc8..cf070aa0 100644
--- a/src/obs_cost_test.zig
+++ b/src/obs_cost_test.zig
@@ -15,6 +15,7 @@ fn resetCost(io: Io) void {
c.usd = 0;
c.in_tokens = 0;
c.cache_tokens = 0;
+ c.cache_write_tokens = 0;
c.out_tokens = 0;
c.api_calls = 0;
c.sub_calls = 0;
@@ -39,7 +40,7 @@ test "usage/debug match the cost-tally renderer and add turn/decision extras" {
defer obs.reset();
obs.attach(io);
- pricing.g_cost.add(io, .priced, "gpt-5.5", 1000, 200, 50);
+ pricing.g_cost.add(io, .priced, "gpt-5.5", 1000, 200, 0, 50);
obs.turn(.completed);
obs.note(.{ .tool_rejected = .{
.name = "mcp__github__create_issue",
@@ -74,8 +75,8 @@ test "usage/debug match the cost-tally renderer and add turn/decision extras" {
try std.testing.expect(!contains(debug, "create_issue"));
try std.testing.expect(contains(debug, "mcp_tool"));
- pricing.g_cost.add(io, .sub, "gpt-5.5", 10, 0, 10);
- pricing.g_cost.add(io, .unpriced, "no-such-model", 10, 0, 10);
+ pricing.g_cost.add(io, .sub, "gpt-5.5", 10, 0, 0, 10);
+ pricing.g_cost.add(io, .unpriced, "no-such-model", 10, 0, 0, 10);
var cost2_buf: [384]u8 = undefined;
const cost2 = renderCost(io, &cost2_buf);
try std.testing.expect(contains(cost2, "subscription"));
@@ -120,7 +121,7 @@ test "live emit path fills HUD and OTLP like a real turn" {
const sink = engine_sink.writerSink(null);
sink.emit(io, .{ .session_banner = .{ .cwd = "/Users/secret/repo", .trace_path = "/tmp/trace.jsonl" } });
obs.prompt(11, "gpt-5.5");
- pricing.g_cost.add(io, .priced, "gpt-5.5", 1000, 200, 50);
+ pricing.g_cost.add(io, .priced, "gpt-5.5", 1000, 200, 0, 50);
sink.emit(io, .{ .tool_call_started = .{ .name = "bash", .input = .null } });
sink.emit(io, .{ .tool_call_finished = .{ .name = "bash", .text = "cat /etc/passwd", .is_error = false, .ms = 12 } });
obs.turn(.completed);
diff --git a/src/pricing.zig b/src/pricing.zig
index e454fdec..f33178bf 100644
--- a/src/pricing.zig
+++ b/src/pricing.zig
@@ -70,17 +70,10 @@ pub fn priceFor(model: []const u8) ?ModelPrice {
/// credential source, neither of which belongs in a price sheet.
pub const Billing = enum { sub, priced, unpriced };
-/// USD for one request at price `p` (negative token counts clamp to 0).
-/// When `high_at` is set and prompt tokens (uncached+cached) meet it, the
-/// whole request uses the high band — grok-4.6's published ≥200k rates.
+pub const usdForUsage = @import("pricing_cache.zig").usdForUsage;
+
pub fn usdFor(p: ModelPrice, uncached_in: i64, cache_in: i64, out: i64) f64 {
- const ui = @max(uncached_in, 0);
- const ci = @max(cache_in, 0);
- const high = p.high_at > 0 and @as(u64, @intCast(ui)) +| @as(u64, @intCast(ci)) >= p.high_at;
- const fi: f64 = @floatFromInt(ui);
- const fc: f64 = @floatFromInt(ci);
- const fo: f64 = @floatFromInt(@max(out, 0));
- return (fi * (if (high) p.high_in else p.in) + fc * (if (high) p.high_cache else p.cache) + fo * (if (high) p.high_out else p.out)) / 1_000_000.0;
+ return usdForUsage(p, "", uncached_in, cache_in, 0, out);
}
/// Session-wide usage/cost tally. Every API response lands here — the root
@@ -92,8 +85,9 @@ pub fn usdFor(p: ModelPrice, uncached_in: i64, cache_in: i64, out: i64) f64 {
pub const CostTally = struct {
mutex: Io.Mutex = .init,
usd: f64 = 0,
- in_tokens: u64 = 0, // uncached input
+ in_tokens: u64 = 0, // ordinary + cache-write input
cache_tokens: u64 = 0, // cache-read input
+ cache_write_tokens: u64 = 0,
out_tokens: u64 = 0,
api_calls: u64 = 0,
sub_calls: u64 = 0, // subscription-billed (flat-rate; contribute $0)
@@ -102,19 +96,20 @@ pub const CostTally = struct {
/// `billing` is the caller's already-classified seat (billing.forSeat): a
/// flat-rate login and a metered env key on the SAME provider+model are
/// different classes, so the tally cannot derive it itself (#471).
- pub fn add(self: *CostTally, io: Io, billing: Billing, model: []const u8, uncached_in: i64, cache_in: i64, out: i64) void {
+ pub fn add(self: *CostTally, io: Io, billing: Billing, model: []const u8, ordinary_in: i64, cache_in: i64, cache_write_in: i64, out: i64) void {
self.mutex.lockUncancelable(io);
defer self.mutex.unlock(io);
self.api_calls +|= 1;
- self.in_tokens +|= @intCast(@max(uncached_in, 0));
+ self.in_tokens +|= @intCast(@max(ordinary_in, 0) +| @max(cache_write_in, 0));
self.cache_tokens +|= @intCast(@max(cache_in, 0));
+ self.cache_write_tokens +|= @intCast(@max(cache_write_in, 0));
self.out_tokens +|= @intCast(@max(out, 0));
switch (billing) {
.sub => self.sub_calls +|= 1,
.unpriced => self.unpriced_calls +|= 1,
// No `.?`: the class comes from the caller; a dropped row falls back.
.priced => {
- if (priceFor(model)) |p| self.usd += usdFor(p, uncached_in, cache_in, out) else self.unpriced_calls +|= 1;
+ if (priceFor(model)) |p| self.usd += usdForUsage(p, model, ordinary_in, cache_in, cache_write_in, out) else self.unpriced_calls +|= 1;
},
}
}
@@ -130,8 +125,8 @@ pub const CostTally = struct {
/// One-line summary shared by /cost and the one-shot stderr report.
pub fn render(c: CostTally, w: *Io.Writer) !void {
- try w.print("{d} api call(s) · {d} in ({d} cached) + {d} out tokens · ${d:.4}", .{
- c.api_calls, c.in_tokens +| c.cache_tokens, c.cache_tokens, c.out_tokens, c.usd,
+ try w.print("{d} api call(s) · {d} in ({d} cached, {d} cache writes) + {d} out tokens · ${d:.4}", .{
+ c.api_calls, c.in_tokens +| c.cache_tokens, c.cache_tokens, c.cache_write_tokens, c.out_tokens, c.usd,
});
if (c.sub_calls > 0) try w.print(" · {d} subscription call(s), flat-rate (not in $)", .{c.sub_calls});
if (c.unpriced_calls > 0) try w.print(" · {d} call(s) on unpriced models", .{c.unpriced_calls});
diff --git a/src/pricing_cache.zig b/src/pricing_cache.zig
new file mode 100644
index 00000000..225441bb
--- /dev/null
+++ b/src/pricing_cache.zig
@@ -0,0 +1,21 @@
+//! Cache-aware token pricing kept separate from the model catalog and tally.
+
+const std = @import("std");
+
+/// USD for one request (negative token counts clamp to zero). Cache writes are
+/// separate from ordinary input: GPT-5.6 and Anthropic ephemeral caches bill
+/// writes at 1.25× the ordinary input rate.
+pub fn usdForUsage(p: anytype, model: []const u8, ordinary_in: i64, cache_in: i64, cache_write_in: i64, out: i64) f64 {
+ const ui = @max(ordinary_in, 0);
+ const ci = @max(cache_in, 0);
+ const wi = @max(cache_write_in, 0);
+ const prompt: u64 = @as(u64, @intCast(ui)) +| @as(u64, @intCast(ci)) +| @as(u64, @intCast(wi));
+ const high = p.high_at > 0 and prompt >= p.high_at;
+ const input_rate = if (high) p.high_in else p.in;
+ const write_multiplier: f64 = if (std.mem.startsWith(u8, model, "gpt-5.6") or std.mem.startsWith(u8, model, "claude-")) 1.25 else 1.0;
+ const fi: f64 = @floatFromInt(ui);
+ const fc: f64 = @floatFromInt(ci);
+ const fw: f64 = @floatFromInt(wi);
+ const fo: f64 = @floatFromInt(@max(out, 0));
+ return (fi * input_rate + fc * (if (high) p.high_cache else p.cache) + fw * input_rate * write_multiplier + fo * (if (high) p.high_out else p.out)) / 1_000_000.0;
+}
diff --git a/src/pricing_tests.zig b/src/pricing_tests.zig
index 4b2c34b8..9f4f20a1 100644
--- a/src/pricing_tests.zig
+++ b/src/pricing_tests.zig
@@ -8,13 +8,15 @@ test "CostTally token and call counters saturate" {
var tally: pricing.CostTally = .{
.in_tokens = std.math.maxInt(u64) - 1,
.cache_tokens = std.math.maxInt(u64),
+ .cache_write_tokens = std.math.maxInt(u64),
.out_tokens = std.math.maxInt(u64) - 2,
.api_calls = std.math.maxInt(u64),
.sub_calls = std.math.maxInt(u64),
};
- tally.add(std.testing.io, .sub, "gpt-5.5", 10, 10, 10);
+ tally.add(std.testing.io, .sub, "gpt-5.5", 10, 10, 10, 10);
try std.testing.expectEqual(std.math.maxInt(u64), tally.in_tokens);
try std.testing.expectEqual(std.math.maxInt(u64), tally.cache_tokens);
+ try std.testing.expectEqual(std.math.maxInt(u64), tally.cache_write_tokens);
try std.testing.expectEqual(std.math.maxInt(u64), tally.out_tokens);
try std.testing.expectEqual(std.math.maxInt(u64), tally.api_calls);
try std.testing.expectEqual(std.math.maxInt(u64), tally.sub_calls);
@@ -50,12 +52,14 @@ test "resolveModelName (#377): family-prefixed spelling resolves to the provider
try std.testing.expect(!pricing.familyAliasEquals("codex", "k3", "kimi-k3"));
}
-test "usdFor: per-million math and negative clamping" {
+test "usdFor: per-million math, cache writes, and negative clamping" {
const p = pricing.priceFor("gpt-5.5").?; // $5 in / $30 out / $0.5 cache per 1M
try std.testing.expectApproxEqAbs(@as(f64, 5.0), pricing.usdFor(p, 1_000_000, 0, 0), 1e-9);
try std.testing.expectApproxEqAbs(@as(f64, 0.5), pricing.usdFor(p, 0, 1_000_000, 0), 1e-9);
try std.testing.expectApproxEqAbs(@as(f64, 3.0), pricing.usdFor(p, 0, 0, 100_000), 1e-9);
try std.testing.expectApproxEqAbs(@as(f64, 0.0), pricing.usdFor(p, -42, -1, 0), 1e-9); // clamped
+ const p56 = pricing.priceFor("gpt-5.6").?;
+ try std.testing.expectApproxEqAbs(@as(f64, 6.25), pricing.usdForUsage(p56, "gpt-5.6", 0, 0, 1_000_000, 0), 1e-9);
}
test "grok-4.6 window is 500k and compact-at is 80%" {
diff --git a/src/tui_launch.zig b/src/tui_launch.zig
index bd86e9a1..89036361 100644
--- a/src/tui_launch.zig
+++ b/src/tui_launch.zig
@@ -381,6 +381,7 @@ test "hudCb usage/debug use the cost-tally renderer, not chars" {
c.usd = 0;
c.in_tokens = 0;
c.cache_tokens = 0;
+ c.cache_write_tokens = 0;
c.out_tokens = 0;
c.api_calls = 0;
c.sub_calls = 0;
@@ -400,7 +401,7 @@ test "hudCb usage/debug use the cost-tally renderer, not chars" {
obs.reset();
defer obs.reset();
obs.attach(io);
- pricing.g_cost.add(io, .priced, "gpt-5.5", 1000, 200, 50);
+ pricing.g_cost.add(io, .priced, "gpt-5.5", 1000, 200, 0, 50);
obs.turn(.completed);
var cost_buf: [256]u8 = undefined;
diff --git a/src/usage_attribution_tests.zig b/src/usage_attribution_tests.zig
index 2cecc311..589d4d8e 100644
--- a/src/usage_attribution_tests.zig
+++ b/src/usage_attribution_tests.zig
@@ -159,15 +159,16 @@ test "#418: parent context is identical with and without an attributed child; on
// The BILL: the run-wide tally moved by EXACTLY the children's usage.
const cost_after = pricing.g_cost.snap(io);
try std.testing.expectEqual(cost_before.api_calls + fleet_size, cost_after.api_calls);
- // recordUsage folds anthropic cache WRITES into uncached input; cache
- // READS bill on their own line.
+ // Cache writes remain part of total non-read input, while their dedicated
+ // counter and 1.25× price stay visible; cache reads bill on their own line.
const billed_in: u64 = @intCast(child_sample.input + child_sample.cache_write);
const billed_cache: u64 = @intCast(child_sample.cache_read);
const billed_out: u64 = @intCast(child_sample.output);
try std.testing.expectEqual(cost_before.in_tokens + fleet_size * billed_in, cost_after.in_tokens);
try std.testing.expectEqual(cost_before.cache_tokens + fleet_size * billed_cache, cost_after.cache_tokens);
+ try std.testing.expectEqual(cost_before.cache_write_tokens + fleet_size * @as(u64, @intCast(child_sample.cache_write)), cost_after.cache_write_tokens);
try std.testing.expectEqual(cost_before.out_tokens + fleet_size * billed_out, cost_after.out_tokens);
- const per_child = pricing.usdFor(pricing.priceFor(child_model).?, child_sample.input + child_sample.cache_write, child_sample.cache_read, child_sample.output);
+ const per_child = pricing.usdForUsage(pricing.priceFor(child_model).?, child_model, child_sample.input, child_sample.cache_read, child_sample.cache_write, child_sample.output);
try std.testing.expect(per_child > 0); // the assertion below is only worth anything if the model is priced
try std.testing.expectApproxEqAbs(cost_before.usd + @as(f64, @floatFromInt(fleet_size)) * per_child, cost_after.usd, 1e-9);
}