Skip to content

[RFC] Canonical model-call accounting: one ModelCallAttempt record per real provider request #1679

Closed

Description

@ARE404

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:

  1. Provider retries carry no kind anywhere. The main telemetry record aggregates across retries, and provider_retry is barred from the AgentRun ledger (agent-run.ts:482). A retried call is invisible as a distinct billable event.
  2. The RuntimeEvent ledger attributes no compaction cost. Kernel compaction writes a phantom input: 0, output: 0 turn (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.
  3. The pi backend records no telemetry at all. recordLlmCall has zero references in pi-agent-backend.ts, so those sessions show tokens in the ledger and $0 in 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, recordProviderRequestCapture rejects when there's no active run while recordProviderRequestAttempt is run?.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. pi produces 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 from costUsd: 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:

  1. Fail loudly. recordProviderRequestAttempt gets the same treatment as recordProviderRequestCapture — a missing active run is an error, not a silent return.
  2. 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.
  3. One path for every kind. main, retries, semantic_compact, and history_compact all 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

Proposed PR breakdown

  1. Contract + tests. ModelCallAttempt type, event-type registration, validation, and pure projection helpers. No behavior change.
  2. Canonical seam. ProviderRequestTracker upgrade: fail-loud writes, unbind from capture, all four paths routed through it.
  3. Usage authority integration. Records feed feat(runtime-host): extract Usage/Pricing authority #1596's writer; rollups gain UsageCoverage; pi marked aggregate.
  4. Remove double metering. Delete the send-level and attempt-usage writes, one-time migration.

Open questions

  1. pi aggregates — should they land as granularity: 'aggregate' ModelCallAttempt records 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.
  2. Cost resolution point — resolve costUsd at record time (frozen at call time, matching what RuntimeEvent already stores) or at projection time from the pricing authority? I lean toward record time: a later price change shouldn't rewrite history.
  3. Migration fidelity — old telemetry rows have no attempt granularity. Migrate them as granularity: 'aggregate' rather than fabricating per-attempt structure?
  4. Retry semantics — is retryOf + shared traceId sufficient, or should there be an explicit terminal-attempt marker per logical call for "what did this call finally cost"?

Activity

  1. Astro-Han commented on Jul 31, 2026

    @Astro-Han
    Contributor

    The honesty framing (granularity: 'aggregate', costBasis: 'unpriced', costUsd: 0 reserved 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

    • Gap 1 is overstated. Each retry already re-enters the wrapped doStream (ai-sdk-backend.ts:1229,1453; wrap at model-adapter.ts:168-178), and attemptsByStep increments per step (provider-request-telemetry.ts:254-255). Per-physical-attempt records with tokens already exist in the AgentRun ledger today. What's missing is callKind, costUsd, and a retry link, not the event. provider_retry is barred only from the RuntimeEvent generic lane (agent-run.ts:482), not from the attempt event.
    • Gap 3 is harbor-only, not a production billing hole. PiAgentBackend is instantiated only at packages/headless/src/harbor-cell.ts:769; the desktop app never creates it. The "indistinguishable-from-real $0" framing overstates production urgency.
    • "Attempt writes drop silently" is partly overstated. A missing active run is a no-op, but a store-append failure is recorded via enqueueTraceWriteFailure (agent-run.ts:1343-1353); it isn't fully silent.
    • Line drift: the phantom compact input:0,output:0 turn is at runtime-kernel.ts:904-911, not 816-822.

    P1 findings

    1. "Fail loud" as specified corrupts the provider stream. finalize is awaited inside the ReadableStream pull handler (provider-request-telemetry.ts:171-204); today recordAttempt failure is swallowed (:284-288). If it rejects, the rejection propagates into pull's catch, then controller.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 from finalize. Capture's "same treatment" only works because capture is awaited before doStream.
    2. The RFC still can't prove completeness, its own stated goal. Attempts only finalize after the provider returns; a crash between dispatch and finalize leaves no record and no expected count. Capture dedups on (step, requestHash), so retries share one capture and it can't serve as a dispatch counter. UsageCoverage classifies records present, not records missing. Need a per-dispatch durable intent + settlement (outbox/seal), or accept that "complete" is unprovable and say so.
    3. semantic_compact doesn't touch the seam. model-adapter.ts:109-110: "Auxiliary model calls intentionally omit it"; ai-sdk-compaction.ts:1027 calls generateCompactSummary directly 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.
    4. traceId is 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 by traceId" 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 explicit logicalCallId. retryOf plus shared traceId alone is insufficient (Q4).
    5. AgentRunEvent isn't a strict accounting contract yet. decodeAgentRunEvent only checks that data is a record (core/agent-run.ts:302-314), not field shape; append is dedup-less JSONL; the attempt append doesn't request durable:true. For a canonical accounting record you need a subtype codec, schemaVersion, attemptId idempotency, and an explicit durability contract. "No new table/store/writer" undersells that.
    6. Abort freezes the bill too early. The abort listener immediately calls finalize('aborted') and sets finished=true; a finish with 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.
    7. Tracker existence is gated on capture wiring. 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 before doStream and is fail-closed. Capture already gates dispatch today; making attempts fail-loud pre-dispatch adds a second gate. State the gating policy.

    P2 findings

    1. Telemetry projection loses fields the sketched record doesn't carry (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 to ModelCallAttempt, join via captureArtifactId, or drop the diagnostics. Pick one.
    2. The Usage authority reads stores.telemetry.* over the LlmCallRecord table (HostUsagePricingCoordinator); the attempt-based event ledger is a per-session JSONL scan. "One read path" means re-implementing summary/buckets/paginated-logs over ModelCallAttempt, likely a materialized projection with rebuild/checkpoint rules. Not just "extend the writer."
    3. unpriced conflates two problems. Failed/error/abort paths often have no usage, which is "usage unknown," not "price unknown." Add usageBasis: reported | partial | missing alongside costBasis, or unpricedCalls mixes the two.
    4. Historical costUsd: 0 already mixes free with unknown-price (computeCost returns 0 when no pricing is configured). Migration can't honestly produce priced/unpriced for old rows. Either don't migrate old telemetry into the canonical store (keep it a frozen read-only projection) or add a legacy_unknown basis.
    5. "Delete the attempt-usage write" is ambiguous. Candidates: usage_recorded RunTraceEvent, token_usage SessionEvent, RuntimeEvent aggregates. The latter two feed replay/recovery; deleting them breaks replay and contradicts the non-goal. Say precisely which write dies.
    6. The RFC overturns a documented invariant without saying so. 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 use ts: attempt.completedAt appended asynchronously, so ts-order differs from append-order. Projections must define which they use.

    Open questions

    • Q1 (pi): defer. Keep the canonical store attempt-only; a harbor-only backend doesn't justify granularity: 'aggregate' in the core contract now. Add it when a second aggregate source actually ships.
    • Q2 (cost): record-time, frozen. Also persist the pricing revision/rates used (the Host already snapshots pricing at backend creation), not just the computed amount, so the figure is auditable.
    • Q3 (migration): recommend don't migrate. Keep the LlmCallRecord table as a frozen read-only historical projection and have the canonical store start honest at cutover. This sidesteps the historical-$0 ambiguity. Tradeoff: "all-time" usage queries must merge two sources until the old table ages out. State that explicitly.
    • Q4 (retry): traceId alone is insufficient (per Document Runtime v2 architecture evolution #4). Formalize the logical-call key as (traceId, step) or add logicalCallId; retryOf is 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 recordLlmCall and usage_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 自声明的修正

    • Gap 1 被高估。 每次重试都已经重新进入被包裹的 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。
    • Gap 3 是 harbor 专用,不是生产计费漏洞。 PiAgentBackend 只在 packages/headless/src/harbor-cell.ts:769 实例化;desktop 从不创建它。"和真免费无法区分的 $0"夸大了生产紧迫性。
    • "attempt 写入静默丢失"部分被高估。 缺 active run 时确实是 no-op,但 store-append 失败会经 enqueueTraceWriteFailure 记录(agent-run.ts:1343-1353);并非完全静默。
    • 行号漂移: 幽灵 compact input:0,output:0 turn 在 runtime-kernel.ts:904-911,不是 816-822。

    P1 findings

    1. "Fail loud" 按现在写法会破坏 provider 流。 finalize 在 ReadableStream 的 pull handler 里被 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。
    2. RFC 仍证不了"完整",这是它自己声称的目标。 attempt 只在 provider 返回后才 finalize;dispatch 后、落账前崩溃 = 既没记录也没 expected count。capture 按 (step, requestHash) 去重,多次重试共用一条,当不了 dispatch 计数器。UsageCoverage 只能分类"已有的",发现不了"缺失的"。需要 per-dispatch 的 durable intent + settlement(outbox/seal),或者承认"完整"不可证并明说。
    3. 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 说的改动大。
    4. traceId 是 per-tracker-instance,不是 per logical call。 每次 send 新 id(ai-sdk-backend.ts:776);history-compact 每次 summary 新 id(history-compact-summarizer.ts:112)。"grouped by traceId" 组不了一个 turn 的调用,也连不上 compact 调用和它的 turn。有效 key 是 (traceId, step)。把它定形,或加显式 logicalCallId。光靠 retryOf + 共享 traceId 不够(见 Q4)。
    5. AgentRunEvent 还不是严格账务契约。 decodeAgentRunEvent 只查 data 是不是 record(core/agent-run.ts:302-314),不查字段;append 是无去重 JSONL;attempt append 不带 durable:true。作为 canonical 记账记录,需要 subtype codec、schemaVersion、attemptId 幂等和明确的持久性契约。"不建新表/新 store/新 writer"低估了这点。
    6. abort 过早冻结账单。 abort listener 立刻调 finalize('aborted') 并置 finished=true;之后到的带 usage 的 finish 被忽略。一次有真实花费的调用可能落成永久无 token、无 cost 的记录。把"已请求取消"和"provider 已结算"分开,允许 usage 延后结算。
    7. tracker 的存在被 capture 接线门控。 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

    1. 遥测投影丢掉草案记录里没有的字段(connectionSlug, callId, systemPromptHash, prefixHash, requestShapeHash/ChangeReason, toolSchemaChangeReason, toolAvailability, promptSegments, contextBudget, toolName, rawUsage)。"删双写、从 canonical 投影"三选一:加进 ModelCallAttempt、经 captureArtifactId join、或丢弃这些诊断。选一个。
    2. Usage authority 读的是 stores.telemetry.*,基于 LlmCallRecord 表(HostUsagePricingCoordinator);基于 attempt 的 event ledger 是 per-session JSONL 扫描。"one read path"意味着要在 ModelCallAttempt 上重实现 summary/buckets/分页 logs,大概率是个带 rebuild/checkpoint 规则的物化投影。不只是"扩展现有 writer"。
    3. unpriced 混了两个问题。 failed/error/abort 路径常常没有 usage,那是"usage 未知",不是"价格未知"。在 costBasis 旁加 usageBasis: reported | partial | missing,否则 unpricedCalls 把两者混在一起。
    4. 历史 costUsd: 0 已经把真免费和价格未知混在一起(computeCost 在无 pricing 时返回 0)。迁移没法诚实地产出旧行的 priced/unpriced。要么不把旧遥测迁进 canonical store(留作只读历史投影),要么加 legacy_unknown basis。
    5. "删 attempt-usage write"有歧义。 候选:usage_recorded RunTraceEvent、token_usage SessionEvent、RuntimeEvent 聚合。后两者喂 replay/recovery;删了会断 replay,和非目标冲突。说清到底删哪个。
    6. RFC 推翻了一条已记录的不变量却没说。 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

    • Q1(pi): defer。canonical store 先只做 attempt;harbor-only 后端不值得现在把 granularity: 'aggregate' 放进核心契约。等真有第二个 aggregate 源再加。
    • Q2(cost): 记录时冻结。同时持久化所用的 pricing revision/rates(Host 在 backend 创建时已 snapshot pricing),不只是算出的金额,这样数字可审计。
    • Q3(迁移): 建议不迁。把 LlmCallRecord 表留作只读历史投影,canonical store 从 cutover 起诚实。这绕开历史 $0 的歧义。代价:"全时段"用量查询在旧表淘汰前要合两个源。这点要明说。
    • Q4(retry): 光 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 还在跑。

  2. ARE404 commented on Jul 31, 2026

    @ARE404
    ContributorAuthor

    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

    • Gap 1 is callKind + costUsd + a logical-call link missing from an event that already exists, not a missing event. Retries already re-enter the wrapped doStream and attemptsByStep increments per step.
    • Gap 3 is harbor-only (PiAgentBackend is constructed at headless/harbor-cell.ts:769 and 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.
    • Silent drop — store-append failures do surface via 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.
    • Phantom compact turn is 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:

    • finalize never throws. It stays best-effort at the stream boundary, including the void finalize('aborted') path.
    • The accounting precondition (active run resolvable, writer available) is checked pre-dispatch, alongside capture at :159-161 — not as a second gate, see Prefer RuntimeEvent read model for session reads #13.
    • A post-dispatch write failure marks the run's accounting incomplete rather than failing the turn. That's the honest outcome: the model call happened and was billed, so failing the turn would misreport it.

    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: ModelCallAttempt is authoritative for the calls it records, the RFC states plainly that a crash between dispatch and finalize is unrecoverable and undetectable, and UsageCoverage is 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: generateCompactSummary is 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 logicalCallId rather 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. retryOf is dropped from the record per your note that it's derivable from attempt ordering within a logical call.

    5 — AgentRunEvent strictness. 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, attemptId as an idempotency key on append, and durable: true on the attempt append. This is contract work, so it lands in PR 1.

    6 — abort settlement. Accepted. finished gets split into "cancel requested" and "provider settled"; a finish carrying 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 ? … : undefined means 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 via captureArtifactId, since they're capture-side facts already; contextBudget stays on the RuntimeEvent usage where it's consumed today; toolName is 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 — unpriced conflation. Accepted, adding usageBasis: 'reported' | 'partial' | 'missing' alongside costBasis. "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. LlmCallRecord stays 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 fake priced/unpriced for rows where 0 already means both free and unknown.

    12 — which write dies. Precisely: recordLlmCall (send-level telemetry) and the usage_recorded RunTraceEvent. token_usage SessionEvent 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 carry ts: attempt.completedAt and 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

    export interface ModelCallAttempt {
      schemaVersion: 1;
    
      // identity
      logicalCallId: string;   // one logical model call; attempts share it
      attemptId: string;       // idempotency key on append
      traceId: string;         // tracker instance, retained for capture join
      sessionId: string; runId: string; turnId: string;
      step: number; attempt: number;
    
      callKind: 'main' | 'semantic_compact' | 'history_compact';
      connectionSlug?: string;
      providerId: string; modelId: string;
      contextWindow?: number;
      captureArtifactId?: string;   // join key for request-shape diagnostics
    
      // timing
      startedAt: number; completedAt: number;
      latencyMs: number; timeToFirstTokenMs?: number;
    
      // outcome
      status: 'completed' | 'failed' | 'interrupted' | 'aborted';
      finishReason?: string; errorClass?: string;
    
      // usage
      usageBasis: 'reported' | 'partial' | 'missing';
      inputTokens?: number; outputTokens?: number;
      cacheReadInputTokens?: number; cacheMissInputTokens?: number;
      cacheWriteInputTokens?: number; reasoningTokens?: number;
    
      // accounting
      costBasis: 'priced' | 'unpriced';
      costUsd?: number;               // absent unless costBasis === 'priced'
      pricingRevision?: number;       // basis, for audit
      pricingRates?: PricingRates;
    }

    granularity is gone (Q1 deferred); it returns with a second aggregate source, not before.

    Revised PR sequence

    1. Contract + tests — record, subtype codec, schemaVersion, idempotency, durability contract, pure projection helpers. No behavior change.
    2. Canonical seam + remove double metering (your merge of old Harden runtime, storage, gateway, credentials, and IPC inputs #2 and Document Runtime v2 architecture evolution #4) — tracker restructuring, pre-dispatch precondition, abort settlement, recordLlmCall and usage_recorded deleted in the same change so no release ships a triple write.
    3. semantic_compact routing — split out per Extract runtime kernel boundaries and durable AgentRun recovery #3, since it's new wiring rather than a re-route.
    4. Authority read path — materialized projection with rebuild/checkpoint rules; must not ship before 2 lands.

    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.

  3. ARE404 commented on Jul 31, 2026

    @ARE404
    ContributorAuthor

    PR 2's seam half is built — ProviderRequestTracker now emits ModelCallAttempt with the pre-dispatch gate (never throwing from finalize), abort-then-late-settlement under one attemptId, and logicalCallId per 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 recordLlmCall in PR 2 leaves the Usage surface with no new data until PR 3 lands. HostUsagePricingCoordinator reads stores.telemetry.summary / buckets / logs / toolLogs, and the LlmCallRecord rows behind those are exactly what recordLlmCall writes. 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:

    1. PR 2's canonical writer also projects into the telemetry table, and PR 3 drops that projection when the read path moves. This keeps Usage working throughout. It is technically a second write, but not the failure mode the RFC targets: one canonical source rendered twice, not two independent meters that can disagree. The drift you want killed comes from independent measurement, and there is none here.
    2. PR 2 and PR 3 land together in one release, never shipped apart. Satisfies both constraints, but makes the read-path re-implementation part of the same merge window rather than a separately reviewable change.
    3. PR 2 keeps recordLlmCall and 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:

    • Where should recordModelCallAttempt be wired? My plan is runtime-kernel → AgentRun store as a model_call_attempt_recorded event with durable: 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, leaving token_usage SessionEvent 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.
  4. Astro-Han commented on Jul 31, 2026

    @Astro-Han
    Contributor

    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:

    • Release-gating two separate PRs keeps the constraint at the discipline level — someone has to remember not to cut a release between them. A single PR moves the guarantee into the structure: main stays clean and releasable at every commit, with nothing to remember.
    • On option 1 — I can see the appeal, but I'd gently argue against it, on its own terms. Projecting canonical records into the old telemetry table means (a) code written with a planned deletion date, (b) re-aggregating per-attempt records back into per-send rows — the exact structure this RFC removes — to serve a table on its way out, and (c) the part that tips it for me: it reintroduces dishonest zeros. The old schema can't express usageBasis/costBasis, so unpriced or usage-missing records land as costUsd: 0, indistinguishable from free. That's the failure mode this RFC exists to kill, showing up again in the interim window.
    • Option 3 we both already agree on — the interim triple-write.

    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.:

    1. Tracker/seam restructuring — pre-dispatch gate, abort late-settlement, logicalCallId. Behavior-testable on its own.
    2. Materialized projection with rebuild/checkpoint rules.
    3. Read-path switch + delete recordLlmCall and the usage_recorded RunTraceEvent, 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 as model_call_attempt_recorded with durable: 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_usage SessionEvent and RuntimeEvent per-turn aggregates stay for replay/recovery: matches my P2-12 reading exactly.

    The sequence would then become:

    1. Contract + tests — merged (feat(core): add canonical ModelCallAttempt accounting contract #1687).
    2. Canonical seam + projection + read-path switch + double-write removal — one PR.
    3. semantic_compact routing — stays separate; it's new wiring, and it has no intermediate-state problem.
    中文对照

    关于排序问题——我的建议是取你选项 2 的更严格版本:考虑把 PR 2 和 PR 3 合成一个 PR,作为一个原子切片,端到端可验收。当然由你决定——以下是我这么想的理由:

    • 两个 PR 分开 + release gating 把约束留在纪律层面——得有人记得在两个 PR 之间不切 release。单个 PR 把保证移进结构:main 在每个 commit 都干净、可发布,没有任何需要记的东西。
    • 关于选项 1——我能看到它的吸引力,但想温和地反对一下,按它自己的逻辑。把 canonical 记录投影进旧 telemetry 表意味着:(a) 一套写好时就预定了删除日期的代码;(b) 把 per-attempt 记录反向重聚合回 per-send 行——正是本 RFC 拆掉的结构——只为伺候一张将死的表;(c) 对我来说最关键的一点:它重新引入了不诚实零。旧 schema 表达不了 usageBasis/costBasis,unpriced 或缺 usage 的记录只能落成 costUsd: 0,和真免费不可区分。这正是本 RFC 要消灭的失败模式,在中间窗口里又出现了。
    • 选项 3 我们已经一致——过渡期 triple-write。

    单 PR 也符合通常的拆分标准:各部分可独立 review 且可独立合并时才值得拆。PR 2 单独合入会产生尴尬中间态,所以本来就不太满足"可独立合并"——拆开或许是为拆而拆。

    诚实的代价:这是最重的两块合在一起,review 体量会大。如果走这条路,可以用 commit 级结构让它按序可走,比如:

    1. tracker/seam 重构——pre-dispatch 门、abort 延迟结算、logicalCallId,自身可行为测试;
    2. 带 rebuild/checkpoint 规则的物化投影;
    3. 读路径切换 + 删 recordLlmCall 和 usage_recorded RunTraceEvent,放同一个 commit 保证切换原子。

    好处是验收真正端到端:provider 调用 → attempt 记录 → 投影 → Usage 页,一个切片走完。

    如果你还是更倾向两个 PR + release 协调,那也可行——我只是觉得结构性保证比靠记的保证更难出错。

    两个小确认——都没问题:

    • recordModelCallAttempt → AgentRun store,事件 model_call_attempt_recorded 带 durable: true:同意。现有 attempt append 是诊断性的、刻意不 durable;canonical 是账务记录,必须 durable。
    • usage_recorded 只指 RunTraceEvent;token_usage SessionEvent 和 RuntimeEvent per-turn 聚合保留给 replay/recovery:与我在 P2-12 的口径完全一致。

    序列随之变为:

    1. 契约 + 测试——已合(feat(core): add canonical ModelCallAttempt accounting contract #1687);
    2. canonical seam + 投影 + 读路径切换 + 删双写——一个 PR;
    3. semantic_compact 接线——保持独立,它是新接线,且没有中间态问题。
  5. ARE404 commented on Jul 31, 2026

    @ARE404
    ContributorAuthor

    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 as costUsd: 0 in 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 — finalize runs in the stream's pull handler), abort recorded provisionally so a later finish settles under the same attemptId, and logicalCallId per 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 recordLlmCall and the usage_recorded RunTraceEvent. Acceptance will be the end-to-end path you described: provider call → attempt record → projection → Usage surface.

    Both confirmations noted — durable: true on model_call_attempt_recorded, and usage_recorded scoped to the RunTraceEvent only.

    I'll open it as one PR once the read path is green rather than pushing a half slice.

  6. 14 remaining items

  7. added
    enhancement
    on Aug 20, 2026
  8. added
    stale
    on Sep 2, 2026
  9. github-actions commented on Sep 2, 2026

    @github-actions

    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 main and add any information that would help move it forward. Assigned issues and issues labelled pinned are exempt from this policy.

  10. Astro-Han commented on Sep 17, 2026

    @Astro-Han
    Contributor

    The canonical per-attempt record has landed. ModelCallAttempt is defined in packages/core/src/model-call-attempt.ts carrying callKind, usageBasis and costBasis, 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementstale

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions