Skip to content

Commit 388f9d1

Browse files
jay-tauCopilot
andcommitted
refactor(adapter/copilot): drop unused _event_id param + trim 3 multi-paragraph comments
External review ccusage#13 raised two related items: ## Nit a: Drop unused `_event_id` from `build_aggregate_credit_entry` The function takes `_event_id: &str` but never uses it — the dedup key is content-based by design (`credit-aggregate:{session_id}:{nano_aiu}` omits event_id deliberately, mirroring the per-model credit-only path). Since this is a private helper with one call site, drop the parameter entirely rather than passing-and-discarding `&event.id`. Removed both the parameter declaration in `build_aggregate_credit_entry` (parser.rs:1040) and the corresponding argument at the call site in `parse_session_state_file` (parser.rs:884). Pure simplification — behavior unchanged, no caller exists that passed a meaningful event_id. ## Item 3: Comment-trim pass on three remaining multi-paragraph blocks Reviewer flagged that despite the recent comment-density work in `b529041`, three blocks (mode-dispatch table in `usage_entry_to_loaded`, aggregate-credit guard in `parse_session_state_file`, and the `build_aggregate_credit_entry` dedup-key doc) still read as design docs inlined into source. Continued the trim direction the branch has been moving: - **`loader.rs` mode-dispatch comment**: 47 lines -> 20 lines. Kept the load-bearing field-presence invariant, the behavior table, the free-tier middle-column note, and the synthetic-aggregate bypass pointer. Dropped: the multi-paragraph era-vs-date justification (now points to the adapter README), the duplicate "`auto`/`display` follow this ladder" restatement, and the prose about each cell's derivation (the table is self-explanatory). - **`parser.rs` aggregate-credit guard comment**: 47 lines -> 18 lines. Restructured as three labeled invariants (priced-billing check / `skip_metrics_row` mirror / narrower-than-any-data) with the load-bearing trade-off (visible over-count vs. silent under-count) preserved as a single bullet. Dropped: the multi-paragraph "corpus measurement" prose (the unobserved forward-compat status is captured in one phrase), the redundant closing summary, and the Display-no-stack note (already implicit in the mode-dispatch table). - **`parser.rs` `build_aggregate_credit_entry` dedup-key doc**: 19 lines -> 9 lines. Kept the structural decision (content-based key, omits event_id, mirrors per-model path), the load-bearing trade-off (silent-under-count vs. silent-double-count), and the README cross-reference. Dropped: the longer real-data explanation (already in the README's "Resumed sessions and dedup-key design" section that the new comment now references) and the monotonic- totals aside. Net: -85 comment lines, -1 unused parameter. Same load-bearing rationale, denser presentation. Future maintainers can follow the adapter README cross-references for the longer context. ## Items NOT actioned this round - Item 2 (fold OTel removal vs re-file ccusage#1208): user decision. - Item 4 (confirm product intent on global `--mode api`): maintainer decision (not the contributor's call). - Item 5 (`== 0.0` float compare): explicitly "acceptable as-is per the comment" by the reviewer. - Nit b (schema oxfmt churn): "not actionable, heads-up". - Nit c (72 commits, squash-merge): squash-message content already captured in the PR body's "Behavior changes" section. ## Validation at this tip - `cd rust && cargo fmt --check` — clean - `cd rust && cargo clippy --workspace --all-targets -- -D warnings` — clean - `cd rust && cargo test --workspace` — 368 tests pass (unchanged; comment-and-param-only change, all parsed-output behavior unchanged) Refs ccusage#1174. Co-authored-by: Copilot <[email protected]>
1 parent b0e777a commit 388f9d1

2 files changed

Lines changed: 48 additions & 109 deletions

File tree

‎rust/crates/ccusage/src/adapter/copilot/loader.rs‎

Lines changed: 16 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -226,52 +226,30 @@ fn usage_entry_to_loaded(
226226
.map(|requests| requests * PREMIUM_REQUEST_COST_USD);
227227
let has_premium_data = premium_cost.is_some();
228228

229-
// Mode dispatch — Copilot's "true billing" is era-dependent:
230-
//
231-
// * Post-cutover (CLI ≥ 1.0.40): `(totalNanoAiu / 1e9) × $0.01` (AI Credits)
232-
// * Pre-cutover (older CLI): `requests.cost × $0.04` (premium requests)
233-
//
234-
// **The dispatch keys off field PRESENCE, not the cutover date.** We
235-
// never compare `entry.timestamp` against June 1, 2026 — we just ask
236-
// "did this row ship an AIU value?" and pick the AIU billing if so.
237-
// That's deliberate: a pre-cutover session that happened to carry AIU
238-
// would bill as AIU (which is the correct behavior — the CLI only
239-
// ships AIU when GitHub actually charged AIU), and the implementation
240-
// is robust to GitHub backfilling AIU into older rows or to a future
241-
// schema change that introduces a third billing channel. The cutover
242-
// date is the *why* behind the two columns existing; it is not a
243-
// branching condition in the code.
244-
//
245-
// `auto` and `display` follow this true-bill ladder; `calculate` /
246-
// `api` is always token-priced.
247-
//
248-
// Behavior table:
229+
// Mode dispatch — Copilot's "true billing" is billing-field-aware
230+
// (not date-based): the loader keys off `has_aiu` / `has_premium_data`,
231+
// never `entry.timestamp`. This is robust to backfills and future
232+
// billing channels — see `adapter/copilot/README.md` for the cutover
233+
// history and the field-presence rationale.
249234
//
250235
// | AIU present | AIU absent, premium present | AIU absent, premium absent
251236
// -----------------|-----------------|-----------------------------|---------------------------
252237
// Auto (default) | credits × $0.01 | requests.cost × $0.04 | token-priced
253238
// Display | credits × $0.01 | requests.cost × $0.04 | 0
254239
// Calculate / api | token-priced | token-priced | token-priced
255240
//
256-
// Note: "premium present" means `premium_cost.is_some()`, which is
257-
// `true` even for `Some(0.0)`. The middle column therefore covers
258-
// free-tier sonnet/haiku rows whose `requests.cost == 0` — Auto/Display
259-
// bill them as a genuine `$0` against the premium-request plan, not as
260-
// missing data. The rightmost Auto cell's "token-priced" branch only
261-
// ever fires when the source ships NEITHER AIU nor `requests.cost` at
262-
// all (e.g. historical OTel data, or some future Copilot CLI variant).
263-
// For current session-state data `requests.cost` is always present, so
264-
// free-tier rows take the middle-column branch — intentionally,
265-
// because falling through to token pricing would invent cost the user
266-
// never owed under the premium-request plan.
241+
// "premium present" = `premium_cost.is_some()`, true even for
242+
// `Some(0.0)`. The middle column therefore covers free-tier
243+
// sonnet/haiku rows whose `requests.cost == 0` — Auto/Display bill
244+
// those as a genuine `$0` against the premium-request plan, not as
245+
// missing data. The rightmost Auto cell's token-priced fallback only
246+
// fires when the source ships NEITHER billing field (historical OTel
247+
// or a future Copilot CLI variant).
267248
//
268-
// Synthetic aggregate-credit rows (emitted when `data.totalNanoAiu > 0`
269-
// AND no per-model row already carries a priced billing signal — see
270-
// `parser.rs::parse_session_state_file` for the exact guard) bypass
271-
// this table entirely — they are handled by the
272-
// `if entry.model.is_empty()` branch immediately below, where Auto /
273-
// Display bill from the aggregate AIU and Calculate contributes
274-
// nothing (no model or tokens to price).
249+
// Synthetic aggregate-credit rows (empty `entry.model`, emitted by
250+
// `parser.rs::parse_session_state_file` when `data.totalNanoAiu > 0`
251+
// and no per-model row carries a priced signal) bypass this table —
252+
// see the `if entry.model.is_empty()` branch immediately below.
275253
let (cost, missing_pricing_model) = if entry.model.is_empty() {
276254
// Aggregate-credit synthetic rows carry no model. Modes that honor
277255
// source-precomputed cost (Auto / Display) bill from the aggregate

‎rust/crates/ccusage/src/adapter/copilot/parser.rs‎

Lines changed: 32 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -824,54 +824,29 @@ pub(super) fn parse_session_state_file(path: &Path) -> Result<Vec<CopilotUsageEn
824824
));
825825
}
826826

827-
// Aggregate-only credits path: when the shutdown event reports a
827+
// Aggregate-only credits path: when the shutdown event reports
828828
// session-level `totalNanoAiu > 0` AND no EMITTED per-model row
829-
// already carries a priced billing signal (per-model `naiu > 0`
830-
// OR `requests.cost > 0`), emit a synthetic zero-token,
831-
// model-less entry that carries the aggregate credits.
829+
// already carries a priced billing signal (`naiu > 0` OR
830+
// `cost > 0`), emit a synthetic zero-token, model-less entry
831+
// that carries the aggregate credits.
832832
//
833-
// The guard checks for priced billing — not just per-model AIU —
834-
// because the wire format may continue to ship `requests.cost` on
835-
// post-cutover sessions for backward compatibility. Without this
836-
// tightening, a future shape with `aggregate AIU > 0` + per-model
837-
// `cost > 0` + no per-model AIU would bill the same usage twice in
838-
// two currencies: per-model rows via `cost × $0.04` (Auto's premium
839-
// ladder) AND the synthetic via `aiu × $0.01` (Auto's AIU ladder).
840-
//
841-
// The guard MUST mirror the `skip_metrics_row` filter applied
842-
// above when iterating model_metrics. Otherwise a row that was
843-
// skipped (no entry emitted) could still suppress the synthetic
844-
// aggregate-credit — silently losing the session's only priced
845-
// signal. The shape that exposes this is unreachable on observed
846-
// data (`requests.cost` = `count × multiplier`, so
847-
// `count == 0` ⇒ `cost == 0`), but the symmetric check costs
848-
// nothing and removes the "what was actually emitted vs. what
849-
// the raw map shows" inconsistency.
850-
//
851-
// The check is intentionally narrower than "any per-model row with
852-
// any data": a per-model row with tokens but neither AIU nor cost
853-
// is treated as a forward-compat shape where the aggregate AIU is
854-
// the only **source-provided** priced signal — so the synthetic is
855-
// preserved. Note that under `--mode auto`, the per-model row is
856-
// still independently token-priced via LiteLLM, so the session's
857-
// total billing for this shape STACKS the per-model token cost on
858-
// top of the synthetic's `aiu × $0.01`. We accept this stack
859-
// because:
860-
// * The shape is unobserved in the local 200-file corpus
861-
// (current CLI versions ship `requests.cost` on every
862-
// priced row, so this branch never fires today).
863-
// * If the CLI ever emits this shape, dropping the aggregate
864-
// AIU would silently lose a real charge the user owed, which
865-
// is the worse failure mode (silent under-count) vs. the
866-
// visible over-count (token cost stacked on AIU cost, with
867-
// `credits` JSON-surfaced for diagnosis).
868-
// * `--mode display` does NOT have this stack — the per-model
869-
// row bills $0 in Display when neither AIU nor cost is
870-
// present, so only the synthetic contributes.
871-
//
872-
// Not observed in the local 200-file corpus (every aggregate seen
873-
// so far is also present per-model with non-zero AIU) but kept as
874-
// a forward-compat guard against schema evolution.
833+
// Three load-bearing invariants:
834+
// - **Guard checks priced billing, not just AIU**: prevents
835+
// double-billing when post-cutover rows still ship the inert
836+
// `requests.cost`.
837+
// - **Guard mirrors `skip_metrics_row`**: a skipped row must
838+
// not suppress the synthetic (currently unreachable since
839+
// `cost = count × multiplier`, but the symmetry costs nothing
840+
// and removes a "raw vs. emitted" inconsistency).
841+
// - **Narrower than "any data"**: a per-model row with tokens
842+
// but neither AIU nor cost preserves the synthetic. Under
843+
// Auto this stacks per-model token cost on the synthetic AIU
844+
// cost — accepted because the shape is unobserved in the
845+
// local corpus and a visible over-count with `credits`
846+
// JSON-surfaced is a strictly better failure mode than
847+
// silently losing the aggregate AIU. Display has no stack
848+
// (per-model row bills $0 without a source-precomputed
849+
// signal).
875850
let aggregate_naiu = event.data.total_nano_aiu;
876851
let any_per_model_priced_billing = event.data.model_metrics.iter().any(|(model, m)| {
877852
!skip_metrics_row(model, m)
@@ -880,12 +855,7 @@ pub(super) fn parse_session_state_file(path: &Path) -> Result<Vec<CopilotUsageEn
880855
});
881856
if let Some(naiu) = aggregate_naiu {
882857
if !any_per_model_priced_billing && naiu > 0 {
883-
entries.push(build_aggregate_credit_entry(
884-
&session_id,
885-
&event.id,
886-
naiu,
887-
timestamp,
888-
));
858+
entries.push(build_aggregate_credit_entry(&session_id, naiu, timestamp));
889859
}
890860
}
891861
}
@@ -1040,7 +1010,6 @@ fn build_session_state_entry(
10401010
/// clean while still surfacing the credit total.
10411011
fn build_aggregate_credit_entry(
10421012
session_id: &str,
1043-
_event_id: &str,
10441013
nano_aiu: u64,
10451014
timestamp: TimestampMs,
10461015
) -> CopilotUsageEntry {
@@ -1055,24 +1024,16 @@ fn build_aggregate_credit_entry(
10551024
cache_creation_tokens: 0,
10561025
cache_read_tokens: 0,
10571026
reasoning_output_tokens: 0,
1058-
// Content-based dedup key mirroring the per-model credit-only path
1059-
// (`credit-shutdown:{session_id}:{model}:{naiu}`). The per-model
1060-
// path deliberately omits `event_id` because real session-state
1061-
// data ships credit-only snapshots in duplicate pairs with
1062-
// identical `totalNanoAiu` but distinct event ids; an event-id
1063-
// key would let both rows survive loader dedup and double-bill.
1064-
//
1065-
// No real-data evidence yet shows whether aggregate-only
1066-
// shutdowns follow the same duplicate-pair pattern (the
1067-
// aggregate-only code path is forward-compat — no observed
1068-
// session in the local corpus emits aggregate AIU without
1069-
// per-model AIU). But the silent-double-count risk if they DO
1070-
// follow it is strictly worse than the silent-under-count risk
1071-
// if two genuinely distinct aggregate snapshots in one session
1072-
// happened to report identical AIU; the latter is unlikely
1073-
// (genuine session totals are monotonic), the former is
1074-
// exactly the regression the per-model path already prevents.
1075-
// Pick the same conservative strategy here for symmetry.
1027+
// Content-based dedup key, deliberately omitting `event_id` to
1028+
// mirror the per-model `credit-shutdown:{session}:{model}:{naiu}`
1029+
// path. Real session-state ships credit-only snapshots in pairs
1030+
// with distinct event ids but identical naiu — an event-id key
1031+
// would double-bill. Aggregate-only behavior is forward-compat
1032+
// (unobserved in the local corpus); the silent-under-count risk
1033+
// if two distinct snapshots share naiu is preferable to the
1034+
// silent-double-count risk the per-model path explicitly
1035+
// prevents. See adapter README "Resumed sessions and dedup-key
1036+
// design".
10761037
dedup_key: format!("credit-aggregate:{session_id}:{nano_aiu}"),
10771038
nano_aiu: Some(nano_aiu),
10781039
// Synthetic aggregate has no per-model premium-request breakdown.

0 commit comments

Comments
 (0)