Merge pull request #1284 from xiaozhenliu/fix/dsh-session-formats-1281

Fix DSH v0–v3 session discovery and usage accounting
This commit is contained in:
ozymandiashh 2026-09-11 19:59:58 +03:00 • committed by GitHub
commit fef63c147a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 1068 additions and 145 deletions

View file

@ -13,17 +13,27 @@ DeepSeek's open-source agent harness (`dsh`, npm `@deepseek-ai/dsh`). Unrelated
| sessions | — | `<root>/sessions` |
| root | `DSH_HOME` | `~/.dsh` |
An empty `DSH_HOME` is treated as unset. `probeRoots()` reports the resolved sessions dir, so `codeburn doctor` distinguishes "dsh not installed" from "`DSH_HOME` pointing somewhere empty".
An empty `DSH_HOME` is treated as unset. `probeRoots()` reports the resolved sessions dir, so `codeburn doctor` distinguishes "dsh not installed" from "`DSH_HOME` pointing somewhere empty". When discovery skips unknown highest generations, doctor reports `skippedVersionCount` in JSON and the skipped session count in its error verdict. Warnings are emitted once per unknown version, while every excluded session contributes to the count.
## Storage format
```
sessions/--<slugified-cwd>--/<session-id>/
session.jsonl.zstd default (compression: zstd)
session.jsonl when compression: none
session.jsonl[.zstd] format v0
session.v1.jsonl[.zstd] format v1
session.v2.jsonl[.zstd] format v2
session.v3.jsonl[.zstd] format v3
```
Both variants are read; a session directory never holds both. The log is append-only JSONL whose first line is the session header:
Separate sessions are all counted, including sessions with only legacy v0/v1
logs alongside sessions using v2/v3. Generation selection applies only within
one session directory; a newer-format session never supersedes another session.
Both compression variants are read. Migrated generations are immutable and may
coexist; CodeBurn selects the numerically highest canonical generation per
Session. If that generation is unknown, corrupt, or disagrees with its header,
the Session is skipped with a notice instead of silently falling back to an
older snapshot. The log is append-only JSONL whose first line is the session header:
```jsonc
{ "type": "session", "version": 0, "id": "...", "createdAt": 1783352050748,
@ -32,18 +42,25 @@ Both variants are read; a session directory never holds both. The log is append-
`cwd` becomes `projectPath` / `workingDirectory` (git-repo attribution) and its last segment the project name.
Every later line is one event `{ type, seq, time, data }`. The parser reads:
Every later line is one event `{ type, seq, time, data }`. Formats v0/v1 keep
stream chunks as top-level events (with delta runs packed into storage rows).
Formats v2/v3 embed the compact stream in each `assistant/message` or
`assistant/attempt`. The parser reads:
| Event | Used for |
|---|---|
| `turn/start` | current turn number |
| `user/message` | the turn's preview, when `data.source.kind === 'user'` |
| `request/header` | `data.header.config.model` — the model for steps that follow |
| `assistant/chunk` with `chunk.type === 'usage'` | streamed usage sample for `(turn, step)` |
| `assistant/message` | final usage for `(turn, step)`, plus `data.message.source.model` |
| `assistant/chunk` with `chunk.type === 'usage'` | v0/v1 streamed usage sample for `(turn, step)` |
| `assistant/message` | successful attempt; top-level usage wins, then embedded stream usage; plus `data.message.source.model` |
| `assistant/attempt` | failed/retried attempt usage from its embedded stream |
| `llm/retry-started` | closes the replacement slot so the next settlement is an additional billed attempt |
| `request/context` | actual route/model fallback for attempts without a successful message |
| `tool/call` | tool names, bash commands, skill names |
One parsed call per `(turn, step)` — one model call and the tools it requested. Dedup key: `dsh:<sessionId>:<turn>:<step>`.
One parsed call per model attempt. The first attempt keeps dedup key
`dsh:<sessionId>:<turn>:<step>`; retries add `:attempt:<n>`.
`.zstd` logs are a concatenation of **independent** zstd frames, one per write batch, so they are decoded frame by frame behind a structural frame scan ported from `@deepseek-ai/dsh-session-persistence-jsonl`. Needs Node 22.15+ for `zlib.zstdDecompressSync`; below that dsh is skipped with a notice instead of counted as $0.
@ -53,19 +70,22 @@ None at the provider level; the log file is the cached source path and the norma
## Quirks
- **DSH is a developer preview.** `SESSION_FORMAT_VERSION` is pinned at `0` with "no compatibility implied" upstream, and breaking changes are expected. The parser reads version `0` only and skips a log stamped with anything else, with a notice — reading a bumped format under today's assumptions would report confident wrong numbers. **A version bump upstream means this parser needs updating, not just relaxing the check.**
- **DSH is a developer preview.** The parser explicitly supports released formats v0-v3 and checks both the canonical generation filename and header. A future version is skipped with a notice; **a version bump upstream still requires a semantic reader update, not just relaxing the check.**
- **The JSONL backend only.** DSH also ships an opt-in SQLite persistence backend (`@deepseek-ai/dsh-session-persistence-sqlite`); it is not the default and is not read.
- **DSH records tokens, never dollars.** `usage` is `{ inputTokens, outputTokens, cacheReadTokens?, cacheWriteTokens?, reasoningTokens? }` with no cost field, so every call is priced from the shared tables. Reasoning bills at the output rate (same as Gemini and Hermes): `outputTokens + reasoningTokens` goes into `calculateCost`, while the two stay separate on the emitted call. Tokens are the provider's own exact counts, so `costIsEstimated` stays false.
- **DSH records tokens, never dollars.** `usage` is `{ inputTokens, outputTokens, cacheReadTokens?, cacheWriteTokens?, reasoningTokens? }` with no cost field, so every call is priced from the shared tables. The buckets are disjoint on input; `reasoningTokens` is informational detail already included in `outputTokens`, as documented in the [DSH TokenUsage contract](https://github.com/deepseek-ai/deepseek-harness/blob/c291e7961a515f6d7af9304e7fd1d257929aef26/docs/subsystems/llm-streaming.md#tokenusage). CodeBurn preserves raw output and applies the shared inclusive-output rule to pricing, cached reads, and display. pi-ai routes do not persist separate reasoning detail. Complete valid usage keeps `costIsEstimated` false; incomplete or inconsistent usage is reported with a notice and marked estimated. An attempt without usage is omitted with a notice rather than represented as an exact zero.
- **`assistant/message` usage wins over the `assistant/chunk` sample** for the same `(turn, step)` — the two are adjacent reports of one API call, not two calls. A late chunk never overwrites a final report, so the two are never summed.
- **The model comes from the message, not the request.** `data.message.source.model` is what actually served the step; `request/header` only describes the request DSH was about to make, and is the fallback when a message names no model. The `provider` field there (`deepseek-official`) is the upstream LLM route, not the tool — the codeburn provider name is always `dsh`.
- **A forked session's log replays its parent's events.** The header's `parentSession` + `seedLength` mark that prefix; codeburn parses the parent's own log as its own session, so events with `seq < seedLength` are skipped to avoid billing the same calls twice.
- **The model comes from the message, not the request.** `data.message.source.model` is what actually served the step; the current `request/context` model is the fallback, followed by `request/header`. A changed header model clears the previous context fallback. The `provider` field there (`deepseek-official`) is the upstream LLM route, not the tool — the codeburn provider name is always `dsh`.
- **A forked session's log replays its parent's events.** v0/v1 use header `seedLength` only when `parentSession` is present, preserving the legacy non-fork behavior; v2/v3 use the last `session/end-seed` marker carrying `{ inherited: true }`. CodeBurn excludes the inherited prefix to avoid billing the parent's calls twice.
- **`user/message` also carries agent-injected context** (runtime snapshots, skill bodies, file-change notices) under `source.kind: 'plugin'`. Only `kind: 'user'` messages become the preview.
- **Delta chunks are packed.** Runs of streamed deltas are stored as `text-chunks` / `reasoning-chunks` / `tool-call-chunks` storage rows rather than one event per line. They carry no usage and no tool identity the `tool/call` event lacks, so they are ignored — as is any event type the parser does not know.
- **A torn final zstd frame is ignored.** A crashed writer leaves an incomplete trailing frame; the complete frames before it parse normally. A structurally corrupt file is skipped whole with a notice rather than throwing.
## When fixing a bug here
`v3-retry.jsonl` also covers a failed `assistant/attempt`, scheduled retry, and successful settlement with exact `totalTokens`. The same official strict restore and reducer yield input 110, output 24, cache read 33, and cache write 7 (174 total tokens).
1. Reproduce with a minimal session dir: `sessions/--proj--/<id>/session.jsonl` (uncompressed is easiest to hand-write).
2. `tests/fixtures/dsh/bash-tool-turn.jsonl` is the upstream `examples/acp-agent/tests/snapshots/bash-tool-turn/session.jsonl` snapshot with its template placeholders filled in — refresh it from the DSH repo when the format moves.
3. Run `tests/providers/dsh.test.ts`.
4. `.zstd` fixtures must compress **each batch separately**; one `zstdCompressSync` over the whole file is a single-frame layout DSH never writes.
5. `tests/fixtures/dsh/v0.jsonl` through `v3.jsonl` are minimal synthetic, sanitized format fixtures. Each was restored with DSH's official `sessionFormatCatalog` (`recovery: 'strict', validation: 'current'`) and folded through `tokenUsageProjectionDefinition` at DSH commit `c291e7961a515f6d7af9304e7fd1d257929aef26`. All four yield uncached input 100, full output 20, cache read 30, and cache write 5; the provider tests assert those buckets, including inclusive output and informational reasoning detail. v0/v1 cite their top-level chunk via `sourceEventSeqs`; v2/v3 carry the embedded stream.

View file

@ -178,7 +178,10 @@ import type { DateRange, ProjectSummary } from './types.js'
// explicit estimates retain their status, and surviving Hermes sources replace
// v29 slices produced by the old API-equivalent fallback.
// 31: #1234 Hermes cost contract; 30 is claimed by #1132.
export const DAILY_CACHE_VERSION = 31
// v32: DSH session formats v1-v3 and inclusive reasoning accounting. Re-derive
// finalized DSH days so migrated generations and retry attempts replace the
// v0-only totals, and reasoning detail is not added on top of full output.
export const DAILY_CACHE_VERSION = 32
const MIN_SUPPORTED_VERSION = 28
/// Providers whose per-day CALL COUNT means something different at
@ -206,6 +209,9 @@ const PENDING_REDERIVE_PROVIDER_VERSIONS: Readonly<Record<string, number>> = {
// Tracks DAILY_CACHE_VERSION: a v30 file may have been written by #1132's
// accounting, which never carried the Hermes cost contract.
hermes: 31,
// DSH v0-only parsing and exclusive-reasoning display were both stale in
// finalized days written before the multi-generation reader.
dsh: 32,
}
function providersPendingRederiveFrom(fromVersion: number): string[] {

View file

@ -44,6 +44,8 @@ export type DoctorProviderReport = {
parseVersion?: string
/** Session sources discovered (candidate files/dbs). */
candidatesFound: number
/** Sessions excluded by discovery because their highest format is unknown. */
skippedVersionCount?: number
/** How many discovered sources we attempted to parse (bounded sample). */
sampled: number
parsedOk: number
@ -271,7 +273,9 @@ async function collectOneProvider(
try {
base.probePaths = await collectProbePaths(provider)
const sources = await provider.discoverSessions()
let skippedVersionCount = 0
const sources = await provider.discoverSessions(() => { skippedVersionCount++ })
if (skippedVersionCount > 0) base.skippedVersionCount = skippedVersionCount
base.candidatesFound = sources.length
if (base.probePaths.length === 0) {
base.probePaths = derivePathsFromSources(sources.map(s => s.path))
@ -313,7 +317,10 @@ async function collectOneProvider(
}
}
if (base.parseFailed > 0) {
if (skippedVersionCount > 0) {
base.status = 'errors'
base.verdict = `ERRORS (${pluralSessions(skippedVersionCount)} skipped: unsupported format version; ${pluralSessions(base.candidatesFound)} readable; ${base.parseFailed} sampled parse failures)`
} else if (base.parseFailed > 0) {
base.status = 'errors'
base.verdict = `ERRORS (${base.parseFailed}/${base.sampled} sampled file${base.sampled === 1 ? '' : 's'} failed to parse)`
} else if (base.candidatesFound === 0) {

View file

@ -33,7 +33,9 @@ export type ModelCosts = {
/// and nothing else, and its supplementary store-row/shutdown calls carry
/// reasoningTokens with outputTokens 0 while the per-turn assistant.message call
/// bills the full output, so adding reasoning on top bills it twice.
const REASONING_INCLUDED_IN_OUTPUT = new Set(['claude', 'codex', 'copilot'])
/// DSH TokenUsage includes reasoning in output too; see the pinned contract:
/// https://github.com/deepseek-ai/deepseek-harness/blob/c291e7961a515f6d7af9304e7fd1d257929aef26/docs/subsystems/llm-streaming.md#tokenusage
const REASONING_INCLUDED_IN_OUTPUT = new Set(['claude', 'codex', 'copilot', 'dsh'])
/// Output tokens to bill and display for one call. Single source of truth so
/// the pricing sites and the display sums can never disagree about whether a

View file

@ -1,10 +1,10 @@
import { open, readdir, readFile, stat } from 'fs/promises'
import { join } from 'path'
import { basename, join } from 'path'
import { homedir } from 'os'
import zlib from 'zlib'
import { MAX_SESSION_FILE_BYTES, readSessionFile } from '../fs-utils.js'
import { calculateCost, getShortModelName } from '../models.js'
import { MAX_SESSION_FILE_BYTES, readSessionFile, readSessionLines } from '../fs-utils.js'
import { billableOutputTokens, calculateCost, getShortModelName } from '../models.js'
import { extractBashCommands } from '../bash-utils.js'
import type { ProbeRoot, Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js'
@ -34,7 +34,8 @@ const ZSTD_MAGIC = 0xfd2fb528
// the caller skips the WHOLE file rather than counting the frames it got to.
const MAX_FRAME_DECODED_BYTES = 64 * 1024 * 1024
const SESSION_FORMAT_VERSION = 0
const SUPPORTED_SESSION_FORMAT_VERSIONS = new Set([0, 1, 2, 3])
const SESSION_LOG_NAME = /^session(?:\.v([1-9][0-9]*))?\.jsonl(?:\.zstd)?$/u
const MIN_REASONABLE_TIMESTAMP_MS = 1_000_000_000_000
@ -118,6 +119,7 @@ type DshEvent = {
createdAt?: number
parentSession?: string
seedLength?: number
isSeeded?: boolean
data?: {
turn?: number
step?: number
@ -126,26 +128,31 @@ type DshEvent = {
// `{ kind: 'user' }`, agent-injected context is `{ kind: 'plugin' }`.
source?: { kind?: string }
header?: { config?: { model?: string; provider?: string } }
provider?: string
model?: string
inherited?: boolean
message?: { source?: { kind?: string; model?: string; provider?: string } }
chunk?: { type?: string; usage?: DshUsage }
stream?: Array<{
type?: string
time?: number
chunk?: { type?: string; usage?: DshUsage }
}>
usage?: DshUsage
name?: string
arguments?: string
}
}
type StepBucket = {
type UsageObservation = {
usage: DshUsage
// A usage report from assistant/message is the final value for its
// (turn, step) and replaces an earlier assistant/chunk sample (the two are
// adjacent reports of the same API call, per dsh-token-meter's usage
// projection). Time follows the winning report.
final: boolean
time?: number
// Model that produced this step: the reporting assistant/message's own
// `message.source` when it names one, else the most recent request/header
// config (a header can change the model mid-turn between steps).
model: string
final: boolean
}
type StepBucket = {
observations: UsageObservation[]
tools: string[]
skills: string[]
bashCommands: string[]
@ -176,20 +183,42 @@ function mapToolName(raw: string): string {
// straight into the global token totals and the persisted cache, where
// `0 + [1, 2]` silently becomes "01,2". Same semantics as copilot.ts.
function numberOrZero(raw: unknown): number {
return typeof raw === 'number' && Number.isFinite(raw) && raw > 0 ? raw : 0
return typeof raw === 'number' && Number.isSafeInteger(raw) && raw > 0 ? raw : 0
}
function usageIsComplete(usage: DshUsage): boolean {
const count = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
return count(usage.inputTokens) && count(usage.outputTokens)
&& [usage.cacheReadTokens, usage.cacheWriteTokens, usage.reasoningTokens].every(value => value === undefined || count(value))
&& (usage.reasoningTokens === undefined || usage.reasoningTokens <= usage.outputTokens)
}
// A log stamped with a version this parser was not written against is skipped
// whole: a bump means an event's meaning changed, so reading it with today's
// assumptions would report confident wrong numbers.
function isReadableVersion(header: DshEvent): boolean {
if (header.version === SESSION_FORMAT_VERSION) return true
if (typeof header.version === 'number' && SUPPORTED_SESSION_FORMAT_VERSIONS.has(header.version)) return true
// Keyed on the version, not the path: a DSH upgrade makes EVERY session
// unreadable at once, and one line per session log is noise, not a report.
notice(`codeburn: skipping DSH sessions written in session format version ${String(header.version)}; upgrade codeburn.\n`)
return false
}
function generationFromPath(filePath: string): number | undefined {
const match = SESSION_LOG_NAME.exec(basename(filePath))
if (!match) return undefined
return match[1] === undefined ? 0 : Number(match[1])
}
function headerMatchesPath(header: DshEvent, filePath: string): boolean {
const generation = generationFromPath(filePath)
if (generation === undefined || header.version !== generation) {
notice(`codeburn: skipping DSH session log whose filename and header versions disagree: ${filePath}\n`)
return false
}
return isReadableVersion(header)
}
// DSH writes epoch milliseconds; promote a seconds-resolution value and reject
// what stays implausible, matching the guard cline-cli.ts uses on the hazard.
function isoTimestamp(value: number | undefined, fallback: string): string {
@ -308,8 +337,10 @@ async function readSessionHeader(filePath: string): Promise<DshEvent | null> {
}).toString('utf-8')
return text.split('\n').find(l => l.trim()) ?? null
}
const content = await readSessionFile(filePath)
return content?.split('\n').find(l => l.trim()) ?? null
for await (const line of readSessionLines(filePath)) {
if (line.trim()) return line
}
return null
}
try {
@ -317,13 +348,13 @@ async function readSessionHeader(filePath: string): Promise<DshEvent | null> {
if (!line) return null
const event = JSON.parse(line) as DshEvent
if (event.type !== 'session') return null
return isReadableVersion(event) ? event : null
return event
} catch {
return null
}
}
async function discoverSessionsInDir(sessionsDir: string): Promise<SessionSource[]> {
async function discoverSessionsInDir(sessionsDir: string, onSkippedVersion?: (version: number) => void): Promise<SessionSource[]> {
const sources: SessionSource[] = []
let projectDirs: string[]
@ -350,21 +381,37 @@ async function discoverSessionsInDir(sessionsDir: string): Promise<SessionSource
const sessionStat = await stat(sessionPath).catch(() => null)
if (!sessionStat?.isDirectory()) continue
// Compressed log first; the uncompressed variant exists when
// compression=none. Never both for the same session.
let filePath: string | null = null
for (const name of ['session.jsonl.zstd', 'session.jsonl']) {
// DSH keeps migrated generations beside their immutable predecessors.
// Resolve the numerically highest canonical generation once per Session;
// never fall back to an older snapshot when that authoritative file is
// unknown or corrupt, since that would silently report stale usage.
const generationFiles: Array<{ path: string; version: number; compressed: boolean }> = []
const names = await readdir(sessionPath).catch(() => [])
for (const name of names) {
const match = SESSION_LOG_NAME.exec(name)
if (!match) continue
const version = match[1] === undefined ? 0 : Number(match[1])
const candidate = join(sessionPath, name)
const fileStat = await stat(candidate).catch(() => null)
if (fileStat?.isFile()) {
filePath = candidate
break
}
if (fileStat?.isFile()) generationFiles.push({ path: candidate, version, compressed: name.endsWith('.zstd') })
}
generationFiles.sort((a, b) => b.version - a.version || Number(b.compressed) - Number(a.compressed))
const selected = generationFiles[0]
if (!selected) continue
const filePath = selected.path
if (!SUPPORTED_SESSION_FORMAT_VERSIONS.has(selected.version)) {
onSkippedVersion?.(selected.version)
notice(`codeburn: skipping DSH sessions written in session format version ${selected.version}; upgrade codeburn.\n`)
continue
}
if (!filePath) continue
const header = await readSessionHeader(filePath)
if (!header) continue
if (!header) {
notice(`codeburn: skipping unreadable DSH session header: ${filePath}\n`)
continue
}
if (!headerMatchesPath(header, filePath)) continue
const cwd = typeof header.cwd === 'string' && header.cwd.trim() ? header.cwd : dirName
sources.push({ path: filePath, project: projectFromCwd(cwd, dirName), provider: 'dsh' })
@ -384,55 +431,118 @@ function parseToolArguments(raw: string | undefined): Record<string, unknown> |
}
}
function usageFromStream(stream: NonNullable<DshEvent['data']>['stream']): DshUsage | undefined {
if (!Array.isArray(stream)) return undefined
for (let index = stream.length - 1; index >= 0; index -= 1) {
const record = stream[index]
if (record?.type === 'chunk' && record.chunk?.type === 'usage') return record.chunk.usage
}
return undefined
}
function emptyStepBucket(): StepBucket {
return { observations: [], tools: [], skills: [], bashCommands: [] }
}
function createParser(source: SessionSource, seenKeys: Set<string>): SessionParser {
return {
async *parse(): AsyncGenerator<ParsedProviderCall> {
const lines = await readEventLines(source.path)
if (!lines) return
let sessionId = ''
let cwd = ''
let model = 'unknown'
const events: DshEvent[] = []
let corruptInterior = false
for (const [index, line] of lines.entries()) {
try {
const value: unknown = JSON.parse(line)
if (!value || typeof value !== 'object' || Array.isArray(value)) {
if (index === 0) return
corruptInterior = true
continue
}
events.push(value as DshEvent)
} catch {
if (index === 0) return
// A torn final append may be discarded. Malformed rows in the middle
// of a versioned log cannot justify a complete historical total.
if (index < lines.length - 1) corruptInterior = true
}
}
const header = events[0]
if (header?.type !== 'session' || !headerMatchesPath(header, source.path)) return
const formatVersion = header.version!
if (formatVersion >= 2 && corruptInterior) {
notice(`codeburn: skipping corrupt DSH session with malformed interior rows: ${source.path}\n`)
return
}
const sessionId = typeof header.id === 'string' ? header.id : ''
const cwd = typeof header.cwd === 'string' ? header.cwd : ''
let headerModel = 'unknown'
let contextModel = ''
let currentTurn = 0
let sessionStart = ''
const sessionStart = isoTimestamp(header.createdAt, '')
// Events a forked session inherited from its parent. They are a verbatim
// copy of the parent's log, which codeburn parses as its own session, so
// counting them here would bill the same calls twice.
let seedLength = 0
let inheritedCut = formatVersion <= 1 && typeof header.parentSession === 'string' && header.parentSession
&& typeof header.seedLength === 'number'
? header.seedLength - 1
: -1
if (formatVersion >= 2) {
const taggedCuts = events
.filter(event => event.type === 'session/end-seed' && event.data?.inherited === true && typeof event.seq === 'number')
.map(event => event.seq!)
if (header.isSeeded === true && taggedCuts.length === 0) {
notice(`codeburn: skipping corrupt seeded DSH session without an inherited end-seed marker: ${source.path}\n`)
return
}
if (header.isSeeded !== true && taggedCuts.length > 0) {
notice(`codeburn: skipping corrupt unseeded DSH session with an inherited end-seed marker: ${source.path}\n`)
return
}
inheritedCut = taggedCuts.at(-1) ?? -1
}
const userMessageByTurn = new Map<number, string>()
const buckets = new Map<string, StepBucket>()
const activeAttempts = new Map<string, number>()
for (const line of lines) {
let event: DshEvent
try {
event = JSON.parse(line) as DshEvent
} catch {
for (const event of events) {
if (event.type === 'session') {
continue
}
if (event.type === 'session') {
if (!isReadableVersion(event)) return
sessionId = event.id ?? sessionId
cwd = event.cwd ?? cwd
sessionStart = isoTimestamp(event.createdAt, sessionStart)
if (typeof event.parentSession === 'string' && event.parentSession && typeof event.seedLength === 'number') {
seedLength = event.seedLength
// Inherited request state can remain authoritative for the child's
// first local attempt even though inherited usage is not billable.
if (event.type === 'request/header') {
// Emitted at most once per request; steps after the last header
// inherit its config as their model.
const nextModel = event.data?.header?.config?.model
if (typeof nextModel === 'string' && nextModel) {
if (nextModel !== headerModel) contextModel = ''
headerModel = nextModel
}
continue
}
if (typeof event.seq === 'number' && event.seq < seedLength) continue
if (event.type === 'request/context') {
const nextModel = event.data?.model
if (typeof nextModel === 'string' && nextModel) contextModel = nextModel
continue
}
if (typeof event.seq === 'number' && event.seq <= inheritedCut) continue
if (event.type === 'turn/start') {
currentTurn = event.data?.turn ?? currentTurn
continue
}
if (event.type === 'request/header') {
// Emitted at most once per request; steps after the last header
// inherit its config as their model.
const headerModel = event.data?.header?.config?.model
if (typeof headerModel === 'string' && headerModel) model = headerModel
if (event.type === 'llm/retry-started') {
const turn = event.data?.turn ?? currentTurn
const step = event.data?.step ?? 0
activeAttempts.delete(`${turn}:${step}`)
continue
}
@ -442,8 +552,9 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
// is a useful preview.
if (event.data?.source?.kind !== 'user') continue
if (userMessageByTurn.has(currentTurn)) continue
const texts = (event.data?.content ?? [])
.filter(c => c.type === 'text' && typeof c.text === 'string' && c.text)
const content = event.data?.content
const texts = (Array.isArray(content) ? content : [])
.filter(c => c?.type === 'text' && typeof c.text === 'string' && c.text)
.map(c => c.text!)
if (texts.length > 0) userMessageByTurn.set(currentTurn, texts.join(' ').slice(0, 500))
continue
@ -453,11 +564,11 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
const turn = event.data?.turn ?? currentTurn
const step = event.data?.step ?? 0
const rawName = event.data?.name
if (!rawName) continue
if (typeof rawName !== 'string' || !rawName) continue
const key = `${turn}:${step}`
let bucket = buckets.get(key)
if (!bucket) {
bucket = { usage: {}, final: false, model, tools: [], skills: [], bashCommands: [] }
bucket = emptyStepBucket()
buckets.set(key, bucket)
}
bucket.tools.push(mapToolName(rawName))
@ -475,35 +586,49 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
let isFinal = false
// The model that actually served the call, when the message records it.
// request/header only describes the request codeburn is about to see.
let reportedModel = model
if (event.type === 'assistant/chunk' && event.data?.chunk?.type === 'usage') {
let reportedModel = contextModel || headerModel
if (formatVersion <= 1 && event.type === 'assistant/chunk' && event.data?.chunk?.type === 'usage') {
usage = event.data.chunk.usage
} else if (event.type === 'assistant/message' && event.data?.usage) {
usage = event.data.usage
} else if (event.type === 'assistant/message') {
usage = event.data?.usage ?? (formatVersion >= 2 ? usageFromStream(event.data?.stream) : undefined)
isFinal = true
const messageModel = event.data.message?.source?.model
const messageModel = event.data?.message?.source?.model
if (typeof messageModel === 'string' && messageModel) reportedModel = messageModel
} else if (formatVersion >= 2 && event.type === 'assistant/attempt') {
usage = usageFromStream(event.data?.stream)
isFinal = true
} else {
continue
}
if (!usage) continue
const turn = event.data?.turn ?? currentTurn
const step = event.data?.step ?? 0
if (![turn, step].every(value => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0)) {
notice(`codeburn: skipping DSH usage with invalid attempt coordinates: ${source.path}\n`)
continue
}
const key = `${turn}:${step}`
if (!usage) {
if (!activeAttempts.has(key)) {
notice(`codeburn: DSH session contains an attempt without usage; totals may be incomplete: ${source.path}\n`)
}
continue
}
let bucket = buckets.get(key)
if (!bucket) {
bucket = { usage: {}, final: false, model, tools: [], skills: [], bashCommands: [] }
bucket = emptyStepBucket()
buckets.set(key, bucket)
}
// A final report replaces an earlier sample; a late sample never
// overwrites a final one. The model snapshot follows the winning
// report (a header can change the model mid-turn between steps).
if (isFinal || !bucket.final) {
bucket.usage = usage
bucket.final = isFinal
bucket.time = event.time
bucket.model = reportedModel
const observation = { usage, time: event.time, model: reportedModel, final: isFinal }
// A different step cannot close this step's replacement slot. Only
// its own retry-started event makes the next observation additive.
const activeIndex = activeAttempts.get(key)
if (activeIndex !== undefined) {
if (!bucket.observations[activeIndex]?.final || isFinal) {
bucket.observations[activeIndex] = observation
}
} else {
bucket.observations.push(observation)
activeAttempts.set(key, bucket.observations.length - 1)
}
}
@ -515,43 +640,54 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
for (const key of sortedKeys) {
const bucket = buckets.get(key)!
const input = numberOrZero(bucket.usage.inputTokens)
const output = numberOrZero(bucket.usage.outputTokens)
const cacheRead = numberOrZero(bucket.usage.cacheReadTokens)
const cacheWrite = numberOrZero(bucket.usage.cacheWriteTokens)
const reasoning = numberOrZero(bucket.usage.reasoningTokens)
if (input + output + cacheRead + cacheWrite + reasoning === 0) continue
for (let attempt = 0; attempt < bucket.observations.length; attempt += 1) {
const observation = bucket.observations[attempt]!
const input = numberOrZero(observation.usage.inputTokens)
const output = numberOrZero(observation.usage.outputTokens)
const cacheRead = numberOrZero(observation.usage.cacheReadTokens)
const cacheWrite = numberOrZero(observation.usage.cacheWriteTokens)
const reasoning = Math.min(numberOrZero(observation.usage.reasoningTokens), output)
const completeUsage = usageIsComplete(observation.usage)
if (!completeUsage) {
notice(`codeburn: DSH session contains incomplete or invalid usage; retained counts are estimated: ${source.path}\n`)
}
if (input + output + cacheRead + cacheWrite === 0) continue
const dedupKey = `dsh:${sessionId || source.path}:${key}`
if (seenKeys.has(dedupKey)) continue
seenKeys.add(dedupKey)
const attemptKey = attempt === 0 ? key : `${key}:attempt:${attempt + 1}`
const dedupKey = `dsh:${sessionId || source.path}:${attemptKey}`
if (seenKeys.has(dedupKey)) continue
seenKeys.add(dedupKey)
// DSH bills reasoning tokens at the output rate (same as Gemini).
const costUSD = calculateCost(bucket.model, input, output + reasoning, cacheWrite, cacheRead, 0)
const [turn] = key.split(':').map(Number)
// DSH TokenUsage defines reasoning as informational detail already
// included in outputTokens. Preserve raw output and use the same
// shared rule as cache rehydration and display (#1075).
const costUSD = calculateCost(observation.model, input, billableOutputTokens('dsh', output, reasoning), cacheWrite, cacheRead, 0)
const [turn] = key.split(':').map(Number)
yield {
provider: 'dsh',
model: bucket.model,
inputTokens: input,
outputTokens: output,
cacheCreationInputTokens: cacheWrite,
cacheReadInputTokens: cacheRead,
cachedInputTokens: cacheRead,
reasoningTokens: reasoning,
webSearchRequests: 0,
costUSD,
tools: [...new Set(bucket.tools)],
bashCommands: bucket.bashCommands,
skills: bucket.skills.length > 0 ? [...new Set(bucket.skills)] : undefined,
timestamp: isoTimestamp(bucket.time, sessionStart),
speed: 'standard',
deduplicationKey: dedupKey,
userMessage: userMessageByTurn.get(turn!) ?? '',
sessionId: sessionId || source.path,
project: cwd ? projectFromCwd(cwd, source.project) : source.project,
projectPath: cwd || undefined,
workingDirectory: cwd || undefined,
yield {
provider: 'dsh',
model: observation.model,
inputTokens: input,
outputTokens: output,
cacheCreationInputTokens: cacheWrite,
cacheReadInputTokens: cacheRead,
cachedInputTokens: cacheRead,
reasoningTokens: reasoning,
webSearchRequests: 0,
costUSD,
costIsEstimated: !completeUsage,
tools: attempt === bucket.observations.length - 1 ? [...new Set(bucket.tools)] : [],
bashCommands: attempt === bucket.observations.length - 1 ? bucket.bashCommands : [],
skills: attempt === bucket.observations.length - 1 && bucket.skills.length > 0 ? [...new Set(bucket.skills)] : undefined,
timestamp: isoTimestamp(observation.time, sessionStart),
speed: 'standard',
deduplicationKey: dedupKey,
userMessage: userMessageByTurn.get(turn!) ?? '',
sessionId: sessionId || source.path,
project: cwd ? projectFromCwd(cwd, source.project) : source.project,
projectPath: cwd || undefined,
workingDirectory: cwd || undefined,
}
}
}
},
@ -578,8 +714,8 @@ export function createDshProvider(dshHomeOverride?: string): Provider {
return [{ path: sessionsDir, label: 'sessions' }]
},
async discoverSessions(): Promise<SessionSource[]> {
return discoverSessionsInDir(sessionsDir)
async discoverSessions(onSkippedVersion): Promise<SessionSource[]> {
return discoverSessionsInDir(sessionsDir, onSkippedVersion)
},
createSessionParser(source: SessionSource, seenKeys: Set<string>): SessionParser {

View file

@ -120,7 +120,9 @@ export type Provider = {
durableSources?: boolean
modelDisplayName(model: string): string
toolDisplayName(rawTool: string): string
discoverSessions(): Promise<SessionSource[]>
// Report once per excluded session, independently of deduplicated warnings.
// The callback belongs to this scan, avoiding stale/shared diagnostic counts.
discoverSessions(onSkippedVersion?: (version: number) => void): Promise<SessionSource[]>
createSessionParser(source: SessionSource, seenKeys: Set<string>, dateRange?: DateRange): SessionParser
// The exact directories/dbs discoverSessions() scans, resolved the same way.
// Optional: providers that implement it let `codeburn doctor` show and

View file

@ -369,10 +369,9 @@ export const PROVIDER_PARSE_VERSIONS: Record<string, string> = {
// authoritative totals, use modelUsage only for priced attribution, clamp
// reasoning per record, and label mixed sessions estimated.
grok: 'authoritative-usage-v4',
// seed-aware-v1: the parser now skips the parent events a forked session
// replays (double-counted before), takes the model from the reporting
// assistant/message, and keeps agent-injected context out of the preview.
dsh: 'seed-aware-v1',
// v0-v3 generations, embedded attempt streams, retry accounting, and the
// version-specific inherited-prefix rules all change cached DSH calls.
dsh: 'session-formats-v0-v3-attempts-v5',
// cost-provenance-v3: preserve Hermes included/estimated/actual status and
// rebuild the provider section alongside the v3 lifetime ledger. The parse
// bump is required with the ledger bump: seeding a new ledger from a section

View file

@ -105,6 +105,12 @@ describe('#1115 billableOutputTokens on report/optimize totals', () => {
expect(sessionBillableOutputTokens(makeSession('codex', 10, 3))).toBe(10)
})
it('inclusive dsh: shared session and daily totals include reasoning exactly once', () => {
expect(billableOutputTokens('dsh', 10, 3)).toBe(10)
expect(sessionBillableOutputTokens(makeSession('dsh', 10, 3))).toBe(10)
expect(aggregateProjectsIntoDays([makeProject(makeSession('dsh', 10, 3))])[0]!.outputTokens).toBe(10)
})
it('day-aggregator uses billable output per call', () => {
const grokDays = aggregateProjectsIntoDays([makeProject(makeSession('grok', 10, 3))])
expect(grokDays[0]!.outputTokens).toBe(13)

View file

@ -800,7 +800,7 @@ describe('#946: a migration re-derives copilot instead of carrying it', () => {
)
const loaded = await loadDailyCache()
expect(loaded.pendingRederive).toEqual(['hermes'])
expect(loaded.pendingRederive).toEqual(['dsh'])
})
it('preserves an older cache pending repair while adding a newer provider repair', async () => {
@ -820,7 +820,7 @@ describe('#946: a migration re-derives copilot instead of carrying it', () => {
)
const loaded = await loadDailyCache()
expect(loaded.pendingRederive).toEqual(['copilot', 'hermes'])
expect(loaded.pendingRederive).toEqual(['copilot', 'dsh'])
})
it('still carries the slice whole when the sources are gone (never-lose, #1033)', async () => {
@ -854,7 +854,7 @@ describe('#946: a migration re-derives copilot instead of carrying it', () => {
it('a PARTIAL parse does not spend the entitlement', async () => {
await seedOlderCache([day(settled, { copilot: PRE_STORE })])
const partial = await ensureCacheHydrated(noSessions, () => [], 'cfg-A', () => false)
expect(partial.pendingRederive).toEqual(['copilot', 'hermes'])
expect(partial.pendingRederive).toEqual(['copilot', 'hermes', 'dsh'])
// The next COMPLETE run still gets to re-derive.
const out = await ensureCacheHydrated(noSessions, () => [day(settled, { copilot: STORE_BACKED })], 'cfg-A')
expect(out.days.find(d => d.date === settled)!.providers['copilot'])

View file

@ -145,14 +145,15 @@ describe('daily-cache adoption of a v30 file written under a different accountin
const loaded = await loadDailyCache()
expect(DAILY_CACHE_VERSION).toBe(31)
expect(loaded.version).toBe(31)
// A v30 candidate must not satisfy the same-version adoption at
// adoptOlderDailyCaches, so its trust markers cannot survive.
expect(DAILY_CACHE_VERSION).toBe(32)
expect(loaded.version).toBe(32)
// A v30 candidate must not satisfy same-version adoption, so its trust
// markers cannot survive migration to the current cache version.
expect(loaded.complete).toBe(false)
expect(loaded.watermarkTrusted).toBe(false)
const carried = loaded.days.find(entry => entry.date === date)
expect(carried?.carried).toBe(true)
expect(loaded.pendingRederive).toContain('hermes')
expect(loaded.pendingRederive).toContain('dsh')
})
})

View file

@ -1,10 +1,11 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises'
import { join } from 'path'
import { tmpdir } from 'os'
import { collectDoctorReport, renderDoctorTable, renderDoctorJson } from '../src/doctor.js'
import { createCodexProvider } from '../src/providers/codex.js'
import { createDshProvider } from '../src/providers/dsh.js'
import { createOpenCodeProvider } from '../src/providers/opencode.js'
import { emptyCache, type SessionCache } from '../src/session-cache.js'
import type { Provider, ProbeRoot, SessionSource } from '../src/providers/types.js'
@ -77,6 +78,28 @@ afterEach(async () => { await rm(tmpDir, { recursive: true, force: true }) })
// ── Real-provider fixture-dir cases: found / empty / missing ───────────────
describe('collectDoctorReport - codex fixture dirs', () => {
it('reports every DSH session skipped for an unknown highest generation', async () => {
const warnings = vi.spyOn(process.stderr, 'write')
try {
for (const id of ['first', 'second']) {
const dir = join(tmpDir, 'sessions', '--fixture--', id)
await mkdir(dir, { recursive: true })
await writeFile(join(dir, 'session.jsonl'), JSON.stringify({ type: 'session', version: 0 }))
await writeFile(join(dir, 'session.v99.jsonl'), 'unreadable future format')
}
const provider = createDshProvider(tmpDir)
const options = { providers: [provider], cache: emptyCache(), dailyCacheDays: [], launchers: [] }
for (let scan = 0; scan < 2; scan++) {
const report = await collectDoctorReport('dsh', options)
expect(only(report, 'dsh')).toMatchObject({ status: 'errors', skippedVersionCount: 2, candidatesFound: 0 })
expect(renderDoctorTable(report)).toContain('2 sessions skipped')
expect(JSON.parse(renderDoctorJson(report)).providers[0].skippedVersionCount).toBe(2)
}
expect(warnings.mock.calls.filter(([message]) => String(message).includes('session format version 99;'))).toHaveLength(1)
} finally {
warnings.mockRestore()
}
})
it('found: a real session file yields an OK verdict and a parsed sample', async () => {
await writeCodexSession(tmpDir)
const provider = createCodexProvider(tmpDir)

View file

@ -0,0 +1,261 @@
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { createHash } from 'crypto'
import { mkdir, readFile, rm, writeFile } from 'fs/promises'
import { join } from 'path'
const testRoot = vi.hoisted(() => {
const root = `${process.env['TMPDIR'] || '/tmp'}/dsh-cache-inv-${process.pid}-${Date.now()}`
process.env['DSH_HOME'] = `${root}/dsh`
return root
})
import { clearSessionCache, parseAllSessions } from '../src/parser.js'
import { billableOutputTokens, calculateCost } from '../src/models.js'
import { aggregateSessions } from '../src/sessions-report.js'
import { aggregateModelStats } from '../src/compare-stats.js'
import { aggregateProjectsIntoDays } from '../src/day-aggregator.js'
import { currentTzKey, ensureCacheHydrated, loadDailyCache } from '../src/daily-cache.js'
import {
CACHE_VERSION,
computeEnvFingerprint,
fingerprintFile,
type SessionCache,
} from '../src/session-cache.js'
import { readCacheOnDisk, writeCacheOnDisk } from './fixtures/session-cache-io.js'
const DSH_HOME = join(testRoot, 'dsh')
const CACHE_DIR = join(testRoot, 'cache')
const SESSION_DIR = join(DSH_HOME, 'sessions', '--home-u-proj--', 'session-cache')
function header(version: 0 | 3): string {
return JSON.stringify({
type: 'session', version, id: 'session-cache', createdAt: 1786707336131,
cwd: '/home/u/proj', ...(version === 3 ? { isSeeded: false } : {}), delegationDepth: 0,
})
}
function message(seq: number, step: number, inputTokens: number, reasoningTokens = 0, time = 1786707340000 + seq): string {
return JSON.stringify({
type: 'assistant/message', seq, time, surfaceOp: 'append',
data: {
turn: 1, step,
message: { role: 'assistant', content: [], source: { kind: 'model', provider: 'openai', model: 'gpt-5.4' } },
usage: { inputTokens, outputTokens: 5, reasoningTokens },
stream: [],
},
})
}
async function writeLog(version: 0 | 3, inputs: number[]): Promise<string> {
await mkdir(SESSION_DIR, { recursive: true })
const path = join(SESSION_DIR, version === 0 ? 'session.jsonl' : 'session.v3.jsonl')
await writeFile(path, [header(version), ...inputs.map((input, index) => message(index, index + 1, input))].join('\n') + '\n')
return path
}
async function calls() {
return (await parseAllSessions(undefined, 'dsh'))
.flatMap(project => project.sessions)
.flatMap(session => session.turns)
.flatMap(turn => turn.assistantCalls)
}
function preFixFingerprint(): string {
return createHash('sha256')
.update([`DSH_HOME=${process.env['DSH_HOME'] ?? ''}`, 'parser=seed-aware-v1'].join('\0'))
.digest('hex')
.slice(0, 16)
}
async function seedEmptyCache(path: string, envFingerprint: string): Promise<void> {
const fingerprint = await fingerprintFile(path)
if (!fingerprint) throw new Error('failed to fingerprint DSH fixture')
const cache: SessionCache = {
version: CACHE_VERSION,
complete: true,
providers: {
dsh: {
envFingerprint,
files: { [path]: { fingerprint, mcpInventory: [], turns: [] } },
},
},
}
await mkdir(CACHE_DIR, { recursive: true })
await writeCacheOnDisk(cache)
clearSessionCache()
}
beforeEach(async () => {
process.env['CODEBURN_CACHE_DIR'] = CACHE_DIR
process.env['DSH_HOME'] = DSH_HOME
clearSessionCache()
await rm(testRoot, { recursive: true, force: true })
})
afterAll(async () => {
clearSessionCache()
await rm(testRoot, { recursive: true, force: true })
})
describe('DSH multi-generation session cache', () => {
it('reparses v4 caches that stored exclusive output before the shared inclusive rule', async () => {
const path = await writeLog(3, [])
await writeFile(path, [header(3), message(0, 1, 100, 3)].join('\n') + '\n')
await calls()
const cache = await readCacheOnDisk()
const section = cache.providers.dsh!
section.envFingerprint = createHash('sha256').update([
`DSH_HOME=${DSH_HOME}`, 'parser=session-formats-v0-v3-attempts-v4',
].join('\0')).digest('hex').slice(0, 16)
for (const turn of section.files[path]!.turns) {
for (const call of turn.calls) call.usage.outputTokens = 2
}
await writeCacheOnDisk(cache)
clearSessionCache()
const corrected = await calls()
expect(corrected[0]!.usage).toMatchObject({ outputTokens: 5, reasoningTokens: 3 })
expect(corrected[0]!.costUSD).toBeCloseTo(calculateCost('gpt-5.4', 100, 5, 0, 0, 0), 12)
})
it('counts separate legacy and current sessions while counting migrated history only once, cold and warm', async () => {
const versions = [0, 1, 2, 3] as const
for (const version of versions) {
const content = await readFile(join(import.meta.dirname, `fixtures/dsh/v${version}.jsonl`), 'utf8')
for (const id of [`independent-v${version}`, ...(version === 0 || version === 3 ? ['migrated'] : [])]) {
const rows = content.trim().split('\n')
const metadata = JSON.parse(rows[0]!)
rows[0] = JSON.stringify({ ...metadata, id })
const dir = join(DSH_HOME, 'sessions', '--fixture--', id)
await mkdir(dir, { recursive: true })
const filename = version === 0 ? 'session.jsonl' : `session.v${version}.jsonl`
await writeFile(join(dir, filename), rows.join('\n') + '\n')
}
}
// Six files represent five sessions. All four independent versions count;
// only the migrated session's v0 file is superseded by its own v3 file.
for (const phase of ['cold', 'warm', 'reloaded']) {
if (phase === 'reloaded') clearSessionCache()
const projects = await parseAllSessions(undefined, 'dsh')
const sessions = projects.flatMap(project => project.sessions)
expect(sessions.map(session => session.sessionId).sort()).toEqual([
'independent-v0', 'independent-v1', 'independent-v2', 'independent-v3', 'migrated',
])
const parsed = sessions.flatMap(session => session.turns).flatMap(turn => turn.assistantCalls)
expect(parsed).toHaveLength(5)
expect(parsed.reduce((sum, call) => sum + call.usage.inputTokens, 0)).toBe(500)
expect(parsed.reduce((sum, call) => sum + billableOutputTokens('dsh', call.usage.outputTokens, call.usage.reasoningTokens), 0)).toBe(100)
expect(parsed.reduce((sum, call) => sum + call.usage.cacheReadInputTokens, 0)).toBe(150)
expect(parsed.reduce((sum, call) => sum + call.usage.cacheCreationInputTokens, 0)).toBe(25)
}
})
it('re-derives finalized v31 days from the authoritative generation even when the call count falls', async () => {
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(new Date('2026-08-16T12:00:00Z'))
try {
await writeLog(0, [100, 200])
const staleDays = aggregateProjectsIntoDays(await parseAllSessions(undefined, 'dsh'))
expect(staleDays[0]!.calls).toBe(2)
const oldCache = {
version: 31, savingsConfigHash: 'dsh-test', tzKey: currentTzKey(),
lastComputedDate: '2026-08-15', days: staleDays, complete: true, watermarkTrusted: true,
}
const oldPath = join(CACHE_DIR, 'daily-cache.v31.json')
await writeFile(oldPath, JSON.stringify(oldCache))
await writeLog(3, [20])
clearSessionCache()
expect((await loadDailyCache()).pendingRederive).toContain('dsh')
const parse = vi.fn(range => parseAllSessions(range, 'dsh'))
const hydrated = await ensureCacheHydrated(parse, aggregateProjectsIntoDays, 'dsh-test')
expect(parse).toHaveBeenCalledTimes(1)
expect(hydrated.complete).toBe(true)
expect(hydrated.pendingRederive).toBeUndefined()
expect(hydrated.days).toEqual([expect.objectContaining({
inputTokens: 20, outputTokens: 5, calls: 1,
providers: expect.objectContaining({ dsh: expect.objectContaining({ inputTokens: 20, calls: 1 }) }),
})])
expect(JSON.parse(await readFile(oldPath, 'utf8'))).toEqual(oldCache)
parse.mockClear()
expect((await ensureCacheHydrated(parse, aggregateProjectsIntoDays, 'dsh-test')).days).toEqual(hydrated.days)
expect(parse).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
})
it('filters a cross-day session identically before and after a disk-cache reload', async () => {
const path = await writeLog(3, [])
await writeFile(path, [header(3),
message(0, 1, 10, 0, Date.parse('2026-08-14T23:59:00Z')),
message(1, 2, 20, 0, Date.parse('2026-08-15T00:01:00Z')),
].join('\n') + '\n')
const range = { start: new Date('2026-08-15T00:00:00Z'), end: new Date('2026-08-15T23:59:59Z') }
for (const reload of [false, true]) {
if (reload) clearSessionCache()
const projects = await parseAllSessions(range, 'dsh')
expect(aggregateSessions(projects)).toEqual([expect.objectContaining({ inputTokens: 20, outputTokens: 5, calls: 1 })])
expect(aggregateProjectsIntoDays(projects)).toEqual([expect.objectContaining({ date: '2026-08-15', inputTokens: 20, calls: 1 })])
}
})
it.each(['unknown', 'corrupt'])('does not revive a cached older generation when its successor is %s', async (kind) => {
await writeLog(0, [100])
expect(await calls()).toHaveLength(1)
const successor = kind === 'unknown' ? 'session.v4.jsonl' : 'session.v3.jsonl'
await writeFile(join(SESSION_DIR, successor), kind === 'unknown'
? JSON.stringify({ type: 'session', version: 4 }) + '\n'
: '{broken\n')
clearSessionCache()
expect(await calls()).toEqual([])
clearSessionCache()
expect(await calls()).toEqual([])
})
it('preserves inclusive reasoning buckets and shared totals through cold and hot caches', async () => {
const path = await writeLog(3, [])
await writeFile(path, [header(3), message(0, 1, 100, 3)].join('\n') + '\n')
const expectedCost = calculateCost('gpt-5.4', 100, 5, 0, 0, 0)
for (const reload of [false, false, true]) {
if (reload) clearSessionCache()
const projects = await parseAllSessions(undefined, 'dsh')
const parsedCalls = projects.flatMap(project => project.sessions)
.flatMap(session => session.turns).flatMap(turn => turn.assistantCalls)
expect(parsedCalls).toHaveLength(1)
expect(parsedCalls[0]!.usage).toMatchObject({ inputTokens: 100, outputTokens: 5, reasoningTokens: 3 })
expect(parsedCalls[0]!.costUSD).toBeCloseTo(expectedCost, 12)
expect(aggregateSessions(projects)).toEqual([expect.objectContaining({ outputTokens: 5, cost: expectedCost })])
expect(aggregateModelStats(projects)).toEqual([expect.objectContaining({ outputTokens: 5, cost: expectedCost })])
expect(aggregateProjectsIntoDays(projects)).toEqual([expect.objectContaining({ outputTokens: 5 })])
}
})
it('invalidates a pre-v3 parser fingerprint instead of trusting stale empty results', async () => {
const path = await writeLog(3, [100])
expect(computeEnvFingerprint('dsh')).not.toBe(preFixFingerprint())
await seedEmptyCache(path, computeEnvFingerprint('dsh'))
expect(await calls()).toHaveLength(0)
await seedEmptyCache(path, preFixFingerprint())
expect((await calls()).map(call => call.usage.inputTokens)).toEqual([100])
})
it('switches generations without double counting, reparses appends, and survives a cold reload', async () => {
await writeLog(0, [10])
expect((await calls()).map(call => call.usage.inputTokens)).toEqual([10])
const v3Path = await writeLog(3, [20])
clearSessionCache()
expect((await calls()).map(call => call.usage.inputTokens)).toEqual([20])
await writeFile(v3Path, [header(3), message(0, 1, 20), message(1, 2, 30)].join('\n') + '\n')
clearSessionCache()
expect((await calls()).map(call => call.usage.inputTokens)).toEqual([20, 30])
clearSessionCache()
expect((await calls()).map(call => call.usage.inputTokens)).toEqual([20, 30])
})
})

8
tests/fixtures/dsh/v0.jsonl vendored Normal file
View file

@ -0,0 +1,8 @@
{"type":"session","version":0,"id":"fixture-session","createdAt":1786707340000,"cwd":"/fixture/project","delegationDepth":0}
{"type":"turn/start","data":{"turn":1},"seq":0,"time":1786707340000}
{"type":"step/start","data":{"turn":1,"step":1},"seq":1,"time":1786707340000}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"Fixture"},"reason":"initial"},"seq":2,"time":1786707340000}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":30,"cacheWriteTokens":5,"reasoningTokens":8}}},"seq":3,"time":1786707340000}
{"type":"assistant/message","surfaceOp":"append","data":{"turn":1,"step":1,"message":{"id":"fixture-message","role":"assistant","content":[{"type":"text","text":"Done"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"}},"usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":30,"cacheWriteTokens":5,"reasoningTokens":8}},"seq":4,"time":1786707340000,"sourceEventSeqs":[3]}
{"type":"step/end","data":{"turn":1,"step":1},"seq":5,"time":1786707340000}
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}},"seq":6,"time":1786707340000}

8
tests/fixtures/dsh/v1.jsonl vendored Normal file
View file

@ -0,0 +1,8 @@
{"type":"session","version":1,"id":"fixture-session","createdAt":1786707340000,"cwd":"/fixture/project","delegationDepth":0}
{"type":"turn/start","data":{"turn":1},"seq":0,"time":1786707340000}
{"type":"step/start","data":{"turn":1,"step":1},"seq":1,"time":1786707340000}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"Fixture"},"reason":"initial"},"seq":2,"time":1786707340000}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":30,"cacheWriteTokens":5,"reasoningTokens":8}}},"seq":3,"time":1786707340000}
{"type":"assistant/message","surfaceOp":"append","data":{"turn":1,"step":1,"message":{"id":"fixture-message","role":"assistant","content":[{"type":"text","text":"Done"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"}},"usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":30,"cacheWriteTokens":5,"reasoningTokens":8}},"seq":4,"time":1786707340000,"sourceEventSeqs":[3]}
{"type":"step/end","data":{"turn":1,"step":1},"seq":5,"time":1786707340000}
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}},"seq":6,"time":1786707340000}

7
tests/fixtures/dsh/v2.jsonl vendored Normal file
View file

@ -0,0 +1,7 @@
{"type":"session","version":2,"id":"fixture-session","createdAt":1786707340000,"cwd":"/fixture/project","delegationDepth":0,"isSeeded":false}
{"type":"turn/start","data":{"turn":1},"seq":0,"time":1786707340000}
{"type":"step/start","data":{"turn":1,"step":1},"seq":1,"time":1786707340000}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"Fixture"},"reason":"initial"},"seq":2,"time":1786707340000}
{"type":"assistant/message","surfaceOp":"append","data":{"turn":1,"step":1,"message":{"id":"fixture-message","role":"assistant","content":[{"type":"text","text":"Done"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"}},"usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":30,"cacheWriteTokens":5,"reasoningTokens":8},"stream":[{"type":"chunk","time":1786707340000,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":30,"cacheWriteTokens":5,"reasoningTokens":8}}}]},"seq":3,"time":1786707340000}
{"type":"step/end","data":{"turn":1,"step":1},"seq":4,"time":1786707340000}
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}},"seq":5,"time":1786707340000}

11
tests/fixtures/dsh/v3-retry.jsonl vendored Normal file
View file

@ -0,0 +1,11 @@
{"type":"session","version":3,"id":"fixture-retry","createdAt":1786707340000,"cwd":"/fixture/project","delegationDepth":0,"isSeeded":false}
{"type":"turn/start","data":{"turn":1},"seq":0,"time":1786707340000}
{"type":"step/start","data":{"turn":1,"step":1},"seq":1,"time":1786707340001}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"}},"reason":"initial"},"seq":2,"time":1786707340002}
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"seq":3,"time":1786707340003}
{"type":"assistant/attempt","data":{"turn":1,"step":1,"stream":[{"type":"chunk","time":1786707340000,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":4,"cacheReadTokens":3,"cacheWriteTokens":2,"reasoningTokens":2,"totalTokens":19}}}]},"seq":4,"time":1786707340004}
{"type":"llm/retry","time":1786707340005,"data":{"retryId":"fixture-retry-1","turn":1,"step":1,"provider":"deepseek-official","mode":"normal","policyKey":"default","retry":1,"maxRetries":1,"delayMs":0,"failure":{"code":"SERVER","message":"Fixture failure"}},"seq":5}
{"type":"llm/retry-started","data":{"turn":1,"step":1,"retryId":"fixture-retry-1","retry":1},"seq":6,"time":1786707340006}
{"type":"assistant/message","surfaceOp":"append","data":{"turn":1,"step":1,"message":{"id":"fixture-success","role":"assistant","content":[{"type":"text","text":"Done"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"}},"usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":30,"cacheWriteTokens":5,"reasoningTokens":8,"totalTokens":155},"stream":[{"type":"chunk","time":1786707340000,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":30,"cacheWriteTokens":5,"reasoningTokens":8,"totalTokens":155}}}]},"seq":7,"time":1786707340007}
{"type":"step/end","data":{"turn":1,"step":1},"seq":8,"time":1786707340008}
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}},"seq":9,"time":1786707340009}

6
tests/fixtures/dsh/v3.jsonl vendored Normal file
View file

@ -0,0 +1,6 @@
{"type":"session","version":3,"id":"fixture-session","createdAt":1786707340000,"cwd":"/fixture/project","delegationDepth":0,"isSeeded":false}
{"type":"turn/start","data":{"turn":1},"seq":0,"time":1786707340000}
{"type":"step/start","data":{"turn":1,"step":1},"seq":1,"time":1786707340000}
{"type":"assistant/message","surfaceOp":"append","data":{"turn":1,"step":1,"message":{"id":"fixture-message","role":"assistant","content":[{"type":"text","text":"Done"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"}},"usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":30,"cacheWriteTokens":5,"reasoningTokens":8},"stream":[{"type":"chunk","time":1786707340000,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":30,"cacheWriteTokens":5,"reasoningTokens":8}}}]},"seq":2,"time":1786707340000}
{"type":"step/end","data":{"turn":1,"step":1},"seq":3,"time":1786707340000}
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}},"seq":4,"time":1786707340000}

View file

@ -1,11 +1,11 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { mkdtemp, mkdir, writeFile, readFile, rm, stat } from 'fs/promises'
import { join } from 'path'
import { homedir, tmpdir } from 'os'
import zlib from 'zlib'
import { createDshProvider, readZstdLines } from '../../src/providers/dsh.js'
import { calculateCost } from '../../src/models.js'
import { billableOutputTokens, calculateCost } from '../../src/models.js'
import type { ParsedProviderCall } from '../../src/providers/types.js'
// DSH session logs are concatenations of INDEPENDENT zstd frames (one per
@ -118,6 +118,51 @@ async function writePlainSession(projectDirName: string, sessionDirName: string,
return filePath
}
async function writeVersionedSession(
version: 1 | 2 | 3,
projectDirName: string,
sessionDirName: string,
lines: string[],
compressed = false,
) {
const dir = join(tmpDir, 'sessions', projectDirName, sessionDirName)
await mkdir(dir, { recursive: true })
const suffix = compressed ? '.zstd' : ''
const filePath = join(dir, `session.v${version}.jsonl${suffix}`)
if (compressed && zstdCompress) {
const split = Math.max(1, Math.floor(lines.length / 2))
const frames = [lines.slice(0, split), lines.slice(split)]
.filter(batch => batch.length > 0)
.map(batch => zstdCompress(Buffer.from(batch.join('\n') + '\n')))
await writeFile(filePath, Buffer.concat(frames))
} else {
await writeFile(filePath, lines.join('\n') + '\n')
}
return filePath
}
// Released layouts checked against deepseek-ai/deepseek-harness at
// c291e7961a515f6d7af9304e7fd1d257929aef26:
// packages/session/session-format-v0-to-v1/src/codec.ts (v1),
// packages/session/session-format-v1-to-v2/src/codec.ts (v2), and
// packages/session/session-format-v2-to-v3/src/codec.ts (v3).
// Embedded usage and retry settlements follow packages/llm/token-meter/src/usage-projection.ts.
function versionedHeader(version: 1 | 2 | 3, opts: { id?: string; cwd?: string; isSeeded?: boolean } = {}) {
return JSON.stringify({
type: 'session',
version,
id: opts.id ?? `session-v${version}`,
createdAt: 1786707336131,
cwd: opts.cwd ?? '/home/u/proj',
...(version <= 1 ? {} : { isSeeded: opts.isSeeded ?? false }),
delegationDepth: 0,
})
}
function embeddedUsage(usage: Record<string, number>, time: number) {
return [{ type: 'chunk', time, chunk: { type: 'usage', usage } }]
}
async function parseAll(provider: ReturnType<typeof createDshProvider>, filePath: string): Promise<ParsedProviderCall[]> {
const source = { path: filePath, project: 'myproject', provider: 'dsh' }
const calls: ParsedProviderCall[] = []
@ -158,6 +203,58 @@ describe('dsh provider - session discovery', () => {
expect(sessions[0]!.project).toBe('proj')
})
it('discovers a v3 session log', async () => {
const dir = join(tmpDir, 'sessions', '--home-u-proj--', 'session-v3')
await mkdir(dir, { recursive: true })
await writeFile(
join(dir, 'session.v3.jsonl'),
JSON.stringify({
type: 'session',
version: 3,
id: 'session-v3',
createdAt: 1786707336131,
cwd: '/home/u/proj',
}) + '\n',
)
const sessions = await createDshProvider(tmpDir).discoverSessions()
expect(sessions).toHaveLength(1)
expect(sessions[0]!.path).toBe(join(dir, 'session.v3.jsonl'))
})
it('selects only the highest generation when migrated logs coexist', async () => {
const dir = join(tmpDir, 'sessions', '--home-u-proj--', 'session-migrated')
await mkdir(dir, { recursive: true })
await writeFile(join(dir, 'session.jsonl'), sessionHeader({ id: 'session-migrated' }) + '\n')
await writeFile(join(dir, 'session.v2.jsonl'), versionedHeader(2, { id: 'session-migrated' }) + '\n')
await writeFile(join(dir, 'session.v3.jsonl'), versionedHeader(3, { id: 'session-migrated' }) + '\n')
const sessions = await createDshProvider(tmpDir).discoverSessions()
expect(sessions).toHaveLength(1)
expect(sessions[0]!.path).toBe(join(dir, 'session.v3.jsonl'))
})
it('does not fall back when the highest generation is corrupt or unknown', async () => {
const corrupt = join(tmpDir, 'sessions', '--home-u-proj--', 'session-corrupt')
const unknown = join(tmpDir, 'sessions', '--home-u-proj--', 'session-unknown')
await mkdir(corrupt, { recursive: true })
await mkdir(unknown, { recursive: true })
await writeFile(join(corrupt, 'session.jsonl'), sessionHeader({ id: 'session-corrupt' }) + '\n')
await writeFile(join(corrupt, 'session.v3.jsonl'), '{broken\n')
await writeFile(join(unknown, 'session.jsonl'), sessionHeader({ id: 'session-unknown' }) + '\n')
await writeFile(join(unknown, 'session.v4.jsonl'), JSON.stringify({ type: 'session', version: 4 }) + '\n')
expect(await createDshProvider(tmpDir).discoverSessions()).toEqual([])
})
it('rejects a filename/header generation mismatch', async () => {
await writeVersionedSession(3, '--home-u-proj--', 'session-mismatch', [versionedHeader(2)])
expect(await createDshProvider(tmpDir).discoverSessions()).toEqual([])
})
it('returns empty for a non-existent home', async () => {
const provider = createDshProvider('/nonexistent/dsh/home')
expect(await provider.discoverSessions()).toEqual([])
@ -170,7 +267,7 @@ describe('dsh provider - session discovery', () => {
})
it('DSH_HOME relocates discovery; an empty string is treated as unset', async () => {
const home = join(tmpDir, 'dsh-home')
const home = join(tmpDir, 'dsh home-café')
await mkdir(join(home, 'sessions', '--x--', 'session-env'), { recursive: true })
await writeFile(
join(home, 'sessions', '--x--', 'session-env', 'session.jsonl'),
@ -205,6 +302,300 @@ describe('dsh provider - session discovery', () => {
})
describe('dsh provider - parsing', () => {
it('counts failed and successful attempts from the official-validated retry fixture', async () => {
const content = await readFile(join(import.meta.dirname, '../fixtures/dsh/v3-retry.jsonl'), 'utf8')
const path = await writeVersionedSession(3, '--fixture--', 'fixture-retry', content.trim().split('\n'))
const calls = await parseAll(createDshProvider(tmpDir), path)
expect(calls.map(call => [call.inputTokens, call.outputTokens, call.reasoningTokens])).toEqual([[10, 4, 2], [100, 20, 8]])
expect(calls.every(call => call.model === 'deepseek-v4-flash')).toBe(true)
expect(calls.reduce((sum, call) => sum + call.inputTokens + billableOutputTokens('dsh', call.outputTokens, call.reasoningTokens)
+ call.cacheReadInputTokens + call.cacheCreationInputTokens, 0)).toBe(174)
})
it.each(([0, 1, 2, 3] as const).flatMap(version => [false, true].map(retry => ({ version, retry }))))(
'replaces non-adjacent settlements per step in v$version (retry=$retry)', async ({ version, retry }) => {
const sample = (step: number, input: number) => version <= 1
? chunkUsage(1, step, { inputTokens: input, outputTokens: 10 }, 1786707340000)
: JSON.stringify({ type: 'assistant/attempt', seq: step, time: 1786707340000,
data: { turn: 1, step, stream: embeddedUsage({ inputTokens: input, outputTokens: 10 }, 1786707340000) } })
const rows = [version === 0 ? sessionHeader() : versionedHeader(version),
sample(1, 100), sample(2, 200),
assistantMessage(1, 1, { inputTokens: 100, outputTokens: 10 }, 1786707340100),
...(retry ? [JSON.stringify({ type: 'llm/retry-started', seq: 8, time: 1786707340150,
data: { turn: 1, step: 1, retryId: 'interleaved-retry', retry: 1 } }),
assistantMessage(1, 1, { inputTokens: 150, outputTokens: 10 }, 1786707340180)] : []),
assistantMessage(1, 2, { inputTokens: 200, outputTokens: 10 }, 1786707340200)]
const path = version === 0 ? await writePlainSession('--fixture--', 'interleaved', rows)
: await writeVersionedSession(version, '--fixture--', 'interleaved', rows)
const calls = await parseAll(createDshProvider(tmpDir), path)
expect(calls.map(call => call.inputTokens)).toEqual(retry ? [100, 150, 200] : [100, 200])
})
it.each([0, 1] as const)('retains non-fork v%s usage when only seedLength is present', async version => {
const rows = [JSON.stringify({ type: 'session', version, id: 'non-fork', seedLength: 4,
createdAt: 1786707340000, cwd: '/fixture/project', delegationDepth: 0 }),
...[1, 2, 3, 4].map((step, seq) => JSON.stringify({ type: 'assistant/message', seq,
time: 1786707340000, data: { turn: 1, step, usage: { inputTokens: 100, outputTokens: 10 } } }))]
const path = version === 0 ? await writePlainSession('--fixture--', 'non-fork', rows)
: await writeVersionedSession(version, '--fixture--', 'non-fork', rows)
expect((await parseAll(createDshProvider(tmpDir), path)).map(call => call.inputTokens)).toEqual([100, 100, 100, 100])
})
it.each([0, 1, 2, 3] as const)('matches official DSH totals for the sanitized v%s fixture', async version => {
const content = await readFile(join(import.meta.dirname, `../fixtures/dsh/v${version}.jsonl`), 'utf8')
const lines = content.trim().split('\n')
const path = version === 0
? await writePlainSession('--fixture--', 'fixture-session', lines)
: await writeVersionedSession(version, '--fixture--', 'fixture-session', lines)
const calls = await parseAll(createDshProvider(tmpDir), path)
expect(calls).toHaveLength(1)
expect(calls[0]).toMatchObject({ inputTokens: 100, outputTokens: 20, reasoningTokens: 8, cacheReadInputTokens: 30, cacheCreationInputTokens: 5 })
expect(billableOutputTokens('dsh', calls[0]!.outputTokens, calls[0]!.reasoningTokens)).toBe(20)
})
it('does not reuse the previous request context after a model change', async () => {
const filePath = await writeVersionedSession(3, '--home-u-proj--', 'session-context-change', [
versionedHeader(3),
requestHeader('first-model'),
JSON.stringify({ type: 'request/context', seq: 1, time: 1786707337000, data: { model: 'first-model', provider: 'route' } }),
assistantMessage(1, 1, { inputTokens: 10, outputTokens: 1 }, 1786707340000),
requestHeader('second-model'),
JSON.stringify({ type: 'assistant/attempt', seq: 4, time: 1786707341000, data: {
turn: 1, step: 2, stream: embeddedUsage({ inputTokens: 20, outputTokens: 2 }, 1786707340900),
} }),
])
expect((await parseAll(createDshProvider(tmpDir), filePath)).map(call => call.model)).toEqual(['first-model', 'second-model'])
})
it('keeps metered attempts when another attempt has no usage, without inventing a zero call', async () => {
const filePath = await writeVersionedSession(3, '--home-u-proj--', 'session-missing-usage', [
versionedHeader(3),
assistantMessage(1, 1, { inputTokens: 10, outputTokens: 1 }, 1786707340000),
JSON.stringify({ type: 'assistant/attempt', seq: 2, time: 1786707341000, data: { turn: 1, step: 2, stream: [] } }),
])
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true)
try {
const calls = await parseAll(createDshProvider(tmpDir), filePath)
expect(calls).toHaveLength(1)
expect(calls[0]).toMatchObject({ inputTokens: 10, outputTokens: 1, costIsEstimated: false })
expect(stderr).toHaveBeenCalledWith(expect.stringContaining('attempt without usage'))
} finally {
stderr.mockRestore()
}
})
it.each([
{ inputTokens: 10 },
{ inputTokens: 10, outputTokens: 2, reasoningTokens: 3 },
])('marks incomplete or inconsistent usage as estimated: %j', async (usage) => {
const filePath = await writeVersionedSession(3, '--home-u-proj--', 'session-incomplete-usage', [
versionedHeader(3),
assistantMessage(1, 1, usage, 1786707340000),
])
const calls = await parseAll(createDshProvider(tmpDir), filePath)
expect(calls).toHaveLength(1)
expect(calls[0]).toMatchObject({ inputTokens: 10, outputTokens: 'outputTokens' in usage ? usage.outputTokens : 0, costIsEstimated: true })
})
it.each([1, 2, 3] as const)('uses only the usage layout belonging to format v%s', async (version) => {
// v1-to-v2 consumes top-level chunks and introduces settlement streams.
// A row from the other physical layout must not become an extra call.
const filePath = await writeVersionedSession(version, '--home-u-proj--', 'session-layout', [
versionedHeader(version),
chunkUsage(1, 1, { inputTokens: 10, outputTokens: 1 }, 1786707340000),
JSON.stringify({
type: 'assistant/attempt', seq: 4, time: 1786707341000,
data: { turn: 1, step: 2, stream: embeddedUsage({ inputTokens: 20, outputTokens: 2 }, 1786707340900) },
}),
])
const calls = await parseAll(createDshProvider(tmpDir), filePath)
expect(calls.map(call => [call.inputTokens, call.outputTokens])).toEqual(version === 1 ? [[10, 1]] : [[20, 2]])
})
it('keeps the released v1 top-level event layout compatible', async () => {
const filePath = await writeVersionedSession(1, '--home-u-proj--', 'session-v1', [
versionedHeader(1, { id: 'session-v1' }),
requestHeader('deepseek-v4-pro'),
assistantMessage(1, 1, { inputTokens: 111, outputTokens: 22 }, 1786707340000),
])
const calls = await parseAll(createDshProvider(tmpDir), filePath)
expect(calls).toHaveLength(1)
expect(calls[0]).toMatchObject({ model: 'deepseek-v4-pro', inputTokens: 111, outputTokens: 22 })
})
it.each([2, 3] as const)('reads v%s embedded streams and prefers message usage', async (version) => {
const filePath = await writeVersionedSession(version, '--home-u-proj--', `session-v${version}`, [
versionedHeader(version, { id: `session-v${version}` }),
JSON.stringify({
type: 'request/context', seq: 0, time: 1786707337000,
data: { provider: 'openai', model: 'requested-model' },
}),
JSON.stringify({
type: 'assistant/message', seq: 1, time: 1786707340000, surfaceOp: 'append',
data: {
turn: 1,
step: 1,
message: { role: 'assistant', content: [], source: { kind: 'model', provider: 'openai', model: 'served-model' } },
stream: embeddedUsage({ inputTokens: 90, outputTokens: 9 }, 1786707339900),
usage: { inputTokens: 100, outputTokens: 10, cacheReadTokens: 30 },
},
}),
])
const calls = await parseAll(createDshProvider(tmpDir), filePath)
expect(calls).toHaveLength(1)
expect(calls[0]).toMatchObject({
model: 'served-model', inputTokens: 100, outputTokens: 10, cacheReadInputTokens: 30,
})
})
it('counts each retry attempt and resolves failed-attempt models from request context', async () => {
const filePath = await writeVersionedSession(3, '--home-u-proj--', 'session-retry', [
versionedHeader(3, { id: 'session-retry' }),
JSON.stringify({ type: 'turn/start', seq: 0, time: 1786707337000, data: { turn: 1 } }),
JSON.stringify({
type: 'request/header', seq: 1, time: 1786707337100,
data: { header: { config: { provider: 'configured', model: 'configured-model' } }, reason: 'initial' },
}),
JSON.stringify({
type: 'request/context', seq: 2, time: 1786707337200,
data: { provider: 'actual-route', model: 'attempt-model' },
}),
JSON.stringify({
type: 'assistant/attempt', seq: 3, time: 1786707338000,
data: { turn: 1, step: 1, stream: embeddedUsage({ inputTokens: 10, outputTokens: 1 }, 1786707337900) },
}),
JSON.stringify({
type: 'llm/retry-started', seq: 4, time: 1786707338100,
data: { retryId: 'retry-1', turn: 1, step: 1, retry: 1 },
}),
JSON.stringify({
type: 'assistant/message', seq: 5, time: 1786707339000, surfaceOp: 'append',
data: {
turn: 1,
step: 1,
message: { role: 'assistant', content: [], source: { kind: 'model', provider: 'actual-route', model: 'served-model' } },
stream: embeddedUsage({ inputTokens: 20, outputTokens: 2 }, 1786707338900),
},
}),
])
const calls = await parseAll(createDshProvider(tmpDir), filePath)
expect(calls.map(call => [call.model, call.inputTokens, call.outputTokens])).toEqual([
['attempt-model', 10, 1],
['served-model', 20, 2],
])
expect(calls.map(call => call.deduplicationKey)).toEqual([
'dsh:session-retry:1:1',
'dsh:session-retry:1:1:attempt:2',
])
})
it.each([2, 3] as const)('excludes the inherited prefix using the last tagged v%s end-seed marker', async (version) => {
const filePath = await writeVersionedSession(version, '--home-u-proj--', `session-v${version}-fork`, [
versionedHeader(version, { id: `session-v${version}-fork`, isSeeded: true }),
JSON.stringify({
type: 'request/context', seq: 0, time: 1786707336900,
data: { provider: 'deepseek', model: 'inherited-model' },
}),
JSON.stringify({
type: 'assistant/message', seq: 1, time: 1786707337000, surfaceOp: 'append',
data: { turn: 1, step: 1, message: { role: 'assistant', content: [] }, usage: { inputTokens: 999, outputTokens: 99 }, stream: [] },
}),
JSON.stringify({ type: 'session/end-seed', seq: 2, time: 1786707337100, data: { inherited: true } }),
JSON.stringify({
type: 'assistant/message', seq: 3, time: 1786707338000, surfaceOp: 'append',
data: { turn: 2, step: 1, message: { role: 'assistant', content: [] }, usage: { inputTokens: 500, outputTokens: 50 }, stream: [] },
}),
JSON.stringify({ type: 'session/end-seed', seq: 4, time: 1786707338100, data: { inherited: true } }),
JSON.stringify({
type: 'assistant/message', seq: 5, time: 1786707339000, surfaceOp: 'append',
data: { turn: 3, step: 1, message: { role: 'assistant', content: [] }, usage: { inputTokens: 100, outputTokens: 10 }, stream: [] },
}),
])
const calls = await parseAll(createDshProvider(tmpDir), filePath)
expect(calls).toHaveLength(1)
expect(calls[0]).toMatchObject({ model: 'inherited-model', inputTokens: 100, outputTokens: 10 })
})
it('treats pi-ai API routes as the same normalized TokenUsage contract', async () => {
const routes = [
['anthropic', 'claude-sonnet-4-5', 10],
['openai-chat-completions', 'gpt-5.4', 20],
['openai-responses', 'gpt-5.4-codex', 30],
] as const
const rows = routes.flatMap(([provider, model, input], index) => [
JSON.stringify({ type: 'request/context', seq: index * 2, time: 1786707337000 + index, data: { provider, model } }),
JSON.stringify({
type: 'assistant/message', seq: index * 2 + 1, time: 1786707340000 + index, surfaceOp: 'append',
data: {
turn: 1, step: index + 1,
message: { role: 'assistant', content: [], source: { kind: 'model', provider, model } },
stream: embeddedUsage({ inputTokens: input, outputTokens: 5, cacheReadTokens: 3, cacheWriteTokens: 2 }, 1786707339000 + index),
},
}),
])
const filePath = await writeVersionedSession(3, '--home-u-proj--', 'session-routes', [
versionedHeader(3, { id: 'session-routes' }),
...rows,
])
const calls = await parseAll(createDshProvider(tmpDir), filePath)
expect(calls.map(call => [call.model, call.inputTokens, call.outputTokens, call.cacheReadInputTokens, call.cacheCreationInputTokens]))
.toEqual(routes.map(([, model, input]) => [model, input, 5, 3, 2]))
})
itZstd('decodes a versioned v3 log split across independent zstd frames', async () => {
const filePath = await writeVersionedSession(3, '--home-u-proj--', 'session-v3-zstd', [
versionedHeader(3, { id: 'session-v3-zstd' }),
JSON.stringify({
type: 'assistant/message', seq: 0, time: 1786707340000, surfaceOp: 'append',
data: { turn: 1, step: 1, message: { role: 'assistant', content: [] }, stream: embeddedUsage({ inputTokens: 12, outputTokens: 3 }, 1786707339900) },
}),
], true)
expect((await parseAll(createDshProvider(tmpDir), filePath))[0]).toMatchObject({ inputTokens: 12, outputTokens: 3 })
})
itZstd('decodes every versioned generation from zstd', async () => {
for (const version of [1, 2, 3] as const) {
const settlement = version === 1
? assistantMessage(1, 1, { inputTokens: version * 10, outputTokens: version }, 1786707340000)
: JSON.stringify({
type: 'assistant/message', seq: 0, time: 1786707340000, surfaceOp: 'append',
data: {
turn: 1, step: 1, message: { role: 'assistant', content: [] },
stream: embeddedUsage({ inputTokens: version * 10, outputTokens: version }, 1786707339900),
},
})
const filePath = await writeVersionedSession(version, '--home-u-proj--', `session-v${version}-zstd`, [
versionedHeader(version, { id: `session-v${version}-zstd` }),
settlement,
], true)
expect((await parseAll(createDshProvider(tmpDir), filePath))[0])
.toMatchObject({ inputTokens: version * 10, outputTokens: version })
}
})
itZstd('ignores a torn trailing frame in a v3 log', async () => {
const filePath = await writeVersionedSession(3, '--home-u-proj--', 'session-v3-torn', [
versionedHeader(3, { id: 'session-v3-torn' }),
JSON.stringify({
type: 'assistant/message', seq: 0, time: 1786707340000, surfaceOp: 'append',
data: { turn: 1, step: 1, message: { role: 'assistant', content: [] }, usage: { inputTokens: 10, outputTokens: 1 }, stream: [] },
}),
], true)
const original = await readFile(filePath)
const torn = zstdCompress!(Buffer.from(JSON.stringify({
type: 'assistant/message', seq: 1, time: 1786707341000, surfaceOp: 'append',
data: { turn: 1, step: 2, message: { role: 'assistant', content: [] }, usage: { inputTokens: 999, outputTokens: 99 }, stream: [] },
}) + '\n'))
await writeFile(filePath, Buffer.concat([original, torn.subarray(0, Math.floor(torn.length / 2))]))
expect((await parseAll(createDshProvider(tmpDir), filePath)).map(call => call.inputTokens)).toEqual([10])
})
itZstd('decodes events spread across multiple independent zstd frames', async () => {
const filePath = await writeZstdSession('--C-Users-test-myproject--', 'session-multi', [
[sessionHeader({ id: 'session-multi', cwd: 'C:\\Users\\test\\myproject' })],
@ -232,6 +623,7 @@ describe('dsh provider - parsing', () => {
const calls = await parseAll(createDshProvider(tmpDir), filePath)
expect(calls).toHaveLength(1)
expect(calls[0]!.inputTokens).toBe(14981)
// Preserve raw output, including reasoning, for the shared billing rule.
expect(calls[0]!.outputTokens).toBe(656)
expect(calls[0]!.reasoningTokens).toBe(609)
expect(calls[0]!.timestamp).toBe(new Date(1786707340050).toISOString())
@ -275,16 +667,20 @@ describe('dsh provider - parsing', () => {
expect(calls.map(c => c.model)).toEqual(['deepseek-v4-pro', 'deepseek-v4-pro', 'deepseek-v4-flash'])
})
it('bills reasoning tokens at the output rate', async () => {
it('preserves inclusive reasoning and bills output once through the shared rule', async () => {
const filePath = await writeZstdSession('--C-Users-test-myproject--', 'session-reason', [
[sessionHeader({ id: 'session-reason' })],
[requestHeader('deepseek-v4-pro')],
[assistantMessage(1, 1, { inputTokens: 1000, outputTokens: 100, cacheWriteTokens: 50, cacheReadTokens: 500, reasoningTokens: 400 }, 1786707340000)],
[assistantMessage(1, 1, { inputTokens: 1000, outputTokens: 100, cacheWriteTokens: 50, cacheReadTokens: 500, reasoningTokens: 40 }, 1786707340000)],
])
const calls = await parseAll(createDshProvider(tmpDir), filePath)
expect(calls).toHaveLength(1)
expect(calls[0]!.costUSD).toBeCloseTo(calculateCost('deepseek-v4-pro', 1000, 500, 50, 500, 0), 12)
expect(calls[0]).toMatchObject({ outputTokens: 100, reasoningTokens: 40 })
expect(billableOutputTokens('dsh', calls[0]!.outputTokens, calls[0]!.reasoningTokens)).toBe(100)
// DSH's TokenUsage reasoningTokens is informational detail already
// included in outputTokens, so the output bucket is billed exactly once.
expect(calls[0]!.costUSD).toBeCloseTo(calculateCost('deepseek-v4-pro', 1000, 100, 50, 500, 0), 12)
})
it('collects mapped tools, skill names and bash commands from tool/call events', async () => {
@ -443,8 +839,8 @@ describe('dsh provider - real log fidelity', () => {
workingDirectory: '/home/u/proj',
})
expect(calls[1]).toMatchObject({ inputTokens: 168, outputTokens: 25, cacheReadInputTokens: 2816, reasoningTokens: 22 })
// Reasoning bills at the output rate, so it must not appear as input.
expect(calls[0]!.costUSD).toBe(calculateCost('deepseek-v4-flash', 2877, 90 + 18, 0, 0, 0))
// Reasoning is a subset of output, so it must not be added a second time.
expect(calls[0]!.costUSD).toBe(calculateCost('deepseek-v4-flash', 2877, 90, 0, 0, 0))
expect(calls[0]!.costUSD).toBeGreaterThan(0)
})
@ -464,6 +860,25 @@ describe('dsh provider - real log fidelity', () => {
})
describe('dsh provider - defensive reads', () => {
it.each([2, 3] as const)('rejects malformed interior JSON in v%s while preserving a torn tail', async (version) => {
const rows = [versionedHeader(version), assistantMessage(1, 1, { inputTokens: 10, outputTokens: 1 }, 1786707340000)]
const corrupt = await writeVersionedSession(version, '--home-u-proj--', 'session-interior', [
rows[0]!, '{broken', rows[1]!,
])
const torn = await writeVersionedSession(version, '--home-u-proj--', 'session-tail', [...rows, '{broken'])
expect(await parseAll(createDshProvider(tmpDir), corrupt)).toEqual([])
expect(await parseAll(createDshProvider(tmpDir), torn)).toEqual([expect.objectContaining({ inputTokens: 10, outputTokens: 1 })])
})
it('does not accept a session header appearing after an unrelated first row', async () => {
const path = await writeVersionedSession(3, '--home-u-proj--', 'session-late-header', [
JSON.stringify({ type: 'turn/start', seq: 0, data: { turn: 1 } }),
versionedHeader(3),
assistantMessage(1, 1, { inputTokens: 10, outputTokens: 1 }, 1786707340000),
])
expect(await parseAll(createDshProvider(tmpDir), path)).toEqual([])
})
it('skips a log stamped with an unsupported session format version', async () => {
const filePath = await writePlainSession('--home-u-proj--', 'session-future', [
JSON.stringify({ type: 'session', version: 1, id: 'session-future', createdAt: 1786707336131, cwd: '/home/u/proj', delegationDepth: 0 }),
@ -500,6 +915,11 @@ describe('dsh provider - defensive reads', () => {
JSON.stringify({ type: 'agent/inbox/spliced', seq: 0, time: 1786707337000, data: { target: 'next-turn' } }),
JSON.stringify({ type: 'reasoning-chunks', seq0: 1, time0: 1786707337100, data: { turn: 1, step: 1, index: 0, dt: [0], texts: ['a', 'b'] } }),
'{ not json at all',
'null',
'42',
'[]',
JSON.stringify({ type: 'user/message', data: { source: { kind: 'user' }, content: {} } }),
JSON.stringify({ type: 'user/message', data: { source: { kind: 'user' }, content: [null] } }),
' ',
chunkUsage(1, 1, { inputTokens: 100, outputTokens: 10 }, 1786707340000),
])