Skip to content

[BUG]: Session fork double-counts pre-fork API costs in opencode stats and cost reporting #31032

Description

@lindeberg

Summary

Forking a session inflates cost reporting for the fork by the full cost of the original session at fork time. This is most clearly wrong in opencode stats, which sums all session costs with no fork-lineage awareness — every fork session directly inflates Total Cost, Avg Cost/Day, and each model's cost line. Whether the TUI sidebar should show inherited cost is a separate UX question; the aggregation in opencode stats is unambiguously incorrect.

Affected surfaces

Surface How cost is read Impact
opencode stats total cost session.cost column, summed across all sessions Inflated by full pre-fork spend for each fork
opencode stats --models breakdown message.info.cost summed per assistant message Copied messages carry original cost → double-counted per model
TUI sidebar session.cost column Debatable — may be intentional as "inherited context cost"

Steps to reproduce

  1. Run a session with meaningful spend across multiple assistant turns.
  2. Fork the session (branch button in TUI, or session.fork() API).
  3. Run opencode stats (or opencode stats --models).
  4. Observe that Total Cost and the model cost breakdown are inflated by the pre-fork spend appearing twice.

Expected behaviour

Fork sessions contribute only their post-fork API calls to cost aggregates. Pre-fork history is shared context, not new spend.

Actual behaviour

Fork sessions contribute the full original session cost + new post-fork cost to every aggregate. With N forks of the same session, the pre-fork spend is counted N+1 times.

Root cause

Two pieces of code interact to produce the double-count:

1. packages/opencode/src/session/session.ts — fork()

The fork function iterates every message from the original session and calls updatePart(p) for each cloned part. Parts are spread verbatim, only id and sessionID are replaced:

const p: SessionV1.Part = {
  ...part,              // cost/tokens fields preserved from original
  id: PartID.ascending(), // fresh ID — no prior DB row
  messageID: cloned.id,
  sessionID: session.id,  // fork session
}
yield* updatePart(p)

2. packages/core/src/session/projector.ts — PartUpdated handler

The projector accumulates cost by diffing the previous and next state of each part:

const row = yield* db.select().from(PartTable).where(eq(PartTable.id, id)).get()...
const previous = row && usage(row.data)  // undefined — new ID has no prior row
const next = usage(event.data.part)      // {cost, tokens} extracted from step-finish
if (previous) yield* applyUsage(db, row.session_id, previous, -1)  // skipped
if (next)     yield* applyUsage(db, sessionID, next)               // full cost applied!

Because every cloned step-finish part has a fresh PartID, previous is always undefined, so only the additive path runs. The fork session's cost column ends up equal to the sum of all pre-fork step-finish costs.

The stats --models breakdown is a separate path: it reads message.info.cost directly from cloned assistant messages, which also carry the original cost verbatim.

Proposed fix

Part 1 — session.cost (sidebar + stats total)

Zero out cost and tokens on cloned step-finish parts in fork(). This is the clean fix: the projector's diff logic was designed to handle zero-cost parts, reverting/removing pre-fork messages from a fork correctly subtracts $0 (rather than going negative), and compaction is also unaffected.

// packages/opencode/src/session/session.ts, inside fork()
const emptyTokens = { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }

const p: SessionV1.Part = {
  ...part,
  id: PartID.ascending(),
  messageID: cloned.id,
  sessionID: session.id,
  ...(part.type === 'step-finish'
    ? { cost: 0, tokens: emptyTokens }
    : {}),
}

Part 2 — stats --models model breakdown

Zeroing message.info.cost on cloned messages would fix the stats double-count but destroys per-message cost data at the fork level — any future "cost per message" feature would show $0 for all pre-fork turns. A more principled fix is to change stats --models to derive model costs from step-finish parts (the same source that drives session.cost) rather than message.info.cost. That keeps cloned message objects as honest records of the original calls while the accounting fix lives entirely in the accumulation layer.

An alternative that enables either approach is to mark fork sessions with a parentID pointing at the original session (currently fork() does not set parentID, unlike subagent child sessions). With lineage tracked, stats could explicitly exclude or de-duplicate forked pre-fork cost.

Environment

  • OpenCode version: 1.15.13
  • Provider: GitHub Copilot

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions