Paid, hosted product at menivor.com, now retired as a company project. Fresh squashed history of the cleaned working tree (secret-scanned, no .env, no customer data, no outreach logs). Built on MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
11 KiB
Relay Merge: TensorZero base + clean-room billing
Status date: 2026-08-19
This document records the merge that made apps/relay a TensorZero-based
inference gateway with the clean-room, success-only microdollar billing engine
grafted on. It covers what shipped, the exact hook point, the honest build
status, what remains from the clean-room source, and the next steps to finish
wiring Mint / AITP-402.
1. What apps/relay now is
apps/relay is now the upstream TensorZero gateway/workspace, licensed
Apache-2.0 (apps/relay/LICENSE). It is the real product base: the Cargo
workspace root is apps/relay/crates, and all cargo commands run from there
(per apps/relay/AGENTS.md). The gateway binary lives in
apps/relay/crates/gateway, alongside the full TensorZero crate set
(tensorzero-core, tensorzero-auth, tensorzero-mcp, etc.).
Onto this base we grafted a single new workspace member — the billing engine —
plus a thin, additive middleware in the gateway. Nothing in tensorzero-core
was modified; the graft is deliberately least-invasive.
2. The ported billing crate
- Name:
relay-billing - Path:
apps/relay/crates/relay-billing - License: Apache-2.0 (matches the TensorZero base)
- Workspace registration: already present in
apps/relay/crates/Cargo.toml[workspace].membersas"relay-billing".
It is a self-contained consolidation of the clean-room relay-core,
relay-store, and relay-billing crates into ONE crate, so the graft adds a
single member with zero coupling to TensorZero internals. Modules:
money.rs—Microsinteger-microdollar newtype (ADR-0001: no float in the money path; checked arithmetic).domain.rs/usage.rs/error.rs— frozen shared vocabulary (AccountId,JobId,ModelId,Usage,BillingError, ...).store/{mod.rs,records.rs,error.rs}— the asyncStoretrait (the single persistence seam) plus a pureInMemoryStoretest double.ledger.rs— theLedgerreserve → settle/release engine (ADR-0002: success-only;settleis the ONLY debit path; failure nets exactly zero).
Public API (re-exported from lib.rs)
- Domain:
AccountId,ChatMessage,JobId,KeyId,ModelId,Role,OPENROUTER_PREFIX - Errors:
BillingError,ProviderError,RelayError,Result - Ledger:
Ledger,Reservation,cost_micros - Money:
Micros,usd_to_micros,MICROS_PER_USD - Store:
Store,InMemoryStore,KeyStore,LedgerStore,LedgerEntry,LedgerKind,ReserveOutcome,UsageStore,UsageRecord,StoredApiKey,StoreError,Timestamp,now_ms - Usage:
Usage
Ledger surface: new(Arc<dyn Store>), available_micros, reserve,
settle, release (plus debit_on_success).
Note:
relay-billing/Cargo.tomldeclaresuuiddirectly with thev4feature rather than inheriting the workspaceuuid(which only enablesv7), because the ledger mintsUuid::new_v4. Inheriting the workspace dependency would fail to compile.
3. The exact gateway hook point
Hook site: apps/relay/crates/gateway/src/router.rs : build_axum_router
(the billing layer is added at the if crate::billing::billing_enabled() block,
around lines 83–98).
Middleware implementation:
apps/relay/crates/gateway/src/billing.rs : billing_middleware.
Supporting call-site wiring (all present and correct):
apps/relay/crates/gateway/src/main.rs—mod billing;(line 39).apps/relay/crates/gateway/Cargo.toml—relay-billing = { path = "../relay-billing" }(line 12).router.rs— builds anInMemoryStore-backedLedger, wraps it inBillingState, and layersmiddleware::from_fn_with_state(billing_state, billing_middleware)inside the auth layer.
Layering (why "inside the auth layer")
Axum's .layer composes inner-to-outer, so the billing layer is added to the
router before the auth layer in source order, which makes auth run first
at request time. By the time billing_middleware runs, the authenticated
API-key identity (tensorzero_auth::middleware::RequestApiKeyExtension) is
already in the request extensions, and the middleware resolves the billing
AccountId from key_info.public_id. Unauthenticated requests and
non-inference routes pass straight through untouched.
Hold → capture/release, success-only flow
Billable paths are the inference-shaped routes only: */inference,
*/chat/completions, */completions, */responses. For those:
- HOLD.
Ledger::reserve(account, estimate, job)places an estimate hold before any upstream call. OnBillingError::InsufficientCreditsthe middleware short-circuits402 Payment Requiredand the model is never invoked.JobIdkeys idempotency, so a retry cannot double-charge. - Run the real handler (
next.run(request)), guarded by an RAIIHoldGuardarmed atreserve(). If the handler panics/unwinds, the guard drops and releases the hold (no leak). It is disarmed the instant the handler returns normally, after which every terminal path is explicit. - Terminal action (success-only):
- Non-2xx / transport failure →
releasethe hold in full. A failed job costs exactly zero (ADR-0002). - Non-streaming 2xx →
capture_non_streaming: checkContent-Lengthfirst (bodies overMAX_CAPTURE_BODY_BYTES= 16 MiB are forwarded untouched, hold released, no charge; an undeclared-length body that blows the cap while reading returns an explicit502 billing_capture_errorrather than a truncated 2xx). Otherwise buffer, parse theusageobject, andsettlethe EXACT actual cost in integer microdollars — never the estimate. Ifsettleerrors, it logs andreleases as a terminal-idempotent fallback so the hold nets to zero. - Streaming 2xx (SSE) → wrap the body in a
StreamCarryDrop guard (GuardedBody) that parses SSE event frames as bytes flow to the client, extracting the terminalusageframe (treating"usage": nullas "no usage" so intermediate chunks never settle a zero placeholder). On stream end/drop: if a usage frame was observed,settle_holdsettles the exact actual cost; if none was seen (aborted/errored stream),releasethe hold. So streaming success is billed and an aborted stream still costs zero.
- Non-2xx / transport failure →
Cost model today (EstimatePolicy::default): $0.10 hold, ~$0.000003/input
token, ~$0.000015/output token. A later phase can make this model-aware via a
price table keyed on ModelId.
Safety gate (default OFF)
The entire billing layer is gated behind crate::billing::billing_enabled()
(env RELAY_BILLING_ENABLED, accepts 1|true|TRUE|yes|YES), default OFF.
The Ledger is currently backed by an in-memory, per-process, UNFUNDED
InMemoryStore. If it were live by default it would reject every authenticated
inference request with 402 (there is no deposit path yet), lose all holds on
restart, and keep an independent balance per replica. With the gate OFF, the
empty store is never in the money path. When explicitly opted in, a
tracing::warn documents that balances must be seeded and holds do not survive
a restart, and directs wiring a durable/funded Store behind the same Ledger
trait before production or multi-replica use.
4. Clean-room source retirement
The former apps/relay-cleanroom workspace was removed on 2026-08-22. Its
product-specific billing lineage (relay-core, relay-store, and
relay-billing) had already been consolidated into
apps/relay/crates/relay-billing; TensorZero supplies the active auth/key,
normalization, provider-proxy, streaming-usage, and server implementations.
This document retains the provenance and merge decisions without keeping a
second inactive Rust workspace in the product tree.
5. Honest build status
Verified on 2026-08-19 from apps/relay/crates (the real workspace root):
relay-billingcrate: compiles.relay-billingtests: pass —cargo test -p relay-billing→ 45 passed, 0 failed (plus 0 doc-tests).- Gateway full build: builds —
cargo check -p gatewayexits 0.- This is NOT env-limited for Rust. The only output is non-fatal build-script
warnings from
tensorzero-ts-types(tsc/pnpmnot installed), which affect optional TypeScript bundle validation only — not the Rust compile.
- This is NOT env-limited for Rust. The only output is non-fatal build-script
warnings from
- Hook wiring present and correct:
mod billing;inmain.rs,relay-billingpath dep ingateway/Cargo.toml, and theInMemoryStore-backedLedger+BillingStatelayered inside the auth layer inrouter.rs.
Findings fixed during the graft (in billing.rs / router.rs)
- router.rs (critical ×2 + high): gated the whole billing layer behind
billing_enabled()(default OFF) so the empty/unfunded per-process store is never in the live money path — eliminating a402inference outage; opt-in emits atracing::warnand the comment directs wiring a durable/funded store. - capture settle-swallow (high):
settleerrors now log andreleaseas a terminal-idempotent fallback instead oflet _ = settle(...). - RAII panic-safety (high):
HoldGuardreleases the hold on handler panic/unwind; disarmed on normal return. - oversized body (high):
Content-Lengthchecked before consuming; oversized bodies forwarded untouched (hold released); undeclared-length overflow returns an explicit502instead of an empty 2xx. - streaming never-settled (high ×2):
GuardedBodyparses the SSE stream and settles the exact actual on stream end (viasettle_hold), releasing only when no usage was seen;"usage": nullis treated as None.
6. What is done vs pending
Done: billing engine ported and tested; gateway hook wired and building; hold→capture/release success-only lifecycle implemented with panic-safety, streaming settlement, and oversized-body handling; safety gate default-OFF.
Pending: everything below in "Next steps" — there is no funding/deposit path, no durable store, no Mint/AITP-402 wiring yet. Billing is a working seam, not a live billed money path.
7. Next steps — finish wiring Mint / AITP-402
- Durable, funded
Store. Implement a Postgres/ClickHouse-backedStore(the same traitInMemoryStoreimplements) and construct theLedgerfrom it inrouter.rs. No change needed inbilling.rs. - Funding / deposit path (Mint). Add the credit/deposit flow that seeds
account balances (
Ledgerdebit/credit into the store) so authenticated inference does not universally402. This is the prerequisite for turningRELAY_BILLING_ENABLEDon. - AITP-402 payment challenge. Extend the
402 Payment Requiredshort-circuit inbilling.rs(payment_required()) to emit the AITP-402 payment challenge envelope (payment requirements/quote) instead of a bare error JSON, and accept the corresponding payment proof header to top up / reserve. - Model-aware pricing. Replace the flat
EstimatePolicywith a price table keyed onModelIdfor both the hold estimate and the settle rate. - Enable + verify. Turn on
RELAY_BILLING_ENABLEDagainst the durable funded store, verify hold→settle for non-streaming and streaming,402on insufficient credits, and zero-cost on failure/abort; then remove the interim in-memory warning. - Persistence tests for the durable store impl and end-to-end gateway tests
through the middleware (funded success, insufficient-credit
402, failure release, streaming settle).