Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,279 @@
> **Synced from Hive.** This page is pulled from [hivecommons/hive@v5](https://github.com/hivecommons/hive/blob/v5/src/docs/adr/0027-hybrid-wire-and-transcript-cost-accounting.md) 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:

| Condition | Winner | Recorded as |
|---|---|---|
| A wire row and a transcript row share a request id | One reconciled row | `reconciled` |
| No shared id, and the agent has a transcript covering the request window | Transcript | `transcript` |
| No shared id, and the agent has no transcript | Wire | `wire` |
| Neither source saw the request | Nothing | Counted 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:

| Field | Values | Answers |
|---|---|---|
| `measure_source` | `wire`, `transcript`, `reconciled` | Who measured this row |
| `price_source` | `gateway`, `table`, `tier`, `unknown` (existing) | Where the rate came from |
| `price_catalog_pin` | catalog commit and table date (from #21082) | Which rate table was used |
| `billing_basis` | `cash`, `avoided`, `unknown` | What 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

| Path | Transcript written | Transcript readable | Wire sees it | Attribution |
|---|---|---|---|---|
| Through the proxy, CLI writes a session file | Yes | Yes | Yes | Reconciled or transcript; PR attribution intact |
| Through the proxy, bare-mode agent, no session file | No | n/a | Yes | Wire; agent-level only, no PR attribution |
| Through the proxy, session file unparseable | Yes | No | Yes | Wire; agent-level only |
| Bypasses the proxy, CLI writes a session file | Yes | Yes | No | Transcript; PR attribution intact; wire blind |
| Bypasses the proxy, no session file | No | n/a | No | Unattributed, reported as a gap |
| Caller not identified, request refused | n/a | n/a | No | No 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.

| Phase | Change | Reversible by | Totals |
|---|---|---|---|
| P1 | Wire rows emitted, metadata only, one per request, into the append-only ledger. Nothing reads them. | Disable emission; sink path untouched | Unchanged |
| P2 | Ledger 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 read | Unchanged |
| P3 | Wire-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 bucket | Unchanged |
| P4 | Reconciliation 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 endpoint | Unchanged |
| later | Any change that replaces a transcript total with a wire total | Its own reviewed change | Changes 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.
1 change: 1 addition & 0 deletions docs/content/hive/adr/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,4 @@ sequencing; ADR-0019/0025 give their current action/mode contract first.
- [ADR-0024: Provider credential lifecycle](/docs/hive/adr/0024-provider-credential-lifecycle) — **Proposed**, not a credential-pool or refresh-service setup guide.
- [ADR-0025: One stage engine derives and writes every `stage/*` label](/docs/hive/adr/0025-central-stage-engine)
- [ADR-0026: Sandbox runtime selection](/docs/hive/adr/0026-sandbox-runtime-selection) (Accepted — phase 1 implemented, runtime opt-in)
- [ADR-0027: Hybrid wire and transcript cost accounting](/docs/hive/adr/0027-hybrid-wire-and-transcript-cost-accounting) — **Proposed**, design only; no phase is started.
Loading
Loading