CodexBar icon indicating copy to clipboard operation
CodexBar copied to clipboard

Codex cost: one unpriced request hides the whole model/day estimate, and a day with an unpriced model reads as fully priced

Open gabrielrojasc opened this issue 1 month ago • 4 comments

Summary

makeCodexBilledDayEntry (CostUsageScanner+ForkCoverage.swift) prices a model/day group from its rows only when codexRowCostBreakdown(...).isTrusted holds. isTrusted rejects the whole group as soon as one row has unpricedTokens > 0 (CostUsageScanner+CacheHelpers.swift, hasIncompletePricing). The aggregate fallback is also blocked for that group, so the model's cost becomes nil, even when every other request in the group can be priced. Quota windows (addCodexHourly) already handle the same rows per request: they skip the marked request, price the rest, and mark the window costIsComplete == false.

A second, related gap: when one model on a day has a cost and another has none, the day entry keeps the priced model's cost and leaves unpricedRequestCount nil. coverageCounts then reports the day as fully priced (priced: 1, unpriced: 0).

Real-world effect: after the 0.72.0 ledger upgrade marked many September requests (#4270), the menu's 30-day total showed cents while "Recent windows" showed partial estimates in the hundreds of dollars for the same period, from the same cache.

Repro: Tests/CodexBarTests/CostUsageCodexPartialPricingTests.swift

CostUsageCodexPartialPricingTests.swift
import Foundation
import Testing
@testable import CodexBarCore

@Suite(.serialized)
struct CostUsageCodexPartialPricingTests {
    /// One request with unknown historical pricing should not erase the estimate for the other requests of the same
    /// model and day. Quota windows already price those requests and flag the window incomplete.
    @Test
    func `an unpriced request keeps the priced subtotal of its model day`() throws {
        let env = try CostUsageTestEnvironment()
        defer { env.cleanup() }
        let day = try env.makeLocalNoon(year: 2026, month: 9, day: 10)
        let file = try env.writeCodexSessionFile(
            day: day,
            filename: "partial.jsonl",
            contents: Self.session(
                day: day,
                env: env,
                id: "partial",
                model: "gpt-5.4",
                inputs: [100_000, 200_000, 300_000]))
        let cache = try Self.scannedCache(day: day, env: env)
        let priced = try #require(Self.report(cache, day: day).data.first?.costUSD)

        var marked = cache
        var usage = try #require(marked.files[file.path])
        usage.codexRows = usage.codexRows?.enumerated().map { index, row in
            var row = row
            if index == 0 { row.unpricedTokens = row.input + row.output }
            return row
        }
        marked.files[file.path] = usage
        let report = Self.report(marked, day: day)
        let entry = try #require(report.data.first)
        let slice = try #require(report.quotaSlices.first { ($0.costUSD ?? 0) > 0 })
        print(
            "[partial-pricing] fullyPricedDay=\(priced) "
                + "dayCostWithOneMarkedRequest=\(String(describing: entry.costUSD)) "
                + "unpricedRequestCount=\(String(describing: entry.unpricedRequestCount)) "
                + "quotaSliceCost=\(String(describing: slice.costUSD)) quotaSliceComplete=\(slice.costIsComplete)")
        let windowSubtotal: Double = report.quotaSlices.compactMap(\.costUSD).reduce(0, +)
        #expect(abs((entry.costUSD ?? 0) - windowSubtotal) < 1e-9)
        #expect(entry.unpricedRequestCount == 1)
    }

    /// A day whose second model has no estimate is a partial day, not a fully priced one.
    @Test
    func `a day with an unpriced model reports incomplete coverage`() throws {
        let env = try CostUsageTestEnvironment()
        defer { env.cleanup() }
        let day = try env.makeLocalNoon(year: 2026, month: 9, day: 10)
        _ = try env.writeCodexSessionFile(
            day: day,
            filename: "priced.jsonl",
            contents: Self.session(day: day, env: env, id: "priced", model: "gpt-5.4", inputs: [100_000]))
        let other = try env.writeCodexSessionFile(
            day: day,
            filename: "unknown.jsonl",
            contents: Self.session(day: day, env: env, id: "unknown", model: "gpt-5.5", inputs: [100_000]))
        var cache = try Self.scannedCache(day: day, env: env)
        var usage = try #require(cache.files[other.path])
        usage.codexRows = usage.codexRows?.map { row in
            var row = row
            row.unpricedTokens = row.input + row.output
            return row
        }
        cache.files[other.path] = usage
        let entry = try #require(Self.report(cache, day: day).data.first)
        let models = (entry.modelBreakdowns ?? []).map { "\($0.modelName)=\(String(describing: $0.costUSD))" }
        print("[partial-pricing] dayCost=\(String(describing: entry.costUSD)) models=\(models) "
            + "unpricedRequestCount=\(String(describing: entry.unpricedRequestCount)) coverage=\(entry.coverageCounts)")
        #expect((entry.unpricedRequestCount ?? 0) > 0)
    }

    private static func scannedCache(day: Date, env: CostUsageTestEnvironment) throws -> CostUsageCache {
        var options = CostUsageScanner.Options(
            codexSessionsRoot: env.codexSessionsRoot,
            claudeProjectsRoots: nil,
            cacheRoot: env.cacheRoot,
            codexTraceDatabaseURL: env.root.appendingPathComponent("missing-traces.sqlite"))
        options.refreshMinIntervalSeconds = 0
        _ = CostUsageScanner.loadDailyReport(provider: .codex, since: day, until: day, now: day, options: options)
        return CostUsageStoreAccess.read(cacheRoot: env.cacheRoot)
    }

    private static func report(_ cache: CostUsageCache, day: Date) -> CostUsageDailyReport {
        CostUsageScanner.buildCodexReportFromCache(
            cache: cache,
            range: .init(since: day, until: day),
            modelsDevCatalog: ModelsDevCatalog(providers: [:]))
    }

    static func session(
        day: Date,
        env: CostUsageTestEnvironment,
        id: String,
        model: String,
        inputs: [Int]) throws -> String
    {
        let timestamp = env.isoString(for: day)
        var records: [[String: Any]] = [
            ["type": "session_meta", "timestamp": timestamp, "payload": ["id": id]],
            ["type": "turn_context", "timestamp": timestamp, "payload": ["model": model]],
            ["type": "event_msg", "timestamp": timestamp, "payload": ["type": "task_started", "turn_id": "\(id)-turn"]],
        ]
        for input in inputs {
            records.append(["type": "event_msg", "timestamp": timestamp, "payload": [
                "type": "token_count",
                "info": ["last_token_usage": ["input_tokens": input, "cached_input_tokens": 0, "output_tokens": 0]],
            ]])
        }
        return try env.jsonl(records)
    }
}
make test-fast FILTER='CostUsageCodexPartialPricingTests'

On main @ ea5d7d9bc:

[partial-pricing] fullyPricedDay=2.25 dayCostWithOneMarkedRequest=nil unpricedRequestCount=Optional(1) quotaSliceCost=Optional(2.0) quotaSliceComplete=false
✘ Test "an unpriced request keeps the priced subtotal of its model day" recorded an issue at CostUsageCodexPartialPricingTests.swift:43:9: Expectation failed: abs((entry.costUSD ?? 0) - windowSubtotal) < 1e-9
[partial-pricing] dayCost=Optional(0.25) models=["gpt-5.4=Optional(0.25)", "gpt-5.5=nil"] unpricedRequestCount=nil coverage=CostUsageCoverageCounts(priced: 1, unpriced: 0, unmetered: 0, estimated: 0)
✘ Test "a day with an unpriced model reports incomplete coverage" recorded an issue at CostUsageCodexPartialPricingTests.swift:73:9: Expectation failed: (entry.unpricedRequestCount ?? 0) > 0

In the first case, three requests price at 2.25 together. After marking the first request, quota windows still report 2.00 for the other two (incomplete), but the daily entry drops to nil.

Expected

  • A model/day group whose rows otherwise cover the group reports the known subtotal of its priceable requests, and counts the unknown ones in unpricedRequestCount. Ideally it also counts the priced ones in pricedRequestCount, so coverage stays request-based.
  • A day with any model lacking a cost reports unpricedRequestCount > 0, so coverageCounts, the Spend dashboard's lower-bound display (≥), and the CLI "Partial estimate" line treat it as partial.
  • Unknown requests stay unknown: no current-list-price fallback for marked rows, and the aggregate fallback stays blocked for them.

Notes for a fix

  • The Spend dashboard already renders a cost with unpricedRequestCount > 0 as a lower bound (SpendDashboardModel.costIsLowerBound), so Entry needs no new field.
  • SpendDashboardModel+ModelBreakdown.hasCompleteModelCostCoverage checks only that model costs sum to the day cost. It would also need to require unpricedRequestCount == 0, or a partial model subtotal would read as complete.
  • Session rows (CostUsageSessionBreakdown) have only costUSD. A partial session would either need a coverage field or stay nil.

gabrielrojasc avatar Oct 05 '26 05:10 gabrielrojasc

Codex review: this still needs some work. Reviewed October 5, 2026, 1:53 AM ET / 05:53 UTC.

Summary Both defects remain in current main and v0.72.0. The linked upgrade-pricing PR addresses how unpriced markers arise, but leaves partial daily aggregation unresolved; this issue merits a focused repair.

Reproducibility: yes. the supplied cache fixtures and failure transcript match the current daily-builder and coverage logic. This read-only review verified the source path without executing tests.

Root-cause cluster Relationship: canonical Canonical: https://github.com/steipete/codexbar/issues/4273 Summary: This issue owns partial daily aggregation; the related PR repairs an upstream source of unpriced markers.

Members:

  • adjacent_distinct: https://github.com/steipete/codexbar/pull/4270 - Legacy pricing-key recovery reduces upgrade-generated markers but does not repair reporting when unknown prices remain.

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Next step A focused computed-report repair is source-proven and remains distinct from the open upgrade-pricing PR.

Review details

Best possible solution:

Daily reports should retain only provable request subtotals, carry accurate partial coverage into dashboard and CLI output, and preserve unknown prices and ownership safeguards.

Do we have a high-confidence way to reproduce the issue?

Yes: the supplied cache fixtures and failure transcript match the current daily-builder and coverage logic. This read-only review verified the source path without executing tests.

Is this the best way to solve the issue?

Yes, retaining structurally trustworthy partial subtotals follows existing quota-window behavior; simply removing the incomplete-pricing guard would incorrectly price marked rows.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against ea5d7d9bc30b.

Label changes

Label changes:

  • add P2: Incorrect Codex spend totals and completeness indicators are a bounded reporting defect.
  • add impact:other: Known spending estimates disappear or appear fully priced despite missing request prices.
  • add issue-rating: 🦞 diamond lobster: Current issue advisory state selects this label.
  • add clawsweeper:source-repro: Current issue advisory state selects this label.
  • add clawsweeper:queueable-fix: Current issue advisory state selects this label.
  • add clawsweeper:fix-shape-clear: Current issue advisory state selects this label.

Label justifications:

  • P2: Incorrect Codex spend totals and completeness indicators are a bounded reporting defect.
  • impact:other: Known spending estimates disappear or appear fully priced despite missing request prices.
Evidence reviewed

Acceptance criteria:

  • make test-fast FILTER='CostUsageCodexPartialPricingTests|CostUsageCodexSourceRecoveryTests|CostUsageCodexRequestLedgerTests|CostProvenanceTests|SpendDashboardPartialCostTests'
  • make test
  • make check

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • stabey: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Yuxin-Qiao: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

clawsweeper[bot] avatar Oct 05 '26 05:10 clawsweeper[bot]

Proposed scope for a fix, for maintainer review before I open a PR:

  • When a model/day group's rows cover the group, report the subtotal of its priceable requests. Count the marked requests in unpricedRequestCount and the priced ones in pricedRequestCount. Marked requests stay unpriced: no list-price fallback, and the aggregate fallback stays blocked.
  • A day that has any model without a cost reports unpricedRequestCount > 0.
  • hasCompleteModelCostCoverage also requires unpricedRequestCount == 0, so the Spend dashboard shows a partial model breakdown as partial.
  • Session rows keep their single costUSD. A partially priced session would show its known subtotal, as mixed sessions already do today. A session coverage field is out of scope.

Both this fix and #4270 regenerate the Codex parser hash, so I plan to open the PR after #4270 merges, with the repro tests above as its regression tests.

gabrielrojasc avatar Oct 05 '26 06:10 gabrielrojasc

I opened the focused implementation as PR #4278. The report aggregation fix is independent of #4270: it preserves priceable request subtotals, counts priced/unpriced requests, and marks mixed model/day coverage partial without using list-price fallback for marked rows.

The current main baseline cannot pass the repository checks before #4270 lands: Scripts/regenerate-codex-parser-hash.sh --check reports the tracked ed735dc27ffa70d9 hash is stale (78c6e6e391a5fa93 is generated from current main). #4270 changes the same generated parser hash as part of its parser recovery work, so updating that file here would create an overlapping/conflicting change. PR #4278 is therefore blocked on #4270 merging (or maintainers otherwise resolving the shared generated hash), while the functional patch remains ready for review.

luochen211 avatar Oct 05 '26 07:10 luochen211

Fixed by #4279 via the merge train #4317 (d919d238). The known $2.00 subtotal stays visible when another request is unpriced, with partial coverage and ownership safeguards preserved. Thanks @gabrielrojasc and @luochen211. Ships in the next release.

steipete avatar Oct 07 '26 06:10 steipete