Repository navigation
Description
Summary
Make one canonical record per real provider request attempt the source of truth for model-call accounting, and feed the Host-owned Usage authority (#1596) from it. Today the same spend is recorded by two independent writers at two different granularities, with three known gaps — and neither writer can answer "what did this turn actually cost, and is that number complete?"
This is the metering half of #1625. The Session Inspector stays downstream and becomes a pure read model over these records once they exist.
cc @likun666661 (#1649 sequencing) — see Relationship to #1649.
Problem
Two writers record model spend, neither completely:
| Path | Writer | Granularity | Carries cost? |
|---|---|---|---|
| Telemetry | recordLlmCall (ai-sdk-backend.ts:1826) |
one record per send, aggregated across retries | yes |
| AgentRun ledger | recordProviderRequestAttempt (agent-run.ts:292) |
one record per physical attempt | no |
Neither is authoritative, and the split produces three gaps:
- Provider retries carry no kind anywhere. The main telemetry record aggregates across retries, and
provider_retryis barred from the AgentRun ledger (agent-run.ts:482). A retried call is invisible as a distinct billable event. - The
RuntimeEventledger attributes no compaction cost. Kernel compaction writes a phantominput: 0, output: 0turn (runtime-kernel.ts:816-822) while the real usage goes to telemetry. Anything projecting cost from the event ledger under-reports on exactly the turns that compacted. - The
pibackend records no telemetry at all.recordLlmCallhas zero references inpi-agent-backend.ts, so those sessions show tokens in the ledger and$0in telemetry — an indistinguishable-from-real zero.
Two more properties make the current state hard to build on:
- Attempt writes drop silently. Two lines apart in
runtime-kernel.ts:2462-2477,recordProviderRequestCapturerejects when there's no active run whilerecordProviderRequestAttemptisrun?.recordProviderRequestAttempt(attempt). A late finalize after turn teardown vanishes with no trace. - Incompleteness is undetectable. Nothing records an expected attempt count, and captures dedup on
(step, requestHash), so a partial record set can't even be recognized as partial — let alone bounded.
callKind covers three of the paths after #1637 ('main' | 'semantic_compact' | 'history_compact', usage-stats/types.ts:52). Retry and pi remain unmodelled.
Proposal
One canonical record
Extend the existing per-attempt shape (ProviderRequestAttemptRecord, provider-request-telemetry.ts:53) into the canonical accounting record. It already carries identity, timing, and tokens; what it lacks is kind, cost, and honesty about coverage.
export interface ModelCallAttempt {
// identity — already present
traceId: string; // groups attempts belonging to one logical call
attemptId: string;
sessionId: string;
runId: string;
turnId: string;
step: number;
attempt: number;
// what kind of call this is — extended
callKind: 'main' | 'semantic_compact' | 'history_compact';
retryOf?: string; // attemptId this retries; absent on first attempt
// provider identity — already present
providerId: string;
modelId: string;
contextWindow?: number;
// timing — already present
startedAt: number;
completedAt: number;
latencyMs: number;
timeToFirstTokenMs?: number;
// outcome — already present
status: 'completed' | 'failed' | 'interrupted' | 'aborted';
finishReason?: string;
errorClass?: string;
// tokens — already present via ProviderRequestUsage
inputTokens?: number;
outputTokens?: number;
cacheReadInputTokens?: number;
cacheMissInputTokens?: number;
cacheWriteInputTokens?: number;
reasoningTokens?: number;
// accounting — new, and deliberately honest
costUsd?: number; // absent = unknown, never coerced to 0
costBasis?: 'priced' | 'unpriced' | 'aggregate';
granularity: 'attempt' | 'aggregate'; // 'aggregate' = backend can't split (pi)
}Two fields carry the honesty requirement:
granularity: 'aggregate'marks a record that stands for an unknown number of physical attempts.piproduces these. A consumer may sum them for totals but must never present them as per-attempt truth.costBasis: 'unpriced'marks a real call whose cost could not be resolved. Distinct fromcostUsd: 0, which must only ever mean genuinely free.
Retries stop being invisible: each physical attempt is its own record, linked by retryOf and grouped by traceId.
Where it lives
As a new AgentRunEvent type, extending the seam provider_request_attempt_recorded already occupies (AGENT_RUN_EVENT_TYPES, core/agent-run.ts:168). No new table, no new store, no new writer.
This is deliberate: per @Astro-Han's note on #1625, an AgentRunEvent type needs no coordination with #1649, because that migration carries whatever event types exist and keeps store APIs stable across the cutover.
Collection seam
ProviderRequestTracker (provider-request-telemetry.ts:157) already sits at the real doStream / doGenerate boundary and observes step, attempt, latency, and tokens. Three changes make it canonical rather than diagnostic:
- Fail loudly.
recordProviderRequestAttemptgets the same treatment asrecordProviderRequestCapture— a missing active run is an error, not a silent return. - Unbind from request capture. Attempt recording currently rides the capture path (
provider-request-telemetry.ts:261); accounting must not be conditional on diagnostic capture being enabled. - One path for every kind.
main, retries,semantic_compact, andhistory_compactall emit through this seam, so no billable call reaches a ledger by a private route.
Usage authority and coverage
Records feed the Host Usage/Pricing authority (#1596) — extending the existing single writer, not adding a second one. Rollups gain explicit coverage rather than exposing a single confident number:
interface UsageCoverage {
pricedCalls: number;
unpricedCalls: number; // real spend, cost unknown
aggregateCalls: number; // pi-style, attempt count unknown
}A totalCostUsd presented without its coverage is the failure mode this whole change exists to remove.
Removing the double write
Once the canonical record lands, the send-level recordLlmCall and the AgentRun attempt-usage write are redundant. Both get removed in favour of projecting telemetry from the canonical records. Existing data migrates once; no parallel old/new writing — a dual-write period would reintroduce exactly the reconciliation problem this replaces.
Non-goals
- Not turning
RuntimeEventinto a per-attempt billing ledger. Its job stays conversation causality, recovery, and replay; it keeps per-turn aggregates plus refs to canonical records (refs.providerRequestTraceIdalready exists for this). - Not touching Runtime Host ownership, election, or session admission.
- Not adding authority to the Desktop embedded writer path (
session-stream.ts:289) — [Tracking] Runtime Host M3 domain ownership migration #1167's M5 removes it. - Not the Inspector UI. That stays in [RFC] Session Inspector: a per-session runtime event trace, replay, and cost-attribution surface #1625, downstream.
Proposed PR breakdown
- Contract + tests.
ModelCallAttempttype, event-type registration, validation, and pure projection helpers. No behavior change. - Canonical seam.
ProviderRequestTrackerupgrade: fail-loud writes, unbind from capture, all four paths routed through it. - Usage authority integration. Records feed feat(runtime-host): extract Usage/Pricing authority #1596's writer; rollups gain
UsageCoverage;pimarkedaggregate. - Remove double metering. Delete the send-level and attempt-usage writes, one-time migration.
Open questions
piaggregates — should they land asgranularity: 'aggregate'ModelCallAttemptrecords so one query answers everything, or stay out of the canonical store with the Usage layer merging two sources? I lean toward the former for a single read path.- Cost resolution point — resolve
costUsdat record time (frozen at call time, matching whatRuntimeEventalready stores) or at projection time from the pricing authority? I lean toward record time: a later price change shouldn't rewrite history. - Migration fidelity — old telemetry rows have no attempt granularity. Migrate them as
granularity: 'aggregate'rather than fabricating per-attempt structure? - Retry semantics — is
retryOf+ sharedtraceIdsufficient, or should there be an explicit terminal-attempt marker per logical call for "what did this call finally cost"?
Activity
Astro-Han commentedon Jul 31, 2026
The honesty framing (
granularity: 'aggregate',costBasis: 'unpriced',costUsd: 0reserved for genuinely free) is worth keeping. No blocker to PR #1; the items below need pinning before #2.Corrections to the RFC's own claims
doStream(ai-sdk-backend.ts:1229,1453; wrap atmodel-adapter.ts:168-178), andattemptsByStepincrements per step (provider-request-telemetry.ts:254-255). Per-physical-attempt records with tokens already exist in the AgentRun ledger today. What's missing iscallKind,costUsd, and a retry link, not the event.provider_retryis barred only from the RuntimeEvent generic lane (agent-run.ts:482), not from the attempt event.PiAgentBackendis instantiated only atpackages/headless/src/harbor-cell.ts:769; the desktop app never creates it. The "indistinguishable-from-real $0" framing overstates production urgency.enqueueTraceWriteFailure(agent-run.ts:1343-1353); it isn't fully silent.input:0,output:0turn is atruntime-kernel.ts:904-911, not 816-822.P1 findings
finalizeis awaited inside the ReadableStreampullhandler (provider-request-telemetry.ts:171-204); todayrecordAttemptfailure is swallowed (:284-288). If it rejects, the rejection propagates intopull's catch, thencontroller.error. A store-write failure errors an otherwise-complete model stream to the consumer. The abort path is worse:void finalize('aborted')(:259-262) is fire-and-forget, so fail-loud becomes an unhandled rejection. Check fail-loud pre-dispatch (alongside capture at:159-161) or surface it at the turn boundary; never throw fromfinalize. Capture's "same treatment" only works because capture is awaited beforedoStream.(step, requestHash), so retries share one capture and it can't serve as a dispatch counter.UsageCoverageclassifies records present, not records missing. Need a per-dispatch durable intent + settlement (outbox/seal), or accept that "complete" is unprovable and say so.semantic_compactdoesn't touch the seam.model-adapter.ts:109-110: "Auxiliary model calls intentionally omit it";ai-sdk-compaction.ts:1027callsgenerateCompactSummarydirectly and skips telemetry entirely when usage is missing (:1147). Routing it through the tracker is new wiring, and pre-turn compaction may have no active run, so the fail-loud policy there is unspecified. "One path for every kind" is a bigger change than the RFC states.traceIdis per-tracker-instance, not per logical call. New id per send (ai-sdk-backend.ts:776); history-compact gets a fresh id per summary (history-compact-summarizer.ts:112). "Grouped bytraceId" won't group a turn's calls or link compact calls to their turn. The effective key is(traceId, step). Formalize that, or add an explicitlogicalCallId.retryOfplus sharedtraceIdalone is insufficient (Q4).AgentRunEventisn't a strict accounting contract yet.decodeAgentRunEventonly checks thatdatais a record (core/agent-run.ts:302-314), not field shape; append is dedup-less JSONL; the attempt append doesn't requestdurable:true. For a canonical accounting record you need a subtype codec,schemaVersion,attemptIdidempotency, and an explicit durability contract. "No new table/store/writer" undersells that.finalize('aborted')and setsfinished=true; afinishwith usage arriving after is ignored. A call with real cost can land as a permanently token-less, cost-less record. Separate "cancel requested" from "provider settled" and allow late usage settlement.providerRequestTraceId = recordProviderRequestCapture ? this.newId() : undefined(ai-sdk-backend.ts:776-777): no capture wiring means no tracker, means zero attempts. "Unbind from capture" is restructuring construction, not just decoupling the attempt call. And capture is awaited beforedoStreamand is fail-closed. Capture already gates dispatch today; making attempts fail-loud pre-dispatch adds a second gate. State the gating policy.P2 findings
connectionSlug, callId, systemPromptHash, prefixHash, requestShapeHash/ChangeReason, toolSchemaChangeReason, toolAvailability, promptSegments, contextBudget, toolName, rawUsage). "Remove the double write, project from canonical records" needs one of: add them toModelCallAttempt, join viacaptureArtifactId, or drop the diagnostics. Pick one.stores.telemetry.*over theLlmCallRecordtable (HostUsagePricingCoordinator); the attempt-based event ledger is a per-session JSONL scan. "One read path" means re-implementing summary/buckets/paginated-logs overModelCallAttempt, likely a materialized projection with rebuild/checkpoint rules. Not just "extend the writer."unpricedconflates two problems. Failed/error/abort paths often have no usage, which is "usage unknown," not "price unknown." AddusageBasis: reported | partial | missingalongsidecostBasis, orunpricedCallsmixes the two.costUsd: 0already mixes free with unknown-price (computeCostreturns 0 when no pricing is configured). Migration can't honestly producepriced/unpricedfor old rows. Either don't migrate old telemetry into the canonical store (keep it a frozen read-only projection) or add alegacy_unknownbasis.usage_recordedRunTraceEvent,token_usageSessionEvent, RuntimeEvent aggregates. The latter two feed replay/recovery; deleting them breaks replay and contradicts the non-goal. Say precisely which write dies.agent-run.ts:1338-1343: "a required capture independently gates every provider dispatch." Fail-loud attempts add a second dispatch gate; the policy (gate dispatch / fail the turn / mark run incomplete) must be explicit. Also: attempt events usets: attempt.completedAtappended asynchronously, so ts-order differs from append-order. Projections must define which they use.Open questions
granularity: 'aggregate'in the core contract now. Add it when a second aggregate source actually ships.LlmCallRecordtable as a frozen read-only historical projection and have the canonical store start honest at cutover. This sidesteps the historical-$0ambiguity. Tradeoff: "all-time" usage queries must merge two sources until the old table ages out. State that explicitly.traceIdalone is insufficient (per Document Runtime v2 architecture evolution #4). Formalize the logical-call key as(traceId, step)or addlogicalCallId;retryOfis derivable from attempt ordering; a terminal marker is a projection concern, not a record field.Verdict on the PR breakdown: merge #2 and #4. After #2 alone, cost-carrying attempt records coexist with
recordLlmCallandusage_recorded. That's an interim triple-write that reintroduces the reconciliation drift this RFC exists to kill. Keep #3 (authority read-path switch) separate, since the projections must be re-implemented regardless. But ensure no release ships where the authority reads canonical while the old writers still run.中文对照
诚实性建模(
granularity: 'aggregate'、costBasis: 'unpriced'、costUsd: 0只留给真正免费)值得保留。PR #1 没有阻塞项;下面这些要在 #2 之前敲定。对 RFC 自声明的修正
doStream(ai-sdk-backend.ts:1229,1453;包裹在model-adapter.ts:168-178),attemptsByStep按 step 递增(provider-request-telemetry.ts:254-255)。带 token 的 per-physical-attempt 记录今天就已经在 AgentRun ledger 里。缺的是callKind、costUsd和重试链接,不是事件本身。provider_retry只被挡在 RuntimeEvent 通用 lane 外(agent-run.ts:482),不是 attempt event。PiAgentBackend只在packages/headless/src/harbor-cell.ts:769实例化;desktop 从不创建它。"和真免费无法区分的 $0"夸大了生产紧迫性。enqueueTraceWriteFailure记录(agent-run.ts:1343-1353);并非完全静默。input:0,output:0turn 在runtime-kernel.ts:904-911,不是 816-822。P1 findings
finalize在 ReadableStream 的pullhandler 里被 await(provider-request-telemetry.ts:171-204);今天recordAttempt失败被吞(:284-288)。改成 reject 会传进pull的 catch,再到controller.error。一次 store 写失败会把本已完成的模型流判成失败。abort 路径更糟:void finalize('aborted')(:259-262)是 fire-and-forget,fail-loud 会变成未处理 rejection。fail-loud 要在 dispatch 前(和 capture 一起在:159-161)检查,或在 turn 边界暴露;绝不能从finalize抛。capture 能用"同样处理"是因为它在doStream之前被 await。(step, requestHash)去重,多次重试共用一条,当不了 dispatch 计数器。UsageCoverage只能分类"已有的",发现不了"缺失的"。需要 per-dispatch 的 durable intent + settlement(outbox/seal),或者承认"完整"不可证并明说。semantic_compact根本不经过 seam。model-adapter.ts:109-110:"Auxiliary model calls intentionally omit it";ai-sdk-compaction.ts:1027直接调generateCompactSummary,且:1147在 usage 缺失时整条跳过。接进 tracker 是新接线,而且 pre-turn compaction 可能没有 active run,fail-loud 策略未定。"One path for every kind"比 RFC 说的改动大。traceId是 per-tracker-instance,不是 per logical call。 每次 send 新 id(ai-sdk-backend.ts:776);history-compact 每次 summary 新 id(history-compact-summarizer.ts:112)。"grouped bytraceId" 组不了一个 turn 的调用,也连不上 compact 调用和它的 turn。有效 key 是(traceId, step)。把它定形,或加显式logicalCallId。光靠retryOf+ 共享traceId不够(见 Q4)。AgentRunEvent还不是严格账务契约。decodeAgentRunEvent只查data是不是 record(core/agent-run.ts:302-314),不查字段;append 是无去重 JSONL;attempt append 不带durable:true。作为 canonical 记账记录,需要 subtype codec、schemaVersion、attemptId幂等和明确的持久性契约。"不建新表/新 store/新 writer"低估了这点。finalize('aborted')并置finished=true;之后到的带 usage 的finish被忽略。一次有真实花费的调用可能落成永久无 token、无 cost 的记录。把"已请求取消"和"provider 已结算"分开,允许 usage 延后结算。providerRequestTraceId = recordProviderRequestCapture ? this.newId() : undefined(ai-sdk-backend.ts:776-777):没 capture 接线就没 tracker,就没 attempt。"unbind from capture"是重构构造,不只是解耦 attempt 调用。而且 capture 在doStream前被 await 且 fail-closed。今天 capture 已经在门控 dispatch;让 attempt 在 dispatch 前 fail-loud 等于加第二道门。说清门控策略。P2 findings
connectionSlug, callId, systemPromptHash, prefixHash, requestShapeHash/ChangeReason, toolSchemaChangeReason, toolAvailability, promptSegments, contextBudget, toolName, rawUsage)。"删双写、从 canonical 投影"三选一:加进ModelCallAttempt、经captureArtifactIdjoin、或丢弃这些诊断。选一个。stores.telemetry.*,基于LlmCallRecord表(HostUsagePricingCoordinator);基于 attempt 的 event ledger 是 per-session JSONL 扫描。"one read path"意味着要在ModelCallAttempt上重实现 summary/buckets/分页 logs,大概率是个带 rebuild/checkpoint 规则的物化投影。不只是"扩展现有 writer"。unpriced混了两个问题。 failed/error/abort 路径常常没有 usage,那是"usage 未知",不是"价格未知"。在costBasis旁加usageBasis: reported | partial | missing,否则unpricedCalls把两者混在一起。costUsd: 0已经把真免费和价格未知混在一起(computeCost在无 pricing 时返回 0)。迁移没法诚实地产出旧行的priced/unpriced。要么不把旧遥测迁进 canonical store(留作只读历史投影),要么加legacy_unknownbasis。usage_recordedRunTraceEvent、token_usageSessionEvent、RuntimeEvent 聚合。后两者喂 replay/recovery;删了会断 replay,和非目标冲突。说清到底删哪个。agent-run.ts:1338-1343:"a required capture independently gates every provider dispatch." fail-loud attempt 加了第二道 dispatch 门;策略(门控 dispatch / 失败 turn / 标 run 不完整)必须明说。另外:attempt event 用ts: attempt.completedAt异步后写,所以 ts 序和 append 序不一致。投影必须定义用哪个。Open questions
granularity: 'aggregate'放进核心契约。等真有第二个 aggregate 源再加。LlmCallRecord表留作只读历史投影,canonical store 从 cutover 起诚实。这绕开历史$0的歧义。代价:"全时段"用量查询在旧表淘汰前要合两个源。这点要明说。traceId不够(见 Document Runtime v2 architecture evolution #4)。把 logical-call key 定形为(traceId, step)或加logicalCallId;retryOf可从 attempt 序推得;terminal marker 是投影问题,不是记录字段。PR 拆分结论: 合并 #2 和 #4。只做 #2 的话,带 cost 的 attempt 记录会和
recordLlmCall、usage_recorded共存。那是过渡期的 triple-write,会重新引入这个 RFC 要消灭的对账漂移。#3(authority 读路径切换)单独做,因为投影本来就要重写。但确保不会有哪个 release 在 authority 读 canonical 的同时旧 writer 还在跑。ARE404 commentedon Jul 31, 2026
All four corrections accepted — the gap list was overstated and I've rewritten it below. Taking the findings as decisions rather than questions where I can; flagging the two places I'm choosing a weaker guarantee on purpose.
Corrections folded in
callKind+costUsd+ a logical-call link missing from an event that already exists, not a missing event. Retries already re-enter the wrappeddoStreamandattemptsByStepincrements per step.PiAgentBackendis constructed atheadless/harbor-cell.ts:769and nowhere in desktop). Reclassified from "production billing hole" to "a second backend shape the contract shouldn't hard-code around yet" — which lines up with deferring Q1.enqueueTraceWriteFailure. The real gap is narrower: a missing active run is a no-op, and a post-dispatch write failure doesn't mark the run's accounting incomplete.runtime-kernel.ts:904-911.P1
1 — fail-loud placement. Accepted, and this was the most useful catch: erroring a completed model stream because a store write failed is strictly worse than the gap it was meant to close. Revised policy, three parts:
finalizenever throws. It stays best-effort at the stream boundary, including thevoid finalize('aborted')path.:159-161— not as a second gate, see Prefer RuntimeEvent read model for session reads #13.2 — provability. Choosing the weaker guarantee explicitly: no outbox in this RFC, and the contract will not claim completeness. A per-dispatch durable intent + settlement is the right mechanism, but it's a persistence-layer change of its own and bundling it here makes this unreviewable. So:
ModelCallAttemptis authoritative for the calls it records, the RFC states plainly that a crash between dispatch and finalize is unrecoverable and undetectable, andUsageCoverageis documented as classifying present records only — never as a completeness proof. Outbox/seal gets its own follow-up issue, and I'd rather name that limitation in the contract than imply a guarantee the storage layer can't make.3 —
semantic_compact. Accepted that this is real wiring, not a re-route:generateCompactSummaryis called directly and skips telemetry entirely when usage is missing, and pre-turn compaction may have no active run. Given #1's policy, the pre-turn case resolves cleanly — no active run means the precondition fails pre-dispatch, and for compaction that must not block the call; it records as accounting-incomplete instead. Since this is the largest single piece of new wiring, I'd like to split it out as its own PR after the seam lands, rather than hide it inside the merged #2+#4.4 — logical call identity. Adopting an explicit
logicalCallIdrather than formalizing the(traceId, step)tuple — a compound key that has to be reconstructed by every consumer is exactly the kind of implicit contract this RFC exists to remove.retryOfis dropped from the record per your note that it's derivable from attempt ordering within a logical call.5 —
AgentRunEventstrictness. Accepted; "no new table/store/writer" did undersell it. The contract adds a subtype codec validating field shape (not just "data is a record"),schemaVersion,attemptIdas an idempotency key on append, anddurable: trueon the attempt append. This is contract work, so it lands in PR 1.6 — abort settlement. Accepted.
finishedgets split into "cancel requested" and "provider settled"; afinishcarrying usage after an abort settles the record instead of being dropped. A cancelled call that consumed tokens is exactly the case that must not land as a zero.7 — tracker construction. Accepted —
providerRequestTraceId = recordProviderRequestCapture ? … : undefinedmeans unbinding is restructuring construction so the tracker exists whenever a provider dispatch happens, independent of capture wiring. Scoped into the seam PR.P2
8 — lost projection fields. Splitting rather than picking one bucket for all of them: identity fields (
connectionSlug,callId→logicalCallId) go onto the record; request-shape diagnostics (systemPromptHash,prefixHash,requestShapeHash/ChangeReason,toolSchemaChangeReason,toolAvailability,promptSegments) join viacaptureArtifactId, since they're capture-side facts already;contextBudgetstays on the RuntimeEvent usage where it's consumed today;toolNameis tool-invocation telemetry and out of scope here. Consequence stated up front: when capture is disabled those diagnostics are absent — which is already true today.9 — read path. Accepted: a per-session JSONL scan can't serve summary/buckets/paginated logs, so PR 3 is a materialized projection with explicit rebuild and checkpoint rules, not a writer swap. I'll scope it that way rather than as "extend the authority."
10 —
unpricedconflation. Accepted, addingusageBasis: 'reported' | 'partial' | 'missing'alongsidecostBasis. "The provider never reported usage" and "we have usage but no price" are different failures and shouldn't collapse into one counter.11 + Q3 — migration. Taking your recommendation: don't migrate.
LlmCallRecordstays a frozen read-only historical projection; the canonical store starts honest at cutover. Stated tradeoff: all-time usage queries merge two sources until the old table ages out, and the boundary date is user-visible. That's better than minting fakepriced/unpricedfor rows where0already means both free and unknown.12 — which write dies. Precisely:
recordLlmCall(send-level telemetry) and theusage_recordedRunTraceEvent.token_usageSessionEvent and the RuntimeEvent per-turn aggregates stay — they feed replay and recovery, and removing them would contradict the non-goal. The RFC text will name these four explicitly instead of saying "the attempt-usage write."13 — invariant and ordering. Both stated explicitly in the revised text. Capture remains the single dispatch gate; accounting preconditions are checked in the same pre-dispatch step rather than adding a second gate, and a post-dispatch accounting failure marks the run incomplete (never fails the turn). Projections order by append order, not
ts, since attempt events carryts: attempt.completedAtand are appended asynchronously.Open questions
Q1 defer, Q2 record-time frozen plus the pricing revision and rates used (agreed — a computed amount with no basis isn't auditable), Q3 don't migrate, Q4
logicalCallId. All four adopted as you proposed.Revised contract
granularityis gone (Q1 deferred); it returns with a second aggregate source, not before.Revised PR sequence
schemaVersion, idempotency, durability contract, pure projection helpers. No behavior change.recordLlmCallandusage_recordeddeleted in the same change so no release ships a triple write.semantic_compactrouting — split out per Extract runtime kernel boundaries and durable AgentRun recovery #3, since it's new wiring rather than a re-route.Starting on PR 1 now since it's unblocked. If the completeness call in P1-2 is the wrong trade — i.e. you'd rather the outbox be in scope than have the contract disclaim completeness — that's the one decision I'd want to reverse before the contract freezes.
feat(core): add canonical ModelCallAttempt accounting contract
feat(core): add canonical ModelCallAttempt accounting contract
feat(core): add canonical ModelCallAttempt accounting contract (#1687)
ARE404 commentedon Jul 31, 2026
PR 2's seam half is built —
ProviderRequestTrackernow emitsModelCallAttemptwith the pre-dispatch gate (never throwing fromfinalize), abort-then-late-settlement under oneattemptId, andlogicalCallIdper step reused across retries. Tracker suite 28/28.Before I finish the other half and open it, one ordering question I don't want to guess at.
Deleting
recordLlmCallin PR 2 leaves the Usage surface with no new data until PR 3 lands.HostUsagePricingCoordinatorreadsstores.telemetry.summary/buckets/logs/toolLogs, and theLlmCallRecordrows behind those are exactly whatrecordLlmCallwrites. So removing the writer in PR 2 while the read-path switch stays in PR 3 means every release in between shows a Usage page that stops accruing.Your constraint covers the opposite direction — no release where the authority reads canonical while the old writers still run. This is the mirror case, and I don't think the verdict settles it.
Three ways I can see, and I'd rather have your call than pick:
recordLlmCalland only PR 3 deletes it. This is the interim triple-write you already rejected, so I'm listing it only for completeness.I lean 1: it keeps the surface honest at every commit, keeps PR 3 independently reviewable, and the projection is deleted by the same PR that stops needing it. But it does add a write to PR 2 that PR 3 then removes, which cuts against "no parallel old/new writing" as literally stated — hence asking rather than assuming.
Two smaller ones while I'm here:
recordModelCallAttemptbe wired? My plan is runtime-kernel → AgentRun store as amodel_call_attempt_recordedevent withdurable: true, matching the durability contract from the P1-5 note. Confirming since the existing attempt append deliberately isn't durable.usage_recorded— I'm treating this as the RunTraceEvent only, leavingtoken_usageSessionEvent and the RuntimeEvent per-turn aggregates alone since they feed replay. That matches your P2-12 answer; flagging it so a wrong reading gets caught now rather than in review.Astro-Han commentedon Jul 31, 2026
On the ordering question — my suggestion would be a slightly stricter version of your option 2: consider merging PR 2 and PR 3 into one PR, as a single atomic slice that's end-to-end verifiable. Your call, of course — here's the reasoning that leads me there:
mainstays clean and releasable at every commit, with nothing to remember.usageBasis/costBasis, so unpriced or usage-missing records land ascostUsd: 0, indistinguishable from free. That's the failure mode this RFC exists to kill, showing up again in the interim window.A single PR also seems to fit the usual split criterion: parts are worth splitting when each can be independently reviewed and merged. PR 2 alone produces the awkward intermediate state, so it was never quite independently mergeable — splitting it may have been splitting for its own sake.
The honest cost: this puts the two heaviest pieces in one PR, which makes for a bigger review. If you go this way, a commit-level structure could keep it walkable in order, e.g.:
logicalCallId. Behavior-testable on its own.recordLlmCalland theusage_recordedRunTraceEvent, in the same commit so the switch is atomic.The upside is that acceptance becomes genuinely end-to-end: provider call → attempt record → projection → Usage surface, all in one slice.
If you still prefer keeping them as two PRs with release coordination, that's workable too — I just find the structural guarantee harder to get wrong than the remembered one.
Confirmations on the two smaller items — both look right to me:
recordModelCallAttempt→ AgentRun store asmodel_call_attempt_recordedwithdurable: true: agreed. The existing attempt append is diagnostic and deliberately non-durable; the canonical record is accounting and shouldn't be.usage_recorded= the RunTraceEvent only;token_usageSessionEvent and RuntimeEvent per-turn aggregates stay for replay/recovery: matches my P2-12 reading exactly.The sequence would then become:
Contract + tests— merged (feat(core): add canonical ModelCallAttempt accounting contract #1687).semantic_compactrouting — stays separate; it's new wiring, and it has no intermediate-state problem.中文对照
关于排序问题——我的建议是取你选项 2 的更严格版本:考虑把 PR 2 和 PR 3 合成一个 PR,作为一个原子切片,端到端可验收。当然由你决定——以下是我这么想的理由:
usageBasis/costBasis,unpriced 或缺 usage 的记录只能落成costUsd: 0,和真免费不可区分。这正是本 RFC 要消灭的失败模式,在中间窗口里又出现了。单 PR 也符合通常的拆分标准:各部分可独立 review 且可独立合并时才值得拆。PR 2 单独合入会产生尴尬中间态,所以本来就不太满足"可独立合并"——拆开或许是为拆而拆。
诚实的代价:这是最重的两块合在一起,review 体量会大。如果走这条路,可以用 commit 级结构让它按序可走,比如:
logicalCallId,自身可行为测试;recordLlmCall和usage_recordedRunTraceEvent,放同一个 commit 保证切换原子。好处是验收真正端到端:provider 调用 → attempt 记录 → 投影 → Usage 页,一个切片走完。
如果你还是更倾向两个 PR + release 协调,那也可行——我只是觉得结构性保证比靠记的保证更难出错。
两个小确认——都没问题:
recordModelCallAttempt→ AgentRun store,事件model_call_attempt_recorded带durable: true:同意。现有 attempt append 是诊断性的、刻意不 durable;canonical 是账务记录,必须 durable。usage_recorded只指 RunTraceEvent;token_usageSessionEvent 和 RuntimeEvent per-turn 聚合保留给 replay/recovery:与我在 P2-12 的口径完全一致。序列随之变为:
契约 + 测试——已合(feat(core): add canonical ModelCallAttempt accounting contract #1687);semantic_compact接线——保持独立,它是新接线,且没有中间态问题。ARE404 commentedon Jul 31, 2026
Merging them. And the argument against option 1 lands — I'd been weighing it as "one source rendered twice, so no drift", and missed that the old schema simply cannot carry
usageBasis/costBasis. Unpriced and usage-missing records would land ascostUsd: 0in the projection, indistinguishable from free. That's the failure mode this whole RFC exists to remove, reintroduced for the duration of the interim window. Option 1 is worse than the problem it solves.Agreed too that PR 2 was never independently mergeable — it only looked splittable because it was independently reviewable, and those aren't the same test.
Taking your commit structure as-is. Commit 1 is already built on my branch and matches it: pre-dispatch gate (settlement never throws —
finalizeruns in the stream'spullhandler), abort recorded provisionally so a laterfinishsettles under the sameattemptId, andlogicalCallIdper step reused across retries. 7 new tests, tracker suite 28/28.Next two commits are the materialized projection with rebuild/checkpoint rules, then the atomic read-path switch plus deletion of
recordLlmCalland theusage_recordedRunTraceEvent. Acceptance will be the end-to-end path you described: provider call → attempt record → projection → Usage surface.Both confirmations noted —
durable: trueonmodel_call_attempt_recorded, andusage_recordedscoped to the RunTraceEvent only.I'll open it as one PR once the read path is green rather than pushing a half slice.
feat(metering): read Usage from the canonical ledger and drop the sen…
feat(runtime): emit canonical ModelCallAttempt from the provider seam
feat(core): project Usage aggregates from the canonical attempt ledger
feat(metering): read Usage from the canonical ledger and drop the sen…
feat(runtime): emit canonical ModelCallAttempt from the provider seam
feat(core): project Usage aggregates from the canonical attempt ledger
feat(metering): read Usage from the canonical ledger and drop the sen…
14 remaining items
feat(desktop): lead the session trace with an Astryx-native overview (#…
feat(inspector): say what the context is full of, not just how full
feat(inspector): say what the context is full of, not just how full
refactor(context): give prompt composition to the owner that already …
feat(inspector): say what the context is full of, not just how full
refactor(context): give prompt composition to the owner that already …
feat(inspector): say what the context is full of, not just how full
refactor(context): give prompt composition to the owner that already …
github-actions commentedon Sep 2, 2026
This issue has had no human activity for 30 days and has been marked stale. It will be closed in 30 days unless someone comments.
If the issue is still current, please confirm it against the latest
mainand add any information that would help move it forward. Assigned issues and issues labelledpinnedare exempt from this policy.refactor(usage): give the model-call read model real pricing columns (#…
Astro-Han commentedon Sep 17, 2026
The canonical per-attempt record has landed.
ModelCallAttemptis defined inpackages/core/src/model-call-attempt.tscarryingcallKind,usageBasisandcostBasis, added by #1687 and made the metering source of truth by #1755, with compaction calls routed through the same seam in #1877. Closing as delivered; the Inspector that consumes these records continues in #1625.