The compiler is a Rust library. Servers embed it and load the schema at startup, with no generated server code: change the schema, restart, done. Your services call one gRPC API through clients generated from the same schema.
The schema
pricing.usage
Structs, types, rate tables, meters, metrics, plans and tests.
usage-core
Rust compiler and engine
Exact decimals, unit checks, quotas with atomic holds.
Both servers give the same answers: the demo checks their invoices match to the cent.
Typed clients
cusage gen-client writes a method per struct, and the schema’s types and plans as types: a model the schema doesn’t sell is a compile error in Go and TypeScript and a ValueError in Python. Fields with defaults are optional.
cusage gen-client pricing.usage --lang python --out usage_client.py
cusage gen-client pricing.usage --lang go --out usage/usage.go --package usage
cusage gen-client pricing.usage --lang ts --out usage.tsconst usage = new UsageClient("localhost:50051");
// size is "512" | "1024" | "2048": any other value won't compile
await usage.imageGen("cus_acme", { size: "1024", user_id: "ben" });
const invoice = await usage.invoice("cus_acme", "starter", { start, end });Recording usage
Every struct becomes a method. Events carry an id, so a batch that’s sent twice is counted once.
Usage that already happened is always recorded, even over a limit, so invoices stay right; it shows up as over the limit. Pass enforce when the event is the work itself and it should only count if there’s room.
service.py
# One event, typed by the schema.
usage.llm_call("cus_acme", model=Model.SMALL, input_tokens=2_000, output_tokens=500, user_id="ana")
# A batch with ids: if it's sent again, it's counted once.
usage.track("cus_acme", *batch, ids=batch_ids)
# Recorded only if every limit has room, checked and recorded in one step.
usage.track("cus_acme", ApiRequest(route="/v1/chat", status=200), enforce=True)Quotas
A limit counts what is recorded in its window plus every open hold. A reservation checks and holds in one atomic step, so two callers can never both take the last unit. Holds expire (60 seconds by default, at most an hour), so a crashed service can’t keep quota, and a reserve with a hold_id is safe to retry.
Exact: reserve, do the work, commit. For seats, workspaces, API keys and spend caps. Reservations run through the schema’s own meters, so a distinct-count seat limit refuses a fifth person while four keep working.
Fast: a limiter leases a block of units and admits locally, for requests and other high-volume work. The server never leases more than is left, so the limit still holds; the gap is units sitting in other replicas’ leases.
workspaces.py · exact
# Holds a slot, or raises QuotaExceeded when the plan is full.
with usage.reserve("cus_globex", WorkspaceChange(workspace_id="ws-7", delta=1)) as slot:
provision_workspace("ws-7")
slot.commit() # if provisioning raises instead, the slot is releasedllm.py · hold the worst case, commit what happened
# An LLM call costs what it costs only afterwards: hold the most it can cost.
worst = LlmCall(model=Model.GPT_4O, input_tokens=prompt_tokens, output_tokens=max_tokens, user_id=user)
with usage.reserve(customer, worst) as hold:
reply = call_model(max_tokens=max_tokens)
hold.commit(LlmCall(model=Model.GPT_4O, input_tokens=prompt_tokens,
output_tokens=reply.output_tokens, user_id=user))gateway.ts · leased
const gate = usage.limiter(customer, {
type: "api_request", data: { route: "/v1/chat", status: 200 },
}, { lease: 50 });
// Admits from the lease: an RPC only when it runs out.
if (!(await gate.allow())) return reply.code(429).send();
gate.record({ type: "api_request", data: { route, status } });Errors and exceptions
A limit said no. QuotaExceeded in Python and TypeScript, *QuotaExceededError in Go. It carries the limits that blocked (what was used, reserved and allowed, and the window) and when to retry: retry_at, retryAt or RetryAt(), ready for a Retry-After header. A limit without a window has no retry time: only less usage frees it.
The server refused events. UsageRejected in Python, RejectedError in TypeScript and Go, with each event’s index and reason. It usually means the client and the server run different schemas.
A schema that doesn’t compile is reported like rustc does, with the place and a hint. Servers refuse to start on one, and on a failing test.
Python
try:
slot = usage.reserve("cus_globex", WorkspaceChange(workspace_id="ws-8", delta=1))
except QuotaExceeded as e:
e.blocked # the limits that said no: quantity, used, reserved, limit, window
e.retry_at # when every blocking window starts over; None if one has no window
raise HTTPException(429, str(e)) # quota exceeded for cus_globex: workspaces: 3 used + 0 reserved of 3 workspaceTypeScript
try {
await usage.track(customer, event, { enforce: true });
} catch (e) {
if (!(e instanceof QuotaExceeded)) throw e;
const wait = e.retryAt ? Math.ceil((e.retryAt.getTime() - Date.now()) / 1000) : 60;
return reply.code(429).header("Retry-After", wait).send(e.message);
}Go
var quota *nimbus.QuotaExceededError
if errors.As(err, "a) {
if at := quota.RetryAt(); !at.IsZero() {
w.Header().Set("Retry-After", strconv.Itoa(int(time.Until(at).Seconds())+1))
}
http.Error(w, quota.Error(), http.StatusTooManyRequests)
return
}error: table `input_rate` has no rate for "small"
--> pricing.usage:5:7
|
5 | table input_rate[Model]: credit/token {
| ^^^^^^^^^^
= hint: every Model needs a rate: add it, or a defaultWhat the servers answer when a call can’t be done. The messages below are the engine’s own, for the AI platform example.
| INVALID_ARGUMENT | An event or a request the schema doesn't allow.line 1: data.input_tokens must be an integer |
| INVALID_ARGUMENT | A value outside a type.line 1: data.model must be one of "gpt-4o", "claude-sonnet", "small" |
| NOT_FOUND | A plan the schema doesn't have, or a hold that expired with nothing to record.unknown plan "gold" |
| FAILED_PRECONDITION | A subject with no plan, when none is passed.cus_acme has no plan: pass one, or subscribe the subject to a plan first |
The gRPC API
Event fields travel as map<string, Value> (string, int64, decimal as a string, bool), so the server needs no code per schema. Clients send the hash of the schema they were generated from; servers log a warning on a mismatch, and GetSchema lets a client check at startup.
| RPC | Takes | What it does |
|---|---|---|
| Ingest | events, schema_hash | Validates each event against the schema. Repeated ids count as duplicates, not usage. |
| GetUsage | subject, start, end | Every meter and metric, with by breakdowns. |
| GetInvoice | subject, plan, start, end | Priced lines with a readable detail, subtotal and total. |
| GetSchema | The hash, structs, plans and a JSON description of the running schema. | |
| Subscribe | subject, plan, limits | Puts a subject on a plan, with its own caps on that plan's limits. |
| CheckLimits | subject, plan, at | Each limit's used, reserved, remaining and reset time; allowed if all have room. |
| Reserve | subject, events, count, partial, ttl, commit | Checks and holds room in one atomic step: granted, or the blocked limits. |
| Commit | hold_id, events | Records what the work did and releases the hold. |
| Release | hold_id | Gives a hold back unused. |
| Estimate | lines, plans | Prices made-up usage on each plan without recording it. |
Embedding the engine
Rust · usage-core
let schema = Schema::compile_file(&std::fs::read_to_string("pricing.usage")?, "pricing.usage")?;
let event = schema.parse_event(&json!({ "id": "e1", "type": "llm_call", "subject": "cus_acme",
"time": "2026-11-02T10:00:00Z",
"data": { "model": "gpt-4o", "input_tokens": 12000, "output_tokens": 3000, "user_id": "ana" } }))?;
let ev = schema.evaluate(&[event], Some("pro"), time::parse_ms("2026-11-01"), time::parse_ms("2026-12-01"))?;
let invoice = ev.invoice.unwrap();
println!("{} {}", invoice.money(invoice.total), invoice.currency); // 99.00 USD (the plan minimum)Go · cgo over libusage_ffi.a
schema, err := usage.Compile(string(src), "pricing.usage") // the Rust compiler, through cgo
if err != nil {
log.Fatal(err) // the same rustc-style report
}
defer schema.Close()
ev, err := schema.Evaluate(eventsJSON, "pro", "2026-11-01", "2026-12-01")
fmt.Println(ev.Invoice.Total, ev.Invoice.Currency) // 99.00 USDThe browser · usage-wasm (this website runs it)
import init, { analyze, Engine } from "./usage.js"; // scripts/wasm.sh builds it
await init();
const report = JSON.parse(analyze(source, "pricing.usage")); // diagnostics, tests, prices
const engine = new Engine(source, "pricing.usage");
const quote = JSON.parse(engine.call("estimate", JSON.stringify({ lines }), Date.now()));crates/usage-ffi/include/usage.h
A small C ABI with JSON in and out: compile, validate an event, evaluate, run tests, and a store (usage_store_call) that takes every server method, quotas included. Python ctypes, Node-API, JVM Panama and .NET P/Invoke can embed it the same way.
The command line
cusage check pricing.usage [--json] type-check and print diagnostics
cusage test pricing.usage run the schema's test blocks
cusage info pricing.usage print the compiled schema as JSON
cusage gen-client pricing.usage --lang go|python|ts --out <path> [--package <name>]
cusage scenarios pricing.usage [--scales 0.5,1,10] every test on every plan, as JSONEvery release of livesession/cusage has cusage and usage-server for macOS, Linux and Windows. Or give your agent the SKILL.md: it installs them and knows the language.