Skip to content

feat(fetcher): add codex_usage + codex_subscription, unify llm pricing via Actions sync - #252

Merged
unhappychoice merged 11 commits into
mainfrom
feat/codex-fetchers
May 23, 2026
Merged

unhappychoice merged 11 commits into
mainfrom
feat/codex-fetchers

Conversation

@unhappychoice

@unhappychoice unhappychoice commented May 23, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds two codex_* fetchers for OpenAI Codex CLI users, mirroring what claude_* ships for Claude Code:

  • codex_usage — token + cost rollup from local ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl. Aggregates per-turn usage under since (today / 7d / 30d / all) and groups by project / model / day.
  • codex_subscription — 5h / 7d rate-limit utilisation parsed from the most recent session's last token_count event. Codex CLI already carries the rate-limit payload on every event, so we read what's there rather than making a billable inference call.

Both are Safety::Safe: every session read stays under ~/.codex/sessions/ (or $CODEX_HOME/sessions/). codex_usage does make one host-fixed HTTP GET for the LLM pricing snapshot — see the dedicated change below.

While stitching codex into the codebase the PR also unifies the pricing path across both codex_* and claude_*:

  • New src/fetcher/llm_pricing.rs carries one shared PriceMap, fetched from raw.githubusercontent.com/unhappychoice/splashboard/main/data/llm_pricing.json (host hardcoded → stays Safe).
  • New data/llm_pricing.json is the initial seed, extracted from LiteLLM's model_prices_and_context_window_backup.json and filtered to OpenAI / Anthropic chat models (117 rows, ~14 KB).
  • New .github/workflows/sync-llm-pricing.yml runs daily, pulls LiteLLM, normalises, and opens a PR via peter-evans/create-pull-request@v7 on diff. No auto-merge.
  • claude_code_usage's hardcoded PRICE_TABLE is dropped in favour of the shared helper. This unwinds an inadvertent over-charge: the hardcoded Opus tier was still at Opus 4.1's $15 / $75 / MTok while Anthropic dropped Opus 4.5+ to $5 / $25 / MTok (verified against docs.claude.com/.../pricing). Sonnet and Haiku figures are unchanged.

Cold-cache first paint over realistic ~/.codex/sessions/ (1,453 files, 527 MB) was multiple seconds. Two perf commits at the tail of the branch take it back to milliseconds:

  • codex_usage filters the file list by the rollout-YYYY-MM-DD… filename prefix before opening.
  • claude_code_usage filters by mtime (Claude session files are <uuid>.jsonl — no date in the filename to read).

For since = "all" both fetchers still walk every file; the filename / mtime filter only kicks in for windowed queries.

Test plan

  • cargo fmt --all -- --check ✅
  • cargo clippy --all-targets -- -D warnings ✅
  • cargo test --all-targets ✅ (3229 lib + integration tests pass)
  • Smoke-tested locally with a 9-widget .splashboard/dashboard.toml exercising every shape: codex_usage × 4 (Text / Bars / TextBlock / NumberSeries) + codex_subscription × 3 (Ratio / TextBlock / Badge) + claude_code_usage × 2 (Text / TextBlock).
  • Verified splashboard catalog fetcher codex_usage / codex_subscription print the expected option schema and compatible renderer set.

Reference (mirrors auto-generated docs)

codex_usage

Token and cost rollup from local Codex CLI session JSONL files. Aggregates per-turn usage under the chosen since window and groups it by project, model, or day.

Kind Safety Shapes
cached Safe text, text_block, markdown_text_block, entries, bars, number_series, badge

Options

Option Type Required Default Description
since "today" | "7d" | "30d" | "all" no "today" Window the rollup covers, anchored on the current UTC day.
limit integer (1..=50) no 10 Maximum rows surfaced by multi-row shapes (Bars, Entries, …).
group_by "project" | "model" | "day" no "project" Axis used by Bars / Entries / TextBlock row shapes.

Compatible renderers

codex_subscription

Codex CLI subscription utilisation, parsed from the local session JSONL. Each token_count event Codex writes carries the 5h (primary) and 7d (secondary) rate-limit windows; we read the most recent one.

Kind Safety Shapes
cached Safe ratio, text, text_block, markdown_text_block, entries, bars, badge, timeline

Options

Option Type Required Default Description
window "5h" | "7d" | "primary" | "secondary" no "5h" Which window the single-value shapes (Ratio, Badge) report. Multi-row shapes always list both windows.

Compatible renderers

Catalog

Ticks codex_usage in #64 (already a checkbox under "AI / LLM — local agent activity"). Adds a new codex_subscription entry to the same issue's "AI / LLM — subscription seat / rate-limit headroom" section after merge.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added Codex usage fetcher to track token consumption and costs by project and model.
    • Added Codex subscription fetcher to display plan utilization and reset timing.
    • Integrated dynamic cost calculations into usage tracking with automated daily pricing refresh (manual trigger available).
  • Chores

    • Centralized LLM pricing into a shared module and seeded pricing snapshot for consistent cost reporting.

Review Change Stack

unhappychoice and others added 10 commits May 23, 2026 20:03
Lays the foundation for the codex_* family. `common.rs` carries the bits that
both upcoming fetchers will share:

- `discover_session_dirs()` + `list_session_files()` walk `~/.codex/sessions/`
  (or `$CODEX_HOME/sessions/`) and enumerate `rollout-*.jsonl` under the
  `YYYY/MM/DD/` tree, sorted lexically so the prefix gives free chronological
  order.
- `price_for()` / `cost_usd()` cover the GPT-5 / GPT-4.1 / o-series prices
  with a longest-prefix-wins lookup; unknown models contribute $0 rather than
  hiding token activity behind an error.
- `format_cost` / `format_tokens` keep figures compact enough for Badge or
  Text headlines; `project_name_from_cwd` / `short_model_name` normalise the
  axis labels that downstream rollups will use.

`fetchers()` returns an empty vec for now — member fetchers join in follow-up
commits.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Walks `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl` (or `$CODEX_HOME/sessions/...`)
via the helpers shipped in the family scaffold, extracts per-turn token usage
from each `event_msg` of type `token_count`, and aggregates by project / model
/ day. The `turn_context` event that precedes each turn carries the model id
and `cwd`; we thread that state forward as we parse so usage gets attributed
to the right turn.

Shape coverage matches `claude_code_usage`: Text / TextBlock /
MarkdownTextBlock / Entries / Bars / NumberSeries / Badge (seven). Options
mirror it too — `since` (today/7d/30d/all), `limit`, `group_by`
(project/model/day). `Safety::Safe` — every read is local; unknown models
contribute $0 rather than hiding their token activity behind an error.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ocal JSONL

Codex CLI piggybacks plan rate-limit state on every `token_count` event in the
session JSONL (`primary` = 5h window, `secondary` = 7d window, `plan_type`).
This fetcher walks the newest session (via the discovery helpers from the
codex scaffold) and reads the last such event — the same view Codex itself
shows.

Deliberately no network call even though OpenAI's API can return the same
payload: the only way to re-fetch it is a billable inference request, which is
not what a splash widget should do. Freshness is bounded by "when did the user
last run Codex"; the renderer falls back to `resets now` for a window that has
already rolled over, which surfaces the staleness honestly.

Shape coverage matches `claude_subscription`: Ratio / Text / TextBlock /
MarkdownTextBlock / Entries / Bars / Badge / Timeline (eight). `Safety::Safe`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The codex_* and claude_* families both need OpenAI / Anthropic per-token
pricing to translate raw token counts into a USD figure. Until now both
hardcoded a Price table in their own `common.rs`, which drifts as soon as
either vendor changes rates (verified: the hardcoded Claude Opus tier was
still at the Opus 4.1 $15/$75 line, while Anthropic dropped Opus 4.5 onward
to $5/$25 — splashboard was over-charging Opus 4.7 sessions by ~3x).

Replaces the per-family tables with one shared snapshot:

- `data/llm_pricing.json` — initial seed, extracted from LiteLLM's
  `model_prices_and_context_window_backup.json` filtered to OpenAI /
  Anthropic chat models (117 rows, ~14 KB). Cross-checked against
  Anthropic's `docs.claude.com/.../pricing` table; matches exactly.
- `src/fetcher/llm_pricing.rs` — runtime helper. Fetches
  `raw.githubusercontent.com/unhappychoice/splashboard/main/data/llm_pricing.json`
  on every call (the fetcher's own 5-minute disk cache absorbs the
  redundancy), falls back to a tiny `embedded_floor` covering the current
  headline models when offline.

A follow-up commit wires `chore: sync llm pricing daily via Actions` so the
snapshot stays current without human work.

Safety stays `Safe` — host is hardcoded, no token leaves the process.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds `.github/workflows/sync-llm-pricing.yml`. Cron triggers at 00:00 UTC
daily (plus `workflow_dispatch` for manual refresh); pulls LiteLLM's price
table, filters to OpenAI + Anthropic chat models, normalises per-token →
per-million-tokens, and opens a PR via `peter-evans/create-pull-request@v7`
whenever `data/llm_pricing.json` changes.

No auto-merge — agent PRs always wait for a human merge per repo policy.
The PR body is a review checklist (plausibility, no disappearances, schema
guard test) so reviewers know what to spot-check.

The `snapshot_parses_repo_seed` test in `src/fetcher/llm_pricing.rs` already
guards LiteLLM schema drift; if a future sync ships a structurally
incompatible file the PR's CI catches it before merge.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Drops the per-family hardcoded `PRICE_TABLE` / `cost_usd` / `Price` from
`codex/common.rs` and threads the shared `llm_pricing::PriceMap` through
`build_snapshot` / `group_rows` / `UsageEvent::cost` instead. The pricing
map is fetched once per `fetch()` call (which the daemon's 5-minute disk
cache already throttles); cost math is identical for known models because
the embedded floor mirrors the original hardcoded values.

Module doc updated to reflect that the fetcher now makes one host-fixed
HTTP GET for prices alongside its local JSONL reads. Safety::Safe class
holds (host hardcoded; no token leaves the process).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Drops the per-family hardcoded `PRICE_TABLE` / `cost_usd` / `Price` from
`claude/common.rs` and threads the shared `llm_pricing::PriceMap` through
the same call sites as the codex refactor in the previous commit.

This is a behaviour change for **Opus 4.7 sessions specifically**: the
hardcoded table still had Opus at the 4.1-tier $15 / $75 / MTok line, but
Anthropic dropped Opus 4.5+ to $5 / $25 / MTok (verified against
docs.claude.com pricing on 2026-05-23). Migrating to LiteLLM-derived data
unwinds the ~3x over-charge. Sonnet and Haiku figures are unchanged.

Module doc updated to reflect the host-fixed HTTP GET that now backs the
pricing lookup; safety class stays `Safe`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
skill checklist calls out per-shape branch coverage; the initial cuts
relied on `sample_body(*s).is_some()` plus a handful of badge-specific
asserts, which didn't actually exercise the render_body match arms.

codex_usage: adds direct tests for text / text_block / markdown /
entries / bars / number_series — including the empty-state fall-throughs
(no rows → "no recent" line, no rows → single placeholder entry).

codex_subscription: adds text_block and markdown coverage with their
plan-line prefix and empty-snapshot fallbacks.

No behavioural change; +12 tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…by filename

Codex names every session file `rollout-YYYY-MM-DDTHH-MM-SS-uuid.jsonl`, so
we can read the date right off the filename without opening it. Filter the
list ahead of the line-by-line walk and skip everything older than the
`since` cutoff (with a one-day buffer for sessions that started before
midnight and spilled past it).

Concrete numbers from one developer's `~/.codex/sessions/`: 1,453 JSONL
files, ~527 MB total. With `since = "today"` the filter drops it to a
handful of files, taking first-paint from seconds to milliseconds. For
`since = "all"` no files are skipped — same behaviour as before.

The per-line `since.includes(ts)` filter is still the source of truth for
event-level inclusion; this commit only prunes the file *list* up front.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Claude names every session file `<uuid>.jsonl` — no date in the filename,
so we can't do the same filename-prefix trick the codex side just got.
Stat each file instead (~10µs per syscall) and skip the open+line-parse
path when the mtime is older than the `since` cutoff with a one-day
buffer.

On one developer's `~/.claude/projects/`: 1,431 JSONL files, ~454 MB
total. With `since = "today"` only the handful of sessions touched today
get opened; cold-cache first paint drops from seconds to milliseconds.
`since = "all"` keeps reading everything, same as before.

The per-line `since.includes(ts)` filter remains the source of truth for
event-level inclusion; this commit only prunes the file *list* up front.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented May 23, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds a shared LLM pricing module with HTTP fetch and embedded fallback, refactors Claude to use it (with mtime-based session filtering), introduces Codex common helpers plus two Codex fetchers (usage and subscription), adds a pricing seed file and sync workflow, and wires fetchers into the registry.

Changes

LLM Pricing Infrastructure and Codex Fetchers

Layer / File(s) Summary
Shared LLM Pricing Module
src/fetcher/llm_pricing.rs
Price and PriceMap types, fetch_pricing() with HTTP retrieval and embedded fallback, price_for() case-insensitive longest-prefix model resolution, and cost_usd() computing USD cost across token tiers.
Pricing Data and Sync Workflow
data/llm_pricing.json, .github/workflows/sync-llm-pricing.yml
Adds seed pricing snapshot and a GitHub Actions workflow to fetch LiteLLM pricing, filter/convert to per-1M USD rates (including cache tiers), write deterministic snapshot, and open/update a PR on chore/sync-llm-pricing.
Claude Pricing Refactoring and Session Filtering
src/fetcher/claude/common.rs, src/fetcher/claude/code_usage.rs
Removes Claude hardcoded pricing from shared common, moves pricing to llm_pricing, threads PriceMap into UsageEvent::cost/build_snapshot/group_rows, and adds mtime-based prefiltering with unit tests.
Codex Common Helpers
src/fetcher/codex/common.rs
Formatting helpers (format_cost, format_tokens), session discovery (discover_session_dirs, list_session_files), project name extraction, and model family normalization (short_model_name) with tests.
Codex Subscription Fetcher
src/fetcher/codex/subscription.rs
CodexSubscription reads latest local session JSONL, extracts rate_limits windows, computes utilization/reset timestamps, and renders multiple widget shapes with status bucketing and tests.
Codex Usage Fetcher
src/fetcher/codex/usage.rs
CodexUsage reads $CODEX_HOME session JSONL, threads model/cwd context, filters by time window (with mtime cutoff), computes tokens and costs via shared pricing, groups/truncates results, produces daily series, and renders widget shapes with tests.
Fetcher Module Wiring
src/fetcher/codex/mod.rs, src/fetcher/mod.rs
Declares and exposes codex and llm_pricing modules, provides codex::fetchers() returning both Codex fetchers, and registers Codex fetchers in Registry::with_builtins().

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

Poem

🐰 I hop through JSON, prices in tow,
Codex sessions whisper what tokens know,
Claude now asks the pricing stream to sing,
Workflows fetch the numbers every morning,
Widgets bloom from logs — hooray for spring!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.92% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat(fetcher): add codex_usage + codex_subscription, unify llm pricing via Actions sync' accurately and concisely describes the three main changes: adding two Codex fetchers, unifying LLM pricing management, and introducing an Actions workflow for syncing.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/codex-fetchers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented May 23, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.43645% with 122 lines in your changes missing coverage. Please review.
✅ Project coverage is 95.62%. Comparing base (833bc31) to head (6d09272).

Files with missing lines Patch % Lines
src/fetcher/codex/usage.rs 91.18% 58 Missing ⚠️
src/fetcher/codex/subscription.rs 90.25% 53 Missing ⚠️
src/fetcher/codex/common.rs 95.13% 7 Missing ⚠️
src/fetcher/llm_pricing.rs 98.33% 3 Missing ⚠️
src/fetcher/claude/code_usage.rs 98.59% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #252      +/-   ##
==========================================
- Coverage   95.70%   95.62%   -0.09%     
==========================================
  Files         243      248       +5     
  Lines       66271    67826    +1555     
==========================================
+ Hits        63424    64857    +1433     
- Misses       2847     2969     +122     
Files with missing lines Coverage Δ
src/fetcher/claude/common.rs 87.83% <ø> (-4.79%) ⬇️
src/fetcher/codex/mod.rs 100.00% <100.00%> (ø)
src/fetcher/mod.rs 99.02% <100.00%> (+<0.01%) ⬆️
src/fetcher/claude/code_usage.rs 86.40% <98.59%> (+1.21%) ⬆️
src/fetcher/llm_pricing.rs 98.33% <98.33%> (ø)
src/fetcher/codex/common.rs 95.13% <95.13%> (ø)
src/fetcher/codex/subscription.rs 90.25% <90.25%> (ø)
src/fetcher/codex/usage.rs 91.18% <91.18%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (3)
src/fetcher/claude/code_usage.rs (1)

952-987: 💤 Low value

Test acquires lock but uses #[allow(clippy::await_holding_lock)] — document why this is safe.

The test holds a mutex guard across an .await point (line 971-975), which clippy warns about because it can cause deadlocks in general async code. Here it's intentional to serialize env-var access, but a brief comment would help future readers understand the safety.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/claude/code_usage.rs` around lines 952 - 987, The test
fetch_reads_jsonl_from_env_override_root intentionally holds the TEST_ENV_LOCK
mutex across an await to serialize environment-variable access to
CLAUDE_CONFIG_DIR; replace the bare #[allow(clippy::await_holding_lock)] with a
short inline comment above the attribute documenting why holding the lock across
the await is safe (e.g., it only serializes test setup/teardown, the lock is
global and not awaited elsewhere, and we immediately release it after the async
call), and mention that the lock prevents concurrent env-var mutation in other
tests so deadlock is not possible here.
src/fetcher/llm_pricing.rs (2)

85-95: 💤 Low value

Case-sensitivity bug in prefix matching: keys in PriceMap are not lowercased.

The exact-match path (line 87) lowercases the input and looks up against the original keys. However, keys in data/llm_pricing.json are lowercase (e.g., "gpt-5", "claude-opus-4-7"), so this works. But the prefix-match path (lines 90-94) compares lower.starts_with(k.as_str()) where k is the original key — if a key were ever uppercase, prefix matching would fail silently.

Consider lowercasing keys during iteration for consistency, or document the contract that PriceMap keys must be lowercase.

Suggested defensive fix
 pub fn price_for<'a>(prices: &'a PriceMap, model: &str) -> Option<&'a Price> {
     let lower = model.to_lowercase();
     if let Some(p) = prices.get(&lower) {
         return Some(p);
     }
     prices
         .iter()
-        .filter(|(k, _)| lower.starts_with(k.as_str()) && !k.is_empty())
+        .filter(|(k, _)| lower.starts_with(&k.to_lowercase()) && !k.is_empty())
         .max_by_key(|(k, _)| k.len())
         .map(|(_, p)| p)
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/llm_pricing.rs` around lines 85 - 95, The prefix-matching branch
in price_for (which takes prices: &PriceMap and model: &str) compares lowercased
input to the original map key, so if keys aren’t guaranteed lowercase prefix
matching can fail; update the prefix check to compare against a lowercased key
(e.g., use k.to_lowercase() or call k.as_str().to_lowercase()) or better yet
normalize PriceMap keys to lowercase when loading so both the exact lookup and
the .starts_with(...) comparison use lowercase keys consistently; adjust
price_for accordingly to use the normalized keys.

126-182: 💤 Low value

embedded_floor() clones the entire HashMap on every call.

The OnceLock caches construction, but .clone() at line 181 copies all entries on each invocation. This is called from fetch_pricing on network failure, so the cost is acceptable there. However, if callers use embedded_floor() directly (e.g., in tests at lines 799 and 1052), repeated cloning is wasteful.

Consider returning &'static PriceMap instead if the clone isn't necessary for the callers:

Alternative returning a reference
-pub fn embedded_floor() -> PriceMap {
+pub fn embedded_floor() -> &'static PriceMap {
     static FLOOR: OnceLock<PriceMap> = OnceLock::new();
     FLOOR
         .get_or_init(|| {
             // ... same initialization ...
         })
-        .clone()
 }

Callers that need ownership can clone explicitly.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/llm_pricing.rs` around lines 126 - 182, The embedded_floor()
currently returns an owned PriceMap by cloning the OnceLock contents on each
call; change its signature to return &'static PriceMap, remove the final
.clone(), and return the reference produced by FLOOR.get_or_init(...) (or
FLOOR.get().unwrap_or_else(...) as appropriate) so callers reuse the single
static map; update call sites (e.g., fetch_pricing and tests that currently
assume ownership) to call .clone() only when they need an owned PriceMap and
otherwise keep the &'static PriceMap to avoid repeated cloning.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.github/workflows/sync-llm-pricing.yml:
- Line 71: Replace the floating tag for the GitHub Action reference to a pinned
commit SHA: locate the workflow step that uses the "uses:
peter-evans/create-pull-request@v7" entry and change it to the full commit SHA
for the current v7 release (e.g., "peter-evans/create-pull-request@<full-sha>").
Find the authoritative SHA from the peter-evans/create-pull-request releases
page and update that "uses:" value so the workflow references the exact commit
instead of the `@v7` tag.
- Line 22: Replace the floating checkout tag and enable credential hardening:
change the current uses reference "actions/checkout@v6" to a pinned full commit
SHA for the actions/checkout action (use the latest stable release commit SHA
from the actions/checkout GitHub releases) and add a "with" parameter setting
persist-credentials: false so the checkout step no longer exposes the workflow
token; locate the step that uses actions/checkout (uses: actions/checkout@v6)
and update it to use the full SHA and include persist-credentials: false in the
step configuration.

In `@src/fetcher/codex/common.rs`:
- Around line 74-81: The current read_jsonl_files function returns all .jsonl
files which can pick up unrelated files; change read_jsonl_files to only return
files whose file_name matches the rollout-*.jsonl pattern (i.e., extension
"jsonl" and file_name starts_with "rollout-" and has at least one char after the
dash) so CodexSubscription::load_snapshot will still pick the lexicographically
last rollout file but will ignore unrelated JSONL files.

In `@src/fetcher/codex/mod.rs`:
- Around line 8-10: The module doc incorrectly states both fetchers are "no
network"; update the comment in mod.rs to reflect that codex_usage performs an
HTTP pricing fetch, so it is not strictly "no network" — keep Safety::Safe for
rooted reads at ~/.codex/sessions/ but explicitly note that codex_usage issues
an outbound HTTP request to retrieve pricing/rate-limit data, describe the
network call and its scope (one-time pricing fetch) and clarify trust/safety
implications compared to the other fetcher.

---

Nitpick comments:
In `@src/fetcher/claude/code_usage.rs`:
- Around line 952-987: The test fetch_reads_jsonl_from_env_override_root
intentionally holds the TEST_ENV_LOCK mutex across an await to serialize
environment-variable access to CLAUDE_CONFIG_DIR; replace the bare
#[allow(clippy::await_holding_lock)] with a short inline comment above the
attribute documenting why holding the lock across the await is safe (e.g., it
only serializes test setup/teardown, the lock is global and not awaited
elsewhere, and we immediately release it after the async call), and mention that
the lock prevents concurrent env-var mutation in other tests so deadlock is not
possible here.

In `@src/fetcher/llm_pricing.rs`:
- Around line 85-95: The prefix-matching branch in price_for (which takes
prices: &PriceMap and model: &str) compares lowercased input to the original map
key, so if keys aren’t guaranteed lowercase prefix matching can fail; update the
prefix check to compare against a lowercased key (e.g., use k.to_lowercase() or
call k.as_str().to_lowercase()) or better yet normalize PriceMap keys to
lowercase when loading so both the exact lookup and the .starts_with(...)
comparison use lowercase keys consistently; adjust price_for accordingly to use
the normalized keys.
- Around line 126-182: The embedded_floor() currently returns an owned PriceMap
by cloning the OnceLock contents on each call; change its signature to return
&'static PriceMap, remove the final .clone(), and return the reference produced
by FLOOR.get_or_init(...) (or FLOOR.get().unwrap_or_else(...) as appropriate) so
callers reuse the single static map; update call sites (e.g., fetch_pricing and
tests that currently assume ownership) to call .clone() only when they need an
owned PriceMap and otherwise keep the &'static PriceMap to avoid repeated
cloning.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d8e7ac46-ad91-4905-9ef8-35fc203fbd5a

📥 Commits

Reviewing files that changed from the base of the PR and between 833bc31 and 6d09272.

📒 Files selected for processing (10)
  • .github/workflows/sync-llm-pricing.yml
  • data/llm_pricing.json
  • src/fetcher/claude/code_usage.rs
  • src/fetcher/claude/common.rs
  • src/fetcher/codex/common.rs
  • src/fetcher/codex/mod.rs
  • src/fetcher/codex/subscription.rs
  • src/fetcher/codex/usage.rs
  • src/fetcher/llm_pricing.rs
  • src/fetcher/mod.rs

name: Refresh pricing snapshot
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Pin checkout action to a full SHA and disable credential persistence.

Static analysis flagged this: using @v6 instead of a SHA hash is a supply-chain risk, and omitting persist-credentials: false leaves the token accessible to subsequent steps.

Suggested fix
-      - uses: actions/checkout@v6
+      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+        with:
+          persist-credentials: false

Note: Use the latest stable SHA from actions/checkout releases. The example above uses v4.2.2; verify the current version.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- uses: actions/checkout@v6
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
🧰 Tools
🪛 zizmor (1.25.2)

[warning] 22-22: credential persistence through GitHub Actions artifacts (artipacked): does not set persist-credentials: false

(artipacked)


[error] 22-22: unpinned action reference (unpinned-uses): action is not pinned to a hash (required by blanket policy)

(unpinned-uses)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/sync-llm-pricing.yml at line 22, Replace the floating
checkout tag and enable credential hardening: change the current uses reference
"actions/checkout@v6" to a pinned full commit SHA for the actions/checkout
action (use the latest stable release commit SHA from the actions/checkout
GitHub releases) and add a "with" parameter setting persist-credentials: false
so the checkout step no longer exposes the workflow token; locate the step that
uses actions/checkout (uses: actions/checkout@v6) and update it to use the full
SHA and include persist-credentials: false in the step configuration.

PY

- name: Open PR if diff
uses: peter-evans/create-pull-request@v7

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Pin create-pull-request action to a full SHA.

Using @v7 instead of a commit SHA is a supply-chain risk if the tag is ever compromised or force-pushed.

Suggested fix
-      - uses: peter-evans/create-pull-request@v7
+      - uses: peter-evans/create-pull-request@<full-sha> # v7.x.x

Look up the current SHA at peter-evans/create-pull-request releases.

🧰 Tools
🪛 zizmor (1.25.2)

[error] 71-71: unpinned action reference (unpinned-uses): action is not pinned to a hash (required by blanket policy)

(unpinned-uses)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/sync-llm-pricing.yml at line 71, Replace the floating tag
for the GitHub Action reference to a pinned commit SHA: locate the workflow step
that uses the "uses: peter-evans/create-pull-request@v7" entry and change it to
the full commit SHA for the current v7 release (e.g.,
"peter-evans/create-pull-request@<full-sha>"). Find the authoritative SHA from
the peter-evans/create-pull-request releases page and update that "uses:" value
so the workflow references the exact commit instead of the `@v7` tag.

Comment thread src/fetcher/codex/common.rs Resolved
Comment thread src/fetcher/codex/mod.rs Resolved
@codecov

codecov Bot commented May 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.45983% with 122 lines in your changes missing coverage. Please review.
✅ Project coverage is 95.62%. Comparing base (833bc31) to head (aad0c6e).
⚠️ Report is 12 commits behind head on main.

Files with missing lines Patch % Lines
src/fetcher/codex/usage.rs 91.18% 58 Missing ⚠️
src/fetcher/codex/subscription.rs 90.25% 53 Missing ⚠️
src/fetcher/codex/common.rs 95.30% 7 Missing ⚠️
src/fetcher/llm_pricing.rs 98.33% 3 Missing ⚠️
src/fetcher/claude/code_usage.rs 98.59% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #252      +/-   ##
==========================================
- Coverage   95.70%   95.62%   -0.09%     
==========================================
  Files         243      248       +5     
  Lines       66271    67831    +1560     
==========================================
+ Hits        63424    64862    +1438     
- Misses       2847     2969     +122     
Files with missing lines Coverage Δ
src/fetcher/claude/common.rs 87.83% <ø> (-4.79%) ⬇️
src/fetcher/codex/mod.rs 100.00% <100.00%> (ø)
src/fetcher/mod.rs 99.02% <100.00%> (+<0.01%) ⬆️
src/fetcher/claude/code_usage.rs 86.40% <98.59%> (+1.21%) ⬆️
src/fetcher/llm_pricing.rs 98.33% <98.33%> (ø)
src/fetcher/codex/common.rs 95.30% <95.30%> (ø)
src/fetcher/codex/subscription.rs 90.25% <90.25%> (ø)
src/fetcher/codex/usage.rs 91.18% <91.18%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

- `read_jsonl_files` now also filters on the `rollout-` filename prefix, so a
  future stray file under `~/.codex/sessions/YYYY/MM/DD/` can't quietly shadow
  the lex-sorted "newest rollup" lookup `codex_subscription` does.
- Module doc on `src/fetcher/codex/mod.rs` previously claimed "no network"
  for both fetchers — corrected: `codex_usage` does make one host-fixed HTTP
  GET for the LLM pricing snapshot. `codex_subscription` stays local-only.
- `llm_pricing::price_for` prefix lookup now lowercases the key it compares
  against. `data/llm_pricing.json` ships lowercase keys today, but the lookup
  shouldn't silently miss if a future LiteLLM sync ships a mixed-case id.
- Workflow's `actions/checkout` step gains `persist-credentials: false` — the
  sync step uses `peter-evans/create-pull-request`'s own token, so checkout
  doesn't need to leave credentials in the workspace.
- Documented why `fetch_reads_jsonl_from_env_override_root` holds
  `TEST_ENV_LOCK` across an `.await`; the future doesn't re-take the lock,
  so the `#[allow(clippy::await_holding_lock)]` is safe.

Skipped from the review:
- SHA-pinning Actions: existing workflows in the repo use floating `@v6` /
  `@v7` tags; matching the precedent. Worth a separate hardening pass.
- Returning `embedded_floor() -> &'static PriceMap`: it's only hit on the
  HTTP-failure cold path, so the clone cost is negligible vs the API
  ergonomics win of returning an owned map.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/fetcher/codex/common.rs (1)

185-213: ⚡ Quick win

Consider adding a non-rollout JSONL test case.

The test verifies that note.txt is ignored, but doesn't explicitly test that a non-rollout JSONL file (e.g., backup-2026-05-23.jsonl) is filtered out. Adding such a file would strengthen coverage of the rollout-prefix filtering logic introduced at lines 84-89.

🧪 Proposed test enhancement
         fs::write(day.join("rollout-2026-05-23T01-00-00-b.jsonl"), "").unwrap();
         fs::write(day.join("rollout-2026-05-23T00-00-00-a.jsonl"), "").unwrap();
-        // Non-jsonl + extra noise must be ignored.
+        // Non-jsonl and non-rollout jsonl files must be ignored.
         fs::write(day.join("note.txt"), "").unwrap();
+        fs::write(day.join("backup-2026-05-23.jsonl"), "").unwrap();
         let files = list_session_files(&[tmp.path().to_path_buf()]);
         assert_eq!(files.len(), 2);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/codex/common.rs` around lines 185 - 213, Update the test
list_session_files_walks_year_month_day_tree_sorted to also create a non-rollout
JSONL file (e.g., write an empty "backup-2026-05-23.jsonl" into the same day
directory) to ensure the rollout-prefix filter is exercised; keep calling
list_session_files(&[tmp.path().to_path_buf()]) and assert the result still has
len == 2 and that none of the returned file_name() strings contain "backup" (or
otherwise assert the two expected rollout names are present), so the test
verifies JSONL files without the "rollout-" prefix are ignored by
list_session_files.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/fetcher/codex/common.rs`:
- Around line 185-213: Update the test
list_session_files_walks_year_month_day_tree_sorted to also create a non-rollout
JSONL file (e.g., write an empty "backup-2026-05-23.jsonl" into the same day
directory) to ensure the rollout-prefix filter is exercised; keep calling
list_session_files(&[tmp.path().to_path_buf()]) and assert the result still has
len == 2 and that none of the returned file_name() strings contain "backup" (or
otherwise assert the two expected rollout names are present), so the test
verifies JSONL files without the "rollout-" prefix are ignored by
list_session_files.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ab3f50c3-9a81-4c8e-844d-59c2e196e249

📥 Commits

Reviewing files that changed from the base of the PR and between 6d09272 and aad0c6e.

📒 Files selected for processing (5)
  • .github/workflows/sync-llm-pricing.yml
  • src/fetcher/claude/code_usage.rs
  • src/fetcher/codex/common.rs
  • src/fetcher/codex/mod.rs
  • src/fetcher/llm_pricing.rs

@unhappychoice
unhappychoice merged commit 4d9bde7 into main May 23, 2026
7 checks passed
@unhappychoice
unhappychoice deleted the feat/codex-fetchers branch May 23, 2026 17:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant