Synced from Hive. This page is pulled from hivecommons/hive@v5 during the docs build. Edit the canonical source in the Hive repository.

ADR-0027: Hybrid wire and transcript cost accounting

Status: Proposed

Wire means token usage the proxy observes on an inference request it carries. Transcript means token usage a scanner reads from the CLI session file an agent wrote. This record makes them one ledger without pretending they are the same measurement.

Context

Hive prices agent work from token counts, and two independent observation paths already exist. They were built separately and do not share a ledger.

The transcript path. The scanners under src/pkg/tokens/ (Claude, Copilot, Bob, Codex, Cline, sandbox) read each CLI’s session file into a SessionSummary with a per-message UsageEvent timeline (src/pkg/tokens/collector.go, usage_timeline.go). The collector merges every scanner into one AggregateSummary, and that aggregate is what the dashboard cost endpoints (src/pkg/dashboard/cost.go), the repo-cost join (src/pkg/dashboard/repo_cost.go), the governor budget and the hub heartbeat all read. This is the only path that carries enough per-message timing to attribute spend to the pull requests an agent touched.

The wire path. The proxy observes the usage block on responses it carries. The inference translator records it through the UsageSink seam (src/crux/proxy/host_seams.go) into InferenceSink (src/pkg/tokens/inference_sink.go), and the Copilot sniff path records live completions the same way (src/crux/proxy/github_proxy_copilot.go). That sink keeps a cumulative per-agent counter and atomically rewrites one inference-<agent>.jsonl file per agent; the collector then scans that file like any other session and deduplicates by session ID.

Today that split has five consequences:

  1. No request grain. Neither path records a request. The sink keeps a running total, and the transcript parsers read message.usage only. “How many requests, each with what usage” cannot be answered, so one event per request cannot be asserted.
  2. No provenance. A total cannot say whether it came from the wire or from a transcript. The two are summed into the same aggregate with no marker.
  3. No billing basis. Token counts times list price are presented the same way whether a metered gateway billed the request or a subscription covered it. A list price is not spend.
  4. Overlap is handled ad hoc. The Copilot scanner defers its session.shutdown totals to live wire capture behind a start-time predicate (SetCopilotLiveCapture), a rule that exists because a naive sum produced the $18k to $394 double-count regression. There is no general rule.
  5. Two blind spots are unnamed. Direct-to-provider traffic that bypasses the proxy is invisible on the wire, and an agent whose transcript cannot be parsed is invisible to the scanners. Which source covers which, and what stays unattributed, is not written down.

Price provenance is being pinned separately (#21082), and tunnelled egress destinations are being audited separately, metadata only, with no new denies (#21080). Neither closes the usage-accounting gap this record addresses.

Decision

1. Two sources, one usage ledger

Add a single append-only usage ledger. Every row is one observation, tagged with the source that observed it:

  • Wire rows are emitted by the proxy at the two points that already parse a usage block: the inference translator, for both the streaming and non-streaming response paths (src/crux/proxy/github_proxy_inference.go), and the Copilot sniff (src/crux/proxy/github_proxy_copilot.go). The emitter mints a request_id at request entry and uses a once guard, so a request produces exactly one row even when the upstream is retried, the response is streamed, or the client cancels. Retries are folded into the same row and counted in an attempts field.
  • Transcript rows are derived by the scanners from the per-message usage they already parse. Their identity is (backend, session_id, event_index), since a transcript line carries no provider request id today.

The ledger is additive to, not a replacement for, the existing cumulative sink files in the first phase. P1 writes the ledger and changes no total. P2 makes the collector read wire usage from the ledger instead of the sink’s cumulative file, with a test proving the totals are identical when only transcripts exist. The flag that disables emission reverts to the sink path unchanged.

A test drives a streaming request, a non-streaming request, a retried request and a cancelled request, and asserts exactly one ledger row per request_id.

Trade-off. A new append-only artifact is a second source of wire truth until P2 removes the sink read. The alternative, extending the cumulative sink in place, cannot express a per-request row or a request id without changing its publication model, which is what makes it safe across restarts.

2. Precedence and dedupe

Rows are joined, never summed across sources for the same request:

ConditionWinnerRecorded as
A wire row and a transcript row share a request idOne reconciled rowreconciled
No shared id, and the agent has a transcript covering the request windowTranscripttranscript
No shared id, and the agent has no transcriptWirewire
Neither source saw the requestNothingCounted as a coverage gap, never as zero

The winner is recorded on the row and on every aggregate derived from it (measure_source, plus a sources set and mixed marker at the total level). A total may sum disjoint rows from different sources; what is forbidden is summing two observations of the same request, or presenting a mixed total without saying that it is mixed.

The existing Copilot live-capture deferral is the per-session instance of this rule and must be preserved exactly: wire wins for a session the proxy observed from its start, transcript wins for sessions that predate capture. That predicate (LiveCaptureSinceMs) is re-expressed in ledger terms, not removed.

Trade-off. Transcript lines carry no provider request id today, so the reconciled row is dormant until a scanner learns the id. Until then precedence is decided per agent session, which is coarser than per request. Choosing transcript-first when both exist means a wire-only helper call inside an agent that also writes a transcript is missing from totals; it appears in the reconciliation report instead. This is deliberate: it keeps totals stable and keeps PR attribution intact.

3. Provenance

Measurement and price are independent questions, so they get independent fields. The existing PriceSource (src/pkg/tokens/gateway_pricing.go) is reused for price and is not overloaded:

FieldValuesAnswers
measure_sourcewire, transcript, reconciledWho measured this row
price_sourcegateway, table, tier, unknown (existing)Where the rate came from
price_catalog_pincatalog commit and table date (from #21082)Which rate table was used
billing_basiscash, avoided, unknownWhat the money means

Every cost row carries all four. The dashboard shows, per row, the measurement source and the price source, and the catalog pin in the footer beside the existing price-table date. A total shows its sources set, and a mixed total carries a mixed chip that opens the per-source breakdown. A row with price_source: unknown stays excluded from the total and is shown as “price unknown”, never as $0, which is the existing behaviour and stays.

Trade-off. Three fields plus a pin is more payload and more UI than one badge. It is accepted because collapsing them lets a reader mistake a transcript-priced row for a wire-measured one, or an estimate for a bill.

4. Billing basis

billing_basis separates what the tokens are worth from what was actually paid:

  • cash: the request was billed per token by a metered gateway. Where the gateway reports native spend (/api/cost native probe), that figure remains the cash truth and the ledger estimate is only a fallback, labelled estimated.
  • avoided: the request was authenticated by a subscription (a Claude, Copilot or Codex plan). Token counts times list price are the cost avoided, not money spent.
  • unknown: the authentication method is not observable for this row.

Dashboard wording follows the basis. A subscription row reads “avoided (list value)”. A cash row reads “estimated cash” until the native probe confirms it, and “spend” only when the gateway reports it. A list price is never labelled “spend”.

The benchmarks cost.basis values stay exactly as they are: tokens_x_pricing means a list-price estimate, unknown means no attribution, and reported stays reserved for a gateway-billed figure. The benchmark schema is not changed by this record, and billing_basis is not folded into cost.basis.

Trade-off. One agent can mix bases across requests, so a per-agent total can be mixed-basis. Basis is therefore per row and the total is labelled, the same as measurement source.

5. Coverage limits, stated plainly

PathTranscript writtenTranscript readableWire sees itAttribution
Through the proxy, CLI writes a session fileYesYesYesReconciled or transcript; PR attribution intact
Through the proxy, bare-mode agent, no session fileNon/aYesWire; agent-level only, no PR attribution
Through the proxy, session file unparseableYesNoYesWire; agent-level only
Bypasses the proxy, CLI writes a session fileYesYesNoTranscript; PR attribution intact; wire blind
Bypasses the proxy, no session fileNon/aNoUnattributed, reported as a gap
Caller not identified, request refusedn/an/aNoNo row; counted in proxy refusal diagnostics

The two blind spots are therefore:

  1. Direct-to-provider traffic that bypasses the proxy. The transcript covers it when the CLI wrote one and the scanner can read it. It stays invisible when neither holds.
  2. Any agent whose transcript we cannot parse. The wire covers it only if the request went through the proxy.

Everything in the last two rows stays unattributed. It is reported as a gap and is never shown as zero spend. The tunnel destination audit (#21080) records which hosts were reached and how many bytes moved; it does not record tokens and does not close this gap.

Trade-off. Forcing every provider request through the proxy would close blind spot 1. That is a policy change to what is allowed, and it is a non-goal here (see section 7).

6. No payload retention

A wire row carries metadata and token counts only. The allowlist is:

request_id, agent, backend, model, input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens, started_at, ended_at, outcome, attempts, measure_source, billing_basis, price_catalog_pin.

A wire row never carries a request or response body, a header of any kind (including Authorization and x-api-key), a query string, a credential, a prompt, a completion, tool content, a file path or a repository name. The agent name is already public inside the pod and the model id is routing metadata.

This matches the metadata-only posture of the tunnel destination audit (#21080): both are observation, neither adds a deny, and neither records payload. P1 to P4 of this record do not make the ledger authoritative for a budget, so a damaged row cannot move a gate. If a later phase makes ledger rows budget-authoritative, those rows go through the existing hash chain.

The proxy already writes truncated request and response previews at INFO in some debug paths. This record adds no new payload retention and does not change those lines; narrowing them is a separate change.

Trade-off. Metadata-only rows cannot be re-priced from content, and cannot explain a surprising delta beyond model and token counts. That is the point: cost accounting does not need an agent’s prompt.

7. Non-goals

  • No change to what the proxy allows or denies. No new deny, no altered connection handling, no new gate.
  • No replacement of transcript attribution to pull requests. The repo-cost join keeps using transcript events for PR rows.
  • No dependency on an external tool, service or schema for the ledger.
  • No payload capture, and no retroactive re-pricing of history.
  • No change to the benchmark schema or its cost.basis values.
  • No implementation in this record’s PR. The phases below are separate issues and none is started until the owner accepts this record.

8. Rollout

Each phase is shippable on its own and reversible. No phase before P4 changes an existing total.

PhaseChangeReversible byTotals
P1Wire rows emitted, metadata only, one per request, into the append-only ledger. Nothing reads them.Disable emission; sink path untouchedUnchanged
P2Ledger merge, precedence, provenance on every row. Collector reads wire usage from the ledger instead of the cumulative sink file. Tests prove one row per request, and totals identical to today when only transcripts exist.Flag back to the sink readUnchanged
P3Wire-only attribution shown: agent-level totals, PR attribution explicitly absent, dashboard label. Repo-cost reports these in a wire-only bucket, not as unattributed.Hide the label and bucketUnchanged
P4Reconciliation report: wire versus transcript deltas per agent and model, with reason buckets (transcript_preferred, wire_only, reconciled, wire_extra, transcript_extra, no_usage_block, bypass_suspected). Read-only endpoint.Remove the endpointUnchanged
laterAny change that replaces a transcript total with a wire totalIts own reviewed changeChanges only after P4

P5, a contributor-relay usage reporting protocol, is a separate epic. It is not filed under this record and is not a dependency of it.

Consequences

  • A cost figure can finally say how it was measured and how it was priced. The trade-off is more fields in the payload and more UI, and a second wire artifact during P1 until P2 removes the sink read.
  • Totals become stable by design: adding wire observation to an agent that already has a transcript does not move its total. Wire-only deltas surface in the reconciliation report instead, which is what lets a total change be reviewed rather than discovered.
  • Subscription cost is separated from cash, so list prices stop reading as spend. The trade-off is that basis can be wrong per row when an agent mixes a subscription and a gateway key, and the total must then be labelled mixed.
  • The two blind spots are named and reported, not hidden. Direct-to-provider traffic without a readable transcript stays unattributed, and no phase here closes it.
  • The existing Copilot live-capture deferral survives as a special case of the general precedence rule rather than as an unstated exception.

Refs #21080, #21082.