sessions: a fork's own calls are counted; only its copies are the parent's (ZCode, Codex)

Sky (skyhuang1994) on Discord, on their real ZCode database after
v0.1.2847 (1d0fc2bb0): September's message table holds 57,787 rows,
13.552B tokens; 5,204 rows (1.537B) carry a forkOrigin and are copies,
and ZCode's cloud usage says 12.057B. The new version took 5.094B out,
3.6B of it real. The biggest was the "msc" session: forked at the end of
August, then 11,409 calls of its own in September (3.489B), none with a
forkOrigin, a custom-UUID provider. The Usage page had 0 of them.

Cause (ZCode): readZCodeCalls marked copies in a map keyed by m.ID. A
row's id is in the message table's id column, not in its data (OpenCode
writes data without id; checked on this machine's real opencode.db: 2 of 2
rows have no $.id), so every message decodes with ID "". One copy in a
session set copies[""], and every assistant message of that session was
left out: a fork that went on working lost all of its own calls. The test
fixtures had "id" inside data, so they never saw it. The Sessions page
(parseOpenCode) asks zcDB.copied per message and was right.
Fix: copies are marked by row index. Only a message whose forkOrigin
names a messageId still in the database is skipped.

Codex: a fork's checkpoint was a copy whenever its {total, last} was one
the parent's rollout holds, anywhere in the fork. A fork goes on working,
and its first own call can carry exactly the numbers of the parent's
next call after the fork (same history, same next prompt). The copies
are now the head of the fork only: the fork's first turn_id the parent
never had (turn_context or task_started) ends them (ownTurn,
CopiedTurns, read with the parent's checkpoints). A rollout with no turn
ids is matched as before; its running total keeps later calls apart.

callParseVersions codex 2, zcode 2 and parseVersions codex 2, so the
parses kept by v0.1.2847 are read again once. ZCode's Sessions parse
didn't change and stays at 1.

Tests (fixtures follow Sky's case: a parent of 08-30, a fork with
forkOrigin copies of its replies, ZCode's fork notice, then 40 replies of
its own in September with no forkOrigin, no id in data, provider a UUID):
- TestZCodeForkThatWentOnWorkingKeepsItsOwnCalls: red on origin/main
  7d022bdb6 ("the fork's calls: 0 {...}, want its 40 own"), as Sky saw.
- TestCodexForkThatWentOnWorkingKeepsItsOwnCalls: red on main and with
  ownTurn turned off by hand (1 call on the fork, want its 2 own).

docs/subsystems/gateway-sessions.md says this.

Run on mote (mote-run) at this change on origin/main 7d022bdb6; rebased
on 08d7bfaaa (gui, redact, gateway-key only), go build ./... and
internal/sessions run again: ok.
- 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|Fork'
  ./internal/gui ./internal/cli : ok

Broken by hand:
- the copies keyed by message id again (origin/main): the ZCode test red,
  0 calls on the fork.
- ownTurn's call in context() off: the Codex test red, 1 call on the fork.

Not tried:
- Sky's real ZCode database; there is none on this machine and no ZCode
  source to read its writer. That ZCode's data has no id, as OpenCode's,
  rests on the symptom (every row of the fork gone) and OpenCode's real
  rows here.
- a real forked Codex rollout that went on working; the turn ids of a
  real 0.117 fork were read from the fixtures' shape, not a real file.
- the whole gui and gateway suites, and a full go test ./...: other
  sessions' suites were running on mote.
This commit is contained in:
yetone
2026-11-03 20:21:17 +08:00
parent 08d7bfaaa5
commit fb1f4856a8
8 changed files with 231 additions and 22 deletions
+15 -4
View File
@@ -581,7 +581,11 @@ first, token_count events included, stamped at the fork's time; its
session_meta names the parent (`forked_from_id`), and a checkpoint the
parent's rollout holds (its total and last call alike) is the parent's,
on Usage and Sessions both (`codexRolloutOf`, `codexCheckpointsOf` in
[`codex_fork.go`](../../internal/sessions/codex_fork.go)). The parent is
[`codex_fork.go`](../../internal/sessions/codex_fork.go)). The copies
are the head of the fork only: its first turn the parent never had (a
`turn_id` of its own) ends them, so a call of the fork's own is counted
even when its numbers are those of one the parent made after the fork.
The parent is
looked for in the same Codex home, by the UUIDv7 day of its id, then
every day, then `archived_sessions`; one not found leaves the fork read
as before. A ZCode side chat, fork or restored checkpoint copies its
@@ -589,11 +593,18 @@ session's messages with new ids and the originals' times and tokens,
each naming its original in `metadata.forkOrigin.messageId`; a copy
whose original is still in the database is not counted (`zcDB.copied`
in [`zcode.go`](../../internal/sessions/zcode.go)), one whose original
is gone is. Both came from Sky (skyhuang1994): a ZCode side chat put a
is gone is. The message without a `forkOrigin` is the session's own and
is counted: copies are marked by row, since a row's id is in its own
column and not in its data (v0.1.2847 marked them by that empty id and
left out every call of a fork that held one copy). Both came from Sky
(skyhuang1994): a ZCode side chat put a
10-31 session's 0.42B tokens on 10-31 again, and a week of gpt-5.4 read
5.1B tokens. Verification: `TestCodexForkCountsOnlyItsOwnCalls`,
5.1B tokens; then a ZCode fork's 11,409 calls of its own (3.49B tokens)
went missing. Verification: `TestCodexForkCountsOnlyItsOwnCalls`,
`TestCodexForkWithoutItsParentCountsTheCopies`,
`TestZCodeCopiesCountedOnce`. OpenCode's fork copies the same way with
`TestCodexForkThatWentOnWorkingKeepsItsOwnCalls`,
`TestZCodeCopiesCountedOnce`,
`TestZCodeForkThatWentOnWorkingKeepsItsOwnCalls`. OpenCode's fork copies the same way with
no pointer to the original, and is still counted twice (#5072).
The other agents the Sessions page reads (Cline,
Qoder, Grok, Droid, Cursor, Hermes, Alma) have no reader yet (#1607). The
+3 -1
View File
@@ -62,7 +62,9 @@ const callCacheVersion = "calls-v15"
// the gateway's, and left out (cindyGatewayProvider).
// codex 1, zcode 1: a fork's copies of its parent's calls are the
// parent's (codex_fork.go, zcDB.copied).
var callParseVersions = map[string]int{"cindy": 1, "codex": 1, "zcode": 1}
// codex 2, zcode 2: only the copies are; a fork's own calls are its own
// (zcode 1 left out every call of a session holding one copy).
var callParseVersions = map[string]int{"cindy": 1, "codex": 2, "zcode": 2}
// CallCacheVersion is callCacheVersion and callParseVersions, for a cache
// of what is made of the calls (usage's requests-v1.bin and heatmap): a
+11 -6
View File
@@ -74,7 +74,7 @@ func readZCodeCalls(f file) (*callFile, bool) {
path, sid := f.path[:i], f.path[i+1:]
var info ocInfo
var msgs [][]byte
copies := map[string]bool{}
var copies []bool
if !withOCCallDB(path, func(db *sql.DB) {
var store ocStore = zcDB{ocDB{db}}
if ocHasTable(db, "session_v2") {
@@ -86,12 +86,17 @@ func readZCodeCalls(f file) (*callFile, bool) {
info, _ = store.info(sid)
msgs = store.messages(sid)
// a copy of a message still in the database (zcDB.copied): the
// original's session counts its call
// original's session counts its call. Marked by row, not by id: a
// row's id is in its own column and not in its data, so every
// message here reads with an empty ID, and one copy marked by id
// left out the whole session, a fork's own replies too (Sky,
// skyhuang1994: a fork's 11,409 calls of its own, 3.49B tokens).
copies = make([]bool, len(msgs))
if z, ok := store.(zcDB); ok {
for _, b := range msgs {
for i, b := range msgs {
var m ocMessage
if json.Unmarshal(b, &m) == nil && m.Role == "assistant" && z.copied(m) {
copies[m.ID] = true
copies[i] = true
}
}
}
@@ -101,9 +106,9 @@ func readZCodeCalls(f file) (*callFile, bool) {
if st.Session == "" {
st.Session = info.ID
}
for _, b := range msgs {
for i, b := range msgs {
var m ocMessage
if json.Unmarshal(b, &m) != nil || m.Role != "assistant" || ocGatewayProvider(m.ProviderID) || copies[m.ID] {
if json.Unmarshal(b, &m) != nil || m.Role != "assistant" || ocGatewayProvider(m.ProviderID) || copies[i] {
continue
}
if c, ok := ocCall(st, m, info.Directory); ok {
+43 -9
View File
@@ -3,6 +3,7 @@ package sessions
import (
"bytes"
"encoding/hex"
"encoding/json"
"os"
"path/filepath"
"strings"
@@ -24,6 +25,14 @@ import (
// 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.
//
// The copies are the head of the fork's rollout and nothing after it: a
// fork goes on working, and its own calls are its own whatever their
// numbers (Sky, skyhuang1994: forks that went on working lost their own
// usage). The fork's first turn the parent never had, a turn_id of its
// own, ends the copies. A rollout with no turn ids is matched by
// checkpoint alone: its running total, which a fork's own call moves past
// the parent's, keeps a later call of either from matching.
// cxCheckpoint is a token_count event's two counters, as written.
type cxCheckpoint struct{ Total, Last cxUsage }
@@ -36,7 +45,14 @@ func (s *codexUsageState) forkedFrom(path, parent string) {
return
}
if p := codexRolloutOf(path, parent); p != "" {
s.Copied = codexCheckpointsOf(p)
s.Copied, s.CopiedTurns = codexCheckpointsOf(p)
}
}
// ownTurn ends the copies at a turn of the fork's own.
func (s *codexUsageState) ownTurn(turn string) {
if turn != "" && s.Copied != nil && s.CopiedTurns != nil && !s.CopiedTurns[turn] {
s.Copied, s.CopiedTurns = nil, nil
}
}
@@ -61,29 +77,47 @@ type codexForkParent struct {
size int64
mod time.Time
marks map[cxCheckpoint]bool
turns map[string]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 {
// path, and its turn ids (nil when it names none); nil when it can't be
// read whole.
func codexCheckpointsOf(path string) (map[cxCheckpoint]bool, map[string]bool) {
fi, err := os.Stat(path)
if err != nil {
return nil
return nil, 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
return k.marks, k.turns
}
}
codexForks.Unlock()
marks := map[cxCheckpoint]bool{}
var turns map[string]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) {
top, payload := typeAfter(h, cxType), typeAfter(h, cxPayload)
if top == "turn_context" || top == "event_msg" && payload == "task_started" {
var l struct {
Payload struct {
TurnID string `json:"turn_id"`
} `json:"payload"`
}
if json.Unmarshal(b, &l) == nil && l.Payload.TurnID != "" {
if turns == nil {
turns = map[string]bool{}
}
turns[l.Payload.TurnID] = true
}
return
}
if top != "event_msg" || payload != "token_count" || bytes.Contains(h, cxInfo) {
return
}
total, ok := cxUsageIn(b, cxTotal)
@@ -95,15 +129,15 @@ func codexCheckpointsOf(path string) map[cxCheckpoint]bool {
}
})
if err != nil {
return nil
return nil, nil
}
codexForks.Lock()
codexForks.kept = append(codexForks.kept, codexForkParent{path, fi.Size(), fi.ModTime(), marks})
codexForks.kept = append(codexForks.kept, codexForkParent{path, fi.Size(), fi.ModTime(), marks, turns})
if n := len(codexForks.kept); n > codexForksKept {
codexForks.kept = append([]codexForkParent(nil), codexForks.kept[n-codexForksKept:]...)
}
codexForks.Unlock()
return marks
return marks, turns
}
// codexRolloutOf is the rollout of thread id in the Codex folder that
+65
View File
@@ -89,3 +89,68 @@ func TestUUIDV7Time(t *testing.T) {
t.Fatal("a v4 id has no time")
}
}
// A fork that went on working: its calls after the copies are its own,
// even one whose numbers are those of a call its parent made after the
// fork (both given the same next prompt over the same history). Only the
// copied lines at the head of the fork are the parent's (Sky,
// skyhuang1994: forks that went on working lost their own usage on
// ZCode; this is Codex's side of it).
func TestCodexForkThatWentOnWorkingKeepsItsOwnCalls(t *testing.T) {
d := setupCalls(t)
const parent, fork = "019d186b-a100-7aaa-8bbb-cccdddeeefff", "019d1f2d-f9c0-7111-8222-333444555666"
read := func(name string) []string {
b, err := os.ReadFile(filepath.Join("testdata", name))
if err != nil {
t.Fatal(err)
}
return strings.Split(strings.TrimSpace(string(b)), "\n")
}
p, c := read("codex-fork-parent.jsonl"), read("codex-fork-child.jsonl")
// the fork's own first call: the parent's call after the fork, number
// for number, at the fork's time; then a second call of its own
same := strings.Replace(p[12], `"timestamp":"2026-03-24T10:00:20.000Z"`, `"timestamp":"2026-03-24T09:30:12.000Z"`, 1)
if same == p[12] || !strings.Contains(c[14], `"type":"token_count"`) {
t.Fatal("the fixtures changed")
}
c[14] = same
next := strings.NewReplacer(
`"timestamp":"2026-03-24T10:00:20.000Z"`, `"timestamp":"2026-03-24T09:40:00.000Z"`,
`{"input_tokens":178000,"cached_input_tokens":134912,"output_tokens":3000,"reasoning_output_tokens":600,"total_tokens":181000}`,
`{"input_tokens":228000,"cached_input_tokens":174912,"output_tokens":3400,"reasoning_output_tokens":650,"total_tokens":231400}`,
`{"input_tokens":46928,"cached_input_tokens":46080,"output_tokens":600,"reasoning_output_tokens":88,"total_tokens":47528}`,
`{"input_tokens":50000,"cached_input_tokens":40000,"output_tokens":400,"reasoning_output_tokens":50,"total_tokens":50400}`,
).Replace(p[12])
c = append(c, next)
writeLines(t, filepath.Join(d.codex, "sessions", "2026", "03", "23", "rollout-2026-03-23T10-00-00-"+parent+".jsonl"), strings.Join(p, "\n"))
writeLines(t, filepath.Join(d.codex, "sessions", "2026", "03", "24", "rollout-2026-03-24T17-30-00-"+fork+".jsonl"), strings.Join(c, "\n"))
call := func(in, cached, out int) Tokens { return Tokens{Input: in - cached, CacheRead: cached, Output: out} }
wantFork := call(46928, 46080, 600)
wantFork.add(call(50000, 40000, 400))
var onFork, all, want Tokens
n := 0
for _, x := range Calls(time.Time{}) {
all.add(x.Tokens)
if strings.Contains(x.File, fork) {
onFork.add(x.Tokens)
n++
}
}
if n != 2 || onFork != wantFork {
t.Fatalf("the fork's calls: %d %+v, want its 2 own %+v", n, onFork, wantFork)
}
for _, v := range []Tokens{call(41200, 3072, 812), call(43680, 41088, 688), call(46192, 44672, 900), call(46928, 46080, 600), wantFork} {
want.add(v)
}
if all != want {
t.Fatalf("calls booked %+v, want %+v", all, want)
}
var listed Tokens
for _, s := range List(0) {
listed.add(s.Tokens)
}
if listed != want {
t.Fatalf("sessions booked %+v, want %+v", listed, want)
}
}
+5 -1
View File
@@ -32,8 +32,11 @@ type codexUsageState struct {
SnapshotTotal *cxUsage
SnapshotOffset *cxUsage
// Copied are the checkpoints of the rollout this one was forked from,
// which it holds copies of (codex_fork.go); never written to after.
// which it holds copies of (codex_fork.go), until the fork's first turn
// of its own; the map is never written to after it is read.
Copied map[cxCheckpoint]bool
// CopiedTurns are that rollout's turn ids, nil when it names none.
CopiedTurns map[string]bool
}
// A paginated subagent starts with a restored compaction and a zero-last
@@ -322,6 +325,7 @@ func (s *codexUsageState) model(turn, fallback string) string {
}
func (s *codexUsageState) context(session, turn, model string) {
s.ownTurn(turn)
if turn != "" && turn != s.Turn {
s.Pending = 0
}
+4 -1
View File
@@ -1120,7 +1120,10 @@ const cacheVersion = 29
//
// codex 1, zcode 1: a fork's copies of its parent's usage are the
// parent's (codex_fork.go, zcDB.copied).
var parseVersions = map[string]int{"codex": 1, "zcode": 1}
//
// codex 2: only a fork's copies are; its own calls after them are its own,
// whatever their numbers.
var parseVersions = map[string]int{"codex": 2, "zcode": 1}
type cacheFile struct {
Version int `json:"version"`
+85
View File
@@ -101,3 +101,88 @@ func TestZCodeCopiesCountedOnce(t *testing.T) {
}
}
}
// A fork that went on working: ZCode copied an August session's replies
// into it, then it made calls of its own through September. ZCode keeps a
// message's id in its row, not in its data, as OpenCode does, so the rows
// here carry none in data; the provider is a custom one, named by a UUID.
// Only the copies are the parent's. Every reply of the fork's own is a
// call (Sky, skyhuang1994: the "msc" fork's 11,409 September calls, 3.49B
// tokens, none with a forkOrigin, went missing from the Usage page once
// the fork held one copy).
func TestZCodeForkThatWentOnWorkingKeepsItsOwnCalls(t *testing.T) {
inZone(t, 0)
home := setupAgents(t)
db, err := sql.Open("sqlite", filepath.Join(home, ".zcode", "cli", "db", "db.sqlite"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
const provider = "6f1c2b9e-4a7d-4c1e-9b2a-3d5e8f0a1b2c"
at := func(m time.Month, d, h, min int) int64 {
return time.Date(2026, m, d, h, min, 0, 0, time.UTC).UnixMilli()
}
for _, s := range []struct {
id string
at int64
}{{"ses_aug", at(8, 30, 0, 0)}, {"ses_msc", at(9, 1, 0, 0)}} {
if _, err := db.Exec("INSERT INTO session (id, project_id, parent_id, slug, directory, title, title_source, version, time_created, time_updated) VALUES (?, 'p', NULL, 's', '/work/msc', ?, 'ai', '3.17.2', ?, ?)",
s.id, s.id, s.at, s.at); err != nil {
t.Fatal(err)
}
}
reply := func(created int64, in, out, read int, meta string) string {
return fmt.Sprintf(`{"role":"assistant","parentID":"msg_u","modelId":"glm-5.3","providerID":%q,"tokens":{"total":%d,"input":%d,"output":%d,"reasoning":0,"cache":{"read":%d,"write":0}},"time":{"created":%d,"completed":%d}%s}`,
provider, in+out, in, out, read, created, created+30000, meta)
}
// the parent's two replies on 08-30, and their copies in the fork
for i := range 2 {
c := at(8, 30, 1, i)
ocInsert(t, db, "ses_aug", fmt.Sprintf("msg_a%d", i), c, c+30000, reply(c, 1000, 100, 600, ""))
ocInsert(t, db, "ses_msc", fmt.Sprintf("msg_k%d", i), c, c+30000,
reply(c, 1000, 100, 600, fmt.Sprintf(`,"metadata":{"forkOrigin":{"sessionId":"ses_aug","messageId":"msg_a%d"}}`, i)))
}
// ZCode's notice of the fork
ocInsert(t, db, "ses_msc", "msg_kn", at(9, 1, 0, 0), at(9, 1, 0, 0),
fmt.Sprintf(`{"role":"assistant","time":{"created":%d},"metadata":{"forkOrigin":{"parentSessionId":"ses_aug","targetMessageId":"msg_a1"}}}`, at(9, 1, 0, 0)))
// the fork's own work in September: no forkOrigin
const own = 40
for i := range own {
c := at(9, 2+i%20, 10, i)
ocInsert(t, db, "ses_msc", fmt.Sprintf("msg_w%02d", i), c, c+30000, reply(c, 500, 50, 200, ""))
}
bySession := map[string]Tokens{}
n := map[string]int{}
for _, c := range Calls(time.Time{}) {
if c.Agent == "zcode" {
v := bySession[c.Session]
v.add(c.Tokens)
bySession[c.Session] = v
n[c.Session]++
}
}
var wantOwn Tokens
for range own {
wantOwn.add(Tokens{300, 50, 200, 0, 0})
}
if n["ses_msc"] != own || bySession["ses_msc"] != wantOwn {
t.Errorf("the fork's calls: %d %+v, want its %d own %+v", n["ses_msc"], bySession["ses_msc"], own, wantOwn)
}
if n["ses_aug"] != 2 || bySession["ses_aug"] != (Tokens{800, 200, 1200, 0, 0}) {
t.Errorf("the parent's calls: %d %+v", n["ses_aug"], bySession["ses_aug"])
}
s := statsAt(0, time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC))
if got, _ := usageOn(s, "2026-08-30", "/work/msc"); got != (Tokens{800, 200, 1200, 0, 0}) {
t.Errorf("the Sessions page's 08-30: %+v, want the parent's alone", got)
}
var sept Tokens
for d := 2; d <= 21; d++ {
got, _ := usageOn(s, fmt.Sprintf("2026-09-%02d", d), "/work/msc")
sept.add(got)
}
if sept != wantOwn {
t.Errorf("the Sessions page's September: %+v, want %+v", sept, wantOwn)
}
}