Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): resolve Codex usage tiers from initial run history #21898

Mergedjuliusmarmingemerged 12 commits intomain fromrefs/pull/21898/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Problem

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. juliusmarminge changed the title

    2. juliusmarminge added labelsmacroscope-review

    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      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).
    4. github-actions[bot](GitHub profile, opens in a new tab)commented

      Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire5.0 KiB4.9 KiB−30 B (−0.6%)6.8 KiB✅
      CodexThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      CodexLive turn WebSocket wire1.2 KiB1.2 KiB−30 B (−2.5%)2.0 KiB✅
      CodexLive turn WebSocket decoded20.9 KiB20.8 KiB−41 B (−0.2%)29.3 KiB✅
      CodexLive turn messages21−1 (−50.0%)8✅
      ClaudeTotal thread wire5.0 KiB5.0 KiB0 B (0.0%)6.8 KiB✅
      ClaudeThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      ClaudeLive turn WebSocket wire1.2 KiB1.2 KiB0 B (0.0%)2.0 KiB✅
      ClaudeLive turn WebSocket decoded21.2 KiB21.2 KiB0 B (0.0%)29.3 KiB✅
      ClaudeLive turn messages220 (0.0%)8✅

      Baseline: c7a2fdc · PR result: 82b1735 · Source CI: success

      Scenario 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.

    5. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ 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_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      Warning

      .coderabbit.config.ts has 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.ts
      Migration 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.ts
      The 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.ts
      Tests 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: Passed 3 · Failed 1
      Failed Failed checks: 1 warning
      Check nameStatusExplanationResolution
      Linked Issues checkWarningIssue [#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 CodexUsageHistory with 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 Passed checks: 3 passed
      Check nameStatusExplanation
      Title checkPassedThe title clearly and concisely describes the main change: resolving Codex usage tiers from initial run history.
      Description checkPassedThe 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 checkPassedThe 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 in CodexUsageHistory.ts and 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 CodexUsageHistory with 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
      Comment `@coderabbitai help` to get the list of available commands.
    6. juliusmarminge merged thisf4e3f25

    7. juliusmarminge closed this

Sign in to join this conversation.