videogen/docs/relay/MERGE.md
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
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.
2026-12-04 02:10:26 +03:00

215 lines
11 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 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].members` as `"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` — `Micros` integer-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 async `Store` trait (the single
persistence seam) plus a pure `InMemoryStore` test double.
- `ledger.rs` — the `Ledger` reserve → settle/release engine (ADR-0002:
success-only; `settle` is 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.toml` declares `uuid` directly with the `v4`
> feature rather than inheriting the workspace `uuid` (which only enables `v7`),
> because the ledger mints `Uuid::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 an `InMemoryStore`-backed `Ledger`, wraps it in
`BillingState`, and layers `middleware::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:
1. **HOLD.** `Ledger::reserve(account, estimate, job)` places an estimate hold
before any upstream call. On `BillingError::InsufficientCredits` the
middleware short-circuits **`402 Payment Required`** and the model is never
invoked. `JobId` keys idempotency, so a retry cannot double-charge.
2. **Run** the real handler (`next.run(request)`), guarded by an RAII
`HoldGuard` armed at `reserve()`. 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.
3. **Terminal action (success-only):**
- **Non-2xx / transport failure →** `release` the hold in full. A failed job
costs exactly zero (ADR-0002).
- **Non-streaming 2xx →** `capture_non_streaming`: check `Content-Length`
first (bodies over `MAX_CAPTURE_BODY_BYTES` = 16 MiB are forwarded
untouched, hold released, no charge; an undeclared-length body that blows
the cap while reading returns an explicit `502 billing_capture_error`
rather than a truncated 2xx). Otherwise buffer, parse the `usage` object,
and `settle` the EXACT actual cost in integer microdollars — never the
estimate. If `settle` errors, it logs and `release`s as a
terminal-idempotent fallback so the hold nets to zero.
- **Streaming 2xx (SSE) →** wrap the body in a `StreamCarry` Drop guard
(`GuardedBody`) that parses SSE event frames as bytes flow to the client,
extracting the terminal `usage` frame (treating `"usage": null` as "no
usage" so intermediate chunks never settle a zero placeholder). On stream
end/drop: if a usage frame was observed, `settle_hold` settles the exact
actual cost; if none was seen (aborted/errored stream), `release` the hold.
So streaming success is billed and an aborted stream still costs zero.
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-billing` crate: compiles.**
- **`relay-billing` tests: pass** — `cargo test -p relay-billing` → 45 passed,
0 failed (plus 0 doc-tests).
- **Gateway full build: builds** — `cargo check -p gateway` **exits 0**.
- This is NOT env-limited for Rust. The only output is non-fatal build-script
**warnings** from `tensorzero-ts-types` (`tsc`/`pnpm` not installed), which
affect optional TypeScript bundle validation only — not the Rust compile.
- **Hook wiring present and correct:** `mod billing;` in `main.rs`,
`relay-billing` path dep in `gateway/Cargo.toml`, and the `InMemoryStore`-backed
`Ledger` + `BillingState` layered inside the auth layer in `router.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 a `402` inference outage; opt-in
emits a `tracing::warn` and the comment directs wiring a durable/funded store.
- **capture settle-swallow (high):** `settle` errors now log and `release` as a
terminal-idempotent fallback instead of `let _ = settle(...)`.
- **RAII panic-safety (high):** `HoldGuard` releases the hold on handler
panic/unwind; disarmed on normal return.
- **oversized body (high):** `Content-Length` checked before consuming; oversized
bodies forwarded untouched (hold released); undeclared-length overflow returns
an explicit `502` instead of an empty 2xx.
- **streaming never-settled (high ×2):** `GuardedBody` parses the SSE stream and
settles the exact actual on stream end (via `settle_hold`), releasing only when
no usage was seen; `"usage": null` is 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
1. **Durable, funded `Store`.** Implement a Postgres/ClickHouse-backed `Store`
(the same trait `InMemoryStore` implements) and construct the `Ledger` from
it in `router.rs`. No change needed in `billing.rs`.
2. **Funding / deposit path (Mint).** Add the credit/deposit flow that seeds
account balances (`Ledger` debit/credit into the store) so authenticated
inference does not universally `402`. This is the prerequisite for turning
`RELAY_BILLING_ENABLED` on.
3. **AITP-402 payment challenge.** Extend the `402 Payment Required` short-circuit
in `billing.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.
4. **Model-aware pricing.** Replace the flat `EstimatePolicy` with a price table
keyed on `ModelId` for both the hold estimate and the settle rate.
5. **Enable + verify.** Turn on `RELAY_BILLING_ENABLED` against the durable
funded store, verify hold→settle for non-streaming and streaming, `402` on
insufficient credits, and zero-cost on failure/abort; then remove the interim
in-memory warning.
6. **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).