Files
magpie/internal/sessions/codex_fork.go
T
yetone 1d0fc2bb08 sessions: a fork's copies of its parent's calls are counted once (Codex, ZCode)
Sky (skyhuang1994) on Discord: on ZCode, 10-31 showed ~0.70B GLM-5.3
tokens where ZCode's own model_usage had ~0.28B. A selection side chat
opened on 11-02 from a 10-31 session holds a copy of its 860 assistant
messages, with the 10-31 times and the same 421,041,276 tokens, and made
no calls. On Codex, a week of 2026-03 read 5,136,041,178 gpt-5.4 tokens,
where the machine had spent ~0.27B.

ZCode: ZCode 3.17's CLI copies a session's messages (gce, for a side
chat, a fork and a checkpoint restored) with a new id and session, the
original's time, model and tokens, and metadata.forkOrigin
{sessionId, messageId}. zcDB.copied says a message is a copy of one still
in the database, and readZCodeCalls and parseOpenCode (for ZCode) leave
it out. A copy of a copy names the copy it came from, so of each chain
one is counted. A copy whose original is gone is counted. ZCode's own
fork notices carry a forkOrigin with no messageId, and are not copies.

Codex: a fork (/fork, spawn_agent with the parent's context) writes every
line of the parent's rollout into its own first, token_count events too,
stamped at the fork's time (codex-rs 0.117 record_initial_history,
InitialHistory::Forked). Each copied checkpoint was booked as a call on
the fork's day. The fork's session_meta has forked_from_id. The parent's
rollout is found in the same Codex home: the UUIDv7 day of its id ±1
day, then every day, then archived_sessions. Its checkpoints, {total,
last}, are read once (8 parents kept), and a fork's checkpoint found among
them only advances the running total, on Usage (calls) and Sessions
(stats) both. A parent not found leaves the fork read as before.

callParseVersions and parseVersions raise codex and zcode to 1, so their
kept parses are read again once. The version tests (call_versions,
parse_versions, cache_decode) now hold the versions at none raised: they
test the mechanism, not the current numbers.

docs/subsystems/gateway-sessions.md says all of this. Filed #5072:
OpenCode's fork copies the same way and names no original, so it is
still counted twice.

Run at this head on mote (mote-run):
- gofmt -l internal: empty
- GOOS=linux go vet -tags nogui ./... ; GOOS=windows go vet ./... : ok
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage
  ./internal/tune ./internal/otlp ./internal/davsync ./internal/tui : ok
- go test -run 'Session|Usage|Calls|Ledger|Stats|ZCode|Codex'
  ./internal/gui ./internal/cli : ok

Broken by hand:
- zcDB.copied returning false: TestZCodeCopiesCountedOnce red. msg_c1 and
  msg_d1 were counted as calls, and the Sessions page's 10-31 read
  {1200 300 1800} for {400 100 600}.
- the copied() check in count() off: TestCodexForkCountsOnlyItsOwnCalls
  red. 4 calls on the fork, {87984 5950 268416} for {45744 3550 179584}.

Not tried:
- a real ZCode database or side chat. There is none on this machine.
  The copy shape was read from ZCode 3.17.2's zcode.cjs (gce).
- a real forked Codex rollout or one from 2026-03. ~/.codex/sessions here
  spans 2026-07 to 11 and has no forks. The fixtures follow codex-rs
  0.117's writer. Whether Sky's 5.1B week is all fork copies is not
  known; a cumulative count read as per-turn in an older format was not
  found in that source.
- newer rollouts' token_usage_record copies in a fork, and a parent in
  another Codex home (WSL, CODEX_HOME).
- the whole gui and gateway suites. Another session's suite was running
  on mote; gui and cli ran only the tests above.
2026-11-03 19:13:00 +08:00

160 lines
4.8 KiB
Go

package sessions
import (
"bytes"
"encoding/hex"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// A Codex fork (the CLI's /fork, the app's fork, a spawn_agent with the
// parent's context) starts a rollout of its own and writes every item of
// its parent's into it first, token_count events included, as they were
// (codex-rs record_initial_history, InitialHistory::Forked). Each copied
// line is stamped when the fork wrote it, so a copied checkpoint is the
// parent's call again, at the fork's time, and read as one it counted the
// parent's whole history a second time on the day of the fork (Sky,
// skyhuang1994: a week of 5.1B gpt-5.4 tokens where the machine had spent
// ~0.27B). The fork's own session_meta names the parent (forked_from_id),
// and a checkpoint the parent's rollout holds, its running total and its
// last call alike, is a copy: the parent's file counts it. A fork of a fork
// holds its grandparent's lines through its parent's file, which holds
// them too. When the parent's rollout can't be found or read, the fork's
// lines are read as before.
// cxCheckpoint is a token_count event's two counters, as written.
type cxCheckpoint struct{ Total, Last cxUsage }
// forkedFrom notes, from the first session_meta of the rollout at path,
// the parent the rollout was forked from, and reads that parent's
// checkpoints.
func (s *codexUsageState) forkedFrom(path, parent string) {
if parent == "" || path == "" {
return
}
if p := codexRolloutOf(path, parent); p != "" {
s.Copied = codexCheckpointsOf(p)
}
}
// copied says whether a checkpoint is one of the parent's, copied in.
func (s *codexUsageState) copied(total, last *cxUsage) bool {
if len(s.Copied) == 0 || total == nil || last == nil {
return false
}
return s.Copied[cxCheckpoint{*total, *last}]
}
// codexForks keeps the checkpoints of the parents last read, by path,
// size and time: forks a spawn_agent makes are of one parent, often many
// at a time.
var codexForks struct {
sync.Mutex
kept []codexForkParent
}
type codexForkParent struct {
path string
size int64
mod time.Time
marks map[cxCheckpoint]bool
}
const codexForksKept = 8
// codexCheckpointsOf are the token_count checkpoints of the rollout at
// path; nil when it can't be read whole.
func codexCheckpointsOf(path string) map[cxCheckpoint]bool {
fi, err := os.Stat(path)
if err != nil {
return nil
}
codexForks.Lock()
for _, k := range codexForks.kept {
if k.path == path && k.size == fi.Size() && k.mod.Equal(fi.ModTime()) {
codexForks.Unlock()
return k.marks
}
}
codexForks.Unlock()
marks := map[cxCheckpoint]bool{}
err = eachLine(path, func(b []byte) {
h := b[:min(len(b), 1024)]
if typeAfter(h, cxType) != "event_msg" || typeAfter(h, cxPayload) != "token_count" || bytes.Contains(h, cxInfo) {
return
}
total, ok := cxUsageIn(b, cxTotal)
if !ok {
return
}
if last, ok := cxUsageIn(b, cxLast); ok {
marks[cxCheckpoint{*total, *last}] = true
}
})
if err != nil {
return nil
}
codexForks.Lock()
codexForks.kept = append(codexForks.kept, codexForkParent{path, fi.Size(), fi.ModTime(), marks})
if n := len(codexForks.kept); n > codexForksKept {
codexForks.kept = append([]codexForkParent(nil), codexForks.kept[n-codexForksKept:]...)
}
codexForks.Unlock()
return marks
}
// codexRolloutOf is the rollout of thread id in the Codex folder that
// holds the rollout at path, "" when there is none. Codex files a rollout
// under sessions/YYYY/MM/DD, the local day it began, and a thread id is a
// UUIDv7, which carries that time: the days around it are looked in
// first, then every day, then archived_sessions.
func codexRolloutOf(path, id string) string {
home := codexHomeOf(path)
if home == "" || strings.ContainsAny(id, `/\*?[`) {
return ""
}
name := "rollout-*-" + id + "*.jsonl*"
match := func(pattern string) string {
found, _ := filepath.Glob(pattern)
for _, p := range found {
if m := rolloutName.FindStringSubmatch(filepath.Base(p)); m != nil && m[1] == id && p != path {
return p
}
}
return ""
}
sessions := filepath.Join(home, "sessions")
if at, ok := uuidV7Time(id); ok {
for _, d := range []int{0, -1, 1} {
day := at.AddDate(0, 0, d).Local()
if p := match(filepath.Join(sessions, day.Format("2006"), day.Format("01"), day.Format("02"), name)); p != "" {
return p
}
}
}
if p := match(filepath.Join(sessions, "*", "*", "*", name)); p != "" {
return p
}
return match(filepath.Join(home, "archived_sessions", name))
}
// uuidV7Time is the time a UUIDv7 was made, its first 48 bits.
func uuidV7Time(id string) (time.Time, bool) {
h := strings.ReplaceAll(id, "-", "")
if len(h) != 32 || h[12] != '7' {
return time.Time{}, false
}
b, err := hex.DecodeString(h[:12])
if err != nil {
return time.Time{}, false
}
var ms int64
for _, c := range b {
ms = ms<<8 | int64(c)
}
return time.UnixMilli(ms), true
}