Skip to content

Durable receipts

Last updated: 2026-11-23T09:00:15-03:00 (UTC-3)

Normal usage recording is best effort: if the database fails midway, an event can be lost. With durable receipts, the gateway writes a receipt to PostgreSQL before calling the provider. If it cannot write it, it does not call: it responds 503. Every call that went out to the provider therefore has a record. Flag: durable_usage, which requires usage_analytics and PostgreSQL.

Receipts are the foundation of budgets and TPM, which depend on knowing, with certainty, what was sent.

  1. The key is authenticated and authorized (scopes, team policy, RPM, model).
  2. The gateway writes the receipt and only then checks the cache or calls the provider. The response carries the ID in X-Gateway-Usage-Receipt.
  3. When the response ends, the receipt and the usage event are finalized together, in one transaction.
State Meaning
pending The request was accepted; the final outcome has not been recorded yet
completed The gateway recorded the final observation. It does not mean HTTP success or a reconciled charge
indeterminate The outcome could not be proven (crash, cancellation, a stream with no recognized end). It does not mean the provider did not process it

The receipt stores identities, team, route, alias, correlation IDs, timestamps and state; after the end, the provider, status and reported counters. It does not store the prompt, the response, authorization headers or credentials.

  • Each request has its own internal ID: the same X-Request-Id can appear in several receipts.
  • Finalizing twice with the same data does not duplicate the event; divergent data is rejected.
  • In streams, the gateway recognizes the end event of Chat, Messages, Responses and Gemini. Without a recognized end, the receipt stays indeterminate, and the content is still delivered.
  • Once the provider’s answer has ended (the recognized end event of a stream, or the end of a JSON body), a client that disconnects or stops reading does not make the receipt indeterminate: the provider’s outcome is already known. A disconnect before that end does.

A realtime session has one receipt per response, not one per session:

  • The receipt is written when the response is admitted (on the client’s response.create, or on response.created for a response the provider starts by itself), before the request reaches the provider. If it cannot be written, the response is refused with an error event (durable_usage_unavailable) and the session stays open.
  • It is completed on response.done, with the reported usage, whatever the response’s status (completed, cancelled, failed, incomplete). A response.done whose counters cannot be validated makes it indeterminate.
  • A response still running when the session ends (client disconnect, provider close, session ceiling, drain, emergency stop) makes it indeterminate, and its budget reservation stays held.
  • A response the provider refused before starting (an error naming the event_id of the response.create) is completed with status 400 and no tokens.
  • Every receipt of a session carries the upgrade’s request_id; the upgrade itself has no receipt, since nothing is billed until a response starts.

A live operation owns its pending receipt. Each replica tracks its active request contexts and, for Realtime, each unfinished response. The receipt follows that actual lifecycle; it has no second timer based on the alias’s ordinary request_timeout. Renewal does not extend the operation’s own timeout. Opt-in stream clocks can allow a healthy stream beyond ordinary request_timeout; its receipt still follows that actual context, with no second deadline or replay. Timeout classification does not by itself prove a charge or make an incomplete outcome complete.

  • The existing lease is 5 minutes; the replica renews its active pending receipts every one-third of that lease (100 seconds), in bounded batches of up to 1,000. It renews before the worker’s initial recovery pass.
  • Recovery still runs every 30 seconds on each replica, in batches of up to 500.
  • Only pending rows renew. A completed or recovered receipt is never revived by a heartbeat, and final observations/fingerprints are not rewritten.
  • Normal completion, actual context cancellation and Realtime response/session termination release local ownership. Cleanup also runs if finalization fails, recording is bypassed or a panic unwinds the handler. An already-running renewal may finish after release, so abandonment is measured from the last successful renewal, not exactly from disconnect.
  • A pending receipt whose lease expired without a final observation becomes indeterminate in a recovery pass. An active stream can therefore outlive five minutes when its heartbeats succeed; a crashed replica stops renewing. Nothing is ever resent to the provider.
  • If the database goes down after the send, the response is still delivered to the client; renewal/finalization may fail and recovery conservatively marks an expired unproven outcome indeterminate. A late original final observation still uses the existing idempotent finalization.
  • Turning off the flag makes new requests go back to best-effort mode; recovery of the old ones continues.

Use the receipt’s internal ID together with its request_id and trace_id; a repeated client request ID is not a unique receipt. A receipt older than five minutes can be legitimately pending while its handler or Realtime response is still active. Investigate durable_lease_renew_failed, database connectivity and worker shutdown before concluding that it was abandoned. The recovery state alone does not establish whether the provider charged and must never trigger inference replay or release an unknown budget reservation; use the separate financial proof/reconciliation.

Without it, a request protected by a budget or TPM limit makes three separate durable commits after the provider answers: the quota measurement, the quota settlement and the receipt’s finalization. Each has its own timeout, and a failure between them leaves one side recorded: the budget charged with no usage event, or a usage event whose reservation stays reserved until a manual reconciliation.

Flag: single_charge_settlement (operator control, off by default; requires budget_limits or tpm_limits, and the usage and quota stores on the same PostgreSQL). With it on:

  • The receipt carries its reservation. When the request is admitted under a quota reservation, the receipt is written with that reservation’s ID, and the usage event repeats it (quota_reservation_id). The link is part of the receipt’s captured identity: a final event that names another reservation is refused. An asynchronous video job is not linked; it still settles at its terminal proof.
  • One transaction. When the answer ends, the measurement, the settlement of every counter of the reservation (team, key, end user, group, global, provider, customer organizations, teams, members and their per-model allowances), the usage event, its valuation and the receipt commit together, or none of them does. The settlement decision is the same as without the flag: the approved rate captured at admission, unknown when the answer does not prove a priced measurement, released when no provider attempt started.
  • Refusals do not lose the observation. A measurement the reservation refuses (another response model, an unpriced category, a unit cost the approved rate does not accept) settles the reservation as unknown, holding its reserved amount, instead of leaving it open. A reservation another decision already closed (a reconciliation, or an earlier settlement) keeps that decision; the receipt still records its observation, with charge_resolution: decided_elsewhere, and a late owner’s exact measurement is still recorded as evidence for a reconciliation.
  • A failed transaction falls back to separate writes, without losing the observation. If the single transaction fails (database error, timeout, deadlock after one retry), nothing of it commits. The request then records the usage event, its valuation and the receipt in their own transaction, keyed on the receipt: its final fingerprint makes a repeat, or a single transaction that did commit after all, a no-op, never a second event. It then writes the measurement and the settlement in their own transactions, exactly as without the flag, so a failed write never turns an exact charge into a held one; only an open reservation moves its counters, so it is never charged twice. The receipt is completed, or indeterminate when the outcome really is unknown. Whatever the database still refuses stays open for the recovery worker. Nothing is settled from memory after a crash and the provider is never called again.
  • The recovery worker resumes what stays open. The durable usage recovery pass (every 30 seconds on each replica) first marks expired leases indeterminate, as before, and then resumes the final receipts (completed or indeterminate) whose linked reservation has no recorded decision and that have not changed for the grace period. When the reservation is still reserved and a quota measurement was recorded for it, the worker settles from that measurement (recovered_measurement); with no measurement it holds the reservation as unknown (recovered_held), which keeps the reserved amount charged until a reconciliation; a reservation already decided is recorded as decided_elsewhere. Each receipt is its own transaction, locked with SKIP LOCKED, so replicas run it at once without double settlement; a resumed receipt is never resumed again, and one that fails waits another grace without stopping the others. A late owner that finalizes within the grace commits its own exact charge; one that comes after the worker records its event and keeps the worker’s decision. The pass also runs with the flag turned off, for receipts linked while it was on.
charge_resolution Meaning
finalized Settled in the receipt’s own finalization transaction
decided_elsewhere The reservation was already closed (reconciliation, earlier settlement) or archived
recovered_measurement The worker settled it from the recorded quota measurement
recovered_held No measurement proves the usage; held as unknown at the reserved amount

The worker’s bounds are boot configuration (restart to change):

charge_accounting:
recovery_batch: 100 # 1-500 receipts per recovery pass
recovery_grace_seconds: 300 # 60-86400; a final receipt waits, unchanged, this long
Key Default What it does
charge_accounting.recovery_batch 100 How many receipts one recovery pass resumes, 1–500
charge_accounting.recovery_grace_seconds 300 How long a final receipt waits unchanged before the worker resumes its open reservation, 60–86400; a late request can still settle its own charge in that time

Both are boot settings (restart to change), shown read-only by the API and the console; 0 takes the default.

GET /api/v1/admin/durable-usage then adds quota_reservation_id and charge_resolution to each linked receipt and a charge_accounting object with the effective bounds under their YAML names (recovery_batch, recovery_grace_seconds, background_poll_seconds, background_max_age_seconds) and a single_charge block with the filtered counts (linked, awaiting_recovery, recovered, held); the console shows them under Logs → Delivery receipts → Single charge. With the flag off, new receipts and events carry no link, and the API shows no single_charge block.

Write cost. The three post-response commits become one. The before and after measurement with the T044 harness is in how performance is measured.

Upgrade. Migration 166 adds the nullable link and resolution columns and two partial indexes; existing receipts and events keep no link. Turn the flag on after every replica runs this version: an older replica keeps the separate writes for its own requests, which is safe, and the worker also resumes a linked receipt that an older path finalized without settling. Turning the flag off stops new links; receipts linked while it was on keep their link in the API and are still resumed.

With quota_background_responses (T168), a Responses background create is reserved but not linked to its receipt: its reservation settles later, from the provider’s terminal response, as described in budgets and TPM. The same charge_accounting block bounds its worker:

charge_accounting:
background_poll_seconds: 30 # 5-3600; how often open background responses are asked about
background_max_age_seconds: 86400 # 600-604800; then one never seen ending is held as unknown

GET /api/v1/admin/durable-usage then adds a background_responses block (the installation-wide counts pending, settled, released, unknown, expired); the console shows it under Logs → Delivery receipts → Background responses. With organization admins on, a team-scoped session (team user, team viewer, team or organization admin) counts only the team it reads, so one organization never sees another’s background activity.

Acceptance, finalization and recovery require fsync=on in PostgreSQL and force synchronous commit. Reliable disks, backups, failover and synchronous replicas remain the installation’s responsibility.

In the console: Logs → Delivery receipts, with filters, the three states and pagination. Fields that were not observed are shown as such, never as zero.

Through the API: GET /api/v1/admin/durable-usage, with analytics:read.

Filter Values
from, to RFC3339, up to 90 days (by acceptance time in PostgreSQL)
principal, model, team, provider, key_id, operation Exact, up to 256 bytes
request_id, internal_event_id Exact
state pending, completed or indeterminate
offset 0 to 10,000; 50 items per page

The response includes coverage by state, the items, has_more and next_offset. Team roles see only their own teams; operator does not read usage. The provider is known only at the end, so filtering by provider excludes pending receipts.

Keep the gateway and database clocks in sync: a database clock that runs ahead can push recent receipts out of the default window.

  • It is not a financial ledger, an invoice or an exactly-once guarantee at the provider. For money, see budgets and reconciliation.
  • One receipt per request, not per attempt: retries show up in the logs, not in separate receipts. A realtime session is the exception: one receipt per response.
  • An indeterminate outcome leaves the valuation unknown.
  • The database grows with the receipts: plan retention, backup and capacity.
  • To turn it off, use the flag; never drop the table.

Event/valuation/receipt writes share a typed writer contract. Acceptance commits before dispatch; finalization commits the event, optional captured valuation/rate and receipt state together. A failed selected writer is never replaced by another database, and failed durable finalization does not fall through to best-effort event recording. Recovery and pending-only renewal continue for existing receipts after the operational flag is disabled; shutdown owns their worker lifecycle.

This internal boundary does not expose an additional operator-selectable database mode or change the API/flags above. General regressions use PostgreSQL only. Optional database support qualification is separate and reused, as described in quality.

m7gtwcontact@m7gtw.com