Skip to content

[feature] Add tj backfill codex — Codex CLI rollout session backfill - #433

Merged
anilmurty merged 3 commits into
mainfrom
feat/codex-backfill
Jul 9, 2026
Merged

anilmurty merged 3 commits into
mainfrom
feat/codex-backfill

Conversation

@anilmurty

Copy link
Copy Markdown
Contributor

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.

Summary

  • New adapter tokenjam/core/ingest_adapters/codex.py parsing Codex rollout JSONL into NormalizedSpans, mirroring core/backfill.py's ingest_claude_code.
  • New CLI subcommand tj backfill codex (--root, --since) registered in cmd_backfill.py.
  • 11 unit tests in tests/unit/test_backfill_codex.py; docs page docs/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.

  • Location: ~/.codex/sessions/YYYY/MM/DD/rollout-<timestamp>-<uuid>.jsonl (macOS/Linux).
  • Format: newline-delimited RolloutLine — {"timestamp": "<iso8601>", "type": "<kind>", "payload": {...}} (codex-rs RolloutItem enum, #[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":{...}} → TokenUsage fields input_tokens, cached_input_tokens, output_tokens, reasoning_output_tokens, total_tokens (as last_token_usage per-turn delta + total_token_usage cumulative).
    • response_item → inner {"type":"function_call","name":...,"call_id":...} → tool calls (flat call_id pairing, no nesting).

Field names verified against openai/codex source (codex-rs/protocol/src/protocol.rs, SessionMeta/TurnContextItem/TokenUsage/RolloutItem).

Implementation notes

  • Idempotency: deterministic span IDs — (session_id, per-turn index) for LLM spans, (session_id, call_id) for tool spans. Re-run inserts nothing new (test test_ingest_is_idempotent).
  • Plan tier from [budget.openai] plan, matching the live path ([bug] Claude Code backfill doesn't propagate config plan to SessionRecord.plan_tier #176) — falls back to unknown with no config.
  • Provider/agent always openai / codex_exec (Codex hardcodes service.name=codex_exec), so backfill and live ingest attribute to one agent.
  • Token accounting: one LLM span per token_count using the per-turn last_token_usage delta, so summed spans equal cumulative total_token_usage (no double-count). cached_input_tokens is a subset of input_tokens → billable input is input − cached; reasoning_output_tokens fold into output. OpenAI auto-caching has no cache-creation charge → cache_write_tokens = 0 (mirrors routes/logs.py, ingest: thread cache_write_tokens through logs adapter + Langfuse/Helicone backfill #93).
  • Cost recomputed from 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 across turn_context, empty-session → None), iter (walk + since), ingest (writes spans+session, idempotency, plan-tier propagation + fallbacks, --since window). 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/ and mypy tokenjam/core/ingest_adapters/codex.py clean.
  • pytest tests/unit/test_backfill.py tests/unit/test_backfill_codex.py tests/integration/test_cli.py → 128 passed.
  • Live smoke: built a rollout fixture, ran 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)

  • No content capture — token/cost/tool-shape only, no prompt/completion text (Codex rollouts do carry message text; a [capture]-gated pass could follow the Claude Code model later).
  • No sub-agent attribution — Codex rollouts lack a Claude-Code-style sidechain marker.
  • No tj onboard --codex auto-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.
  • No Codex model rows in pricing/models.toml — unknown-model fallback applies (same as any new model); adding exact Codex rates is a pricing PR.

🤖 Generated with Claude Code

anilmurty and others added 2 commits July 8, 2026 16:25
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
@anilmurty
anilmurty marked this pull request as ready for review July 8, 2026 23:56
@anilmurty
anilmurty merged commit b2d5a3b into main Jul 9, 2026
4 checks passed
@anilmurty
anilmurty deleted the feat/codex-backfill branch July 9, 2026 00:00
@greptile-apps

greptile-apps Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

Adds tj backfill codex — a new on-disk adapter that parses Codex CLI rollout JSONL files (~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl) into NormalizedSpans, letting users backfill Codex session history before they onboarded live telemetry. The implementation mirrors the existing Claude Code path: deterministic span IDs, plan-tier resolution from config, cost recomputed from pricing/models.toml, and idempotent re-runs.

  • tokenjam/core/ingest_adapters/codex.py: New adapter parsing session_meta, turn_context, event_msg/token_count, and response_item/function_call rollout lines into LLM and tool spans; (session_id, turn_index) keyed for LLM spans and (session_id, call_id) for tool spans; provider/agent always openai/codex_exec.
  • tokenjam/cli/cmd_backfill.py: New codex subcommand with --root and --since flags, consistent error handling, and progress output aligned with the claude-code subcommand.
  • tests/unit/test_backfill_codex.py + docs/backfill/codex.md: 11 unit tests and a new adapter doc page; docs/backfill/overview.md adds Codex to the supported-sources table but leaves two now-inaccurate general statements uncorrected.

Confidence Score: 4/5

Safe to merge; the adapter is well-tested and the correctness issues are doc inconsistencies and a performance gap vs the established bulk pattern.

The core adapter logic, token accounting, idempotency semantics, and CLI wiring are all solid and consistent with the Claude Code path. The two findings are: ingest_codex uses per-span SELECTs rather than the bulk _existing_span_ids() approach in core/backfill, which would slow large backfills but never causes incorrect data; and docs/backfill/overview.md still carries two statements (adapter flags, plan-tier default) that are now incorrect for both the Codex and Claude Code adapters.

tokenjam/core/ingest_adapters/codex.py (idempotency loop pattern) and docs/backfill/overview.md (stale general statements)

Important Files Changed

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)
Loading
%%{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)
Loading

Comments Outside Diff (1)

  1. docs/backfill/overview.md, line 17-31 (link)

    P2 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 [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 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.

    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

Comment on lines +434 to +447
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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 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!

anilmurty added a commit that referenced this pull request Jul 9, 2026
… (#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]>
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