Commit Graph
5 Commits
Author SHA1 Message Date
yetone fb1f4856a8 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.
2026-11-03 20:21:17 +08:00
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
yetone ec15f87393 sessions: a Codex Desktop fork's replayed parent checkpoints book no usage, so a thread_spawn session isn't counted ~1000x (#2234, zlxdengtianhei)
A token_count event that can't be paired with a response record fell
back to the cumulative total's delta whenever a previous total existed,
even when the event's own last_token_usage was there. A Codex Desktop
subagent fork (thread_spawn) writes two cumulative counters into one
rollout: its parent's, replayed with last=0, and its own. Each switch
from the fork's lower counter back up to the parent's booked the gap,
tens of millions of tokens, as one call. The reporter's day read 187.4B
tokens where ~10.3B was real.

last_token_usage is the request's own usage, exact even when zero, so it
is used whenever it is valid; only a missing or invalid last falls back
to the delta, and with no previous total to the total itself, as before.

Run:
- TestCodexUsageForkReplayCountsOnlyLast (new), on the reporter's own five
  lines (testdata/codex-fork-replay-checkpoints.jsonl, numbers untouched),
  checking both Calls and the session summary. Old code: FAIL "calls
  booked {Input:832145 Output:281374 CacheRead:82834688 ...}, want
  {Input:3273 Output:1201 CacheRead:72448 ...}". New: PASS, on macOS and
  on the Windows box with every TestCodex* test.
- TestCodexUsageUnpairedCountKeepsLegacyDelta and the other Codex usage
  tests still pass; go test -tags nogui ./... on macOS with this series:
  every package ok.
- gofmt -l, go vet ./... on darwin, linux (nogui) and windows: clean.

Not run: a reindex of the reporter's full dataset; the numbers above are
from their excerpt.
2026-10-15 03:34:58 +08:00
Hogee 644f4316f9 sessions, usage, gui: separate Codex thread relationships and consumption (#1591)
Preserve native Codex thread IDs and explicit parent chains. Associate gateway
calls with their actual thread by unique response ID before legacy matching;
fold identical native history copies and keep ambiguous actors unknown.

Existing Sessions APIs expose optional Codex roles, parent/root relationships
and per-thread model/effort consumption. The overview uses its existing calendar
range. Usage request APIs expose query-time actor classification and reuse
session/subagent/parent_agent for Codex. Other agents, pricing, gateway routing,
UI assets, raw Usage logs and model-only aggregation retain their semantics.

Verified after rebasing onto main 331c27703a,
at commit 50baace0a52953263dddc49f4dc55f97a8457dd1, code tree
78743e334f8c841e2a188aafe26996c016a8fa4b. Only this message is amended afterward.
Go 1.26.8 darwin/arm64; tests used temporary HOME and pinned Go caches.

Passed (each exit 0):
- git diff --name-only origin/main...HEAD -- '*.go' | xargs gofmt -l (no output)
- go vet ./...
- GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go vet -tags nogui ./...
- GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go vet ./...
- go build -o /tmp/magpie-codex-session-identity-p4-darwin
- GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -tags nogui -o /tmp/magpie-codex-session-identity-p4-linux
- GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -o /tmp/magpie-codex-session-identity-p4-windows.exe
- go test -tags nogui ./...
- go test -race -tags nogui ./internal/sessions ./internal/usage ./internal/gui -run '^(TestCodexIdentityParentChainsAndSummaryCache|TestCodexIdentityParentMergeAcrossRolloutFiles|TestCodexCallThreadIDPriorityAndCache|TestCodexCompactionPromotesThreadID|TestCodexSourceNativeVariants|TestCodexIdentityFieldsOmitOtherAgents|TestCodexIdentityInvalidatesOldSummaryCache|TestCodexLedgerResponseIdentityAndOwnConsumption|TestCodexRequestPageFoldsCopiesBeforeResponseMatching|TestCodexExactResponsePairPreemptsLegacyMatchInLedgerAndDirect|TestCodexQueryPageExactResponsePairPreemptsLegacyMatch|TestCodexRejectedGatewayDoesNotPairWithNativeCall|TestCodexKnownSubagentWithUnknownRootKeepsOwnConsumption|TestCodexQueryPageRefreshesIdentityAndSharesJSONFields|TestCodexActorSurvivesPackedRequestChunk|TestPackedRequestPageCallerAndRouteIdentity|TestPackedGatewayRetainsOversizedSnapshot|TestCodexSessionAPIAddsOwnModelEffort)$' -count=1
- git diff --check

Behavior-break proof: removing identity/thread-ID promotion fails native identity,
upgrade/conflict and compaction assertions. Disabling exact-pair preemption loses
a neighboring main call. Removing API enrichment yields missing consumption;
using All for a 7-day overview yields 740/74 instead of 40/4. Restored code passed
its targeted tests and the final checks above.

Native checks had Clang enum/linker deployment-target warnings.
Linux/Windows runtime, real accounts/vendors and manual UI were not exercised.
No frontend suite was run because the change does not touch GUI assets.

Refs #1591 (Codex portion only).

Reviewed and applied by yetone (cherry-picked from Hogeexxl's fork, bf8c8c9e).
The one conflict was call_cache.go's version: main had taken calls-v13 for
compaction times (e1dcd1e1d), so this is calls-v14. Run with the follow-up
commit on top, at tree 122b933ba4c474e443f2b29c6d0a4163ae364f78 on origin/main e5cd125f0 (Go 1.26.8
darwin/arm64, sandbox HOME, private GOCACHE):
- gofmt -l on the changed files: none
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...
- the darwin, linux (nogui) and windows builds
- go test -tags nogui -timeout 40m ./...: all ok
- go test -race -tags nogui -run 'Codex|Packed|QueryPage|RequestPage'
  ./internal/sessions ./internal/usage ./internal/gui: ok
Broken by hand, each red: codexIdentityRow not setting Subagent (8 usage
tests), setting it for a main thread too (2), Session kept raw instead of
the root (7), thread_spawn's parent_thread_id not read (3 sessions tests),
response pairs not reserved before the old matching (6).
Not tried: a real Codex subagent rollout (none on this machine; every
recent rollout is a vscode main thread whose session_id equals its id),
and the GUI by hand. Claude Code's fields are unchanged.
2026-10-14 22:45:40 +08:00
Fanbuz 67004a7e8f sessions: count Codex RECORD and compaction usage without a history parent (#695)
* fix: 按本地事件配对统计 Codex 响应与压缩用量

* fix: 限制用量索引内存并精简磁盘缓存

* fix: 淘汰解析索引后仍释放请求行缓存
2026-10-04 07:57:49 +08:00