codeburn/src/codex-cache.ts
Resham Joshi 1284290743
fix(codex): mask fork replay records against the parent rollout (#1678)
* fix(codex): mask fork replay records against the parent rollout

A fork's replay burst was dropped whole, losing calls that exist only in
the fork. Drop a burst record only when the parent rollout recorded it
before the fork, and count the rest as their own calls. Parent missing or
a burst that does not open with a parent record keeps the old behavior.

Bumps CODEX_CACHE_VERSION to 22 and DAILY_CACHE_VERSION to 66.

* fix(codex): bump the codex parse version for fork masking, fix the comments

Cached forks that dropped the whole burst need to re-parse, so the codex
parse version gains codex-fork-mask-v1. The burst records that now count
are the parent's work its rollout kept only inside a running total, not
fork-only usage.
2026-10-08 00:27:52 +02:00

410 lines
17 KiB
TypeScript

import { readFile, mkdir, stat, open, rename, unlink } from 'fs/promises'
import { existsSync } from 'fs'
import { randomBytes } from 'crypto'
import { join, resolve } from 'path'
import { AsyncLocalStorage } from 'node:async_hooks'
import { getCodeburnCacheDir, readExistingTextFile } from './cache-dir.js'
import type { ParsedProviderCall } from './providers/types.js'
import { isWslUncPath } from './wsl.js'
// v4: attribute MCP calls emitted as event_msg/mcp_tool_call_end (issue #478).
// Recent Codex sessions cached under v3 dropped these, so force a re-parse.
// v5: also attribute CLI-wrapped MCP calls (`mcp-cli call server tool`) that
// Codex logs as a plain exec_command (issue #478 follow-up). Force a re-parse
// so sessions cached under v4 pick up the CLI-MCP attribution.
// v6/v7: rich-session-capture — per-call locAdded/locRemoved/editFailed from
// patch_apply_end. Sessions cached under v5 lack these fields; re-parse to add.
// v8: persist native MCP timing and compact invocation attribution.
// Deliberately NOT bumped for the resume fields (dev/ino + resumeOffset/
// resumeState): they are additive and absence-safe in both directions, so a
// bump would only throw away a warm multi-hundred-MB cache to gain nothing. An
// entry without them simply re-parses in full once and gains them.
// v9: parse large session_meta records structurally so nested provenance.model
// cannot overwrite the model selected by turn_context.
// v10: same depth-1 window for the rest of session_meta's raw string fields
// (cwd/name/originator/session_id/forked_from_id/model_provider).
// v11: codex pricing fix (#1075) - reasoning is no longer added on top of
// output, and cache_write_input_tokens is carved out of the input bucket. This
// file stores each call's costUSD and token buckets verbatim, so entries
// written by v10 carry the old (overstated) cost and must be re-derived.
// v13: codex throughput fix (#1079) - activeGeneratedTokens was summing
// output + reasoning, the same double-count Fix A removed from cost. This
// file stores activeGeneratedTokens/activeDurationMs/toolWaitMs verbatim (not
// re-derived on read), so v11 entries carry the overstated numerator and must
// re-parse. Not 12: v12 is claimed by feat/core-extraction's own port of this
// throughput feature (PR #1086), so reusing it would let two incompatible
// schemas share a filename.
// v14: MCP + Skill attribution for the shapes the classic `function_call` path
// never reached (#478) - the `exec` custom tool's `input` program and the item
// model's `item_completed`/`CommandExecution` item - plus SKILL.md reads landing
// in `skills`. This file stores each call's `tools`/`toolSequence`/`skills`
// verbatim (they are passed through on read, never re-derived), so v13 entries
// keep the old, MCP- and skill-less attribution until they re-parse.
// v15: builtin alias prices `codex-auto-review` (#1047). Exact-hit cache
// entries still hold the pre-alias $0; bump so unchanged rollouts reprice.
// Must be max(main v14 #1092, this)+1 — #1092 spent v14 on MCP/skills.
// No bump for #1264: the missing-cumulative branch is a no-op on real data
// (0 occurrences of info-without-total across 137k+ events; null-info pings
// already take the estimate path), so cached numbers are identical and a
// bump would only force a cold reparse.
// v17: fork replay suppression now ends at the first timestamp gap over one
// second, or five seconds past the fork regardless of gaps, so first real
// work is retained. Exact entries can hold the old undercount, and resume
// state used the old fixed cutoff; reparse both. Not 16: v16 was briefly
// shipped by a reverted PR, so reusing it would let stale entries pass the
// version check unreparsed.
// v18: read response-level token_usage_record and ignore later token_count
// twins. v17 entries miss interrupted/compaction usage and can include counts
// now suppressed after the source handover, so they must reparse.
// v19: codex priority-tier pricing (#1616) - turns run under Codex's Fast
// speed setting (thread_settings_applied service_tier "priority") now bill at
// the priority rates. This file stores each call's costUSD and speed verbatim,
// so v18 entries carry the standard-rate cost and must be re-derived.
// v20: `codex-auto-review` prices by date (gpt-5.4 before 30 Jul 2026, GPT-5.6
// Luna from then on) instead of gpt-5.5. Stored costUSD is the old price.
// v21: service_tier "flex" bills at the published Flex rates (it billed at
// standard), and `gpt-reserve` / `gpt-5.3-spark` price as GPT-5.6 Luna /
// GPT-5.3 Codex Spark instead of $0. Stored costUSD and speed are the old ones.
// v22: a fork's replay burst drops only records found in the parent rollout
// and counts the rest. v21 entries dropped the whole burst.
export const CODEX_CACHE_VERSION = 22
export const CODEX_LEGACY_CACHE_FILE = 'codex-results.json'
export function codexCacheFileName(version = CODEX_CACHE_VERSION): string {
return `codex-results.v${version}.json`
}
// Discovery only needs each rollout's project, so it reads this small index
// instead of the whole results file. Keyed by the same fingerprint, so an
// index that lags the results file only misses, never answers wrong.
export function codexProjectsFileName(version = CODEX_CACHE_VERSION): string {
return `codex-projects.v${version}.json`
}
export type CodexFileFingerprint = { dev: number; ino: number; mtimeMs: number; sizeBytes: number }
type FileFingerprint = CodexFileFingerprint
type FileEntry = {
// Absent on entries written before the resume support landed.
dev?: number
ino?: number
mtimeMs: number
sizeBytes: number
project: string
calls: ParsedProviderCall[]
/** Byte offset of a complete-line boundary the parser can restart from. */
resumeOffset?: number
/** Opaque parser state captured at `resumeOffset` (shape owned by the Codex parser). */
resumeState?: unknown
/** How many of `calls` were decoded before `resumeOffset`. */
resumeCallCount?: number
}
/** An exact fingerprint match, or an append the parser can resume into. */
export type CodexCacheHit =
| { kind: 'exact'; calls: ParsedProviderCall[] }
| { kind: 'resume'; calls: ParsedProviderCall[]; offset: number; state: unknown; callCount: number }
type ResultCache = {
version: number
files: Record<string, FileEntry>
}
type ProjectEntry = Pick<FileEntry, 'dev' | 'ino' | 'mtimeMs' | 'sizeBytes' | 'project'>
const cacheDirContext = new AsyncLocalStorage<string>()
function currentCacheDir(): string {
return cacheDirContext.getStore() ?? resolve(getCodeburnCacheDir())
}
// A parse can cross many async boundaries before the Codex provider publishes
// its incremental cache. Embedded hosts are allowed to change the process env
// between calls, so pin the call-time directory for the whole transaction
// instead of re-reading CODEBURN_CACHE_DIR at each cache operation.
export function withCodexCacheDirectory<T>(cacheDir: string, operation: () => T): T {
return cacheDirContext.run(resolve(cacheDir), operation)
}
function getCachePath(cacheDir: string): string {
return join(cacheDir, codexCacheFileName())
}
function getLegacyCachePath(cacheDir: string): string {
return join(cacheDir, CODEX_LEGACY_CACHE_FILE)
}
function isCurrentCache(cache: ResultCache): boolean {
return cache.version === CODEX_CACHE_VERSION && !!cache.files && typeof cache.files === 'object'
}
// Embedded consumers can change CODEBURN_CACHE_DIR without reloading this
// module. Keep each directory's in-memory state separate so a warm cache (or an
// unflushed update) from A can never be read from or written into B.
const memCaches = new Map<string, ResultCache>()
// Dropped by the resident RSS guard. Every write is published by
// flushCodexCache() in the parse's finally, so the next load re-reads disk.
export function clearCodexMemCaches(): void {
memCaches.clear()
inFlightLoads.clear()
projectIndexes.clear()
}
const projectIndexes = new Map<string, Promise<Record<string, ProjectEntry>>>()
function loadProjectIndex(cacheDir: string): Promise<Record<string, ProjectEntry>> {
let index = projectIndexes.get(cacheDir)
if (!index) {
index = readProjectIndex(cacheDir)
projectIndexes.set(cacheDir, index)
}
return index
}
// Missing (a cache written before the index existed): built once from the
// results file, which is what discovery read before.
async function readProjectIndex(cacheDir: string): Promise<Record<string, ProjectEntry>> {
try {
const parsed = JSON.parse(await readFile(join(cacheDir, codexProjectsFileName()), 'utf-8')) as { version?: unknown; files?: unknown }
if (parsed.version === CODEX_CACHE_VERSION && parsed.files && typeof parsed.files === 'object') return parsed.files as Record<string, ProjectEntry>
} catch {}
const cache = await loadCache(cacheDir)
if (Object.keys(cache.files).length > 0) await writeProjectIndex(cacheDir, cache)
return cache.files
}
async function writeProjectIndex(cacheDir: string, cache: ResultCache): Promise<void> {
const files: Record<string, ProjectEntry> = {}
for (const [path, e] of Object.entries(cache.files)) {
files[path] = { dev: e.dev, ino: e.ino, mtimeMs: e.mtimeMs, sizeBytes: e.sizeBytes, project: e.project }
}
try {
await writeFileAtomic(join(cacheDir, codexProjectsFileName()), JSON.stringify({ version: CODEX_CACHE_VERSION, files }))
} catch {}
}
async function writeFileAtomic(finalPath: string, payload: string): Promise<void> {
const tempPath = `${finalPath}.${randomBytes(8).toString('hex')}.tmp`
const handle = await open(tempPath, 'w', 0o600)
try {
await handle.writeFile(payload, { encoding: 'utf-8' })
await handle.sync()
} finally {
await handle.close()
}
try {
await rename(tempPath, finalPath)
} catch (err) {
try { await unlink(tempPath) } catch {}
throw err
}
}
// Concurrent callers must share one load. The memo below is only populated
// after the read + JSON.parse resolves, so without this every in-flight caller
// would re-read and re-parse the same (hundreds-of-MB) cache file.
const inFlightLoads = new Map<string, Promise<ResultCache>>()
function loadCache(cacheDir: string): Promise<ResultCache> {
const inMemory = memCaches.get(cacheDir)
if (inMemory) return Promise.resolve(inMemory)
const pending = inFlightLoads.get(cacheDir)
if (pending) return pending
const load = loadCacheFromDisk(cacheDir).finally(() => inFlightLoads.delete(cacheDir))
inFlightLoads.set(cacheDir, load)
return load
}
async function loadCacheFromDisk(cacheDir: string): Promise<ResultCache> {
const empty = { version: CODEX_CACHE_VERSION, files: {} }
const versioned = await readExistingTextFile(getCachePath(cacheDir))
if (versioned.status === 'ok') {
try {
const cache = JSON.parse(versioned.text) as ResultCache
if (isCurrentCache(cache)) {
memCaches.set(cacheDir, cache)
return cache
}
} catch {}
memCaches.set(cacheDir, empty)
return empty
}
if (versioned.status === 'unreadable') {
memCaches.set(cacheDir, empty)
return empty
}
// Versioned file is absent (ENOENT). Adopt the unsuffixed file only when its
// version matches — old binaries still own that path; we never write or delete it.
try {
const raw = await readFile(getLegacyCachePath(cacheDir), 'utf-8')
const cache = JSON.parse(raw) as ResultCache
if (isCurrentCache(cache)) {
memCaches.set(cacheDir, cache)
return cache
}
} catch {}
memCaches.set(cacheDir, empty)
return empty
}
function getEntry<T extends ProjectEntry>(files: Record<string, T>, filePath: string, fp: FileFingerprint): T | null {
if (!Object.hasOwn(files, filePath)) return null
const entry = files[filePath]
if (
entry
&& entry.dev === fp.dev
&& entry.ino === fp.ino
&& entry.mtimeMs === fp.mtimeMs
&& entry.sizeBytes === fp.sizeBytes
) {
return entry
}
return null
}
// A grown file is only assumed to be an APPEND if the recorded boundary still
// falls right after a newline. A same-inode rewrite (truncate + refill, or an
// in-place edit) that happens to end up larger would otherwise resume into the
// middle of an unrelated line. Reading one byte is cheaper than being wrong.
async function endsLineAt(filePath: string, offset: number): Promise<boolean> {
if (offset === 0) return true
try {
const handle = await open(filePath, 'r')
try {
const buf = Buffer.alloc(1)
const { bytesRead } = await handle.read(buf, 0, 1, offset - 1)
return bytesRead === 1 && buf[0] === 0x0a
} finally {
await handle.close()
}
} catch {
return false
}
}
/// WSL's 9P share synthesizes dev/ino per mount, so they can differ run to run
/// for an unchanged file. Zero them for `\\wsl$\...` paths so the resume check
/// below still matches instead of re-reading every WSL rollout whole (#1059).
function fingerprintFromStat(filePath: string, s: { dev: number; ino: number; mtimeMs: number; size: number }): FileFingerprint {
if (isWslUncPath(filePath)) return { dev: 0, ino: 0, mtimeMs: s.mtimeMs, sizeBytes: s.size }
return { dev: s.dev, ino: s.ino, mtimeMs: s.mtimeMs, sizeBytes: s.size }
}
export async function readCachedCodexResults(
filePath: string,
): Promise<CodexCacheHit | null> {
try {
const s = await stat(filePath)
const cache = await loadCache(currentCacheDir())
const fp = fingerprintFromStat(filePath, s)
const entry = getEntry(cache.files, filePath, fp)
if (entry) return { kind: 'exact', calls: entry.calls }
// Rollouts are append-only: the same inode, grown past a boundary we
// recorded, can be picked up from that boundary instead of re-read whole.
const stale = cache.files[filePath]
if (
stale
&& stale.dev === fp.dev
&& stale.ino === fp.ino
&& stale.resumeOffset !== undefined
&& stale.resumeState !== undefined
&& stale.resumeCallCount !== undefined
&& fp.sizeBytes > stale.sizeBytes
&& stale.resumeOffset <= fp.sizeBytes
&& await endsLineAt(filePath, stale.resumeOffset)
) {
return { kind: 'resume', calls: stale.calls, offset: stale.resumeOffset, state: stale.resumeState, callCount: stale.resumeCallCount }
}
} catch {}
return null
}
export async function getCachedCodexProject(
filePath: string,
): Promise<string | null> {
try {
const s = await stat(filePath)
const cacheDir = currentCacheDir()
const files = memCaches.get(cacheDir)?.files ?? await loadProjectIndex(cacheDir)
const entry = getEntry(files, filePath, fingerprintFromStat(filePath, s))
return entry?.project ?? null
} catch {}
return null
}
export async function fingerprintFile(
filePath: string,
): Promise<FileFingerprint | null> {
try {
return fingerprintFromStat(filePath, await stat(filePath))
} catch {
return null
}
}
export async function writeCachedCodexResults(
filePath: string,
project: string,
calls: ParsedProviderCall[],
fingerprint: FileFingerprint,
resume?: { offset: number; state: unknown; callCount: number },
): Promise<void> {
try {
const cache = await loadCache(currentCacheDir())
cache.files[filePath] = {
dev: fingerprint.dev,
ino: fingerprint.ino,
mtimeMs: fingerprint.mtimeMs,
sizeBytes: fingerprint.sizeBytes,
project,
calls,
...(resume ? { resumeOffset: resume.offset, resumeState: resume.state, resumeCallCount: resume.callCount } : {}),
}
} catch {}
}
/// Remove exact source paths after the session-cache reconciliation has proved
/// they were deleted under an active WSL home. The generic flush cannot make
/// that decision itself: statting an offline UNC share can hang, while treating
/// the resulting failure as deletion would lose a stopped distro's warm cache.
export async function evictCachedCodexResults(filePaths: Iterable<string>): Promise<boolean> {
try {
const cache = await loadCache(currentCacheDir())
let changed = false
for (const filePath of filePaths) {
if (!Object.hasOwn(cache.files, filePath)) continue
delete cache.files[filePath]
changed = true
}
return changed
} catch {
return false
}
}
export async function flushCodexCache(): Promise<void> {
const cacheDir = currentCacheDir()
const memCache = memCaches.get(cacheDir)
if (!memCache) return
try {
// Evict entries for files that no longer exist on disk
const paths = Object.keys(memCache.files)
for (const p of paths) {
// A stopped WSL distro makes its UNC share unavailable. Probing it here
// can block for the OS/network timeout, and would evict the entry even
// though the source is still durable. WSL discovery owns availability;
// retain the entry until a later parse can observe the file again.
if (isWslUncPath(p)) continue
try {
await stat(p)
} catch {
delete memCache.files[p]
}
}
if (!existsSync(cacheDir)) await mkdir(cacheDir, { recursive: true })
await writeFileAtomic(getCachePath(cacheDir), JSON.stringify(memCache))
await writeProjectIndex(cacheDir, memCache)
projectIndexes.delete(cacheDir)
} catch {}
}