fix(server): resolve Codex usage tiers from initial run history #21898
main fromrefs/pull/21898/head·merged by juliusmarminge View on GitHubProblem#
Codex can omit its initial rollout settings even when T3 requested Fast or Ultrafast. Recovering that tier requires reliable historical evidence; a later steering selection can describe a different price.
Change#
Add a SQL-backed history service that resolves a batch of native turn IDs using the exact attempt's first running V2 event. Native session and model must match, and duplicate mappings remain unresolved. Add a nonunique partial index so lookups search Codex native IDs without scanning the provider-turn table. Route historical reads through the SQLite reader worker to avoid blocking orchestration commits.
Rebuilt from @PixPMusic's #15275. Transcript and cache integration is in #21899. This layer sits above the usage-counter reconciliation.
Scope and approval#
Addresses the retained V2 history portion of #15267, under the maintainer takeover. Historical cost attribution still needs human maintainer review. V1-only histories without retained attempts stay unchanged; the issue remains open.
Verification#
Four fresh parallel review rounds with Opus 5.5 and GPT-6 Sol covered both layers. They caught and fixed writer-thread SQL execution and unnecessary v6 Pi cache invalidation. CI also exposed a stale migration-64 test expectation, which now includes migration 65. The final round found no blockers.
- 55 focused tests in four existing service/migration suites, up from 51: first-running selection, later steering, legacy options, mismatched or ambiguous history, missing V2 evidence, SQL failure and retry, and released/preview migration upgrades.
- The actual production SQL uses
SEARCH turn USING INDEX orchestration_v2_provider_turns_codex_native_id_idx; duplicate candidates are preserved. - Scoped server typecheck, lint, formatting, and export checks passed.
- Verified on headless Linux with in-memory SQLite. Native Windows, macOS, iOS, Android, and Electron were not run. This layer alone does not change the displayed estimate.
Implementation: GPT-6.1 Sol; tests: GPT-6 Astra. Harness: Codex in T3 Code.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge changed the title
juliusmarminge added labelsmacroscope-review
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Provider Metric Main baseline This PR Impact PR ceiling Codex Total thread wire 5.0 KiB 4.9 KiB −30 B (−0.6%) 6.8 KiB ✅ Codex Thread snapshot wire 3.8 KiB 3.8 KiB 0 B (0.0%) 4.9 KiB ✅ Codex Live turn WebSocket wire 1.2 KiB 1.2 KiB −30 B (−2.5%) 2.0 KiB ✅ Codex Live turn WebSocket decoded 20.9 KiB 20.8 KiB −41 B (−0.2%) 29.3 KiB ✅ Codex Live turn messages 2 1 −1 (−50.0%) 8 ✅ Claude Total thread wire 5.0 KiB 5.0 KiB 0 B (0.0%) 6.8 KiB ✅ Claude Thread snapshot wire 3.8 KiB 3.8 KiB 0 B (0.0%) 4.9 KiB ✅ Claude Live turn WebSocket wire 1.2 KiB 1.2 KiB 0 B (0.0%) 2.0 KiB ✅ Claude Live turn WebSocket decoded 21.2 KiB 21.2 KiB 0 B (0.0%) 29.3 KiB ✅ Claude Live turn messages 2 2 0 (0.0%) 8 ✅ Baseline:
c7a2fdc· PR result:82b1735· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
- Codex decoded thread snapshot: 108.5 KiB
- Claude decoded thread snapshot: 108.8 KiB
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.
Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
-
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Team
- Run ID:
ad6f054b-4ac5-4b11-91df-2a4cc40996f3
You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
- 🔍 Trigger review
Warning
.coderabbit.config.tshas a parsing error#The CodeRabbit configuration file in this repository has a parsing error and default settings were used instead. Please fix the error(s) in the configuration file. You can initialize chat with CodeRabbit to get help with the configuration file.
Parsing errors: 1
-
Error while evaluating .coderabbit.config.ts
⚙️ Configuration instructions
-
- Please see the configuration documentation for more information.
- You can also validate your configuration using the online YAML validator.
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation:
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
-
⚙️ Run configuration
-
- Configuration used: Path: .coderabbit.config.ts
- Review profile: CHILL
- Plan: Team
- Run ID:
58a0625a-3365-4f8c-9976-1357ed96164a
📥 Commits
-
Reviewing files that changed from the base of the PR and between 8c62e5913a3aa95a609e38b536ceadfe4f84460d and e51af66fb8310024c788e3ef096b6e162755adfc.
📒 Files selected for processing: 1
-
apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.
-
📝 Walkthrough
-
The change adds migration 65 with a partial index for Codex native turn IDs. It also adds a service that resolves usage speeds from orchestration history and tests the migration and resolution behavior.
Changes: Codex usage history lookup
Layer / File(s) Summary Add and validate the native-turn index
apps/server/src/persistence/Migrations/065_CodexUsageNativeTurnIndex.ts,apps/server/src/persistence/Migrations.ts,apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts,apps/server/src/persistence/reconcileV2PreviewMigration.test.ts,apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.test.tsMigration 65 creates and registers a partial index on Codex native turn IDs. Migration tests check the upgrade sequence, matching results, and index use. Resolve usage speeds from history
apps/server/src/usage/CodexUsageHistory.tsThe service queries matching Codex turns and running events. It validates turn, session, and model evidence, then maps recognized service tiers to usage speeds. Test history resolution
apps/server/src/usage/UsageService.test.tsTests cover tier mapping, repeated and ambiguous matches, invalid or missing evidence, and typed database read failures. Priority: ➖ Normal
Estimated code review effort: 3 (Moderate) | ~25 minutes
Change: Bug fix · Severity of issue fixed: Medium
Suggested reviewers:
yash-singh1
Merge Risk: ⚪ Minimal · up to
e51af-
This change adds a database index and a history lookup service, but the current production server does not use the service or change usage estimates. No actionable merge risk is established.
Pre-merge checks:
3 · 1-
Failed checks: 1 warningCheck name Status Explanation Resolution Linked Issues check Issue [ #15267] requires initial retained-history usage to be classified and priced as the requested tier, while later tier changes must not rewrite that history. This PR implements the retained V2 loo…Integrate CodexUsageHistorywith the usage classification and pricing path so resolved retained V2 history changes the initial turn's speed and cost, while later native tier changes retain precedence. Add an end-to-end test for the issue … Passed checks: 3 passed-
Check name Status Explanation Title check The title clearly and concisely describes the main change: resolving Codex usage tiers from initial run history. Description check The description includes complete Problem, Change, Scope and approval, and Verification sections. It explains the implementation, linked issue context, test coverage, validation results, and untested … Out of Scope Changes check The service, migration 65, partial Codex native-ID index, migration updates, and focused tests all support the retained V2 history lookup described for issue [ #15267]. The SQL reader-worker path, dupl…Full details: Description check
-
Explanation
The description includes complete Problem, Change, Scope and approval, and Verification sections. It explains the implementation, linked issue context, test coverage, validation results, and untested platforms.
Full details: Out of Scope Changes check
-
Explanation
The service, migration 65, partial Codex native-ID index, migration updates, and focused tests all support the retained V2 history lookup described for issue [
#15267]. The SQL reader-worker path, duplicate handling, and migration-upgrade tests are supporting implementation work.
-
Full details: Linked Issues check
-
Explanation
Issue [
#15267] requires initial retained-history usage to be classified and priced as the requested tier, while later tier changes must not rewrite that history. This PR implements the retained V2 lookup inCodexUsageHistory.tsand tests first-running selection, model/session matching, and ambiguity. The reviewed changes do not integrate the result into the usage scanner or displayed estimate. The PR description also states that this layer alone does not change the displayed estimate.Resolution
Integrate
CodexUsageHistorywith the usage classification and pricing path so resolved retained V2 history changes the initial turn's speed and cost, while later native tier changes retain precedence. Add an end-to-end test for the issue scenario.
-
✨ Finishing Touches
-
📝 Generate docstrings
-
- Commit to this branch
- Create a new PR
🧪 Generate unit tests (beta)
-
- Commit to this branch
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
-
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
juliusmarminge merged thisf4e3f25
juliusmarminge closed this
Sign in to join this conversation.
Approvability#
Verdict: Needs Human Approval
Macroscope's review found this PR requires human approval — This PR adds a production Codex usage-history service and database index to recover historical service tiers, with the resulting speed classification intended for usage/cost attribution. The service is not yet wired into the live usage path, but the new metering-related logic and production migration warrant maintainer review.
Notes:
- Diff unchanged. Approvability was decided on eligibility alone.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).