Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Generated by Scripts/regenerate-codex-parser-hash.sh. Do not edit by hand.

enum CodexParserHash {
static let value = "d2d731a6eb7ad436"
static let value = "f4935b4811fb8a59"
}
60 changes: 43 additions & 17 deletions Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Crypto
#endif
import Foundation

// swiftlint:disable type_body_length
// swiftlint:disable type_body_length file_length
enum CostUsageScanner {
static let log = CodexBarLog.logger(LogCategories.tokenCost)
static let codexActiveSessionLookbackDays = 30
Expand Down Expand Up @@ -78,6 +78,11 @@ enum CostUsageScanner {
let totals: CostUsageCodexTotals
}

enum CodexForkBaseline {
case resolved(CostUsageCodexTotals?)
case unresolved
}

private static func codexTotalsEqual(_ lhs: CostUsageCodexTotals?, _ rhs: CostUsageCodexTotals?) -> Bool {
lhs?.input == rhs?.input && lhs?.cached == rhs?.cached && lhs?.output == rhs?.output
}
Expand Down Expand Up @@ -265,15 +270,20 @@ enum CostUsageScanner {
self.fileIndex = fileIndex
}

func inheritedTotals(for sessionId: String, atOrBefore cutoffTimestamp: String) -> CostUsageCodexTotals? {
guard !cutoffTimestamp.isEmpty else { return nil }
func inheritedTotals(for sessionId: String, atOrBefore cutoffTimestamp: String) -> CodexForkBaseline {
guard !cutoffTimestamp.isEmpty else {
CostUsageScanner.log.warning(
"Codex cost usage fork timestamp missing; treating parent baseline as unresolved",
metadata: ["sessionId": sessionId])
return .unresolved
}
let cutoffDate = CostUsageScanner.dateFromTimestamp(cutoffTimestamp)
if cutoffDate == nil {
CostUsageScanner.log.warning(
"Codex cost usage could not parse fork timestamp; falling back to lexical comparison",
metadata: ["sessionId": sessionId, "timestamp": cutoffTimestamp])
}
let snapshots = self.snapshots(for: sessionId)
guard let snapshots = self.snapshots(for: sessionId) else { return .unresolved }
var inherited: CostUsageCodexTotals?
for snapshot in snapshots {
let isAtOrBefore: Bool = if let snapshotDate = snapshot.date, let cutoffDate {
Expand All @@ -285,25 +295,25 @@ enum CostUsageScanner {
inherited = snapshot.totals
}
}
return inherited
return .resolved(inherited)
}

private func snapshots(for sessionId: String) -> [CodexTimestampedTotals] {
private func snapshots(for sessionId: String) -> [CodexTimestampedTotals]? {
if let cached = self.snapshotsBySessionId[sessionId] {
return cached
}
guard let fileURL = self.fileIndex.fileURL(for: sessionId) else {
CostUsageScanner.log.warning(
"Codex cost usage parent session file not found",
metadata: ["sessionId": sessionId])
return []
return nil
}
let parsed = CostUsageScanner.parseCodexTokenSnapshots(fileURL: fileURL)
guard let parsedSessionId = parsed.sessionId else {
CostUsageScanner.log.warning(
"Codex cost usage parent session missing session metadata",
metadata: ["sessionId": sessionId, "path": fileURL.path])
return []
return nil
}
if parsedSessionId != sessionId {
CostUsageScanner.log.warning(
Expand All @@ -313,9 +323,10 @@ enum CostUsageScanner {
"resolvedSessionId": parsedSessionId,
"path": fileURL.path,
])
return nil
}
self.snapshotsBySessionId[parsedSessionId] = parsed.snapshots
return self.snapshotsBySessionId[sessionId] ?? []
self.snapshotsBySessionId[sessionId] = parsed.snapshots
return parsed.snapshots
}
}

Expand Down Expand Up @@ -1064,14 +1075,16 @@ enum CostUsageScanner {
initialRawTotalsBaseline: CostUsageCodexTotals? = nil,
initialHasDivergentTotals: Bool = false,
initialCodexTurnID: String? = nil,
inheritedTotalsResolver: ((String, String) -> CostUsageCodexTotals?)? = nil) -> CodexParseResult
inheritedTotalsResolver: ((String, String) -> CodexForkBaseline)? = nil) -> CodexParseResult
{
var currentModel = initialModel
var previousTotals = initialTotals
var sessionId: String?
var forkedFromId: String?
var inheritedTotals: CostUsageCodexTotals?
var remainingInheritedTotals: CostUsageCodexTotals?
var forkBaselineResolved = false
var hasUnresolvedForkBaseline = false
var currentTurnID = initialCodexTurnID
var rawTotalsBaseline = initialRawTotalsBaseline ?? initialTotals
var sawDivergentTotals = initialHasDivergentTotals
Expand All @@ -1093,6 +1106,20 @@ enum CostUsageScanner {
days[dayKey] = dayModels
}

func resolveForkBaseline(parentSessionId: String, forkedAt: String) {
guard !forkBaselineResolved else { return }
guard let inheritedTotalsResolver else { return }
forkBaselineResolved = true
switch inheritedTotalsResolver(parentSessionId, forkedAt) {
case let .resolved(totals):
inheritedTotals = totals
remainingInheritedTotals = totals
hasUnresolvedForkBaseline = false
case .unresolved:
hasUnresolvedForkBaseline = true
}
}

let maxLineBytes = 256 * 1024
let prefixBytes = maxLineBytes

Expand All @@ -1105,8 +1132,7 @@ enum CostUsageScanner {
inheritedTotals == nil
{
let forkedAt = metadata.forkTimestamp ?? ""
inheritedTotals = inheritedTotalsResolver?(forkedFromId, forkedAt)
remainingInheritedTotals = inheritedTotals
resolveForkBaseline(parentSessionId: forkedFromId, forkedAt: forkedAt)
}
}

Expand Down Expand Up @@ -1162,12 +1188,11 @@ enum CostUsageScanner {
?? payload?["parent_session_id"] as? String
?? payload?["parentSessionId"] as? String
}
if inheritedTotals == nil, let forkedFromId {
if let forkedFromId {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Ignore empty fork parent IDs before resolving baseline

Treating forked_from_id/parent_session_id as present whenever the field exists (even when it is "") now marks the fork baseline as unresolved, which then suppresses all total_token_usage counting for that session (hasUnresolvedForkBaseline short-circuits those branches). In logs that encode “not forked” as an empty string, this change undercounts usage to only last_token_usage rows (or zero if none). Please gate baseline resolution on a non-empty parent session id.

Useful? React with 👍 / 👎.

let forkedAt = payload?["timestamp"] as? String
?? obj["timestamp"] as? String
?? ""
inheritedTotals = inheritedTotalsResolver?(forkedFromId, forkedAt)
remainingInheritedTotals = inheritedTotals
resolveForkBaseline(parentSessionId: forkedFromId, forkedAt: forkedAt)
}
return
}
Expand Down Expand Up @@ -1250,7 +1275,7 @@ enum CostUsageScanner {
deltaOutput = adjustedDelta.output
let prev = previousTotals ?? .init(input: 0, cached: 0, output: 0)

if let total {
if let total, !hasUnresolvedForkBaseline {
let rawTotals = CostUsageCodexTotals(
input: toInt(total["input_tokens"]),
cached: toInt(total["cached_input_tokens"] ?? total["cache_read_input_tokens"]),
Expand Down Expand Up @@ -1290,6 +1315,7 @@ enum CostUsageScanner {
rawTotalsBaseline = countedTotals
}
} else if let total {
guard !hasUnresolvedForkBaseline else { return }
let rawTotals = CostUsageCodexTotals(
input: toInt(total["input_tokens"]),
cached: toInt(total["cached_input_tokens"] ?? total["cache_read_input_tokens"]),
Expand Down
60 changes: 60 additions & 0 deletions Tests/CodexBarTests/CostUsageScannerBreakdownTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1552,6 +1552,66 @@ struct CostUsageScannerBreakdownTests {
#expect(abs((report.data[0].costUSD ?? 0) - (expectedCost ?? 0)) < 0.000001)
}

@Test
func `codex forked child skips cumulative totals when parent session is missing`() throws {
let env = try CostUsageTestEnvironment()
defer { env.cleanup() }

let parentDay = try env.makeLocalNoon(year: 2026, month: 2, day: 27)
let childDay = try env.makeLocalNoon(year: 2026, month: 3, day: 11)
let model = "openai/gpt-5.2-codex"
let missingParentSessionId = "sess-parent-deleted"
let childSessionId = "sess-child-deleted-parent"
let forkTs = env.isoString(for: parentDay.addingTimeInterval(2.5))

_ = try env.writeCodexSessionFile(
day: childDay,
filename: "rollout-2026-03-11T11-30-27-\(childSessionId).jsonl",
contents: env.jsonl([
[
"type": "session_meta",
"payload": [
"id": childSessionId,
"forked_from_id": missingParentSessionId,
"timestamp": forkTs,
],
],
self.codexTurnContext(timestamp: env.isoString(for: childDay), model: model),
self.codexTokenCount(
timestamp: env.isoString(for: childDay.addingTimeInterval(1)),
model: model,
total: (input: 1_000_000, cached: 100_000, output: 10000)),
self.codexTokenCount(
timestamp: env.isoString(for: childDay.addingTimeInterval(2)),
model: model,
total: (input: 1_000_120, cached: 100_010, output: 10020)),
self.codexTokenCount(
timestamp: env.isoString(for: childDay.addingTimeInterval(3)),
model: model,
total: (input: 1_000_140, cached: 100_012, output: 10023),
last: (input: 20, cached: 2, output: 3)),
]))

var options = CostUsageScanner.Options(
codexSessionsRoot: env.codexSessionsRoot,
claudeProjectsRoots: nil,
cacheRoot: env.cacheRoot)
options.refreshMinIntervalSeconds = 0
options.forceRescan = true

let report = CostUsageScanner.loadDailyReport(
provider: .codex,
since: childDay,
until: childDay,
now: childDay,
options: options)

#expect(report.data.count == 1)
#expect(report.data[0].inputTokens == 20)
#expect(report.data[0].outputTokens == 3)
#expect(report.data[0].totalTokens == 23)
}

@Test
func `codex forked child inherits counted parent totals when totals diverge`() throws {
let env = try CostUsageTestEnvironment()
Expand Down