Session channels and metering
Session payments keep one funded Solana payment channel open across many API calls. The runtime authenticates each call with a cumulative voucher or a reusable payer proof, measures delivered service, and later settles the channel on chain. Subscription payments use a separate recurring challenge and activation path, while shared payment types describe both models and their metering rules. See Rust payment runtime, runtime client payment flows, runtime payment gateway, runtime credit providers and channel profiles, and runtime inference marketplace selling for the surrounding flows.
Session channel lifecycle
An MPP session starts with a server challenge and ends when the channel is settled and distributed. The channel store is the durable record of the accepted cumulative amount and lifecycle deadline. The Rust payment runtime uses the same session model for request gating, response delivery, and settlement.
When a client has no matching credential, the payment gate returns a 402 challenge with intent="session". The client builds an open transaction from the challenge's recent block hash and slot. The server checks the challenge echo, verifies and confirms the open transaction, then records the channel before it accepts later activity. A gateway can also be configured to load an open channel from chain after a restart, so a later voucher can resume from the on-chain watermark instead of forcing a new open.
The main actions have these roles:
opencreates or reuses a funded channel.voucheradvances the client-signed cumulative amount.useauthenticates an operator-signed channel with the payer proof bound at open.topupadds funds after a new on-chain funding transaction.closerequests settlement and distribution at the highest accepted watermark.
The following flow shows how an API call moves from a challenge to channel activity and final settlement.
sequenceDiagram
participant C as Client
participant G as Payment gate
participant S as Session server
participant U as Upstream API
participant P as Solana channel
C->>G: Request without session credential
G-->>C: 402 session challenge
C->>S: open credential and signed transaction
S->>P: Confirm channel open
S-->>C: Active session
C->>G: voucher or use credential
G->>S: Verify channel activity
G->>U: Forward paid request
U-->>G: Response stream or body
G->>S: Accept cumulative usage
G-->>C: Release response and receipt
C->>S: close credential, or idle lifecycle closes
S->>P: Settle, seal, and distribute
References: rust/…/gate.rs• L317-532 rust/…/session.rs• L1704-1973 rust/…/session.rs• L2012-2108 rust/…/session.rs• L254-417
Client-signed channels
In a client-signed channel, the client owns the voucher key and sends a new cumulative voucher for a request. The cumulative value is the total authorized amount rather than the cost of only the current request. This lets many calls share one channel and keeps the on-chain work until close.
The client handle serializes voucher creation so concurrent requests do not sign conflicting watermarks. A close can add a final increment or re-sign the current watermark when no more usage is due. A voucher is accepted only when its channel, signer, challenge binding, expiry, and monotonic cumulative amount are valid.
References: rust/…/session.rs• L36-190 rust/…/session.rs• L1871-1895 rust/…/session.rs• L1911-1973
Operator-signed channels
In an operator-signed channel, the client opens the channel with a reusable payer proof. The client then sends use for each request. The operator measures the successful response and signs the cumulative voucher, so the client does not need to create a voucher for every delivery.
The proof binds the payer and channel to the opening challenge. The outer challenge may rotate during the channel lifetime, but the proof remains tied to the original opening. This separates request authentication from response metering: use permits the request, and the response path decides the amount to debit.
References: rust/…/session.rs• L96-164 rust/…/session.rs• L327-416 rust/…/session.rs• L1518-1615 rust/…/session.rs• L2111-2169
Channel state and activity
Channel state joins off-chain request progress with the on-chain payment channel. It tracks the channel identity, payer, authorized signer, deposit, cumulative amount, accepted voucher details, close state, and lifecycle data. The store can be in memory for local use or supplied as a durable backend for a multi-process service.
Each accepted open, voucher, use, or top-up touches the channel. A touch records an idle deadline. A negotiated idle timeout can shorten the server's configured close delay. The deadline is rounded into a close batch boundary so channels that become idle near the same time can settle together.
The lifecycle owner can run in either mode:
- Embedded: the server process owns the clock and closes channels that it owns when their deadlines pass. It renews ownership with a lease and can adopt persisted deadlines after a restart or after another owner's lease expires.
- External: the server records touches, while a durable reconciliation worker owns close decisions.
An exclusive capacity claim prevents a request, watermark push, and close from using the same channel at the same time. The claim is released when the operation ends, including error and cancellation paths. Delegated usage also reads the durable channel watermark before it signs the next voucher, which lets another gateway instance continue from the latest accepted value.
References: rust/…/session.rs• L274-438 rust/…/session.rs• L623-720 rust/…/session.rs• L763-1189 rust/…/session.rs• L1444-1779 rust/…/session.rs• L1887-2104
Activity deadlines
Streaming requests keep their channel active without a store write for every chunk. The stream meter sends a confirmed touch at setup and then queues best-effort touches at a fixed interval. Delegated streams also hold a capacity lease with a heartbeat for the life of the response.
If a channel is already sealed or has a close request, a new confirmed touch rejects the request. A failed automatic close is not discarded: the lifecycle records a new touch, applies a bounded retry backoff, and tries again later. A close that finds newer activity re-arms the channel instead of closing it.
When settlement seals a channel but cannot distribute a payer refund, the lifecycle keeps a deferred-payout marker. It wakes the runloop and retries the distribution, including when automatic close is disabled, until the channel is paid out or reclaimed.
References: rust/…/session.rs• L655-720 rust/…/session.rs• L907-987 rust/…/session.rs• L1024-1093 rust/…/session.rs• L1540-1660 rust/…/session.rs• L1782-1885 rust/…/session.rs• L1887-2004 rust/…/session_stream.rs• L340-349 rust/…/session_stream.rs• L441-470
Streaming metering
Streaming metering turns response chunks into cumulative usage observations and payment decisions. The meter sits between the upstream response and the client. It releases a chargeable chunk only after the related cumulative amount is committed.
The response path follows this sequence:
- Read a response chunk from the upstream.
- Count the configured observable unit.
- Rate the new cumulative observation against the prior observation.
- Continue when the outstanding amount is below the voucher threshold.
- Wait for a client voucher or sign an operator voucher when the threshold is reached.
- Release the chunk after the commit is durable.
- Apply a final decision at end of stream.
This diagram shows the backpressure boundary. The upstream can produce data, but the client does not receive data that would exceed its committed watermark.
flowchart LR
A[Upstream response chunk] --> B[Usage accumulator]
B --> C[Cumulative rating]
C --> D{Voucher threshold reached?}
D -- No --> E[Release chunk]
D -- Yes --> F{Voucher authority}
F -- Client --> G[Wait for matching client commit]
F -- Operator --> H[Sign and persist operator voucher]
G --> E
H --> E
E --> I[Next chunk or final rating]
Client-voucher streams wait for the client-side watermark to reach the target. The wait has a bounded timeout. Delegated streams do not wait for a client voucher; they reserve channel capacity before forwarding and persist the operator-signed cumulative usage before releasing each chargeable chunk. If late provider usage selects a higher price tier, the delegated stream can collect only the authorization already reserved for that delivery.
References: rust/…/session_stream.rs• L126-221 rust/…/session_stream.rs• L224-349 rust/…/session_stream.rs• L412-510 rust/…/session_metering.rs• L336-470
Stream usage observations
The accumulator supports output bytes, output characters, input tokens, output tokens, requests, and quota units when the selected meter defines them. It treats observations as cumulative and rejects a value that moves backward. For token streams, it reads provider usage frames and also uses visible streamed words as a live lower bound when final token metadata has not arrived.
Server handling supports common SSE shapes from OpenAI-compatible, Responses, Anthropic, and Gemini-style providers. A delegated chat stream asks the upstream to include usage metadata. If a provider reports input usage late and that changes a conditional price tier, the meter rebuilds its price view while preserving the committed watermark. A usage-only late reprice cannot authorize more than the reserved delivery capacity.
References: rust/…/session_stream.rs• L512-650 rust/…/session_stream.rs• L654-801 rust/…/session_stream.rs• L224-337 rust/…/payment.rs• L236-297
Metering profiles and settlement amounts
Metering profiles describe how a service turns usage into a price. A profile contains one or more dimensions, such as input tokens or output bytes. Each dimension has a direction, a billing unit, a scale, and price tiers. A variant selects a different set of dimensions for a model or other request choice.
The runtime resolves a profile in this order:
- Select a matching variant from the request path or request body.
- Use top-level dimensions when no variant matches and they exist.
- Use the first variant as a fallback when no top-level dimensions exist.
- Select the tier that matches request properties such as context length.
- Convert the selected USD price to integer micro-USD for session rating.
Session metering uses integer prices and cumulative ceiling division. This avoids repeated rounding when a stream sends small chunks. It then converts cumulative micro-USD to stablecoin base units using the configured token decimals. A voucher is required when the outstanding base-unit amount reaches the configured minimum, and the final observation requires settlement even when the streaming threshold was not reached.
References: rust/…/session_metering.rs• L77-176 rust/…/session_metering.rs• L247-334 rust/…/session_metering.rs• L472-560
Meter dimensions and variants
The shared Metering type supports direct dimensions and variant-specific dimensions. A MeterDimension can measure input, output, or general usage in units such as tokens, quota units, bytes, characters, or requests. A PriceTier can select by request condition or by volume in the broader metering path.
Session hot-path rating requires dimensions with usable tiers and does not accept SKU tiers. A zero scale, missing required observation, non-finite price, inexact micro-USD price, or arithmetic overflow fails the rating instead of producing an ambiguous charge.
References: rust/…/metering.rs• L1254-1445 rust/…/session_metering.rs• L13-129
Quota-unit conversion
Quota units are abstract service units backed by a token count. The runtime reads the tokens-per-quota-unit hint from the selected tier notes and rounds the cumulative token count up. This keeps the same pricing rule for live streams and for buffered response settlement.
When an endpoint has a request body model or a conditional context tier, the selected variant and tier must be the same for challenge pricing and response rating. The delegated stream path can reprice when the provider reveals the actual input context, but it limits a late usage-only reprice to the authorization already reserved for that delivery.
References: rust/…/metering.rs• L410-447 rust/…/session_stream.rs• L94-124 rust/…/session_stream.rs• L224-337
Settlement and reconciliation
Settlement moves accepted off-chain watermarks to the payment-channel program. A close uses the highest accepted voucher that is newer than the on-chain watermark, then seals the channel and distributes the settled funds. If a periodic watermark push already advanced the chain, close can seal without replaying the same voucher.
The server records a settlement signature for a finalized channel so clients can poll for an out-of-band receipt. A session receipt identifies the channel and reports the accepted, spent, authorized, and remaining cumulative amounts. It does not use a per-request transaction signature because session settlement occurs at watermark push or close time.
References: rust/…/session.rs• L343-353 rust/…/session.rs• L386-397 rust/…/session.rs• L546-607 rust/…/session.rs• L907-987 rust/…/gate.rs• L153-207
Watermark pushes
An optional settlement interval periodically pushes the latest accepted cumulative voucher for active channels without closing them. This bounds the value that exists only in off-chain state while preserving the channel for later requests. The push reads the on-chain channel first and skips channels that are no longer open or that have not reached the minimum delta.
The lifecycle runloop can cap the number of channels pushed in one cycle with PAY_SETTLEMENT_MAX_PER_CYCLE. It rotates the selected set across cycles so the cap limits RPC and chain load without permanently favoring the same channels. It also bounds concurrent channel reads before the settlement worker broadcasts the eligible transactions.
Both embedded lifecycle reconciliation and the external worker use channel claims to avoid concurrent work. The external worker scans durable state, checks the on-chain status and watermark, builds either a watermark or idle-close candidate, batches candidates into transactions, confirms them, and updates durable state.
References: rust/…/session.rs• L406-492 rust/…/session.rs• L2007-2104 rust/…/session.rs• L2120-2133 rust/…/settle_sessions.rs• L368-671 rust/…/settle_sessions.rs• L876-1215
Idle close and distribution
Idle close starts after the persisted deadline or an explicit close request. The close path settles the latest accepted amount, seals the channel, and adds the distribution step for configured recipients. A channel that is already finalized is treated as complete so retries do not fail only because the earlier transaction landed.
The reconciliation worker compares durable state with on-chain state. It can discover distributed channels after a process restart and recover the original distribution plan before it sends recipient payments. It checks that the recovered plan matches the on-chain commitment, then supports the final distribution and rent-reclaim stages. It retains finalized records for the configured retention period, deletes stale records when the on-chain channel is absent and no open slot remains, and reports mismatches such as a durable sealed flag with an unsealed on-chain channel.
In the embedded lifecycle, a failed close is retried with backoff. A payout that was deferred because the payer refund account was not payable is retried separately until it can complete or the channel is reclaimed.
References: rust/…/session.rs• L389-480 rust/…/session.rs• L672-987 rust/…/session.rs• L1782-2004 rust/…/settle_sessions.rs• L773-868 rust/…/settle_sessions.rs• L936-1086 rust/…/channel.rs• L105-208 rust/…/channel.rs• L321-479
Subscription handling
Subscriptions are a recurring payment intent rather than a session channel. A subscription endpoint returns a 402 with a subscription challenge. An activation credential causes an on-chain subscription activation and returns a receipt plus an authenticate challenge for later access.
The later authenticate credential is stateless and does not broadcast a new payment. The gate verifies it and forwards the request. If there is no credential, or verification fails, it returns a fresh challenge. The current Rust path supports challenge emission and activation verification through the SDK; unsupported activation behavior is surfaced as an error rather than silently granting access.
The client side in rust/…/subscription.rs accepts only Solana subscription challenges. It validates the plan and period before signing the activation transaction, and it can sign a bundled authenticate challenge with the same unlocked signer. After activation, it stores the subscription from the subscription receipt. Client paths that do not receive a receipt derive the subscription identity locally and save an active record for later refresh and reconciliation.
References: rust/…/gate.rs• L1057-1265 rust/…/subscription.rs• L1-22 rust/…/subscription.rs• L211-222 rust/…/subscription.rs• L86-182 rust/…/subscription.rs• L185-391 rust/…/subscription.rs• L431-538 rust/…/subscription.rs• L560-628
Subscription terms
The SubscriptionEndpoint type carries the billing period, currency, per-period price or explicit base-unit amount, expiry, plan identity, puller, and recipient. Periods use fixed day or week units within the Solana profile's allowed elapsed-time range. A known stablecoin can convert a USD price to base units; an arbitrary mint needs an explicit base-unit amount.
The on-chain plan is published separately and its identity is written back into the API configuration. The runtime refuses to build a handler without the plan identity, valid period, usable price, challenge-binding secret, and realm. These checks keep a bad subscription from producing an unsignable challenge at request time.
References: rust/…/metering.rs• L1047-1210 rust/…/subscription.rs• L63-209 rust/…/subscription.rs• L275-410
Shared payment protocol types
The shared payment types define the vocabulary used by API specifications, the payment gate, session clients, and settlement code. They separate a per-call scheme from a recurring subscription and let one endpoint advertise the schemes that its configured backends can serve.
The main relationships are:
| Type | Role |
|---|---|
SessionSpec | Channel cap, voucher signer, minimum voucher delta, idle policy, settlement cadence, reuse policy, and splits. |
SessionVoucherSigner | Selects client-signed or operator-signed cumulative vouchers. |
Scheme | Identifies MPP charge, MPP session, x402 exact, x402 upto, or x402 batch settlement. |
Metering | Holds dimensions, variants, splits, accepted schemes, and upto policy. |
MeterDimension | Defines direction, unit, scale, tiers, and an optional response usage source. |
UptoMetering | Defines an authorized ceiling, minimum, missing-usage rule, body limit, and provider preset. |
SubscriptionEndpoint | Defines recurring subscription terms for one endpoint. |
An endpoint with a session block receives session scheme defaults when its metering block does not list schemes explicitly. Explicit schemes remain a restriction. Subscription configuration is mutually exclusive with per-call metering for an endpoint.
References: rust/…/metering.rs• L57-62 rust/…/metering.rs• L848-915 rust/…/metering.rs• L1214-1350
Upto settlement policy
The x402 upto policy is a related channel settlement model. It opens a channel up to a ceiling before forwarding, then settles actual response usage after the upstream responds. A successful response can use measured usage or a configured minimum. A failed response settles zero and refunds the authorized amount.
Buffered responses use configured response meters or provider presets. Streamed delegated responses use the session stream gate instead, so each chargeable chunk is held until the operator's cumulative voucher is persisted. Missing usage follows the configured refund, minimum, ceiling, or error policy.
References: rust/…/metering.rs• L1283-1342 rust/…/metering.rs• L269-407 rust/…/gate.rs• L210-289
Change checklist
When these files or sections are changed, remember to consider these:
- Keep
SessionSpecdefaults aligned with the challenge fields, lifecycle runloop settings, channel reuse behavior, and external reconciliation behavior. - Keep
SessionVoucherSignerchanges aligned across client action creation, server verification, response metering, and channel state values. - Keep cumulative watermark rules aligned across stream gating, durable channel state, periodic pushes, close settlement, and receipt fields.
- Keep metering variant and conditional-tier selection aligned between challenge pricing, stream rating, and buffered
uptosettlement. - Keep subscription period and amount validation aligned with the on-chain plan terms, the challenge payload, and client receipt persistence.
- Keep subscription receipt extension fields aligned between activation responses, stored account records, and refresh reconciliation.
- Keep accepted
Schemevalues aligned with endpoint defaults and the payment backends that the gate can advertise. - Keep channel distribution recovery aligned with the on-chain commitment and the recipient accounts used by the worker.
- Keep lifecycle ownership leases, close retry state, deferred-payout markers, and settlement-cycle limits aligned between embedded runloops and external reconciliation.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Open credential echoes a challenge that the server did not bind | The server rejects the open before it trusts block hash or slot fields | Verify the challenge binding before action decoding and open processing |
| Client or operator presents a cumulative value below the accepted watermark | The voucher cannot advance settlement and may be rejected as non-monotonic | Rate cumulative observations and keep the committed watermark monotonic |
| A stream crosses its voucher threshold before its commit is durable | The client could receive service that is not covered by the channel watermark | Hold the chunk until the matching commit or operator authorization is persisted |
| A delegated response needs more than the reserved channel capacity | The response cannot be fully authorized and the stream fails rather than overspending | Reserve capacity before forwarding and clamp only the supported late reprice path |
| Idle close races with an active request | A live channel can close during delivery or a request can use stale capacity | Use one exclusive channel claim for serving, watermark push, and close |
| Latest voucher is replayed after a periodic watermark push | Settlement fails because the on-chain watermark already reached the target | Read the on-chain watermark and seal without replaying an equal voucher |
| A restarted gateway adopts a channel for a different payee or mint | The gateway could account for or settle an unrelated channel | Allow reuse only for open channels that match the configured payee and currency |
| Distributed channel data cannot be recovered or fails its commitment check | Recipient distribution and rent reclaim cannot proceed safely | Recover the opening plan and verify its hash before building distribution |
| A close fails after it claims the channel | The channel can remain open without another close attempt | Persist a new lifecycle touch and retry with bounded backoff |
| A payer refund account cannot receive a close refund | The channel is sealed without distribution until the account becomes payable or the grace period ends | Keep the deferred-payout marker and retry distribution from the lifecycle or worker |
| A live lifecycle owner still holds its lease | Another gateway must not close or settle the same channel | Preserve active ownership and reclaim it only after the lease expires |
| Too many active channels are settled in one cycle | RPC load and transaction rate can cause timeouts or throttling | Rotate a per-cycle cap and bound concurrent on-chain reads |
| Subscription plan, secret, realm, or period is incomplete | The endpoint cannot produce a valid recurring-payment challenge | Validate handler inputs at startup and fail closed |
| Activation succeeds without a receipt or the receipt has missing subscription fields | The client cannot fully identify or persist the active subscription | Derive the deterministic identity only as a fallback and let refresh reconcile missing chain data |
| Required response usage is absent or decreases | The final amount is unknown or violates cumulative assumptions | Apply the configured missing-usage policy and reject non-monotonic observations |
Key files
| File | Why to read it |
|---|---|
| rust/…/gate.rs | Shows how request metadata selects session, subscription, and other payment paths and how responses receive settlement annotations. |
| rust/…/session.rs | Defines the server session lifecycle, channel state coordination, idle close, watermark pushes, ownership recovery, deferred payouts, channel reuse, and settlement handoff. |
| rust/…/session.rs | Shows the client-facing open, voucher, use, top-up, and close credential flow. |
| rust/…/subscription.rs | Shows subscription challenge decoding, activation signing, receipt parsing, and local persistence. |
| rust/…/session_stream.rs | Shows response observation, streaming backpressure, client commit waits, and delegated operator authorization. |
| rust/…/session_metering.rs | Defines cumulative rating, base-unit conversion, and voucher threshold decisions. |
| rust/…/metering.rs | Connects shared metering configuration to request properties, variants, response usage, and settlement plans. |
| rust/…/subscription.rs | Bridges subscription endpoint terms to challenge creation, plan publication, and activation verification. |
| rust/…/settle_sessions.rs | Shows durable reconciliation, lease ownership, on-chain comparison, batching, and final channel cleanup. |
| rust/…/channel.rs | Shows how the worker discovers on-chain channel states, recovers distribution plans, and builds final channel instructions. |
| rust/…/metering.rs | Defines the shared session, subscription, scheme, metering, tier, and upto protocol types. |