Repository navigation
[feature] Add tj backfill codex — Codex CLI rollout session backfill - #433
Conversation
The Codex CLI persists every session to disk as a rollout JSONL file (~/.codex/sessions/YYYY/MM/DD/rollout-<ts>-<uuid>.jsonl), the same way Claude Code writes ~/.claude/projects/*.jsonl. Until now tj could only ingest Codex telemetry going forward (out-of-band OTel via tj onboard --codex); a user's history before onboarding was invisible. This adds the historical counterpart. `tj backfill codex` parses rollout files into NormalizedSpans so tj cost / tj optimize can read Codex history, mirroring core/backfill.py's ingest_claude_code: - Deterministic span IDs — (session_id, per-turn index) for LLM spans, (session_id, call_id) for tool spans — so re-runs are idempotent. - Plan tier stamped from [budget.openai] plan, matching the live ingest path so backfilled sessions aren't all "unknown" (#176). - Cost recomputed from pricing/models.toml (the rollout has no cost). - Provider/billing always openai; agent_id codex_exec (Codex hardcodes service.name=codex_exec, so live + backfill attribute to one agent). Token accounting uses info.last_token_usage (the per-turn delta) so summed spans equal the cumulative info.total_token_usage without double-counting. cached_input_tokens is a subset of input_tokens, so billable input is input-cached; reasoning_output_tokens fold into output. OpenAI automatic caching has no cache-creation charge, so cache_write_tokens is always 0 (mirrors routes/logs.py, #93). Registered in cmd_backfill.py alongside the other adapters; docs page added and the four->five source references updated. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015e3DZGhb1R5sXX2x52Y2Ar
|
| Filename | Overview |
|---|---|
| tokenjam/core/ingest_adapters/codex.py | New Codex rollout JSONL adapter; logic is clean and mirrors the Claude Code path closely, but idempotency uses per-span SELECTs (2N round-trips) rather than the bulk _existing_span_ids() + executemany pattern established in core/backfill. |
| tokenjam/cli/cmd_backfill.py | Adds tj backfill codex subcommand wired correctly to ingest_codex; --root / --since handling, error messaging, and progress output all mirror the claude-code subcommand. |
| tests/unit/test_backfill_codex.py | 11 unit tests covering parser, iter, and ingest paths including idempotency, plan-tier propagation, multi-turn delta summing, model tracking, and --since filtering; all fixture-based with no hand-constructed spans. |
| docs/backfill/overview.md | Adds Codex row to the supported-sources table and updates the idempotency section, but two general statements (adapter flags and plan-tier default) are now inaccurate. |
| docs/backfill/codex.md | New per-adapter doc page; field mapping, idempotency, plan-tier, and v1 limitations are accurately described and consistent with the implementation. |
| CLAUDE.md | Correctly updates the ingest_adapters description and backfill subcommands list to include codex.py / tj backfill codex; no inaccuracies introduced. |
Sequence Diagram
%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
participant CLI as tj backfill codex
participant Iter as iter_codex_sessions
participant Parser as parse_codex_rollout
participant DB as DuckDBBackend
CLI->>Iter: root, since
loop "For each rollout-*.jsonl"
Iter->>Iter: mtime pre-filter (since)
Iter->>Parser: path
Parser->>Parser: parse session_meta → session_id, cwd
Parser->>Parser: parse turn_context → current_model
Parser->>Parser: parse event_msg/token_count → LLM span (last_token_usage delta)
Parser->>Parser: parse response_item/function_call → tool span
Parser-->>Iter: ParsedCodexSession (or None)
Iter->>Iter: ended_at post-filter (since)
Iter-->>CLI: ParsedCodexSession
end
loop For each ParsedCodexSession
CLI->>DB: "SELECT 1 FROM spans WHERE span_id=? (per span)"
CLI->>DB: insert_span (new spans only)
CLI->>DB: upsert_session (plan_tier from config)
end
CLI->>DB: recompute_session_totals_from_spans(seen_ids)
CLI-->>CLI: print summary (seen / written / skipped)
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
participant CLI as tj backfill codex
participant Iter as iter_codex_sessions
participant Parser as parse_codex_rollout
participant DB as DuckDBBackend
CLI->>Iter: root, since
loop "For each rollout-*.jsonl"
Iter->>Iter: mtime pre-filter (since)
Iter->>Parser: path
Parser->>Parser: parse session_meta → session_id, cwd
Parser->>Parser: parse turn_context → current_model
Parser->>Parser: parse event_msg/token_count → LLM span (last_token_usage delta)
Parser->>Parser: parse response_item/function_call → tool span
Parser-->>Iter: ParsedCodexSession (or None)
Iter->>Iter: ended_at post-filter (since)
Iter-->>CLI: ParsedCodexSession
end
loop For each ParsedCodexSession
CLI->>DB: "SELECT 1 FROM spans WHERE span_id=? (per span)"
CLI->>DB: insert_span (new spans only)
CLI->>DB: upsert_session (plan_tier from config)
end
CLI->>DB: recompute_session_totals_from_spans(seen_ids)
CLI-->>CLI: print summary (seen / written / skipped)
Comments Outside Diff (1)
-
docs/backfill/overview.md, line 17-31 (link)Two overview statements are now inaccurate after adding the Codex adapter
Line 17 says "Every adapter accepts
--source-url(live endpoint) or--source-file(offline JSON dump)" — the Codex adapter accepts--rootinstead (the on-disk path), which the CLAUDE.md update correctly calls out. Line 31 says "Backfilled sessions getSessionRecord.plan_tier = 'unknown'because the source data doesn't carry a plan-tier identifier" — this has been false for Claude Code since [bug] Claude Code backfill doesn't propagate config plan to SessionRecord.plan_tier #176 and is false for Codex too; both adapters call_plan_tier_for_provider(config, provider)and stamp the configured plan. A user who runstj backfill codexaftertj onboardand then reads this paragraph would incorrectly believe their sessions areplan_tier = 'unknown'and re-runtj onboard --reconfigureunnecessarily.Prompt To Fix With AI
This is a comment left during a code review. Path: docs/backfill/overview.md Line: 17-31 Comment: **Two overview statements are now inaccurate after adding the Codex adapter** Line 17 says "Every adapter accepts `--source-url` (live endpoint) or `--source-file` (offline JSON dump)" — the Codex adapter accepts `--root` instead (the on-disk path), which the CLAUDE.md update correctly calls out. Line 31 says "Backfilled sessions get `SessionRecord.plan_tier = 'unknown'` because the source data doesn't carry a plan-tier identifier" — this has been false for Claude Code since #176 and is false for Codex too; both adapters call `_plan_tier_for_provider(config, provider)` and stamp the configured plan. A user who runs `tj backfill codex` after `tj onboard` and then reads this paragraph would incorrectly believe their sessions are `plan_tier = 'unknown'` and re-run `tj onboard --reconfigure` unnecessarily. How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 2
tokenjam/core/ingest_adapters/codex.py:434-447
**Per-span SELECT diverges from the established bulk idempotency pattern**
`ingest_codex` issues one `SELECT 1 FROM spans WHERE span_id = $1` per span, then one `db.insert_span()` per new span. The Claude Code path in `core/backfill._insert_session_idempotent` was upgraded exactly because of this: it uses `_existing_span_ids()` (a single `WHERE span_id IN (...)` query per session, chunked at 5,000) followed by `conn.executemany()` for the new spans — bringing the per-session round-trips from `2N` to `2` regardless of how many spans a session contains. A user backfilling 500 Codex sessions with 20 spans each would issue ~10,000 individual SELECTs here instead of ~500 batched ones.
### Issue 2 of 2
docs/backfill/overview.md:17-31
**Two overview statements are now inaccurate after adding the Codex adapter**
Line 17 says "Every adapter accepts `--source-url` (live endpoint) or `--source-file` (offline JSON dump)" — the Codex adapter accepts `--root` instead (the on-disk path), which the CLAUDE.md update correctly calls out. Line 31 says "Backfilled sessions get `SessionRecord.plan_tier = 'unknown'` because the source data doesn't carry a plan-tier identifier" — this has been false for Claude Code since #176 and is false for Codex too; both adapters call `_plan_tier_for_provider(config, provider)` and stamp the configured plan. A user who runs `tj backfill codex` after `tj onboard` and then reads this paragraph would incorrectly believe their sessions are `plan_tier = 'unknown'` and re-run `tj onboard --reconfigure` unnecessarily.
Reviews (1): Last reviewed commit: "Merge branch 'main' into feat/codex-back..." | Re-trigger Greptile
| for span in parsed.spans: | ||
| if conn is not None: | ||
| existing = conn.execute( | ||
| "SELECT 1 FROM spans WHERE span_id = $1", [span.span_id] | ||
| ).fetchone() | ||
| if existing: | ||
| spans_skipped += 1 | ||
| continue | ||
| try: | ||
| db.insert_span(span) | ||
| inserted += 1 | ||
| except Exception: | ||
| spans_skipped += 1 | ||
| db.upsert_session( |
There was a problem hiding this comment.
Per-span SELECT diverges from the established bulk idempotency pattern
ingest_codex issues one SELECT 1 FROM spans WHERE span_id = $1 per span, then one db.insert_span() per new span. The Claude Code path in core/backfill._insert_session_idempotent was upgraded exactly because of this: it uses _existing_span_ids() (a single WHERE span_id IN (...) query per session, chunked at 5,000) followed by conn.executemany() for the new spans — bringing the per-session round-trips from 2N to 2 regardless of how many spans a session contains. A user backfilling 500 Codex sessions with 20 spans each would issue ~10,000 individual SELECTs here instead of ~500 batched ones.
Prompt To Fix With AI
This is a comment left during a code review.
Path: tokenjam/core/ingest_adapters/codex.py
Line: 434-447
Comment:
**Per-span SELECT diverges from the established bulk idempotency pattern**
`ingest_codex` issues one `SELECT 1 FROM spans WHERE span_id = $1` per span, then one `db.insert_span()` per new span. The Claude Code path in `core/backfill._insert_session_idempotent` was upgraded exactly because of this: it uses `_existing_span_ids()` (a single `WHERE span_id IN (...)` query per session, chunked at 5,000) followed by `conn.executemany()` for the new spans — bringing the per-session round-trips from `2N` to `2` regardless of how many spans a session contains. A user backfilling 500 Codex sessions with 20 spans each would issue ~10,000 individual SELECTs here instead of ~500 batched ones.
How can I resolve this? If you propose a fix, please make it concise.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
… (#434) Five review findings from the just-merged onboarding batch, addressed together because they cluster around the same onboard/uninstall UX and the SDK exporter/backfill idempotency touched in that batch. #432 (P1): the combination path double-ran the Codex backfill and printed the closing home banner up to three times. `_onboard_codex` ran its own backfill AND printed the banner, `_onboard_claude_code` printed the banner too, and `_onboard_combination` did both again. Fix: give both per-path sub-onboarders a `standalone: bool = True` parameter. The combination flow passes `standalone=False`, which suppresses each sub-onboarder's own Codex backfill and closing banner — so the backfill runs exactly once (in the combination leg) and the banner prints exactly once (at the very end). Single-path flows keep `standalone=True` and are unchanged. #430 (P1): after a successful `pipx uninstall tokenjam`, the venv is gone, so the printed reinstall hint `pipx upgrade tokenjam` would fail ("not installed"). Added `_package_fresh_install_hint()` (bare `pipx install` / `pip install`) and use it only on the successful-removal path. The upgrade/--force hint stays where it belongs — when the package REMAINS (a plain install would no-op there). #430 (P2): `--remove-package` help text overstated ("runs pipx/pip uninstall") — for non-pipx installs it only PRINTS the command. Reworded the help + option text and the interactive confirm prompt so they say "runs" for pipx and "prints … for you to run" for pip/venv. #431 (P2): a whitespace-only ingest secret was truthy, so `TjHttpExporter` built `Authorization: Bearer ` — the same illegal header value the empty case already guards against. Now guard on `.strip()` so a blank secret omits the header entirely. #433 (P2): `ingest_codex` issued one `SELECT 1 FROM spans WHERE span_id=$1` per span. Aligned it with the Claude Code path's bulk idempotency by reusing `core.backfill._existing_span_ids` — one chunked `WHERE span_id IN (...)` per session partitions new-vs-existing spans, replacing the per-span existence SELECT. Backends without a `conn` (InMemoryBackend) fall back to plain inserts and let the PRIMARY KEY conflict skip duplicates. Tests: combination path backfills each source ONCE and prints the banner ONCE (TestCombinationPathNoDoubleRun); after-removal reinstall hint is `pipx install` not upgrade; prompt wording matches install type; whitespace-only secret omits the Authorization header; a DuckDB-backed idempotency test exercises the new bulk `_existing_span_ids` path. Claude-Session: https://claude.ai/code/session_015e3DZGhb1R5sXX2x52Y2Ar Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Codex CLI persists every session to disk as a rollout JSONL file (
~/.codex/sessions/YYYY/MM/DD/rollout-<ts>-<uuid>.jsonl), the same way Claude Code writes~/.claude/projects/*.jsonl. Until now tj could only ingest Codex telemetry going forward (out-of-band OTel viatj onboard --codex); a user's history before onboarding was invisible. This adds the historical counterpart.Summary
tokenjam/core/ingest_adapters/codex.pyparsing Codex rollout JSONL intoNormalizedSpans, mirroringcore/backfill.py'singest_claude_code.tj backfill codex(--root,--since) registered incmd_backfill.py.tests/unit/test_backfill_codex.py; docs pagedocs/backfill/codex.md; CLAUDE.md + backfill overview updated (four → five sources).Spike findings (STEP 1)
Codex does persist usable transcripts on disk — the build was warranted.
~/.codex/sessions/YYYY/MM/DD/rollout-<timestamp>-<uuid>.jsonl(macOS/Linux).RolloutLine—{"timestamp": "<iso8601>", "type": "<kind>", "payload": {...}}(codex-rsRolloutItemenum,#[serde(tag="type", content="payload")]). Line kinds consumed:session_meta→session_id/id,timestamp,cwd,cli_version,model_provider.turn_context→model(effective model for following turns).event_msg→ inner{"type":"token_count","info":{...}}→TokenUsagefieldsinput_tokens,cached_input_tokens,output_tokens,reasoning_output_tokens,total_tokens(aslast_token_usageper-turn delta +total_token_usagecumulative).response_item→ inner{"type":"function_call","name":...,"call_id":...}→ tool calls (flatcall_idpairing, no nesting).Field names verified against
openai/codexsource (codex-rs/protocol/src/protocol.rs,SessionMeta/TurnContextItem/TokenUsage/RolloutItem).Implementation notes
(session_id, per-turn index)for LLM spans,(session_id, call_id)for tool spans. Re-run inserts nothing new (testtest_ingest_is_idempotent).[budget.openai] plan, matching the live path ([bug] Claude Code backfill doesn't propagate config plan to SessionRecord.plan_tier #176) — falls back tounknownwith no config.openai/codex_exec(Codex hardcodesservice.name=codex_exec), so backfill and live ingest attribute to one agent.token_countusing the per-turnlast_token_usagedelta, so summed spans equal cumulativetotal_token_usage(no double-count).cached_input_tokensis a subset ofinput_tokens→ billable input isinput − cached;reasoning_output_tokensfold into output. OpenAI auto-caching has no cache-creation charge →cache_write_tokens = 0(mirrorsroutes/logs.py, ingest: thread cache_write_tokens through logs adapter + Langfuse/Helicone backfill #93).pricing/models.toml; models absent from the packaged table fall back to the default rate (users add a pricing override for exact figures).Tests / Verification
tests/unit/test_backfill_codex.py— 11 tests: parser (LLM+tool extraction, per-turn delta summing, model-tracking acrossturn_context, empty-session → None), iter (walk + since), ingest (writes spans+session, idempotency, plan-tier propagation + fallbacks,--sincewindow). All fixtures build on-disk rollout JSONL; spans are the parsed output (Critical Rule 8 respected — the factory is for span inputs, this adapter's input is JSONL).ruff check tokenjam/andmypy tokenjam/core/ingest_adapters/codex.pyclean.pytest tests/unit/test_backfill.py tests/unit/test_backfill_codex.py tests/integration/test_cli.py→ 128 passed.tj --db … backfill codex --root …→Saw 1 session(s); wrote 1 new session(s), 2 new span(s).What's NOT in this PR (deliberately deferred)
[capture]-gated pass could follow the Claude Code model later).tj onboard --codexauto-invoke — the Claude Code backfill auto-runs at the end of onboarding; wiring the Codex equivalent is a separate onboarding change, left out to keep this PR to the adapter.pricing/models.toml— unknown-model fallback applies (same as any new model); adding exact Codex rates is a pricing PR.🤖 Generated with Claude Code