Skip to content

Commit b529041

Browse files
jay-tauCopilot
andcommitted
docs(adapter/all): trim multi-paragraph doc comments to load-bearing rationale
External review ccusage#12 (item 5) flagged comment-density on `build_row_metadata` doc-comment and the surrounding `totals_json` rationale as multi-paragraph essays. While the billing-correctness reasoning is genuinely subtle, the comments had grown into structured explanations that could be summarized without losing the load-bearing facts a future maintainer needs. ## Trims - `build_row_metadata` doc: 38 lines → 18 lines. Kept the 3-source structure (loader metadata / metadata_agents / credits), the reachability note for the metadata-copy branch (session-only), the defensive guard rationale for the agents key, and the motivating regression for credits injection. Dropped: - Detailed code-site walk (`loader.rs:240-249`, `types.rs::into_row`, etc.) — kept the function names but dropped specific line numbers that rot easily. - Repeated `Without injection here, ... ` clause explaining the same bug in two ways. - Enumeration of every loader's metadata keys (`summary_metadata` only inserts X, `codex_group_row` only inserts Y) — kept the substantive claim that no current loader emits an `agents` key. - `totals_json` credits-emission comments: 32 lines (two blocks) → 16 lines (one block). Consolidated the gate semantic, the raw-`json!` emission, the Some(0.0) collapse behavior, the row-layer asymmetry, the backward-compat note, and the totalCost out-of-scope acknowledgment into a single labeled bullet list. Removed the inline secondary comment that duplicated the `json_float` divergence explanation already in the lead comment. Behavior unchanged — pure comment-density reduction with the load-bearing facts preserved. All cited code sites and pinning test names still resolve. The remaining comments are billing-correctness rationale where each line is justified by the cost of getting it wrong. ## 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-only change) Refs ccusage#1174. Co-authored-by: Copilot <[email protected]>
1 parent 9cfa55f commit b529041

1 file changed

Lines changed: 34 additions & 67 deletions

File tree

‎rust/crates/ccusage/src/adapter/all/report.rs‎

Lines changed: 34 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -41,42 +41,25 @@ fn row_json(row: &AllRow) -> Value {
4141

4242
/// Assembles the per-row `metadata` JSON object for `row_json`.
4343
///
44-
/// Combines three signal sources into a single shape:
45-
/// - Per-row session/codex metadata supplied by the loader
46-
/// (`lastActivity`, `projectPath`, `reasoningOutputTokens`, …).
47-
/// **Reachable only for session-mode rows today.** `row_json` is
48-
/// the only renderer that calls this helper, and it renders
49-
/// top-level rows only (never recurses into `agent_breakdowns`).
50-
/// In non-session modes (daily/weekly/monthly), every top-level
51-
/// row is the synthetic `"all"` row produced by
52-
/// `AllAccumulator::into_row`, which hard-sets `metadata: None`
53-
/// (`types.rs::into_row`). In session mode, `load_rows` returns
54-
/// per-session per-agent rows directly without aggregation (skips
55-
/// `aggregate_rows` at `loader.rs:240-249`) — those rows preserve
56-
/// the loader-side `Some(map)` produced by `summary_metadata`
57-
/// (lastActivity, projectPath) and `codex_group_row`
58-
/// (lastActivity, reasoningOutputTokens), and this copy branch
59-
/// surfaces them. The branch is kept active for both paths so any
60-
/// future surface that renders nested or non-aggregated AllRows
61-
/// automatically preserves loader-side metadata.
62-
/// - `metadata_agents` — surfaced as `"agents": [..]`. The
63-
/// `!map.contains_key("agents")` guard is defensive: today no loader
64-
/// (`summary_metadata` only inserts `lastActivity` / `projectPath`;
65-
/// `codex_group_row` only inserts `lastActivity` /
66-
/// `reasoningOutputTokens`) ever puts an `agents` key into the
67-
/// per-row metadata, so the guard never fires in production. It
68-
/// prevents a future loader-side `agents` value from being silently
69-
/// overwritten by the `metadata_agents` derivation.
70-
/// - The first-class `credits` field on `AllRow` — injected as
71-
/// `"credits": ..` regardless of where the row originated. This is
72-
/// the path that makes `daily --all --json` / `weekly --all --json` /
73-
/// `monthly --all --json` surface Copilot credit-only AIU billing on
74-
/// the aggregated `"all"` row (whose `metadata` is `None` because
75-
/// `AllAccumulator::into_row` resets it). Without injection here,
76-
/// the aggregated row's only `metadata` content would be
77-
/// `{"agents": [..]}` and the credits signal would be lost from
78-
/// non-session `--all --json` outputs even though direct
79-
/// `ccusage copilot ... --json` exposes it.
44+
/// Combines three signal sources:
45+
/// - **Per-row loader metadata** (`lastActivity`, `projectPath`,
46+
/// `reasoningOutputTokens`, …). Reachable only for session-mode
47+
/// rows today — non-session paths go through
48+
/// `AllAccumulator::into_row` which resets `metadata: None`. Kept
49+
/// active so future renderers of nested or non-aggregated AllRows
50+
/// automatically preserve loader-side metadata.
51+
/// - **`metadata_agents`** → `"agents": [..]`. The
52+
/// `!map.contains_key("agents")` guard is defensive — no current
53+
/// loader emits an `agents` key, so the guard never fires in
54+
/// production but prevents a future loader-side `agents` value
55+
/// from being silently overwritten.
56+
/// - **First-class `credits`** → `"credits": ..`. Always injected
57+
/// when `Some`, regardless of origin. This is what makes
58+
/// `daily --all --json` (and weekly / monthly) surface Copilot
59+
/// credit-only AIU billing on the aggregated `"all"` row — without
60+
/// this injection, `into_row`'s `metadata: None` reset would lose
61+
/// the credits signal from non-session `--all --json` outputs even
62+
/// though direct `ccusage copilot ... --json` exposes it.
8063
fn build_row_metadata(row: &AllRow) -> Option<Value> {
8164
let mut map = serde_json::Map::new();
8265
if let Some(existing) = row.metadata.as_ref().and_then(Value::as_object) {
@@ -116,40 +99,24 @@ fn totals_json(rows: &[AllRow]) -> Value {
11699
"totalTokens": rows.iter().map(|row| row.total_tokens).sum::<u64>(),
117100
"totalCost": json_float(rows.iter().map(|row| row.total_cost).sum::<f64>()),
118101
});
119-
// `credits` is emitted only when the SUM is positive, matching the
120-
// direct per-agent JSON renderer (`output.rs::totals_json`,
121-
// which gates on `if credits > 0.0`). Using the same gate AND the
122-
// same raw `json!` emission (see below) here makes the `credits`
123-
// field byte-identical across direct and `--all` reports for any
124-
// input — including integer-valued sums (a Copilot day with N
125-
// sonnet calls at 1 AIU each yields a whole-number credit total
126-
// that both renderers serialize as `N.0`, not `N`). A `Some(0.0)`
127-
// row (e.g. a post-cutover Copilot day whose `totalNanoAiu == 0`
128-
// because the user only ran free-tier sonnet/haiku) drops the
129-
// `credits` field on both sides, rather than surfacing as
130-
// `credits: 0` on `--all` and being absent on direct. This
131-
// preserves the prior backward-compat shape for credit-free
132-
// agents (Claude, Codex, Amp, …) too. The per-row injection in
133-
// `build_row_metadata` uses `Option::is_some` instead — that
134-
// matches the per-row direct-agent renderer (`output.rs` per-row
135-
// path, which uses `if let Some(credits) = row.credits`) and
136-
// preserves the "channel absent vs explicit-zero" distinction at
137-
// the row layer where it is most actionable.
102+
// `credits` emission rules — designed for byte-parity with the
103+
// direct per-agent renderer (`output.rs::totals_json`):
104+
// - Gate on positive SUM (matches `if credits > 0.0` in `output.rs`).
105+
// `Some(0.0)` rows collapse to absence on both sides instead of
106+
// `--all` surfacing `credits: 0` while direct omits — a `jq`
107+
// query branching on key presence then works on both.
108+
// - Emit via raw `json!` (not `json_float`) so integer-valued
109+
// sums serialize as `5.0` not `5`, matching `output.rs:97`.
110+
// - Per-row `build_row_metadata` uses `Option::is_some` instead,
111+
// preserving the "channel absent vs explicit-zero" distinction
112+
// at the row layer (most actionable for analytics).
113+
// - Backward-compat for credit-free agents (Claude, Codex, Amp, …):
114+
// no `credits` key appears in totals, same as before this PR.
115+
// - Pre-existing `totalCost` `json_float` divergence above is
116+
// out of scope (predates this PR).
138117
let total_credits = rows.iter().filter_map(|row| row.credits).sum::<f64>();
139118
if total_credits > 0.0 {
140119
if let Some(obj) = totals.as_object_mut() {
141-
// Raw `json!` (not `json_float`) for byte-parity with the
142-
// direct-agent renderer (`output.rs:97`, raw `json!`).
143-
// `json_float` collapses integer-valued floats to JSON
144-
// integer literals (`5.0` → `5`), which is semantically
145-
// identical to every JSON consumer but breaks raw
146-
// byte-diff parity. Per-row injection in
147-
// `build_row_metadata` uses the same raw form for the
148-
// same reason. Note that the pre-existing `totalCost`
149-
// emission above still uses `json_float`, mirroring a
150-
// divergence that already exists between direct and
151-
// `--all` for `totalCost`; that one predates this PR
152-
// and is out of scope here.
153120
obj.insert("credits".to_string(), json!(total_credits));
154121
}
155122
}

0 commit comments

Comments
 (0)