From 667a81dabc94eed5e39852aff2e84173e4879e26 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Thu, 15 Oct 2026 18:13:49 -0400 Subject: [PATCH 1/9] refactor(codex): read native child usage from rollouts A Codex child is a separate thread: its tokens never reach the parent's exec --json stream and live only in the child's rollout. This adds the read and the fold, called by nothing yet: codexChildUsageReadCommand (one bounded in-sandbox command, ids validated and shell-quoted), parseCodexChildUsage (the first turn_context, the last token_count), codexChildIDs (the completed spawn_agent receivers off a tee of the stream) and foldCodexChildUsage (the parent's entry first and always, one request per child thread with usage, child reasoning to the run total only), plus delegating() on the runner-held digest set. Fixtures: four child rollouts modelled on the 0.157.0 paid probe and one stream with completed and failed spawns. Signed-off-by: Dharit Shah --- internal/runtime/codex_integrity.go | 4 + internal/runtime/codex_subagents.go | 286 +++++++++++ internal/runtime/codex_subagents_test.go | 479 ++++++++++++++++++ internal/runtime/testdata/codex/README.md | 21 + .../testdata/codex/child_usage_failed.jsonl | 5 + .../testdata/codex/child_usage_no_model.jsonl | 2 + .../codex/child_usage_other_model.jsonl | 6 + .../codex/child_usage_same_model.jsonl | 7 + .../testdata/codex/collab_spawn.ndjson | 14 + 9 files changed, 824 insertions(+) create mode 100644 internal/runtime/codex_subagents.go create mode 100644 internal/runtime/codex_subagents_test.go create mode 100644 internal/runtime/testdata/codex/child_usage_failed.jsonl create mode 100644 internal/runtime/testdata/codex/child_usage_no_model.jsonl create mode 100644 internal/runtime/testdata/codex/child_usage_other_model.jsonl create mode 100644 internal/runtime/testdata/codex/child_usage_same_model.jsonl create mode 100644 internal/runtime/testdata/codex/collab_spawn.ndjson diff --git a/internal/runtime/codex_integrity.go b/internal/runtime/codex_integrity.go index eec64b7488..7b8b3616b9 100644 --- a/internal/runtime/codex_integrity.go +++ b/internal/runtime/codex_integrity.go @@ -78,6 +78,10 @@ type codexRunnerHeldDigestSet struct { RoleFiles map[string]string } +// delegating reports whether Bootstrap registered native sub-agent roles for +// this run. It reads the runner-held record, never the manifest. +func (d codexRunnerHeldDigestSet) delegating() bool { return len(d.RoleFiles) > 0 } + // codexEnvPair is one runner-owned environment assignment. type codexEnvPair struct { Key string diff --git a/internal/runtime/codex_subagents.go b/internal/runtime/codex_subagents.go new file mode 100644 index 0000000000..bcb550b581 --- /dev/null +++ b/internal/runtime/codex_subagents.go @@ -0,0 +1,286 @@ +package runtime + +import ( + "bufio" + "bytes" + "encoding/json" + "fmt" + "regexp" + "slices" + "strings" + "time" + + "github.com/fullsend-ai/fullsend/internal/sandbox" +) + +// Native child accounting for the Codex runtime. +// +// A Codex child is a separate thread. Its tokens never reach the parent's +// `exec --json` stream (turn.completed.usage excludes children — #6970, probe +// of 2026-09-03), and codex records them only in that thread's rollout under +// $CODEX_HOME/sessions/: the running total in `event_msg`/`token_count` +// lines (`info.total_token_usage`, the stream's five usage fields plus +// total_tokens), the model in the `turn_context` line, and the thread id in +// the file name (rollout--.jsonl). Run reads those +// lines back with one bounded command after codex exits and folds them into +// RunMetrics, so metrics.json carries the children (#6970, transcripts and +// usage). +// +// The fold covers the fields a per-model entry has: input, output, +// cache-creation and cache-read tokens, and cost, which is 0 on codex. Child +// reasoning tokens go to the run-level ReasoningTokens only, as on pi: +// RunMetrics has no per-model reasoning field. + +// codexChildUsageMarker starts the line the read command prints before each +// child's rollout lines, so the parser knows where one child's lines end and +// the next child's begin. A rollout line that imitates it can only +// misattribute that child's own lines. +const codexChildUsageMarker = "fullsend-child" + +// codexChildUsageMaxBytes bounds the read. The sessions directory is +// agent-writable, so an unbounded read is an unbounded allocation in the +// runner (the reason piSubagentUsageMaxBytes exists). The command selects at +// most two lines per child, so a real read is a few kilobytes. +const codexChildUsageMaxBytes = 1 << 20 + +// codexChildUsageThreadID is the shape of a codex thread id (UUID text). A +// child id comes off the stream and goes into a shell command, so nothing +// else is accepted; shellQuote wraps it as well. +var codexChildUsageThreadID = regexp.MustCompile(`^[0-9a-f-]{36}$`) + +// codexChildUsage is what one child's rollout reported. +type codexChildUsage struct { + ID string + // Model is turn_context.payload.model of the child's first turn; "" + // when the rollout has no turn_context. + Model string + // Usage is info.total_token_usage of the child's last token_count: the + // thread's cumulative total, so one snapshot is the whole child. + Usage codexUsage + // HasUsage is false for a child that never reported a token_count: it + // errored before its first response (the provider rejected its model in + // the 2026-09-29 paid probe) and contributes nothing, not even a request. + HasUsage bool +} + +// codexChildUsageReadCommand renders the one in-sandbox command that reads +// the children's rollouts. For each id, sorted and once, it finds the +// thread's rollout by name, prints a marker line, then the rollout's first +// turn_context line and its last token_count line. Two greps rather than a +// cat: a review child's rollout is megabytes and the two lines are all the +// fold needs, so the head -c bound is a safety net, not the usual limit. +// `command -p` bypasses shell functions and uses the system PATH, as the +// launch guards do. +func codexChildUsageReadCommand(sessionsDir string, ids []string) (string, error) { + ids = slices.Clone(ids) + slices.Sort(ids) + ids = slices.Compact(ids) + quoted := make([]string, 0, len(ids)) + for _, id := range ids { + if !codexChildUsageThreadID.MatchString(id) { + return "", fmt.Errorf("child thread id %q is not a codex thread id", id) + } + quoted = append(quoted, shellQuote(id)) + } + return fmt.Sprintf( + `for id in %s; do command -p find %s -type f -name "rollout-*-$id.jsonl" 2>/dev/null | while IFS= read -r f; do printf '%%s %%s\n' %s "$id"; command -p grep -a -e '"type":"turn_context"' -- "$f" 2>/dev/null | command -p head -n 1; command -p grep -a -e '"type":"token_count"' -- "$f" 2>/dev/null | command -p tail -n 1; done; done | command -p head -c %d`, + strings.Join(quoted, " "), shellQuote(sessionsDir), shellQuote(codexChildUsageMarker), codexChildUsageMaxBytes), nil +} + +// parseCodexChildUsage decodes the read command's output: a marker line per +// child, then that child's turn_context and token_count lines. A line before +// the first marker belongs to nobody; a line that is not JSON (the head -c +// cut, or something planted in the agent-writable directory) is skipped. +func parseCodexChildUsage(data []byte) []codexChildUsage { + var out []codexChildUsage + marker := []byte(codexChildUsageMarker + " ") + scanner := bufio.NewScanner(bytes.NewReader(data)) + scanner.Buffer(make([]byte, 0, 64*1024), maxTranscriptLineSize) + for scanner.Scan() { + line := bytes.TrimSpace(scanner.Bytes()) + if len(line) == 0 { + continue + } + if id, ok := bytes.CutPrefix(line, marker); ok { + out = append(out, codexChildUsage{ID: string(id)}) + continue + } + if len(out) == 0 { + continue + } + var env struct { + Type string `json:"type"` + Payload struct { + Type string `json:"type"` + Model string `json:"model"` + Info struct { + Total codexUsage `json:"total_token_usage"` + } `json:"info"` + } `json:"payload"` + } + if json.Unmarshal(line, &env) != nil { + continue + } + cur := &out[len(out)-1] + switch { + case env.Type == "turn_context": + if cur.Model == "" { + cur.Model = strings.TrimSpace(env.Payload.Model) + } + case env.Type == "event_msg" && env.Payload.Type == "token_count": + cur.Usage = env.Payload.Info.Total + cur.HasUsage = true + } + } + return out +} + +// codexChildIDs collects the thread ids of the children the parent spawned. +// It is an io.Writer that Run feeds through a tee of the `exec --json` +// stream: the parser's events carry no thread id (ToolUseEvent is a name and +// a summary) and parseCodexStream's signature is shared with pi's, so the +// ids are read here, one line at a time, from the completed spawn_agent +// items (codexCollabToolCallItem). A spawn that failed made no thread. +// +// A final line with no newline is not scanned; in a codex stream the last +// line is the terminal event, never an item. +type codexChildIDs struct { + IDs []string + line []byte + overlong bool +} + +func (c *codexChildIDs) Write(p []byte) (int, error) { + rest := p + for { + i := bytes.IndexByte(rest, '\n') + if i < 0 { + c.take(rest) + return len(p), nil + } + c.take(rest[:i]) + if !c.overlong { + c.scan(c.line) + } + c.line, c.overlong = c.line[:0], false + rest = rest[i+1:] + } +} + +// take appends to the pending line, dropping it once it passes the parser's +// own line bound (streamBufSize): parseCodexStream skips such a line too. +func (c *codexChildIDs) take(b []byte) { + if c.overlong || len(c.line)+len(b) > streamBufSize { + c.overlong = true + c.line = c.line[:0] + return + } + c.line = append(c.line, b...) +} + +func (c *codexChildIDs) scan(line []byte) { + // Cheap pre-filter: almost no line of a stream names the tool. + if !bytes.Contains(line, []byte("spawn_agent")) { + return + } + var evt struct { + Type string `json:"type"` + Item struct { + codexCollabToolCallItem + Type string `json:"type"` + } `json:"item"` + } + if json.Unmarshal(line, &evt) != nil || evt.Type != "item.completed" || evt.Item.Type != "collab_tool_call" || + evt.Item.Tool != "spawn_agent" || evt.Item.Status != "completed" { + return + } + c.IDs = append(c.IDs, evt.Item.ReceiverThreadIDs...) +} + +// foldCodexChildUsage adds the parent's own entry to m.PerModelUsage and, +// when the parent spawned children, reads their rollouts with one bounded +// sandbox command and folds each child's last cumulative usage into the +// totals and the breakdown. It returns how many child threads reported +// usage. An error is a read that did not happen or did not finish; the +// caller reports it and keeps the run, because losing the breakdown must not +// fail an iteration that succeeded. No sandbox command runs when childIDs is +// empty. +// +// The parent's entry is added first and always. Iterations are summed +// (internal/cli aggregateRunMetrics), so an iteration that dispatched +// nothing, or whose read failed, still has to be in the breakdown or the +// run's per_model_usage stops summing to its totals across a retry. +// +// Requests: one for the parent iteration, one per child thread with usage +// (the invocation-count semantics of the pi fold). A child that never +// reported a token_count contributes nothing. A child whose rollout names +// no model is bucketed under piSubagentUnknownModel, as pi does for a +// record without one. Child reasoning tokens go to the run-level total +// only. The figures come from an agent-writable directory, so every counter +// is floored at zero before it is added, as pi's fold clamps its records. +func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, m *RunMetrics) (folded int, err error) { + per := m.PerModelUsage + if per == nil { + per = make(map[string]ModelUsage, len(childIDs)+1) + } + add := func(key string, u ModelUsage) { + entry := per[key] + entry.Add(u) + per[key] = entry + } + parent := m.Model + if parent == "" { + parent = piSubagentUnknownModel + } + add(parent, ModelUsage{ + Requests: 1, + InputTokens: m.InputTokens, + OutputTokens: m.OutputTokens, + CacheCreationInputTokens: m.CacheCreationInputTokens, + CacheReadInputTokens: m.CacheReadInputTokens, + CostUSD: m.TotalCostUSD, + }) + m.PerModelUsage = per + if len(childIDs) == 0 { + return 0, nil + } + + cmd, err := codexChildUsageReadCommand(r.codexSessionsDir(), childIDs) + if err != nil { + return 0, err + } + stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, cmd, 10*time.Second) + if err != nil { + return 0, fmt.Errorf("reading the child rollouts: %w", err) + } + if exitCode != 0 { + return 0, fmt.Errorf("reading the child rollouts: exited %d: %s", exitCode, strings.TrimSpace(sanitizeOutput(stderr))) + } + for _, child := range parseCodexChildUsage([]byte(stdout)) { + if !child.HasUsage { + continue + } + // counters() floors only its two subtractions; the three raw fields + // are floored here. + c := child.Usage.counters() + reasoning, cacheWrite, cacheRead := nonNegative(c.Reasoning), nonNegative(c.CacheWrite), nonNegative(c.CacheRead) + key := child.Model + if key == "" { + key = piSubagentUnknownModel + } + add(key, ModelUsage{ + Requests: 1, + InputTokens: c.Input, + OutputTokens: c.Output, + CacheCreationInputTokens: cacheWrite, + CacheReadInputTokens: cacheRead, + }) + m.InputTokens += c.Input + m.OutputTokens += c.Output + m.ReasoningTokens += reasoning + m.CacheCreationInputTokens += cacheWrite + m.CacheReadInputTokens += cacheRead + folded++ + } + return folded, nil +} diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go new file mode 100644 index 0000000000..4a2a2d8ad7 --- /dev/null +++ b/internal/runtime/codex_subagents_test.go @@ -0,0 +1,479 @@ +package runtime + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The gate Run uses to decide that a delegating agent's breakdown must carry +// the parent's entry even when it spawned nothing. It reads the runner-held +// record only: the manifest is agent-writable and never authority. +func TestCodexRunnerHeldDigestSet_Delegating(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + roles map[string]string + want bool + }{ + {name: "nil map: no role registered", roles: nil, want: false}, + {name: "empty map: no role registered", roles: map[string]string{}, want: false}, + {name: "one role registered", roles: map[string]string{"default": "d0d0"}, want: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + d := codexRunnerHeldDigestSet{ConfigTOML: "cfg", RoleFiles: tt.roles} + assert.Equal(t, tt.want, d.delegating(), "delegating follows the runner-held role set only") + }) + } +} + +// Thread ids of the fixtures (testdata/codex/README.md, "Child rollout +// fixtures") and of the spawn items in collab_spawn.ndjson. +const ( + codexChildSameModelID = "01a06300-0000-7000-8000-0000000000a1" + codexChildOtherModelID = "01a06300-0000-7000-8000-0000000000a2" + codexChildFailedID = "01a06300-0000-7000-8000-0000000000a3" + codexChildNoModelID = "01a06300-0000-7000-8000-0000000000a4" + codexChildDeniedID = "01a06300-0000-7000-8000-0000000000a9" +) + +// codexChildFixtures maps each child id to its rollout fixture. +var codexChildFixtures = map[string]string{ + codexChildSameModelID: "child_usage_same_model.jsonl", + codexChildOtherModelID: "child_usage_other_model.jsonl", + codexChildFailedID: "child_usage_failed.jsonl", + codexChildNoModelID: "child_usage_no_model.jsonl", +} + +// writeCodexChildRollouts lays the child fixtures out as codex would under a +// sessions directory (YYYY/MM/DD/rollout--.jsonl) and +// returns that directory. +func writeCodexChildRollouts(t *testing.T, ids ...string) string { + t.Helper() + sessions := filepath.Join(t.TempDir(), "sessions") + day := filepath.Join(sessions, "2026", "09", "29") + require.NoError(t, os.MkdirAll(day, 0o755)) + for _, id := range ids { + name := "rollout-2026-09-29T15-46-38-" + id + ".jsonl" + require.NoError(t, os.WriteFile(filepath.Join(day, name), readCodexFixture(t, codexChildFixtures[id]), 0o644)) + } + return sessions +} + +// runCodexChildUsageRead executes the read command under /bin/sh against a +// local sessions directory and parses what it printed. The command is run, +// not inspected: a Go-level assertion on its text would not catch a quoting +// slip (the same reason codex_run_test.go executes the guards). +func runCodexChildUsageRead(t *testing.T, sessions string, ids []string) []codexChildUsage { + t.Helper() + cmd, err := codexChildUsageReadCommand(sessions, ids) + require.NoError(t, err) + out, err := exec.Command("/bin/sh", "-c", cmd).Output() + require.NoError(t, err) + return parseCodexChildUsage(out) +} + +func TestCodexChildUsageReadCommand_RejectsBadIDs(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + id string + }{ + {name: "path segment", id: "../etc/passwd"}, + {name: "upper case", id: "01A06300-0000-7000-8000-0000000000A1"}, + {name: "too short", id: "01a06300-0000-7000-8000-00000000a1"}, + {name: "shell text", id: "'; rm -rf /; '"}, + {name: "empty", id: ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + _, err := codexChildUsageReadCommand("/sandbox/codex-config/sessions", []string{codexChildSameModelID, tt.id}) + require.Error(t, err) + assert.Contains(t, err.Error(), "is not a codex thread id") + }) + } +} + +func TestCodexChildUsageReadCommand_Executes(t *testing.T) { + t.Parallel() + + sessions := writeCodexChildRollouts(t, codexChildSameModelID, codexChildOtherModelID, codexChildFailedID) + // Unsorted, one id twice, one id with no rollout. + ids := []string{codexChildFailedID, codexChildSameModelID, codexChildSameModelID, codexChildOtherModelID, "01a06300-0000-7000-8000-0000000000ff"} + + cmd, err := codexChildUsageReadCommand(sessions, ids) + require.NoError(t, err) + assert.Contains(t, cmd, fmt.Sprintf("command -p head -c %d", codexChildUsageMaxBytes), + "the read is bounded inside the sandbox, not after the bytes arrived") + assert.Contains(t, cmd, `-type f -name "rollout-*-$id.jsonl"`, + "only regular rollout files, found by thread id; never a cat of the directory") + assert.Equal(t, 1, strings.Count(cmd, shellQuote(codexChildSameModelID)), "a repeated id is read once") + + got := runCodexChildUsageRead(t, sessions, ids) + require.Len(t, got, 3, "an id with no rollout yields no record; a repeated id one; sorted by id") + assert.Equal(t, codexChildUsage{ + ID: codexChildSameModelID, Model: "gpt-5.6-luna", HasUsage: true, + Usage: codexUsage{InputTokens: 7381, CacheWriteInputTokens: 7378, OutputTokens: 8}, + }, got[0], "the last cumulative token_count, not the sum of the two") + assert.Equal(t, codexChildUsage{ + ID: codexChildOtherModelID, Model: "gpt-5.6-terra", HasUsage: true, + Usage: codexUsage{InputTokens: 4000, CachedInputTokens: 1000, CacheWriteInputTokens: 2000, OutputTokens: 300, ReasoningOutputTokens: 100}, + }, got[1]) + assert.Equal(t, codexChildUsage{ID: codexChildFailedID, Model: "gpt-5.6-nonexistent"}, got[2], + "a child that errored before its first response has a model and no usage") +} + +func TestParseCodexChildUsage(t *testing.T) { + t.Parallel() + + turn := func(model string) string { + return `{"type":"turn_context","payload":{"model":"` + model + `"}}` + } + count := func(in, out int) string { + return fmt.Sprintf(`{"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":%d,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":%d,"reasoning_output_tokens":0,"total_tokens":%d}}}}`, in, out, in+out) + } + data := strings.Join([]string{ + count(999, 999), // before any marker: nobody's line + codexChildUsageMarker + " " + codexChildSameModelID, + turn("gpt-5.6-terra"), + turn("gpt-5.6-sol"), + count(10, 1), + "not json", + count(20, 2), + "", + codexChildUsageMarker + " " + codexChildOtherModelID, + count(5, 5), + codexChildUsageMarker + " " + codexChildFailedID, + turn("gpt-5.6-terra"), + `{"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":7,"cach`, + }, "\n") + + got := parseCodexChildUsage([]byte(data)) + require.Len(t, got, 3) + assert.Equal(t, codexChildUsage{ID: codexChildSameModelID, Model: "gpt-5.6-terra", HasUsage: true, Usage: codexUsage{InputTokens: 20, OutputTokens: 2}}, + got[0], "first turn_context names the model, the last token_count wins, a malformed line is skipped") + assert.Equal(t, codexChildUsage{ID: codexChildOtherModelID, HasUsage: true, Usage: codexUsage{InputTokens: 5, OutputTokens: 5}}, + got[1], "no turn_context: the model stays empty and the fold buckets it") + assert.Equal(t, codexChildUsage{ID: codexChildFailedID, Model: "gpt-5.6-terra"}, + got[2], "a truncated last line (the head -c cut) is not usage") + assert.Empty(t, parseCodexChildUsage(nil)) +} + +func TestCodexChildIDs_CollectsCompletedSpawns(t *testing.T) { + t.Parallel() + + stream := readCodexFixture(t, "collab_spawn.ndjson") + want := []string{codexChildSameModelID, codexChildOtherModelID, codexChildFailedID} + + whole := &codexChildIDs{} + n, err := whole.Write(stream) + require.NoError(t, err) + assert.Equal(t, len(stream), n, "an io.Writer reports every byte consumed or the TeeReader fails") + assert.Equal(t, want, whole.IDs, + "the three completed spawns in stream order; the failed spawn's receiver is not a child; wait and close items name no new thread") + assert.NotContains(t, whole.IDs, codexChildDeniedID) + + chunked := &codexChildIDs{} + for i := 0; i < len(stream); i += 7 { + _, err := chunked.Write(stream[i:min(i+7, len(stream))]) + require.NoError(t, err) + } + assert.Equal(t, want, chunked.IDs, "lines are reassembled across Write calls, as a TeeReader delivers them") +} + +func TestCodexChildIDs_SkipsOverlongLine(t *testing.T) { + t.Parallel() + + spawn := `{"type":"item.completed","item":{"id":"item_1","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["` + codexChildSameModelID + `"],"prompt":null,"agents_states":{},"status":"completed"}}` + // A completed spawn naming another child, padded past the bound: if the + // line were scanned, its receiver would be collected. + overlong := `{"type":"item.completed","item":{"id":"item_0","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["` + codexChildOtherModelID + `"],"prompt":"` + strings.Repeat("a", streamBufSize) + `","agents_states":{},"status":"completed"}}` + + c := &codexChildIDs{} + _, err := c.Write([]byte(overlong + "\n" + spawn + "\n")) + require.NoError(t, err) + assert.Equal(t, []string{codexChildSameModelID}, c.IDs, + "a line past the parser's own bound is dropped whole, as parseCodexStream drops it, even when it names a child; the next line is still scanned") + assert.Empty(t, c.line, "nothing pending after a newline") +} + +// A failed child is visible in the stream and never fails the run: codex +// exits 0 and completes the turn (paid probe, 2026-09-29), so the wait and +// close items are the only trace. Pinned here because the delegation +// instructions given to the parent depend on it. +func TestParseCodexStream_FailedCollabItem(t *testing.T) { + t.Parallel() + + events, threadID := collectCodexEvents(t, "collab_spawn.ndjson") + assert.Equal(t, "01a06300-0000-7000-8000-000000000050", threadID) + + tools := codexEventsOfType[ToolUseEvent](events) + require.Len(t, tools, 9, "four spawns, two waits, three closes") + for _, tool := range tools { + assert.Equal(t, "Agent", tool.Name) + } + assert.Equal(t, "spawn_agent (1 agent(s))", tools[0].Summary) + assert.Equal(t, "spawn_agent (1 agent(s)) (failed)", tools[3].Summary, "a failed spawn is reported, not hidden") + assert.Equal(t, "wait (2 agent(s))", tools[4].Summary) + assert.Equal(t, "wait (1 agent(s)) (failed)", tools[5].Summary, "the errored child's wait carries status failed") + assert.Equal(t, "close_agent (1 agent(s)) (failed)", tools[8].Summary) + + result := codexOnlyResult(t, events) + assert.False(t, result.IsError, "a failed child never sets the run verdict") + assert.Equal(t, 1, result.NumTurns) + assert.Equal(t, 15, result.InputTokens) + assert.Equal(t, 1140, result.OutputTokens) + assert.Equal(t, 291, result.ReasoningTokens) + assert.Equal(t, 13618, result.CacheCreationInputTokens) + assert.Equal(t, 40590, result.CacheReadInputTokens) +} + +// fakeOpenshellCodexChildren is the fake openshell for the fold and run-level +// tests. It answers the manifest `cat` from storeDir (as fakeOpenshellCodex +// does), streams streamFixture for the codex launch, and executes the +// child-usage read command for real under sh with the sandbox sessions path +// rewritten to sessionsDir, so the command text is exercised, not stubbed. +// FULLSEND_TEST_CHILD_READ_FAIL makes that command exit 1; +// FULLSEND_TEST_CODEX_EXIT sets the launch's exit status. +func fakeOpenshellCodexChildren(t *testing.T, logPath, storeDir, streamFixture, sessionsDir string) { + t.Helper() + binDir := t.TempDir() + script := `#!/bin/sh +echo "$@" >> '` + logPath + `' +if [ "$2" = "exec" ]; then + for last; do :; done + case "$last" in + cat\ *) f=$(printf '%s' "${last#cat }" | tr -d "'" | tr '/' '_'); cat '` + storeDir + `'/"$f"; exit $? ;; + *"exec --json"*) cat '` + streamFixture + `'; exit "${FULLSEND_TEST_CODEX_EXIT:-0}" ;; + *` + codexChildUsageMarker + `*) + if [ -n "${FULLSEND_TEST_CHILD_READ_FAIL:-}" ]; then echo "fake openshell: refusing the rollout read" >&2; exit 1; fi + sh -c "$(printf '%s' "$last" | sed 's#` + CodexRuntime{}.codexSessionsDir() + `#` + sessionsDir + `#g')"; exit $? ;; + esac + exit 0 +fi +exit 0 +` + require.NoError(t, os.WriteFile(filepath.Join(binDir, "openshell"), []byte(script), 0o755)) + t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +// codexParentMetrics is the parent's own iteration as the stream fixture +// reports it (collab_spawn.ndjson, normalized). +func codexParentMetrics(model string) *RunMetrics { + return &RunMetrics{Model: model, NumTurns: 1, InputTokens: 15, OutputTokens: 1140, ReasoningTokens: 291, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590} +} + +// codexTokenTotals is the run-level view the tests compare; RunMetrics +// itself carries an atomic and must not be copied. +type codexTokenTotals struct{ input, output, reasoning, cacheWrite, cacheRead int } + +func codexTotalsOf(m *RunMetrics) codexTokenTotals { + return codexTokenTotals{m.InputTokens, m.OutputTokens, m.ReasoningTokens, m.CacheCreationInputTokens, m.CacheReadInputTokens} +} + +// assertCodexUsageSumsToTotals is the invariant docs/cli/run.md states for +// per_model_usage: the entries sum to the run totals for the five fields an +// entry has. Reasoning is run-level only and outside it. +func assertCodexUsageSumsToTotals(t *testing.T, m *RunMetrics) { + t.Helper() + var sum ModelUsage + for _, u := range m.PerModelUsage { + sum.Add(u) + } + assert.Equal(t, m.InputTokens, sum.InputTokens, "input") + assert.Equal(t, m.OutputTokens, sum.OutputTokens, "output") + assert.Equal(t, m.CacheCreationInputTokens, sum.CacheCreationInputTokens, "cache_creation") + assert.Equal(t, m.CacheReadInputTokens, sum.CacheReadInputTokens, "cache_read") + assert.Equal(t, m.TotalCostUSD, sum.CostUSD, "cost (0 on codex)") +} + +// TestFoldCodexChildUsage is the arithmetic per fixture: the parent's entry, +// then each child's last cumulative snapshot through codexUsage.counters(), +// added exactly once. Numbers: parent 15/1140/291/13618/40590 (real, paid +// probe); luna child 3/8/0/7378/0 (real); terra child 1000/200/100/2000/1000 +// (synthetic); the no-model child 50/5/0/0/0 (synthetic) under unknown; the +// failed child nothing. +func TestFoldCodexChildUsage(t *testing.T) { + r := CodexRuntime{} + parentOnly := ModelUsage{Requests: 1, InputTokens: 15, OutputTokens: 1140, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590} + lunaBoth := ModelUsage{Requests: 2, InputTokens: 18, OutputTokens: 1148, CacheCreationInputTokens: 20996, CacheReadInputTokens: 40590} + terra := ModelUsage{Requests: 1, InputTokens: 1000, OutputTokens: 200, CacheCreationInputTokens: 2000, CacheReadInputTokens: 1000} + + for name, tc := range map[string]struct { + ids []string + folded int + want map[string]ModelUsage + totals codexTokenTotals + }{ + "same model aggregates into one entry": { + ids: []string{codexChildSameModelID}, folded: 1, + want: map[string]ModelUsage{"gpt-5.6-luna": lunaBoth}, + totals: codexTokenTotals{18, 1148, 291, 20996, 40590}, + }, + "different model gets its own entry": { + ids: []string{codexChildOtherModelID}, folded: 1, + want: map[string]ModelUsage{"gpt-5.6-luna": parentOnly, "gpt-5.6-terra": terra}, + totals: codexTokenTotals{1015, 1340, 391, 15618, 41590}, + }, + "failed child contributes nothing, not even a request": { + ids: []string{codexChildFailedID}, folded: 0, + want: map[string]ModelUsage{"gpt-5.6-luna": parentOnly}, + totals: codexTokenTotals{15, 1140, 291, 13618, 40590}, + }, + "a child with usage but no model buckets under unknown": { + ids: []string{codexChildNoModelID}, folded: 1, + want: map[string]ModelUsage{"gpt-5.6-luna": parentOnly, piSubagentUnknownModel: {Requests: 1, InputTokens: 50, OutputTokens: 5}}, + totals: codexTokenTotals{65, 1145, 291, 13618, 40590}, + }, + "all three": { + ids: []string{codexChildSameModelID, codexChildOtherModelID, codexChildFailedID}, folded: 2, + want: map[string]ModelUsage{"gpt-5.6-luna": lunaBoth, "gpt-5.6-terra": terra}, + totals: codexTokenTotals{1018, 1348, 391, 22996, 41590}, + }, + } { + t.Run(name, func(t *testing.T) { + sessions := writeCodexChildRollouts(t, codexChildSameModelID, codexChildOtherModelID, codexChildFailedID, codexChildNoModelID) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + + m := codexParentMetrics("gpt-5.6-luna") + n, err := r.foldCodexChildUsage("sb", tc.ids, m) + require.NoError(t, err) + assert.Equal(t, tc.folded, n, "one per child thread with usage") + assert.Equal(t, tc.want, m.PerModelUsage) + assert.Equal(t, tc.totals, codexTotalsOf(m), "child reasoning is in the run total only") + assert.Zero(t, m.TotalCostUSD, "codex reports no cost; nothing is invented") + assertCodexUsageSumsToTotals(t, m) + }) + } +} + +// A planted rollout cannot lower the run's figures: counters() floors only +// its two subtractions, so the fold floors the three raw fields. +func TestFoldCodexChildUsage_ClampsNegativeCounters(t *testing.T) { + sessions := writeCodexChildRollouts(t) + rollout := `{"type":"turn_context","payload":{"model":"gpt-5.6-luna"}}` + "\n" + + `{"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":10,"cached_input_tokens":-5000,"cache_write_input_tokens":-7000,"output_tokens":20,"reasoning_output_tokens":-900,"total_tokens":30}}}}` + "\n" + require.NoError(t, os.WriteFile(filepath.Join(sessions, "2026", "09", "29", "rollout-2026-09-29T15-46-38-"+codexChildSameModelID+".jsonl"), []byte(rollout), 0o644)) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + + m := codexParentMetrics("gpt-5.6-luna") + n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID}, m) + require.NoError(t, err) + assert.Equal(t, 1, n) + // Input is 10 - (-5000) - (-7000) = 12010 and output 20 - (-900) = 920: + // inflation is accepted, as on pi; nothing drops below the parent's figures. + assert.Equal(t, codexTokenTotals{15 + 12010, 1140 + 920, 291, 13618, 40590}, codexTotalsOf(m)) + assert.Equal(t, ModelUsage{Requests: 2, InputTokens: 15 + 12010, OutputTokens: 1140 + 920, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590}, + m.PerModelUsage["gpt-5.6-luna"]) + assertCodexUsageSumsToTotals(t, m) +} + +// No child id, no sandbox command: PATH holds no openshell, so any exec +// would fail to start. The parent's entry still lands in the breakdown +// (a delegating agent that dispatched nothing), and a parent without a +// model is bucketed as pi buckets a record without one. +func TestFoldCodexChildUsage_NoChildrenNoSandbox(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + + for _, model := range []string{"gpt-5.6-luna", ""} { + m := codexParentMetrics(model) + n, err := CodexRuntime{}.foldCodexChildUsage("sb", nil, m) + require.NoError(t, err, "no id, no sandbox command") + assert.Zero(t, n) + key := model + if key == "" { + key = piSubagentUnknownModel + } + assert.Equal(t, map[string]ModelUsage{key: {Requests: 1, InputTokens: 15, OutputTokens: 1140, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590}}, m.PerModelUsage) + assert.Equal(t, codexTokenTotals{15, 1140, 291, 13618, 40590}, codexTotalsOf(m), "the parent's numbers are not double-counted into the totals") + assertCodexUsageSumsToTotals(t, m) + } +} + +func TestFoldCodexChildUsage_ReadFailuresKeepTheParentEntry(t *testing.T) { + r := CodexRuntime{} + parentOnly := map[string]ModelUsage{"gpt-5.6-luna": {Requests: 1, InputTokens: 15, OutputTokens: 1140, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590}} + + t.Run("a bad id never reaches the shell", func(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + m := codexParentMetrics("gpt-5.6-luna") + n, err := r.foldCodexChildUsage("sb", []string{codexChildSameModelID, "'; rm -rf /; '"}, m) + require.Error(t, err) + assert.Contains(t, err.Error(), "is not a codex thread id") + assert.Zero(t, n) + assert.Equal(t, parentOnly, m.PerModelUsage) + }) + + t.Run("openshell cannot start", func(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + m := codexParentMetrics("gpt-5.6-luna") + _, err := r.foldCodexChildUsage("sb", []string{codexChildSameModelID}, m) + require.Error(t, err) + assert.Contains(t, err.Error(), "reading the child rollouts") + assert.Equal(t, parentOnly, m.PerModelUsage) + assert.Equal(t, codexTokenTotals{15, 1140, 291, 13618, 40590}, codexTotalsOf(m), "totals untouched") + }) + + t.Run("the read command exits non-zero", func(t *testing.T) { + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", t.TempDir()) + t.Setenv("FULLSEND_TEST_CHILD_READ_FAIL", "1") + m := codexParentMetrics("gpt-5.6-luna") + _, err := r.foldCodexChildUsage("sb", []string{codexChildSameModelID}, m) + require.Error(t, err) + assert.Contains(t, err.Error(), "exited 1") + assert.Contains(t, err.Error(), "refusing the rollout read", "stderr is in the message") + assert.Equal(t, parentOnly, m.PerModelUsage) + assertCodexUsageSumsToTotals(t, m) + }) +} + +func TestFoldCodexChildUsage_TwoIterationsSumToTotals(t *testing.T) { + sessions := writeCodexChildRollouts(t, codexChildSameModelID, codexChildOtherModelID) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + r := CodexRuntime{} + + first := codexParentMetrics("gpt-5.6-luna") + n, err := r.foldCodexChildUsage("sb", []string{codexChildSameModelID, codexChildOtherModelID}, first) + require.NoError(t, err) + assert.Equal(t, 2, n) + + // The retry dispatched nothing; a delegating agent still folds, so its + // parent entry is in the breakdown. + second := &RunMetrics{Model: "gpt-5.6-luna", NumTurns: 1, InputTokens: 100, OutputTokens: 50, ReasoningTokens: 7, CacheCreationInputTokens: 20, CacheReadInputTokens: 30} + n, err = r.foldCodexChildUsage("sb", nil, second) + require.NoError(t, err) + assert.Zero(t, n) + + // Summed as internal/cli aggregateRunMetrics sums iterations. + sum := &RunMetrics{PerModelUsage: map[string]ModelUsage{}} + for _, m := range []*RunMetrics{first, second} { + sum.InputTokens += m.InputTokens + sum.OutputTokens += m.OutputTokens + sum.ReasoningTokens += m.ReasoningTokens + sum.CacheCreationInputTokens += m.CacheCreationInputTokens + sum.CacheReadInputTokens += m.CacheReadInputTokens + sum.TotalCostUSD += m.TotalCostUSD + for spec, u := range m.PerModelUsage { + entry := sum.PerModelUsage[spec] + entry.Add(u) + sum.PerModelUsage[spec] = entry + } + } + assert.Equal(t, map[string]ModelUsage{ + "gpt-5.6-luna": {Requests: 3, InputTokens: 118, OutputTokens: 1198, CacheCreationInputTokens: 21016, CacheReadInputTokens: 40620}, + "gpt-5.6-terra": {Requests: 1, InputTokens: 1000, OutputTokens: 200, CacheCreationInputTokens: 2000, CacheReadInputTokens: 1000}, + }, sum.PerModelUsage, "two parent iterations and one luna child under luna; the terra child alone under terra") + assert.Equal(t, codexTokenTotals{1118, 1398, 398, 23016, 41620}, codexTotalsOf(sum)) + assertCodexUsageSumsToTotals(t, sum) +} diff --git a/internal/runtime/testdata/codex/README.md b/internal/runtime/testdata/codex/README.md index c694a18987..271af07d97 100644 --- a/internal/runtime/testdata/codex/README.md +++ b/internal/runtime/testdata/codex/README.md @@ -26,6 +26,27 @@ ARG exists run `CODEX_VERSION=0.152.1 ./regen.sh`. | `truncated.ndjson` | Killed mid-write — the last line stops mid-token and there is no terminal event. (The repo's `end-of-file-fixer` hook keeps a trailing newline after it; the line is still unparseable, which is what the fixture tests.) | | `unknown_types.ndjson` | An unknown top-level event type and an unknown item type: skipped, the run still completes. | | `second_turn_unfinished.ndjson` | A completed turn followed by a second `turn.started` that never finishes: the run is incomplete, not the first turn's success. | +| `collab_spawn.ndjson` | Three completed `spawn_agent` items (one child each), one **failed** `spawn_agent` item whose receiver must not be counted as a child, `wait` and `close_agent` items for the errored child with `status: failed` inside a completed turn, and the real parent usage of the 2026-09-29 paid probe. Note: a spawn a PreToolUse hook denied emits no `collab_tool_call` item at all (seen in a mock run); the failed item here is hand-authored to pin the collector's status filter. | + +## Child rollout fixtures (`child_usage_*.jsonl`) + +Inputs for `foldCodexChildUsage` (`internal/runtime/codex_subagents.go`), not for +`parseCodexStream`: they are codex **rollouts** (`$CODEX_HOME/sessions/**/rollout-*.jsonl`, the +underscored envelope of `codex_redact.go`), not the `exec --json` stream. Line types and fields +were copied from the rollouts of the 0.157.0 paid probe of 2026-09-29, trimmed, with +synthetic ids. The fold reads two lines per rollout: the first `turn_context` (its +`payload.model`) and the last `event_msg`/`token_count` (its `payload.info.total_token_usage`, +cumulative for the thread). + +| Fixture | Covers | +|---|---| +| `child_usage_same_model.jsonl` | A child on the parent's model, `gpt-5.6-luna`, with two cumulative `token_count` lines (3000 then 7381 input): the last one is the child's whole usage. | +| `child_usage_other_model.jsonl` | A child on `gpt-5.6-terra`, every normalized counter non-zero. | +| `child_usage_failed.jsonl` | A child whose model the provider rejected (404): `turn_context` names the model, `task_complete` carries `error`, and there is no `token_count`, so it contributes nothing. | +| `child_usage_no_model.jsonl` | A child with a `token_count` and no `turn_context`: its usage is bucketed under `unknown`. | + +The tests lay the rollouts out under a temporary sessions tree as +`2026/09/29/rollout-2026-09-29T15-46-38-.jsonl`, the name codex gives a rollout. ## Event structs diff --git a/internal/runtime/testdata/codex/child_usage_failed.jsonl b/internal/runtime/testdata/codex/child_usage_failed.jsonl new file mode 100644 index 0000000000..9a53c2738c --- /dev/null +++ b/internal/runtime/testdata/codex/child_usage_failed.jsonl @@ -0,0 +1,5 @@ +{"timestamp":"2026-09-29T19:46:40.162Z","ordinal":0,"type":"session_meta","payload":{"session_id":"01a06300-0000-7000-8000-000000000050","id":"01a06300-0000-7000-8000-0000000000a3","parent_thread_id":"01a06300-0000-7000-8000-000000000050","timestamp":"2026-09-29T19:46:40.136Z","cwd":"/sandbox/workspace/repo","originator":"codex_exec","cli_version":"0.157.0","source":{"subagent":{"thread_spawn":{"parent_thread_id":"01a06300-0000-7000-8000-000000000050","depth":1,"agent_path":null,"agent_nickname":"Mendel","agent_role":"challenger"}}},"thread_source":"subagent","agent_nickname":"Mendel","agent_role":"challenger","model_provider":"openai","base_instructions":"(trimmed)","history_mode":"paginated","multi_agent_version":"v1"}} +{"timestamp":"2026-09-29T19:46:40.162Z","ordinal":1,"type":"event_msg","payload":{"type":"task_started","turn_id":"01a06300-0000-7000-8000-0000000000b3","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","started_at":1790711200,"model_context_window":258400,"collaboration_mode_kind":"default"}} +{"timestamp":"2026-09-29T19:46:40.786Z","ordinal":2,"type":"turn_context","payload":{"turn_id":"01a06300-0000-7000-8000-0000000000b3","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","cwd":"/sandbox/workspace/repo","approval_policy":"never","sandbox_policy":{"type":"danger-full-access"},"model":"gpt-5.6-nonexistent","multi_agent_version":"v1","effort":"medium","summary":"auto"}} +{"timestamp":"2026-09-29T19:46:40.795Z","ordinal":3,"type":"event_msg","payload":{"type":"item_completed","thread_id":"01a06300-0000-7000-8000-0000000000a3","turn_id":"01a06300-0000-7000-8000-0000000000b3","item":{"type":"UserMessage","id":"01a06300-0000-7000-8000-0000000000c3","content":[{"type":"text","text":"Challenge the findings.","text_elements":[]}]},"started_at_ms":1790711200795,"completed_at_ms":1790711200795}} +{"timestamp":"2026-09-29T19:47:27.725Z","ordinal":4,"type":"event_msg","payload":{"type":"task_complete","turn_id":"01a06300-0000-7000-8000-0000000000b3","last_agent_message":null,"error":{"message":"unexpected status 404 Not Found: The model `gpt-5.6-nonexistent` does not exist or you do not have access to it., url: https://api.openai.com/v1/responses","codex_error_info":"other"},"started_at":1790711200,"completed_at":1790711247,"duration_ms":47562}} diff --git a/internal/runtime/testdata/codex/child_usage_no_model.jsonl b/internal/runtime/testdata/codex/child_usage_no_model.jsonl new file mode 100644 index 0000000000..4aab63925f --- /dev/null +++ b/internal/runtime/testdata/codex/child_usage_no_model.jsonl @@ -0,0 +1,2 @@ +{"timestamp":"2026-09-29T19:46:39.000Z","ordinal":0,"type":"session_meta","payload":{"session_id":"01a06300-0000-7000-8000-000000000050","id":"01a06300-0000-7000-8000-0000000000a4","parent_thread_id":"01a06300-0000-7000-8000-000000000050","agent_role":null,"multi_agent_version":"v1"}} +{"timestamp":"2026-09-29T19:46:39.500Z","ordinal":1,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":50,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":5,"reasoning_output_tokens":0,"total_tokens":55}},"rate_limits":null}} diff --git a/internal/runtime/testdata/codex/child_usage_other_model.jsonl b/internal/runtime/testdata/codex/child_usage_other_model.jsonl new file mode 100644 index 0000000000..6d54bce782 --- /dev/null +++ b/internal/runtime/testdata/codex/child_usage_other_model.jsonl @@ -0,0 +1,6 @@ +{"timestamp":"2026-09-29T19:46:38.900Z","ordinal":0,"type":"session_meta","payload":{"session_id":"01a06300-0000-7000-8000-000000000050","id":"01a06300-0000-7000-8000-0000000000a2","parent_thread_id":"01a06300-0000-7000-8000-000000000050","timestamp":"2026-09-29T19:46:38.880Z","cwd":"/sandbox/workspace/repo","originator":"codex_exec","cli_version":"0.157.0","source":{"subagent":{"thread_spawn":{"parent_thread_id":"01a06300-0000-7000-8000-000000000050","depth":1,"agent_path":null,"agent_nickname":"Curie","agent_role":"security"}}},"thread_source":"subagent","agent_nickname":"Curie","agent_role":"security","model_provider":"openai","base_instructions":"(trimmed)","history_mode":"paginated","multi_agent_version":"v1"}} +{"timestamp":"2026-09-29T19:46:38.900Z","ordinal":1,"type":"event_msg","payload":{"type":"task_started","turn_id":"01a06300-0000-7000-8000-0000000000b2","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","started_at":1790711198,"model_context_window":258400,"collaboration_mode_kind":"default"}} +{"timestamp":"2026-09-29T19:46:39.400Z","ordinal":2,"type":"turn_context","payload":{"turn_id":"01a06300-0000-7000-8000-0000000000b2","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","cwd":"/sandbox/workspace/repo","approval_policy":"never","sandbox_policy":{"type":"danger-full-access"},"model":"gpt-5.6-terra","multi_agent_version":"v1","effort":"low","summary":"auto"}} +{"timestamp":"2026-09-29T19:46:41.000Z","ordinal":3,"type":"token_usage_record","payload":{"thread_id":"01a06300-0000-7000-8000-0000000000a2","turn_id":"01a06300-0000-7000-8000-0000000000b2","session_id":"01a06300-0000-7000-8000-000000000050","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","response_id":"resp_fixture_a2_1","usage":{"input_tokens":4000,"cached_input_tokens":1000,"cache_write_input_tokens":2000,"output_tokens":300,"reasoning_output_tokens":100,"total_tokens":4300},"turn_token_usage":{"input_tokens":4000,"cached_input_tokens":1000,"cache_write_input_tokens":2000,"output_tokens":300,"reasoning_output_tokens":100,"total_tokens":4300},"thread_token_usage":{"input_tokens":4000,"cached_input_tokens":1000,"cache_write_input_tokens":2000,"output_tokens":300,"reasoning_output_tokens":100,"total_tokens":4300}}} +{"timestamp":"2026-09-29T19:46:41.000Z","ordinal":4,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":4000,"cached_input_tokens":1000,"cache_write_input_tokens":2000,"output_tokens":300,"reasoning_output_tokens":100,"total_tokens":4300},"last_token_usage":{"input_tokens":4000,"cached_input_tokens":1000,"cache_write_input_tokens":2000,"output_tokens":300,"reasoning_output_tokens":100,"total_tokens":4300},"model_context_window":258400},"rate_limits":null}} +{"timestamp":"2026-09-29T19:46:41.010Z","ordinal":5,"type":"event_msg","payload":{"type":"task_complete","turn_id":"01a06300-0000-7000-8000-0000000000b2","last_agent_message":"One finding.","started_at":1790711198,"completed_at":1790711201,"duration_ms":2100,"time_to_first_token_ms":900}} diff --git a/internal/runtime/testdata/codex/child_usage_same_model.jsonl b/internal/runtime/testdata/codex/child_usage_same_model.jsonl new file mode 100644 index 0000000000..02345acfd3 --- /dev/null +++ b/internal/runtime/testdata/codex/child_usage_same_model.jsonl @@ -0,0 +1,7 @@ +{"timestamp":"2026-09-29T19:46:38.744Z","ordinal":0,"type":"session_meta","payload":{"session_id":"01a06300-0000-7000-8000-000000000050","id":"01a06300-0000-7000-8000-0000000000a1","parent_thread_id":"01a06300-0000-7000-8000-000000000050","timestamp":"2026-09-29T19:46:38.712Z","cwd":"/sandbox/workspace/repo","originator":"codex_exec","cli_version":"0.157.0","source":{"subagent":{"thread_spawn":{"parent_thread_id":"01a06300-0000-7000-8000-000000000050","depth":1,"agent_path":null,"agent_nickname":"Faraday","agent_role":"correctness"}}},"thread_source":"subagent","agent_nickname":"Faraday","agent_role":"correctness","model_provider":"openai","base_instructions":"(trimmed)","history_mode":"paginated","multi_agent_version":"v1"}} +{"timestamp":"2026-09-29T19:46:38.744Z","ordinal":1,"type":"event_msg","payload":{"type":"task_started","turn_id":"01a06300-0000-7000-8000-0000000000b1","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","started_at":1790711198,"model_context_window":258400,"collaboration_mode_kind":"default"}} +{"timestamp":"2026-09-29T19:46:39.366Z","ordinal":2,"type":"turn_context","payload":{"turn_id":"01a06300-0000-7000-8000-0000000000b1","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","cwd":"/sandbox/workspace/repo","approval_policy":"never","sandbox_policy":{"type":"danger-full-access"},"model":"gpt-5.6-luna","multi_agent_version":"v1","effort":"low","summary":"auto"}} +{"timestamp":"2026-09-29T19:46:39.900Z","ordinal":3,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":3000,"cached_input_tokens":0,"cache_write_input_tokens":2990,"output_tokens":4,"reasoning_output_tokens":0,"total_tokens":3004},"last_token_usage":{"input_tokens":3000,"cached_input_tokens":0,"cache_write_input_tokens":2990,"output_tokens":4,"reasoning_output_tokens":0,"total_tokens":3004},"model_context_window":258400},"rate_limits":null}} +{"timestamp":"2026-09-29T19:46:40.124Z","ordinal":4,"type":"token_usage_record","payload":{"thread_id":"01a06300-0000-7000-8000-0000000000a1","turn_id":"01a06300-0000-7000-8000-0000000000b1","session_id":"01a06300-0000-7000-8000-000000000050","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","response_id":"resp_fixture_a1_2","usage":{"input_tokens":4381,"cached_input_tokens":0,"cache_write_input_tokens":4388,"output_tokens":4,"reasoning_output_tokens":0,"total_tokens":4385},"turn_token_usage":{"input_tokens":7381,"cached_input_tokens":0,"cache_write_input_tokens":7378,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":7389},"thread_token_usage":{"input_tokens":7381,"cached_input_tokens":0,"cache_write_input_tokens":7378,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":7389}}} +{"timestamp":"2026-09-29T19:46:40.124Z","ordinal":5,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":7381,"cached_input_tokens":0,"cache_write_input_tokens":7378,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":7389},"last_token_usage":{"input_tokens":4381,"cached_input_tokens":0,"cache_write_input_tokens":4388,"output_tokens":4,"reasoning_output_tokens":0,"total_tokens":4385},"model_context_window":258400},"rate_limits":null}} +{"timestamp":"2026-09-29T19:46:40.128Z","ordinal":6,"type":"event_msg","payload":{"type":"task_complete","turn_id":"01a06300-0000-7000-8000-0000000000b1","last_agent_message":"No defects found.","started_at":1790711198,"completed_at":1790711200,"duration_ms":1384,"time_to_first_token_ms":1284}} diff --git a/internal/runtime/testdata/codex/collab_spawn.ndjson b/internal/runtime/testdata/codex/collab_spawn.ndjson new file mode 100644 index 0000000000..5918333dde --- /dev/null +++ b/internal/runtime/testdata/codex/collab_spawn.ndjson @@ -0,0 +1,14 @@ +{"type":"thread.started","thread_id":"01a06300-0000-7000-8000-000000000050"} +{"type":"turn.started"} +{"type":"item.started","item":{"id":"item_0","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":[],"prompt":"Review for correctness.","agents_states":{},"status":"in_progress"}} +{"type":"item.completed","item":{"id":"item_0","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a1"],"prompt":"Review for correctness.","agents_states":{"01a06300-0000-7000-8000-0000000000a1":{"status":"pending_init","message":null}},"status":"completed"}} +{"type":"item.completed","item":{"id":"item_1","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a2"],"prompt":"Review for security.","agents_states":{"01a06300-0000-7000-8000-0000000000a2":{"status":"pending_init","message":null}},"status":"completed"}} +{"type":"item.completed","item":{"id":"item_2","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a3"],"prompt":"Challenge the findings.","agents_states":{"01a06300-0000-7000-8000-0000000000a3":{"status":"pending_init","message":null}},"status":"completed"}} +{"type":"item.completed","item":{"id":"item_3","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a9"],"prompt":"Fork me.","agents_states":{},"status":"failed"}} +{"type":"item.completed","item":{"id":"item_4","type":"collab_tool_call","tool":"wait","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a1","01a06300-0000-7000-8000-0000000000a2"],"prompt":null,"agents_states":{"01a06300-0000-7000-8000-0000000000a1":{"status":"completed","message":"No defects found."},"01a06300-0000-7000-8000-0000000000a2":{"status":"completed","message":"One finding."}},"status":"completed"}} +{"type":"item.completed","item":{"id":"item_5","type":"collab_tool_call","tool":"wait","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a3"],"prompt":null,"agents_states":{"01a06300-0000-7000-8000-0000000000a3":{"status":"errored","message":"unexpected status 404 Not Found: The model `gpt-5.6-nonexistent` does not exist or you do not have access to it., url: https://api.openai.com/v1/responses"}},"status":"failed"}} +{"type":"item.completed","item":{"id":"item_6","type":"collab_tool_call","tool":"close_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a1"],"prompt":null,"agents_states":{"01a06300-0000-7000-8000-0000000000a1":{"status":"completed","message":"No defects found."}},"status":"completed"}} +{"type":"item.completed","item":{"id":"item_7","type":"collab_tool_call","tool":"close_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a2"],"prompt":null,"agents_states":{"01a06300-0000-7000-8000-0000000000a2":{"status":"completed","message":"One finding."}},"status":"completed"}} +{"type":"item.completed","item":{"id":"item_8","type":"collab_tool_call","tool":"close_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["01a06300-0000-7000-8000-0000000000a3"],"prompt":null,"agents_states":{"01a06300-0000-7000-8000-0000000000a3":{"status":"errored","message":"unexpected status 404 Not Found: The model `gpt-5.6-nonexistent` does not exist or you do not have access to it., url: https://api.openai.com/v1/responses"}},"status":"failed"}} +{"type":"item.completed","item":{"id":"item_9","type":"agent_message","text":"Review complete."}} +{"type":"turn.completed","usage":{"input_tokens":54223,"cached_input_tokens":40590,"cache_write_input_tokens":13618,"output_tokens":1431,"reasoning_output_tokens":291}} From fc0946531ff18d1cc4346269b2d6fec9ff9c4334 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Thu, 15 Oct 2026 18:13:54 -0400 Subject: [PATCH 2/9] refactor(codex): count native child tokens in run metrics When a Codex agent has registered sub-agent roles or its exec --json stream reports a completed spawn, Run reads the children's rollouts with one bounded sandbox command after codex exits and folds each child's last cumulative usage into the totals and per_model_usage. The ids come off a tee of the stream; parseCodexStream's signature is unchanged. A failed read is a printer warning, never a failed run, and a killed, cancelled or timed-out iteration reports the parent's tokens only. Inert until the multi-agent tools are turned on: no agent on main can spawn, so the one visible change is that a delegating agent's metrics.json gains per_model_usage with the parent's entry. Signed-off-by: Dharit Shah --- docs/cli/run.md | 24 +++-- internal/runtime/codex_run.go | 20 ++++ internal/runtime/codex_subagents_test.go | 118 +++++++++++++++++++++++ 3 files changed, 154 insertions(+), 8 deletions(-) diff --git a/docs/cli/run.md b/docs/cli/run.md index 21f0150405..4b6d1ae2b4 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -134,7 +134,7 @@ depend on the process cwd. | `total_cost_usd` | Total inference cost in USD, as reported by the runtime (raw floating-point aggregate across all iterations; no fullsend-side pricing-table fallback). See [Cost data contract](../guides/infrastructure/distributed-tracing.md#cost-data-contract) | | `num_turns` | Number of conversation turns | | `iterations` | Number of agent iterations run; an iteration killed at the budget is not retried (see [Budget and deadline](#budget-and-deadline)) | -| `per_model_usage` | Per-model breakdown, present only when a runtime reports one (today: `pi` with the `Agent` tool enabled, and `claude` when Claude Code's result carries `modelUsage`). See below | +| `per_model_usage` | Per-model breakdown, present only when a runtime reports one (today: `pi` with the `Agent` tool enabled, `claude` when Claude Code's result carries `modelUsage`, and `codex` for an agent with registered sub-agent roles or a spawn in its stream). See below | | `fallback_from` | Models the run moved off, in the order tried, before `model` took over: models the Vertex project did not serve, and on `claude` any model Claude Code's own `--fallback-model` handling left, for example on overload (`claude` and `pi`; see [Claude Code](../runtimes/claude.md#models)). Absent when the first model ran | | `fallback_reasons` | Why the run moved off each `fallback_from` entry, at the same index: `not_served` when the runner retried because the Vertex project does not serve the model, `claude_code:` when Claude Code switched models itself (its `model_fallback` trigger, for example `claude_code:last_resort`). Absent when the first model ran | @@ -142,9 +142,11 @@ depend on the process cwd. A map from model spec to `{requests, input_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens, cost_usd}`. -On `pi` the key is the pi model spec (`anthropic-vertex/claude-opus-4-6`). It exists because a pi -sub-agent is a separate `pi` process whose tokens never appear in the parent's stream, so without it -`total_cost_usd` would grow with no way to attribute it. +On `pi` the key is the pi model spec (`anthropic-vertex/claude-opus-4-6`); on `codex` it is the bare +OpenAI id (`gpt-5.6-luna`). It exists because a sub-agent's tokens never appear in the parent's +stream: a pi sub-agent is a separate `pi` process, and a codex sub-agent is a separate thread whose +usage codex records only in that thread's rollout. Without it `total_cost_usd` would grow with no +way to attribute it on pi, and child tokens would be missing from the totals on codex. On `claude` the key is the model id Claude Code reports (`claude-haiku-4-5@20251001`), with one entry per model that ran, sub-agents included. The token totals come from the result event's @@ -155,7 +157,8 @@ records its last value rather than adding each result's. `requests` has no count Code's result and stays `0`. A result without `modelUsage` keeps the parent-only `usage` totals and records no breakdown, and an iteration that ends without a result (cancelled at the budget) contributes to the totals but not to the breakdown, so the invariant below can fall short in those -two cases. The rest of this section describes the `pi` breakdown. +two cases. The rest of this section describes the `pi` breakdown; `codex` follows it, with the +differences in the last bullet. - **What folds.** Tokens and cost, from both the parent and every child, summed across retry iterations. Each iteration contributes one `requests` for the parent plus one per sub-agent call, @@ -169,9 +172,14 @@ two cases. The rest of this section describes the `pi` breakdown. - **What stays parent-only.** `num_turns` and `tool_calls` are read from the parent's stream and are not broken down or added to per model — a child's turns and tool calls are recorded in its own session transcript (`transcripts/-sub-*.jsonl`) instead. -- A model spec of `unknown` is a usage record that carries no model spec at all; its cost is - bucketed there rather than dropped. A dispatch rejected *before* a model was resolved writes - no record, so it never reaches the breakdown. +- A model spec of `unknown` is a pi usage record, or a codex child rollout, that carries no model + at all; its usage is bucketed there rather than dropped. A dispatch rejected *before* a model was + resolved writes no record, so it never reaches the breakdown. +- **On codex.** `cost_usd` is `0` in every entry: codex reports no dollar cost, so compare tokens + there. `requests` counts one per child thread that reported usage; `wait`, `send_input` and + `close_agent` calls add none, and a child that errored before its first response has no usage + and adds no `requests`. A codex run that is cancelled or times out reports the parent's tokens + only. ## Budget and deadline diff --git a/internal/runtime/codex_run.go b/internal/runtime/codex_run.go index 7b84cd029e..6c9db32e8e 100644 --- a/internal/runtime/codex_run.go +++ b/internal/runtime/codex_run.go @@ -607,6 +607,11 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri } } + // Child thread ids come off a tee of the stream: the parser's events + // carry no thread id. + childIDs := &codexChildIDs{} + reader = io.TeeReader(reader, childIDs) + handler := params.OnEvent if handler == nil { renderer := NewEventRenderer(printer) @@ -654,6 +659,21 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri r.ConfigDir()) } + // Children are separate threads whose tokens never reached the stream + // just parsed; their rollouts are the only record. Read only after a + // clean exit: a killed, cancelled or timed-out iteration reports the + // parent's tokens only. A read failure costs the breakdown, not the + // iteration. + if exitCode == 0 && (digests.delegating() || len(childIDs.IDs) > 0) { + n, ferr := r.foldCodexChildUsage(params.SandboxName, childIDs.IDs, metrics) + if ferr != nil { + printer.StepWarn("Could not read the sub-agent usage: " + sanitizeOutput(ferr.Error())) + } + if n > 0 { + printer.StepInfo(fmt.Sprintf("%d sub-agent thread(s) folded into the run metrics", n)) + } + } + if exitCode == 0 && lastResult != nil && lastResult.IsError { msg := lastResult.ErrorMessage if msg == "" { diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index 4a2a2d8ad7..1363120484 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -1,15 +1,21 @@ package runtime import ( + "bytes" + "context" + "encoding/json" "fmt" "os" "os/exec" "path/filepath" "strings" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/ui" ) // The gate Run uses to decide that a delegating agent's breakdown must carry @@ -477,3 +483,115 @@ func TestFoldCodexChildUsage_TwoIterationsSumToTotals(t *testing.T) { assert.Equal(t, codexTokenTotals{1118, 1398, 398, 23016, 41620}, codexTotalsOf(sum)) assertCodexUsageSumsToTotals(t, sum) } + +// runCodexWithChildren runs CodexRuntime.Run against the fake with the given +// stream fixture and a sessions tree holding the rollouts of the three +// children the stream spawns, and returns the metrics, the exit code, the +// printer output and the fake's argv log. delegating sets RoleFiles on the +// runner-held digests (what Bootstrap records for an agent with the Agent +// tool). +func runCodexWithChildren(t *testing.T, streamFixture string, delegating bool) (*RunMetrics, int, string, string) { + t.Helper() + logPath := filepath.Join(t.TempDir(), "openshell.log") + storeDir := t.TempDir() + r := CodexRuntime{} + seedCodexManifest(t, storeDir, r, nil) + if delegating { + d, ok := lookupRunnerHeldDigests("sb") + require.True(t, ok) + d.RoleFiles = map[string]string{"default": "d0d0", "explore": "e0e0"} + recordRunnerHeldDigests("sb", d) + } + sessions := writeCodexChildRollouts(t, codexChildSameModelID, codexChildOtherModelID, codexChildFailedID) + fakeOpenshellCodexChildren(t, logPath, storeDir, filepath.Join("testdata", "codex", streamFixture), sessions) + + var out bytes.Buffer + metrics := &RunMetrics{} + exit, err := r.Run(context.Background(), RunParams{ + SandboxName: "sb", + RepoDir: "/sandbox/workspace/repo", + Model: "openai/gpt-5.6-luna", + Timeout: time.Minute, + }, ui.New(&out), time.Now(), metrics) + require.NoError(t, err) + return metrics, exit, out.String(), readFileString(t, logPath) +} + +// A run that spawned: metrics.json carries the children. Digests without +// RoleFiles here, so the spawn in the stream alone is what triggers the read +// (the second half of the gate). +func TestCodexRun_FoldsChildUsage(t *testing.T) { + metrics, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", false) + + assert.Equal(t, 0, exit) + assert.Equal(t, "gpt-5.6-luna", metrics.Model) + assert.Equal(t, codexTokenTotals{1018, 1348, 391, 22996, 41590}, codexTotalsOf(metrics), + "parent (15/1140/291/13618/40590) plus the luna child (3/8/0/7378/0) plus the terra child (1000/200/100/2000/1000); the failed child nothing") + assert.Equal(t, map[string]ModelUsage{ + "gpt-5.6-luna": {Requests: 2, InputTokens: 18, OutputTokens: 1148, CacheCreationInputTokens: 20996, CacheReadInputTokens: 40590}, + "gpt-5.6-terra": {Requests: 1, InputTokens: 1000, OutputTokens: 200, CacheCreationInputTokens: 2000, CacheReadInputTokens: 1000}, + }, metrics.PerModelUsage) + assertCodexUsageSumsToTotals(t, metrics) + assert.Zero(t, metrics.TotalCostUSD) + assert.Equal(t, 1, metrics.NumTurns, "turns stay parent-only") + assert.Contains(t, out, "2 sub-agent thread(s) folded into the run metrics") + assert.Equal(t, 1, strings.Count(log, codexChildUsageMarker), "one read command, after the run") + assert.Contains(t, log, shellQuote(codexChildFailedID), "the failed child's rollout is read too; it is its content that contributes nothing") + assert.NotContains(t, log, codexChildDeniedID, "the failed spawn's receiver is never looked up") +} + +// A delegating agent that dispatched nothing: the breakdown carries the +// parent's entry and no sandbox command runs (the first half of the gate). +func TestCodexRun_DelegatingWithoutSpawnHasParentEntry(t *testing.T) { + metrics, exit, _, log := runCodexWithChildren(t, "basic_run.ndjson", true) + + assert.Equal(t, 0, exit) + assert.Equal(t, map[string]ModelUsage{ + "gpt-5.6-luna": {Requests: 1, InputTokens: 12, OutputTokens: 284, CacheCreationInputTokens: 11087, CacheReadInputTokens: 32508}, + }, metrics.PerModelUsage, "the numbers TestApplyCodexMetrics pins for basic_run.ndjson") + assertCodexUsageSumsToTotals(t, metrics) + assert.NotContains(t, log, codexChildUsageMarker, "no id, no sandbox command") +} + +// The byte-equal invariant: a non-delegating agent whose stream reports no +// spawn writes the same metrics.json as before. +func TestCodexRun_NoSpawnNoBreakdown(t *testing.T) { + metrics, exit, _, log := runCodexWithChildren(t, "basic_run.ndjson", false) + + assert.Equal(t, 0, exit) + assert.Nil(t, metrics.PerModelUsage) + data, err := json.Marshal(metrics) + require.NoError(t, err) + assert.NotContains(t, string(data), "per_model_usage", "omitempty keeps the key out") + assert.NotContains(t, log, codexChildUsageMarker) +} + +// A failed read is a warning; the iteration keeps its exit code and the +// parent's numbers, and the breakdown keeps the parent's entry. +func TestCodexRun_ChildReadFailureIsAWarning(t *testing.T) { + t.Setenv("FULLSEND_TEST_CHILD_READ_FAIL", "1") + metrics, exit, out, _ := runCodexWithChildren(t, "collab_spawn.ndjson", false) + + assert.Equal(t, 0, exit, "losing the breakdown must not fail an iteration that succeeded") + assert.Contains(t, out, "! Could not read the sub-agent usage: reading the child rollouts: exited 1: fake openshell: refusing the rollout read") + assert.NotContains(t, out, "folded into the run metrics") + assert.Equal(t, codexTokenTotals{15, 1140, 291, 13618, 40590}, codexTotalsOf(metrics), "the parent's tokens only") + assert.Equal(t, map[string]ModelUsage{ + "gpt-5.6-luna": {Requests: 1, InputTokens: 15, OutputTokens: 1140, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590}, + }, metrics.PerModelUsage) + assertCodexUsageSumsToTotals(t, metrics) +} + +// A codex process that did not exit 0 (killed at the timeout, cancelled, or +// crashed) reports the parent's tokens only and runs no sandbox command: +// the rollouts of a killed run are not read (docs/cli/run.md). +func TestCodexRun_NonZeroExitSkipsTheChildRead(t *testing.T) { + t.Setenv("FULLSEND_TEST_CODEX_EXIT", "137") + metrics, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", true) + + assert.Equal(t, 137, exit) + assert.Nil(t, metrics.PerModelUsage) + assert.Equal(t, codexTokenTotals{15, 1140, 291, 13618, 40590}, codexTotalsOf(metrics)) + assert.NotContains(t, log, codexChildUsageMarker) + assert.NotContains(t, out, "sub-agent") +} From 73f0c68e78e64d3ff8255963b521929517e590ab Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 19 Oct 2026 11:15:06 -0400 Subject: [PATCH 3/9] refactor(codex): read a child's usage from its last token_usage_record Codex writes a token_count with its usage counters at zero when a request overflows the context window, and writes a token_count only after the response's tools finish, so a child's last token_count could read zero or miss its last response. The read now takes the thread total of the child's last token_usage_record, which codex writes as each response completes and never resets. A read cut at its 1 MiB bound is returned as an error, which Run prints as a warning, and a child with a counter past 2^40 is skipped so planted values cannot wrap the run's totals. The Run comment says the read follows any exit 0. Signed-off-by: Dharit Shah --- internal/runtime/codex_run.go | 8 +- internal/runtime/codex_subagents.go | 88 ++++++++++------- internal/runtime/codex_subagents_test.go | 99 ++++++++++++++++--- internal/runtime/testdata/codex/README.md | 10 +- .../testdata/codex/child_usage_no_model.jsonl | 3 +- 5 files changed, 150 insertions(+), 58 deletions(-) diff --git a/internal/runtime/codex_run.go b/internal/runtime/codex_run.go index 6c9db32e8e..0bd9a35669 100644 --- a/internal/runtime/codex_run.go +++ b/internal/runtime/codex_run.go @@ -660,10 +660,10 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri } // Children are separate threads whose tokens never reached the stream - // just parsed; their rollouts are the only record. Read only after a - // clean exit: a killed, cancelled or timed-out iteration reports the - // parent's tokens only. A read failure costs the breakdown, not the - // iteration. + // just parsed; their rollouts are the only record. Read after any exit + // 0, even one the stream reports as an error below; a killed, cancelled + // or timed-out iteration exits non-zero and reports the parent's tokens + // only. A read failure costs the breakdown, not the iteration. if exitCode == 0 && (digests.delegating() || len(childIDs.IDs) > 0) { n, ferr := r.foldCodexChildUsage(params.SandboxName, childIDs.IDs, metrics) if ferr != nil { diff --git a/internal/runtime/codex_subagents.go b/internal/runtime/codex_subagents.go index bcb550b581..988123eb70 100644 --- a/internal/runtime/codex_subagents.go +++ b/internal/runtime/codex_subagents.go @@ -18,8 +18,8 @@ import ( // A Codex child is a separate thread. Its tokens never reach the parent's // `exec --json` stream (turn.completed.usage excludes children — #6970, probe // of 2026-09-03), and codex records them only in that thread's rollout under -// $CODEX_HOME/sessions/: the running total in `event_msg`/`token_count` -// lines (`info.total_token_usage`, the stream's five usage fields plus +// $CODEX_HOME/sessions/: the running total in `token_usage_record` lines +// (`payload.thread_token_usage`, the stream's five usage fields plus // total_tokens), the model in the `turn_context` line, and the thread id in // the file name (rollout--.jsonl). Run reads those // lines back with one bounded command after codex exits and folds them into @@ -43,6 +43,11 @@ const codexChildUsageMarker = "fullsend-child" // most two lines per child, so a real read is a few kilobytes. const codexChildUsageMaxBytes = 1 << 20 +// codexChildUsageMaxTokens is far above any counter a real thread reports. +// A child with a counter past it is skipped, so under the bounded read the +// sums of the counters left cannot wrap the run's figures. +const codexChildUsageMaxTokens = 1 << 40 + // codexChildUsageThreadID is the shape of a codex thread id (UUID text). A // child id comes off the stream and goes into a shell command, so nothing // else is accepted; shellQuote wraps it as well. @@ -54,23 +59,28 @@ type codexChildUsage struct { // Model is turn_context.payload.model of the child's first turn; "" // when the rollout has no turn_context. Model string - // Usage is info.total_token_usage of the child's last token_count: the - // thread's cumulative total, so one snapshot is the whole child. + // Usage is payload.thread_token_usage of the child's last + // token_usage_record: codex adds every completed response to it, and a + // context-window overflow does not reset it, so one record is the whole + // child. Usage codexUsage - // HasUsage is false for a child that never reported a token_count: it - // errored before its first response (the provider rejected its model in - // the 2026-09-29 paid probe) and contributes nothing, not even a request. + // HasUsage is false for a child with no token_usage_record: it errored + // before its first response (the provider rejected its model in the + // 2026-09-29 paid probe) and contributes nothing, not even a request. HasUsage bool } // codexChildUsageReadCommand renders the one in-sandbox command that reads // the children's rollouts. For each id, sorted and once, it finds the // thread's rollout by name, prints a marker line, then the rollout's first -// turn_context line and its last token_count line. Two greps rather than a -// cat: a review child's rollout is megabytes and the two lines are all the -// fold needs, so the head -c bound is a safety net, not the usual limit. -// `command -p` bypasses shell functions and uses the system PATH, as the -// launch guards do. +// turn_context line and its last token_usage_record line. The record and not +// the last token_count: codex writes a token_count whose usage counters are +// zero when a request overflows the context window, and writes it only after +// the response's tools finish, so a child cancelled in between can lack one +// for its last response. Two greps rather than a cat: a review child's +// rollout is megabytes and the two lines are all the fold needs, so the +// head -c bound is a safety net, not the usual limit. `command -p` bypasses +// shell functions and uses the system PATH, as the launch guards do. func codexChildUsageReadCommand(sessionsDir string, ids []string) (string, error) { ids = slices.Clone(ids) slices.Sort(ids) @@ -83,14 +93,15 @@ func codexChildUsageReadCommand(sessionsDir string, ids []string) (string, error quoted = append(quoted, shellQuote(id)) } return fmt.Sprintf( - `for id in %s; do command -p find %s -type f -name "rollout-*-$id.jsonl" 2>/dev/null | while IFS= read -r f; do printf '%%s %%s\n' %s "$id"; command -p grep -a -e '"type":"turn_context"' -- "$f" 2>/dev/null | command -p head -n 1; command -p grep -a -e '"type":"token_count"' -- "$f" 2>/dev/null | command -p tail -n 1; done; done | command -p head -c %d`, + `for id in %s; do command -p find %s -type f -name "rollout-*-$id.jsonl" 2>/dev/null | while IFS= read -r f; do printf '%%s %%s\n' %s "$id"; command -p grep -a -e '"type":"turn_context"' -- "$f" 2>/dev/null | command -p head -n 1; command -p grep -a -e '"type":"token_usage_record"' -- "$f" 2>/dev/null | command -p tail -n 1; done; done | command -p head -c %d`, strings.Join(quoted, " "), shellQuote(sessionsDir), shellQuote(codexChildUsageMarker), codexChildUsageMaxBytes), nil } // parseCodexChildUsage decodes the read command's output: a marker line per -// child, then that child's turn_context and token_count lines. A line before -// the first marker belongs to nobody; a line that is not JSON (the head -c -// cut, or something planted in the agent-writable directory) is skipped. +// child, then that child's turn_context and token_usage_record lines. A line +// before the first marker belongs to nobody; a line that is not JSON (the +// head -c cut, or something planted in the agent-writable directory) is +// skipped. func parseCodexChildUsage(data []byte) []codexChildUsage { var out []codexChildUsage marker := []byte(codexChildUsageMarker + " ") @@ -111,11 +122,8 @@ func parseCodexChildUsage(data []byte) []codexChildUsage { var env struct { Type string `json:"type"` Payload struct { - Type string `json:"type"` - Model string `json:"model"` - Info struct { - Total codexUsage `json:"total_token_usage"` - } `json:"info"` + Model string `json:"model"` + Thread codexUsage `json:"thread_token_usage"` } `json:"payload"` } if json.Unmarshal(line, &env) != nil { @@ -127,8 +135,8 @@ func parseCodexChildUsage(data []byte) []codexChildUsage { if cur.Model == "" { cur.Model = strings.TrimSpace(env.Payload.Model) } - case env.Type == "event_msg" && env.Payload.Type == "token_count": - cur.Usage = env.Payload.Info.Total + case env.Type == "token_usage_record": + cur.Usage = env.Payload.Thread cur.HasUsage = true } } @@ -199,25 +207,27 @@ func (c *codexChildIDs) scan(line []byte) { // foldCodexChildUsage adds the parent's own entry to m.PerModelUsage and, // when the parent spawned children, reads their rollouts with one bounded -// sandbox command and folds each child's last cumulative usage into the -// totals and the breakdown. It returns how many child threads reported -// usage. An error is a read that did not happen or did not finish; the -// caller reports it and keeps the run, because losing the breakdown must not -// fail an iteration that succeeded. No sandbox command runs when childIDs is -// empty. +// sandbox command and folds each child's cumulative usage into the totals +// and the breakdown. It returns how many child threads it folded. An error +// is a read that did not happen or did not finish (a read cut at the bound +// keeps the children before the cut); the caller reports it and keeps the +// run, because losing the breakdown must not fail an iteration that +// succeeded. No sandbox command runs when childIDs is empty. // // The parent's entry is added first and always. Iterations are summed // (internal/cli aggregateRunMetrics), so an iteration that dispatched // nothing, or whose read failed, still has to be in the breakdown or the // run's per_model_usage stops summing to its totals across a retry. // -// Requests: one for the parent iteration, one per child thread with usage -// (the invocation-count semantics of the pi fold). A child that never -// reported a token_count contributes nothing. A child whose rollout names -// no model is bucketed under piSubagentUnknownModel, as pi does for a -// record without one. Child reasoning tokens go to the run-level total -// only. The figures come from an agent-writable directory, so every counter -// is floored at zero before it is added, as pi's fold clamps its records. +// Requests: one for the parent iteration, one per child thread folded (the +// invocation-count semantics of the pi fold). A child with no +// token_usage_record, or whose rollout is missing, recorded nothing and +// contributes nothing. A child whose rollout names no model is bucketed +// under piSubagentUnknownModel, as pi does for a record without one. Child +// reasoning tokens go to the run-level total only. The figures come from an +// agent-writable directory, so every counter is floored at zero, as pi's +// fold clamps its records, and a child with a counter past +// codexChildUsageMaxTokens is skipped; both happen before anything is added. func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, m *RunMetrics) (folded int, err error) { per := m.PerModelUsage if per == nil { @@ -264,6 +274,9 @@ func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, // are floored here. c := child.Usage.counters() reasoning, cacheWrite, cacheRead := nonNegative(c.Reasoning), nonNegative(c.CacheWrite), nonNegative(c.CacheRead) + if max(c.Input, c.Output, reasoning, cacheWrite, cacheRead) > codexChildUsageMaxTokens { + continue + } key := child.Model if key == "" { key = piSubagentUnknownModel @@ -282,5 +295,8 @@ func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, m.CacheReadInputTokens += cacheRead folded++ } + if len(stdout) >= codexChildUsageMaxBytes { + return folded, fmt.Errorf("reading the child rollouts: cut at %d bytes; only the children before the cut are counted", codexChildUsageMaxBytes) + } return folded, nil } diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index 1363120484..607308bf56 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -131,7 +131,7 @@ func TestCodexChildUsageReadCommand_Executes(t *testing.T) { assert.Equal(t, codexChildUsage{ ID: codexChildSameModelID, Model: "gpt-5.6-luna", HasUsage: true, Usage: codexUsage{InputTokens: 7381, CacheWriteInputTokens: 7378, OutputTokens: 8}, - }, got[0], "the last cumulative token_count, not the sum of the two") + }, got[0], "the thread total of the record, not the sum of the two token_counts") assert.Equal(t, codexChildUsage{ ID: codexChildOtherModelID, Model: "gpt-5.6-terra", HasUsage: true, Usage: codexUsage{InputTokens: 4000, CachedInputTokens: 1000, CacheWriteInputTokens: 2000, OutputTokens: 300, ReasoningOutputTokens: 100}, @@ -140,35 +140,70 @@ func TestCodexChildUsageReadCommand_Executes(t *testing.T) { "a child that errored before its first response has a model and no usage") } +// The read takes the thread total of the last token_usage_record. The +// token_count codex writes after a context-window overflow has its usage +// counters at zero, and a rate-limit token_count before the first response +// has no usage; neither is read. +func TestCodexChildUsageReadCommand_ReadsTheThreadTotal(t *testing.T) { + t.Parallel() + + usage := func(in, out, total int) string { + return fmt.Sprintf(`{"input_tokens":%d,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":%d,"reasoning_output_tokens":0,"total_tokens":%d}`, in, out, total) + } + count := func(info string) string { + return `{"type":"event_msg","payload":{"type":"token_count","info":` + info + `}}` + } + record := func(in, out int) string { + return `{"type":"token_usage_record","payload":{"thread_token_usage":` + usage(in, out, in+out) + `}}` + } + rollout := strings.Join([]string{ + `{"type":"turn_context","payload":{"model":"gpt-5.6-luna"}}`, + count(`null`), + record(3000, 4), + count(`{"total_token_usage":` + usage(3000, 4, 3004) + `}`), + record(90000, 20), + count(`{"total_token_usage":` + usage(0, 0, 258400) + `,"last_token_usage":` + usage(0, 0, 168380) + `,"model_context_window":258400}`), + }, "\n") + "\n" + sessions := writeCodexChildRollouts(t) + require.NoError(t, os.WriteFile(filepath.Join(sessions, "2026", "09", "29", "rollout-2026-09-29T15-46-38-"+codexChildSameModelID+".jsonl"), []byte(rollout), 0o644)) + + got := runCodexChildUsageRead(t, sessions, []string{codexChildSameModelID}) + require.Len(t, got, 1) + assert.Equal(t, codexChildUsage{ + ID: codexChildSameModelID, Model: "gpt-5.6-luna", HasUsage: true, + Usage: codexUsage{InputTokens: 90000, OutputTokens: 20}, + }, got[0], "the last record's thread total, not the zeroed token_count after it") +} + func TestParseCodexChildUsage(t *testing.T) { t.Parallel() turn := func(model string) string { return `{"type":"turn_context","payload":{"model":"` + model + `"}}` } - count := func(in, out int) string { - return fmt.Sprintf(`{"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":%d,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":%d,"reasoning_output_tokens":0,"total_tokens":%d}}}}`, in, out, in+out) + record := func(in, out int) string { + return fmt.Sprintf(`{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tokens":%d,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":%d,"reasoning_output_tokens":0,"total_tokens":%d}}}`, in, out, in+out) } data := strings.Join([]string{ - count(999, 999), // before any marker: nobody's line + record(999, 999), // before any marker: nobody's line codexChildUsageMarker + " " + codexChildSameModelID, turn("gpt-5.6-terra"), turn("gpt-5.6-sol"), - count(10, 1), + record(10, 1), "not json", - count(20, 2), + record(20, 2), "", codexChildUsageMarker + " " + codexChildOtherModelID, - count(5, 5), + record(5, 5), codexChildUsageMarker + " " + codexChildFailedID, turn("gpt-5.6-terra"), - `{"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":7,"cach`, + `{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tokens":7,"cach`, }, "\n") got := parseCodexChildUsage([]byte(data)) require.Len(t, got, 3) assert.Equal(t, codexChildUsage{ID: codexChildSameModelID, Model: "gpt-5.6-terra", HasUsage: true, Usage: codexUsage{InputTokens: 20, OutputTokens: 2}}, - got[0], "first turn_context names the model, the last token_count wins, a malformed line is skipped") + got[0], "first turn_context names the model, the last record wins, a malformed line is skipped") assert.Equal(t, codexChildUsage{ID: codexChildOtherModelID, HasUsage: true, Usage: codexUsage{InputTokens: 5, OutputTokens: 5}}, got[1], "no turn_context: the model stays empty and the fold buckets it") assert.Equal(t, codexChildUsage{ID: codexChildFailedID, Model: "gpt-5.6-terra"}, @@ -364,12 +399,13 @@ func TestFoldCodexChildUsage(t *testing.T) { } } -// A planted rollout cannot lower the run's figures: counters() floors only -// its two subtractions, so the fold floors the three raw fields. +// A planted negative counter cannot lower the run's figures: counters() +// floors only its two subtractions, so the fold floors the three raw fields +// (a wrap is TestFoldCodexChildUsage_SkipsImplausibleCounters). func TestFoldCodexChildUsage_ClampsNegativeCounters(t *testing.T) { sessions := writeCodexChildRollouts(t) rollout := `{"type":"turn_context","payload":{"model":"gpt-5.6-luna"}}` + "\n" + - `{"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":10,"cached_input_tokens":-5000,"cache_write_input_tokens":-7000,"output_tokens":20,"reasoning_output_tokens":-900,"total_tokens":30}}}}` + "\n" + `{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tokens":10,"cached_input_tokens":-5000,"cache_write_input_tokens":-7000,"output_tokens":20,"reasoning_output_tokens":-900,"total_tokens":30}}}` + "\n" require.NoError(t, os.WriteFile(filepath.Join(sessions, "2026", "09", "29", "rollout-2026-09-29T15-46-38-"+codexChildSameModelID+".jsonl"), []byte(rollout), 0o644)) fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) @@ -385,6 +421,45 @@ func TestFoldCodexChildUsage_ClampsNegativeCounters(t *testing.T) { assertCodexUsageSumsToTotals(t, m) } +// A read cut at the bound is a warning; the children before the cut stay +// folded and the ones past it are not counted. +func TestFoldCodexChildUsage_CutReadIsAWarning(t *testing.T) { + sessions := writeCodexChildRollouts(t, codexChildSameModelID) + day := filepath.Join(sessions, "2026", "09", "29") + planted := `{"type":"turn_context","payload":{"model":"` + strings.Repeat("x", codexChildUsageMaxBytes) + `"}}` + "\n" + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-2026-09-29T15-46-38-"+codexChildOtherModelID+".jsonl"), []byte(planted), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-2026-09-29T15-46-38-"+codexChildFailedID+".jsonl"), readCodexFixture(t, "child_usage_other_model.jsonl"), 0o644)) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + + m := codexParentMetrics("gpt-5.6-luna") + n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID, codexChildOtherModelID, codexChildFailedID}, m) + require.Error(t, err) + assert.Contains(t, err.Error(), "cut at") + assert.Equal(t, 1, n, "the child before the cut") + assert.NotContains(t, m.PerModelUsage, "gpt-5.6-terra", "the child past the cut") + assert.Equal(t, 2, m.PerModelUsage["gpt-5.6-luna"].Requests) + assertCodexUsageSumsToTotals(t, m) +} + +// A counter no real thread reaches is skipped: two planted rollouts whose +// input sums past MaxInt would otherwise wrap the run's 15 down to 5. +func TestFoldCodexChildUsage_SkipsImplausibleCounters(t *testing.T) { + sessions := writeCodexChildRollouts(t) + day := filepath.Join(sessions, "2026", "09", "29") + for name, input := range map[string]string{"a": "9223372036854775807", "b": "9223372036854775799"} { + rollout := `{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tokens":` + input + `}}}` + "\n" + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-"+name+"-"+codexChildSameModelID+".jsonl"), []byte(rollout), 0o644)) + } + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + + m := codexParentMetrics("gpt-5.6-luna") + n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID}, m) + require.NoError(t, err) + assert.Zero(t, n) + assert.Equal(t, codexTokenTotals{15, 1140, 291, 13618, 40590}, codexTotalsOf(m)) + assertCodexUsageSumsToTotals(t, m) +} + // No child id, no sandbox command: PATH holds no openshell, so any exec // would fail to start. The parent's entry still lands in the breakdown // (a delegating agent that dispatched nothing), and a parent without a diff --git a/internal/runtime/testdata/codex/README.md b/internal/runtime/testdata/codex/README.md index 271af07d97..9df1f051e2 100644 --- a/internal/runtime/testdata/codex/README.md +++ b/internal/runtime/testdata/codex/README.md @@ -35,15 +35,15 @@ Inputs for `foldCodexChildUsage` (`internal/runtime/codex_subagents.go`), not fo underscored envelope of `codex_redact.go`), not the `exec --json` stream. Line types and fields were copied from the rollouts of the 0.157.0 paid probe of 2026-09-29, trimmed, with synthetic ids. The fold reads two lines per rollout: the first `turn_context` (its -`payload.model`) and the last `event_msg`/`token_count` (its `payload.info.total_token_usage`, -cumulative for the thread). +`payload.model`) and the last `token_usage_record` (its `payload.thread_token_usage`, cumulative for +the thread and not reset when a request overflows the context window, unlike `token_count`). | Fixture | Covers | |---|---| -| `child_usage_same_model.jsonl` | A child on the parent's model, `gpt-5.6-luna`, with two cumulative `token_count` lines (3000 then 7381 input): the last one is the child's whole usage. | +| `child_usage_same_model.jsonl` | A child on the parent's model, `gpt-5.6-luna`, with two cumulative `token_count` lines (3000 then 7381 input) and the `token_usage_record` of its second response, whose thread total (7381) is the child's whole usage. | | `child_usage_other_model.jsonl` | A child on `gpt-5.6-terra`, every normalized counter non-zero. | -| `child_usage_failed.jsonl` | A child whose model the provider rejected (404): `turn_context` names the model, `task_complete` carries `error`, and there is no `token_count`, so it contributes nothing. | -| `child_usage_no_model.jsonl` | A child with a `token_count` and no `turn_context`: its usage is bucketed under `unknown`. | +| `child_usage_failed.jsonl` | A child whose model the provider rejected (404): `turn_context` names the model, `task_complete` carries `error`, and there is no `token_usage_record`, so it contributes nothing. | +| `child_usage_no_model.jsonl` | A child with a `token_usage_record` and no `turn_context`: its usage is bucketed under `unknown`. | The tests lay the rollouts out under a temporary sessions tree as `2026/09/29/rollout-2026-09-29T15-46-38-.jsonl`, the name codex gives a rollout. diff --git a/internal/runtime/testdata/codex/child_usage_no_model.jsonl b/internal/runtime/testdata/codex/child_usage_no_model.jsonl index 4aab63925f..295cceaa1d 100644 --- a/internal/runtime/testdata/codex/child_usage_no_model.jsonl +++ b/internal/runtime/testdata/codex/child_usage_no_model.jsonl @@ -1,2 +1,3 @@ {"timestamp":"2026-09-29T19:46:39.000Z","ordinal":0,"type":"session_meta","payload":{"session_id":"01a06300-0000-7000-8000-000000000050","id":"01a06300-0000-7000-8000-0000000000a4","parent_thread_id":"01a06300-0000-7000-8000-000000000050","agent_role":null,"multi_agent_version":"v1"}} -{"timestamp":"2026-09-29T19:46:39.500Z","ordinal":1,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":50,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":5,"reasoning_output_tokens":0,"total_tokens":55}},"rate_limits":null}} +{"timestamp":"2026-09-29T19:46:39.400Z","ordinal":1,"type":"token_usage_record","payload":{"thread_id":"01a06300-0000-7000-8000-0000000000a4","turn_id":"01a06300-0000-7000-8000-0000000000b4","session_id":"01a06300-0000-7000-8000-000000000050","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","response_id":"resp_fixture_a4_1","usage":{"input_tokens":50,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":5,"reasoning_output_tokens":0,"total_tokens":55},"turn_token_usage":{"input_tokens":50,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":5,"reasoning_output_tokens":0,"total_tokens":55},"thread_token_usage":{"input_tokens":50,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":5,"reasoning_output_tokens":0,"total_tokens":55}}} +{"timestamp":"2026-09-29T19:46:39.500Z","ordinal":2,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":50,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":5,"reasoning_output_tokens":0,"total_tokens":55}},"rate_limits":null}} From 6f9252f687e8cfdf1c11dcc5467a91d2b36894eb Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 19 Oct 2026 13:02:38 -0400 Subject: [PATCH 4/9] refactor(codex): warn when a child's rollout cannot be read A rollout the read could not open, or one a failed search of the sessions directory did not find, looked like a child with no usage: a pipeline's status is its last command's, and find and grep send their errors to /dev/null. The read now prints an unreadable marker for such a child, and the fold returns it as an error, which Run prints as a warning, keeping the children it did read. A missing sessions directory warns the same way; a rollout missing from a directory searched without error still adds nothing. Signed-off-by: Dharit Shah --- internal/runtime/codex_subagents.go | 61 ++++++++++++++++++------ internal/runtime/codex_subagents_test.go | 41 ++++++++++++++++ 2 files changed, 87 insertions(+), 15 deletions(-) diff --git a/internal/runtime/codex_subagents.go b/internal/runtime/codex_subagents.go index 988123eb70..5f9ba0bdd2 100644 --- a/internal/runtime/codex_subagents.go +++ b/internal/runtime/codex_subagents.go @@ -37,6 +37,12 @@ import ( // misattribute that child's own lines. const codexChildUsageMarker = "fullsend-child" +// codexChildUnreadableMarker starts the line the read command prints for a +// child whose rollout it could not read, or that a failed search of the +// sessions directory did not find. A rollout line that imitates it can only +// add a warning and misattribute that child's own lines. +const codexChildUnreadableMarker = "fullsend-unreadable" + // codexChildUsageMaxBytes bounds the read. The sessions directory is // agent-writable, so an unbounded read is an unbounded allocation in the // runner (the reason piSubagentUsageMaxBytes exists). The command selects at @@ -68,6 +74,10 @@ type codexChildUsage struct { // before its first response (the provider rejected its model in the // 2026-09-29 paid probe) and contributes nothing, not even a request. HasUsage bool + // Unreadable is set when the read could not read the child's rollout, or + // a failed search of the sessions directory did not find it; the fold + // reports it. + Unreadable bool } // codexChildUsageReadCommand renders the one in-sandbox command that reads @@ -77,10 +87,14 @@ type codexChildUsage struct { // the last token_count: codex writes a token_count whose usage counters are // zero when a request overflows the context window, and writes it only after // the response's tools finish, so a child cancelled in between can lack one -// for its last response. Two greps rather than a cat: a review child's -// rollout is megabytes and the two lines are all the fold needs, so the -// head -c bound is a safety net, not the usual limit. `command -p` bypasses -// shell functions and uses the system PATH, as the launch guards do. +// for its last response. A rollout it cannot read, or one a failed search of +// the sessions directory did not find (a missing directory included), prints +// codexChildUnreadableMarker in its place; a rollout missing from a +// directory searched without error prints nothing. Two greps rather than a +// cat: a review child's rollout is megabytes and the two lines are all the +// fold needs, so the head -c bound is a safety net, not the usual limit. +// `command -p` bypasses shell functions and uses the system PATH, as the +// launch guards do. func codexChildUsageReadCommand(sessionsDir string, ids []string) (string, error) { ids = slices.Clone(ids) slices.Sort(ids) @@ -93,18 +107,19 @@ func codexChildUsageReadCommand(sessionsDir string, ids []string) (string, error quoted = append(quoted, shellQuote(id)) } return fmt.Sprintf( - `for id in %s; do command -p find %s -type f -name "rollout-*-$id.jsonl" 2>/dev/null | while IFS= read -r f; do printf '%%s %%s\n' %s "$id"; command -p grep -a -e '"type":"turn_context"' -- "$f" 2>/dev/null | command -p head -n 1; command -p grep -a -e '"type":"token_usage_record"' -- "$f" 2>/dev/null | command -p tail -n 1; done; done | command -p head -c %d`, - strings.Join(quoted, " "), shellQuote(sessionsDir), shellQuote(codexChildUsageMarker), codexChildUsageMaxBytes), nil + `for id in %s; do files=$(command -p find %s -type f -name "rollout-*-$id.jsonl" 2>/dev/null) || [ -n "$files" ] || printf '%%s %%s\n' %s "$id"; printf '%%s\n' "$files" | while IFS= read -r f; do [ -n "$f" ] || continue; if [ ! -r "$f" ]; then printf '%%s %%s\n' %s "$id"; continue; fi; printf '%%s %%s\n' %s "$id"; command -p grep -a -e '"type":"turn_context"' -- "$f" 2>/dev/null | command -p head -n 1; command -p grep -a -e '"type":"token_usage_record"' -- "$f" 2>/dev/null | command -p tail -n 1; done; done | command -p head -c %d`, + strings.Join(quoted, " "), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(codexChildUnreadableMarker), shellQuote(codexChildUsageMarker), codexChildUsageMaxBytes), nil } // parseCodexChildUsage decodes the read command's output: a marker line per -// child, then that child's turn_context and token_usage_record lines. A line -// before the first marker belongs to nobody; a line that is not JSON (the -// head -c cut, or something planted in the agent-writable directory) is -// skipped. +// child, then that child's turn_context and token_usage_record lines, or an +// unreadable marker line for a child it could not read. A line before the +// first marker belongs to nobody; a line that is not JSON (the head -c cut, +// or something planted in the agent-writable directory) is skipped. func parseCodexChildUsage(data []byte) []codexChildUsage { var out []codexChildUsage marker := []byte(codexChildUsageMarker + " ") + unreadable := []byte(codexChildUnreadableMarker + " ") scanner := bufio.NewScanner(bytes.NewReader(data)) scanner.Buffer(make([]byte, 0, 64*1024), maxTranscriptLineSize) for scanner.Scan() { @@ -116,6 +131,10 @@ func parseCodexChildUsage(data []byte) []codexChildUsage { out = append(out, codexChildUsage{ID: string(id)}) continue } + if id, ok := bytes.CutPrefix(line, unreadable); ok { + out = append(out, codexChildUsage{ID: string(id), Unreadable: true}) + continue + } if len(out) == 0 { continue } @@ -209,10 +228,11 @@ func (c *codexChildIDs) scan(line []byte) { // when the parent spawned children, reads their rollouts with one bounded // sandbox command and folds each child's cumulative usage into the totals // and the breakdown. It returns how many child threads it folded. An error -// is a read that did not happen or did not finish (a read cut at the bound -// keeps the children before the cut); the caller reports it and keeps the -// run, because losing the breakdown must not fail an iteration that -// succeeded. No sandbox command runs when childIDs is empty. +// is a read that did not happen or did not finish (a read cut at the bound, +// or a rollout it could not read, keeps the children it did read); the +// caller reports it and keeps the run, because losing the breakdown must not +// fail an iteration that succeeded. No sandbox command runs when childIDs is +// empty. // // The parent's entry is added first and always. Iterations are summed // (internal/cli aggregateRunMetrics), so an iteration that dispatched @@ -266,7 +286,11 @@ func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, if exitCode != 0 { return 0, fmt.Errorf("reading the child rollouts: exited %d: %s", exitCode, strings.TrimSpace(sanitizeOutput(stderr))) } + unreadable := 0 for _, child := range parseCodexChildUsage([]byte(stdout)) { + if child.Unreadable { + unreadable++ + } if !child.HasUsage { continue } @@ -295,8 +319,15 @@ func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, m.CacheReadInputTokens += cacheRead folded++ } + var lost []string + if unreadable > 0 { + lost = append(lost, fmt.Sprintf("%d child rollout(s) could not be read", unreadable)) + } if len(stdout) >= codexChildUsageMaxBytes { - return folded, fmt.Errorf("reading the child rollouts: cut at %d bytes; only the children before the cut are counted", codexChildUsageMaxBytes) + lost = append(lost, fmt.Sprintf("cut at %d bytes; only the children before the cut are counted", codexChildUsageMaxBytes)) + } + if len(lost) > 0 { + return folded, fmt.Errorf("reading the child rollouts: %s", strings.Join(lost, "; ")) } return folded, nil } diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index 607308bf56..92b84cefb1 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -441,6 +441,47 @@ func TestFoldCodexChildUsage_CutReadIsAWarning(t *testing.T) { assertCodexUsageSumsToTotals(t, m) } +// A rollout the read cannot open, or one a failed search of the sessions +// directory does not find, is a warning; the children it did read stay +// folded. +func TestFoldCodexChildUsage_UnreadableRolloutIsAWarning(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("file modes do not stop root") + } + tests := []struct { + name string + lock func(t *testing.T, sessions string) string + }{ + {name: "rollout file", lock: func(t *testing.T, sessions string) string { + return filepath.Join(sessions, "2026", "09", "29", "rollout-2026-09-29T15-46-38-"+codexChildOtherModelID+".jsonl") + }}, + {name: "sessions subdirectory", lock: func(t *testing.T, sessions string) string { + dir := filepath.Join(sessions, "2026", "09", "30") + require.NoError(t, os.MkdirAll(dir, 0o755)) + name := "rollout-2026-09-29T15-46-38-" + codexChildOtherModelID + ".jsonl" + require.NoError(t, os.Rename(filepath.Join(sessions, "2026", "09", "29", name), filepath.Join(dir, name))) + return dir + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sessions := writeCodexChildRollouts(t, codexChildSameModelID, codexChildOtherModelID) + locked := tt.lock(t, sessions) + require.NoError(t, os.Chmod(locked, 0)) + t.Cleanup(func() { _ = os.Chmod(locked, 0o755) }) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + + m := codexParentMetrics("gpt-5.6-luna") + n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID, codexChildOtherModelID}, m) + require.Error(t, err) + assert.Contains(t, err.Error(), "1 child rollout(s) could not be read", "a failed search that still found a rollout is not a warning for it") + assert.Equal(t, 1, n, "the readable child is still folded") + assert.Equal(t, 2, m.PerModelUsage["gpt-5.6-luna"].Requests) + assertCodexUsageSumsToTotals(t, m) + }) + } +} + // A counter no real thread reaches is skipped: two planted rollouts whose // input sums past MaxInt would otherwise wrap the run's 15 down to 5. func TestFoldCodexChildUsage_SkipsImplausibleCounters(t *testing.T) { From 6757115dd5e367b5e8e54e3be46ce9d21fcdc1cf Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 19 Oct 2026 14:01:31 -0400 Subject: [PATCH 5/9] refactor(codex): count a child's usage whatever codex's exit code The fold ran only after exit 0, and it is what adds the parent's per_model_usage entry, so an iteration that exited non-zero added its tokens to the run's totals with no entry, and its children's recorded usage was dropped without a word. The fold now runs whatever the exit code: codex writes a child's usage record as each response completes, so a failed, interrupted, cancelled or timed-out iteration keeps what its children recorded. The child's model, read from an agent-writable rollout and used as a metrics.json key, goes through the shared secret redactor, and so does the warning Run prints for a fold error. A child skipped for a counter past 2^40 is reported in that warning, a path a planted file name splits outside the sessions directory is skipped, and the stream collector drops a line of exactly the parser's bound, as the parser does. Signed-off-by: Dharit Shah --- docs/cli/run.md | 16 +- internal/runtime/codex_run.go | 17 +- internal/runtime/codex_subagents.go | 88 ++++++----- internal/runtime/codex_subagents_test.go | 192 ++++++++++++++++------- 4 files changed, 207 insertions(+), 106 deletions(-) diff --git a/docs/cli/run.md b/docs/cli/run.md index 4b6d1ae2b4..c41215c283 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -142,11 +142,12 @@ depend on the process cwd. A map from model spec to `{requests, input_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens, cost_usd}`. -On `pi` the key is the pi model spec (`anthropic-vertex/claude-opus-4-6`); on `codex` it is the bare -OpenAI id (`gpt-5.6-luna`). It exists because a sub-agent's tokens never appear in the parent's +On `pi` the key is the pi model spec (`anthropic-vertex/claude-opus-4-6`); on `codex` it is the +model id codex ran (`gpt-5.6-luna`, or the id after `gateway/`). It exists because a sub-agent's tokens never appear in the parent's stream: a pi sub-agent is a separate `pi` process, and a codex sub-agent is a separate thread whose usage codex records only in that thread's rollout. Without it `total_cost_usd` would grow with no -way to attribute it on pi, and child tokens would be missing from the totals on codex. +way to attribute it on pi, and the child tokens the runner adds to the totals on codex could not be +attributed to a model. On `claude` the key is the model id Claude Code reports (`claude-haiku-4-5@20251001`), with one entry per model that ran, sub-agents included. The token totals come from the result event's @@ -176,10 +177,11 @@ differences in the last bullet. at all; its usage is bucketed there rather than dropped. A dispatch rejected *before* a model was resolved writes no record, so it never reaches the breakdown. - **On codex.** `cost_usd` is `0` in every entry: codex reports no dollar cost, so compare tokens - there. `requests` counts one per child thread that reported usage; `wait`, `send_input` and - `close_agent` calls add none, and a child that errored before its first response has no usage - and adds no `requests`. A codex run that is cancelled or times out reports the parent's tokens - only. + there. `requests` counts one per child rollout that reported usage (codex writes one per thread); + `wait`, `send_input` and `close_agent` calls add none, and a child that errored before its first + response has no usage and adds no `requests`. A codex iteration that exits non-zero, after a + failed or interrupted turn, a cancel or a timeout, still counts what its children recorded: codex + writes a child's usage as each response completes. ## Budget and deadline diff --git a/internal/runtime/codex_run.go b/internal/runtime/codex_run.go index 0bd9a35669..fa6e084b42 100644 --- a/internal/runtime/codex_run.go +++ b/internal/runtime/codex_run.go @@ -659,15 +659,18 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri r.ConfigDir()) } - // Children are separate threads whose tokens never reached the stream - // just parsed; their rollouts are the only record. Read after any exit - // 0, even one the stream reports as an error below; a killed, cancelled - // or timed-out iteration exits non-zero and reports the parent's tokens - // only. A read failure costs the breakdown, not the iteration. - if exitCode == 0 && (digests.delegating() || len(childIDs.IDs) > 0) { + // The fold runs whatever the exit code. The parent's entry goes into the + // breakdown, so a retry keeps per_model_usage summing to the totals, and + // the children's rollouts are read: they are separate threads whose + // tokens never reached the stream just parsed, and codex writes a + // child's usage record as each response completes, so a failed, + // interrupted, cancelled or timed-out iteration keeps what its children + // recorded. A read failure costs the children's tokens, not the + // iteration. + if digests.delegating() || len(childIDs.IDs) > 0 { n, ferr := r.foldCodexChildUsage(params.SandboxName, childIDs.IDs, metrics) if ferr != nil { - printer.StepWarn("Could not read the sub-agent usage: " + sanitizeOutput(ferr.Error())) + printer.StepWarn("Sub-agent usage not fully counted: " + redactSummary(sanitizeOutput(ferr.Error()))) } if n > 0 { printer.StepInfo(fmt.Sprintf("%d sub-agent thread(s) folded into the run metrics", n)) diff --git a/internal/runtime/codex_subagents.go b/internal/runtime/codex_subagents.go index 5f9ba0bdd2..a8c73a7cb9 100644 --- a/internal/runtime/codex_subagents.go +++ b/internal/runtime/codex_subagents.go @@ -49,9 +49,11 @@ const codexChildUnreadableMarker = "fullsend-unreadable" // most two lines per child, so a real read is a few kilobytes. const codexChildUsageMaxBytes = 1 << 20 -// codexChildUsageMaxTokens is far above any counter a real thread reports. -// A child with a counter past it is skipped, so under the bounded read the -// sums of the counters left cannot wrap the run's figures. +// codexChildUsageMaxTokens is far above any counter a real thread reports. A +// child whose record carries a counter past it is skipped, with a warning, +// so under the bounded read the sums of the counters left cannot wrap the +// run's figures. A counter past the int range does not decode, so its record +// counts nothing, as a malformed line does. const codexChildUsageMaxTokens = 1 << 40 // codexChildUsageThreadID is the shape of a codex thread id (UUID text). A @@ -70,31 +72,34 @@ type codexChildUsage struct { // context-window overflow does not reset it, so one record is the whole // child. Usage codexUsage - // HasUsage is false for a child with no token_usage_record: it errored - // before its first response (the provider rejected its model in the - // 2026-09-29 paid probe) and contributes nothing, not even a request. + // HasUsage is false for a child with no token_usage_record, such as one + // that errored before its first response (the provider rejected its + // model in the 2026-09-29 paid probe); it contributes nothing, not even a + // request. HasUsage bool - // Unreadable is set when the read could not read the child's rollout, or - // a failed search of the sessions directory did not find it; the fold + // Unreadable is set when the child's rollout failed `test -r`, or a + // failed search of the sessions directory did not find it; the fold // reports it. Unreadable bool } // codexChildUsageReadCommand renders the one in-sandbox command that reads -// the children's rollouts. For each id, sorted and once, it finds the -// thread's rollout by name, prints a marker line, then the rollout's first -// turn_context line and its last token_usage_record line. The record and not -// the last token_count: codex writes a token_count whose usage counters are -// zero when a request overflows the context window, and writes it only after -// the response's tools finish, so a child cancelled in between can lack one -// for its last response. A rollout it cannot read, or one a failed search of -// the sessions directory did not find (a missing directory included), prints -// codexChildUnreadableMarker in its place; a rollout missing from a -// directory searched without error prints nothing. Two greps rather than a -// cat: a review child's rollout is megabytes and the two lines are all the -// fold needs, so the head -c bound is a safety net, not the usual limit. -// `command -p` bypasses shell functions and uses the system PATH, as the -// launch guards do. +// the children's rollouts. For each id, sorted and once, it finds every +// rollout named for the thread (codex writes one), prints a marker line, +// then the rollout's first turn_context line and its last token_usage_record +// line. The record and not the last token_count: codex writes a token_count +// whose usage counters are zero when a request overflows the context window, +// and writes it only after the response's tools finish, so a child cancelled +// in between can lack one for its last response. A rollout that fails +// `test -r`, or one a failed search of the sessions directory did not find +// (a missing directory included), prints codexChildUnreadableMarker in its +// place; a rollout missing from a directory searched without error prints +// nothing, and a path outside the sessions directory (a planted file name +// with a newline in it) is skipped. Two greps rather than a cat: a review +// child's rollout is megabytes and the two lines are all the fold needs, so +// the head -c bound is a safety net, not the usual limit. `command -p` +// bypasses shell functions and uses the system PATH, as the launch guards +// do. func codexChildUsageReadCommand(sessionsDir string, ids []string) (string, error) { ids = slices.Clone(ids) slices.Sort(ids) @@ -107,8 +112,8 @@ func codexChildUsageReadCommand(sessionsDir string, ids []string) (string, error quoted = append(quoted, shellQuote(id)) } return fmt.Sprintf( - `for id in %s; do files=$(command -p find %s -type f -name "rollout-*-$id.jsonl" 2>/dev/null) || [ -n "$files" ] || printf '%%s %%s\n' %s "$id"; printf '%%s\n' "$files" | while IFS= read -r f; do [ -n "$f" ] || continue; if [ ! -r "$f" ]; then printf '%%s %%s\n' %s "$id"; continue; fi; printf '%%s %%s\n' %s "$id"; command -p grep -a -e '"type":"turn_context"' -- "$f" 2>/dev/null | command -p head -n 1; command -p grep -a -e '"type":"token_usage_record"' -- "$f" 2>/dev/null | command -p tail -n 1; done; done | command -p head -c %d`, - strings.Join(quoted, " "), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(codexChildUnreadableMarker), shellQuote(codexChildUsageMarker), codexChildUsageMaxBytes), nil + `for id in %s; do files=$(command -p find %s -type f -name "rollout-*-$id.jsonl" 2>/dev/null) || [ -n "$files" ] || printf '%%s %%s\n' %s "$id"; printf '%%s\n' "$files" | while IFS= read -r f; do case $f in %s/*) ;; *) continue ;; esac; if [ ! -r "$f" ]; then printf '%%s %%s\n' %s "$id"; continue; fi; printf '%%s %%s\n' %s "$id"; command -p grep -a -e '"type":"turn_context"' -- "$f" 2>/dev/null | command -p head -n 1; command -p grep -a -e '"type":"token_usage_record"' -- "$f" 2>/dev/null | command -p tail -n 1; done; done | command -p head -c %d`, + strings.Join(quoted, " "), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(codexChildUsageMarker), codexChildUsageMaxBytes), nil } // parseCodexChildUsage decodes the read command's output: a marker line per @@ -194,10 +199,11 @@ func (c *codexChildIDs) Write(p []byte) (int, error) { } } -// take appends to the pending line, dropping it once it passes the parser's -// own line bound (streamBufSize): parseCodexStream skips such a line too. +// take appends to the pending line, dropping it once it reaches the +// parser's own line bound (streamBufSize): parseCodexStream skips such a +// line too. func (c *codexChildIDs) take(b []byte) { - if c.overlong || len(c.line)+len(b) > streamBufSize { + if c.overlong || len(c.line)+len(b) >= streamBufSize { c.overlong = true c.line = c.line[:0] return @@ -227,19 +233,20 @@ func (c *codexChildIDs) scan(line []byte) { // foldCodexChildUsage adds the parent's own entry to m.PerModelUsage and, // when the parent spawned children, reads their rollouts with one bounded // sandbox command and folds each child's cumulative usage into the totals -// and the breakdown. It returns how many child threads it folded. An error -// is a read that did not happen or did not finish (a read cut at the bound, -// or a rollout it could not read, keeps the children it did read); the -// caller reports it and keeps the run, because losing the breakdown must not -// fail an iteration that succeeded. No sandbox command runs when childIDs is -// empty. +// and the breakdown. It returns how many child rollouts it folded (codex +// writes one per thread). An error names what was not counted: a read that +// did not happen or did not finish, a rollout that could not be read, or a +// child skipped for a counter past codexChildUsageMaxTokens; the children it +// did read stay folded. The caller reports it and keeps the run, because +// losing the children's tokens must not fail an iteration that succeeded. No +// sandbox command runs when childIDs is empty. // // The parent's entry is added first and always. Iterations are summed // (internal/cli aggregateRunMetrics), so an iteration that dispatched // nothing, or whose read failed, still has to be in the breakdown or the // run's per_model_usage stops summing to its totals across a retry. // -// Requests: one for the parent iteration, one per child thread folded (the +// Requests: one for the parent iteration, one per child rollout folded (the // invocation-count semantics of the pi fold). A child with no // token_usage_record, or whose rollout is missing, recorded nothing and // contributes nothing. A child whose rollout names no model is bucketed @@ -247,7 +254,8 @@ func (c *codexChildIDs) scan(line []byte) { // reasoning tokens go to the run-level total only. The figures come from an // agent-writable directory, so every counter is floored at zero, as pi's // fold clamps its records, and a child with a counter past -// codexChildUsageMaxTokens is skipped; both happen before anything is added. +// codexChildUsageMaxTokens is skipped and reported; both happen before +// anything is added. func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, m *RunMetrics) (folded int, err error) { per := m.PerModelUsage if per == nil { @@ -286,7 +294,7 @@ func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, if exitCode != 0 { return 0, fmt.Errorf("reading the child rollouts: exited %d: %s", exitCode, strings.TrimSpace(sanitizeOutput(stderr))) } - unreadable := 0 + unreadable, implausible := 0, 0 for _, child := range parseCodexChildUsage([]byte(stdout)) { if child.Unreadable { unreadable++ @@ -299,9 +307,12 @@ func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, c := child.Usage.counters() reasoning, cacheWrite, cacheRead := nonNegative(c.Reasoning), nonNegative(c.CacheWrite), nonNegative(c.CacheRead) if max(c.Input, c.Output, reasoning, cacheWrite, cacheRead) > codexChildUsageMaxTokens { + implausible++ continue } - key := child.Model + // The model comes from an agent-writable rollout and becomes a + // metrics.json key, so it goes through the shared secret redactor. + key := redactSummary(child.Model) if key == "" { key = piSubagentUnknownModel } @@ -323,6 +334,9 @@ func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, if unreadable > 0 { lost = append(lost, fmt.Sprintf("%d child rollout(s) could not be read", unreadable)) } + if implausible > 0 { + lost = append(lost, fmt.Sprintf("%d child(ren) with a counter past %d not counted", implausible, codexChildUsageMaxTokens)) + } if len(stdout) >= codexChildUsageMaxBytes { lost = append(lost, fmt.Sprintf("cut at %d bytes; only the children before the cut are counted", codexChildUsageMaxBytes)) } diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index 92b84cefb1..61517b56de 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -45,11 +45,11 @@ func TestCodexRunnerHeldDigestSet_Delegating(t *testing.T) { // Thread ids of the fixtures (testdata/codex/README.md, "Child rollout // fixtures") and of the spawn items in collab_spawn.ndjson. const ( - codexChildSameModelID = "01a06300-0000-7000-8000-0000000000a1" - codexChildOtherModelID = "01a06300-0000-7000-8000-0000000000a2" - codexChildFailedID = "01a06300-0000-7000-8000-0000000000a3" - codexChildNoModelID = "01a06300-0000-7000-8000-0000000000a4" - codexChildDeniedID = "01a06300-0000-7000-8000-0000000000a9" + codexChildSameModelID = "01a06300-0000-7000-8000-0000000000a1" + codexChildOtherModelID = "01a06300-0000-7000-8000-0000000000a2" + codexChildFailedID = "01a06300-0000-7000-8000-0000000000a3" + codexChildNoModelID = "01a06300-0000-7000-8000-0000000000a4" + codexChildFailedSpawnID = "01a06300-0000-7000-8000-0000000000a9" ) // codexChildFixtures maps each child id to its rollout fixture. @@ -120,7 +120,7 @@ func TestCodexChildUsageReadCommand_Executes(t *testing.T) { cmd, err := codexChildUsageReadCommand(sessions, ids) require.NoError(t, err) - assert.Contains(t, cmd, fmt.Sprintf("command -p head -c %d", codexChildUsageMaxBytes), + assert.True(t, strings.HasSuffix(cmd, fmt.Sprintf("| command -p head -c %d", codexChildUsageMaxBytes)), "the read is bounded inside the sandbox, not after the bytes arrived") assert.Contains(t, cmd, `-type f -name "rollout-*-$id.jsonl"`, "only regular rollout files, found by thread id; never a cat of the directory") @@ -161,6 +161,7 @@ func TestCodexChildUsageReadCommand_ReadsTheThreadTotal(t *testing.T) { count(`null`), record(3000, 4), count(`{"total_token_usage":` + usage(3000, 4, 3004) + `}`), + `{"type":"turn_context","payload":{"model":"gpt-5.6-terra"}}`, record(90000, 20), count(`{"total_token_usage":` + usage(0, 0, 258400) + `,"last_token_usage":` + usage(0, 0, 168380) + `,"model_context_window":258400}`), }, "\n") + "\n" @@ -172,7 +173,32 @@ func TestCodexChildUsageReadCommand_ReadsTheThreadTotal(t *testing.T) { assert.Equal(t, codexChildUsage{ ID: codexChildSameModelID, Model: "gpt-5.6-luna", HasUsage: true, Usage: codexUsage{InputTokens: 90000, OutputTokens: 20}, - }, got[0], "the last record's thread total, not the zeroed token_count after it") + }, got[0], "the first turn_context's model; the last record's thread total, not the zeroed token_count after it") +} + +// A planted rollout name with a newline in it splits into several "paths"; +// the read keeps only those under the sessions directory, so a file in the +// working directory is never opened. +func TestCodexChildUsageReadCommand_SkipsPathsOutsideTheSessionsDirectory(t *testing.T) { + t.Parallel() + + sessions := writeCodexChildRollouts(t) + day := filepath.Join(sessions, "2026", "09", "29") + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-a\nb-"+codexChildSameModelID+".jsonl"), []byte("{}\n"), 0o644)) + cwd := t.TempDir() + record := `{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tokens":99,"output_tokens":9}}}` + "\n" + require.NoError(t, os.WriteFile(filepath.Join(cwd, "b-"+codexChildSameModelID+".jsonl"), []byte(record), 0o644)) + + cmd, err := codexChildUsageReadCommand(sessions, []string{codexChildSameModelID}) + require.NoError(t, err) + sh := exec.Command("/bin/sh", "-c", cmd) + sh.Dir = cwd + out, err := sh.Output() + require.NoError(t, err) + got := parseCodexChildUsage(out) + require.Len(t, got, 1) + assert.Equal(t, codexChildUsage{ID: codexChildSameModelID, Unreadable: true}, got[0], + "the fragment under the sessions directory is not a file, so it is reported; the one in the working directory is skipped") } func TestParseCodexChildUsage(t *testing.T) { @@ -223,7 +249,7 @@ func TestCodexChildIDs_CollectsCompletedSpawns(t *testing.T) { assert.Equal(t, len(stream), n, "an io.Writer reports every byte consumed or the TeeReader fails") assert.Equal(t, want, whole.IDs, "the three completed spawns in stream order; the failed spawn's receiver is not a child; wait and close items name no new thread") - assert.NotContains(t, whole.IDs, codexChildDeniedID) + assert.NotContains(t, whole.IDs, codexChildFailedSpawnID) chunked := &codexChildIDs{} for i := 0; i < len(stream); i += 7 { @@ -241,11 +267,18 @@ func TestCodexChildIDs_SkipsOverlongLine(t *testing.T) { // line were scanned, its receiver would be collected. overlong := `{"type":"item.completed","item":{"id":"item_0","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["` + codexChildOtherModelID + `"],"prompt":"` + strings.Repeat("a", streamBufSize) + `","agents_states":{},"status":"completed"}}` + // A line of exactly the bound is dropped too: parseCodexStream's reader + // cannot return it whole either. + head := `{"type":"item.completed","item":{"id":"item_2","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["` + codexChildFailedID + `"],"prompt":"` + tail := `","agents_states":{},"status":"completed"}}` + exact := head + strings.Repeat("a", streamBufSize-len(head)-len(tail)) + tail + require.Len(t, exact, streamBufSize) + c := &codexChildIDs{} - _, err := c.Write([]byte(overlong + "\n" + spawn + "\n")) + _, err := c.Write([]byte(overlong + "\n" + exact + "\n" + spawn + "\n")) require.NoError(t, err) assert.Equal(t, []string{codexChildSameModelID}, c.IDs, - "a line past the parser's own bound is dropped whole, as parseCodexStream drops it, even when it names a child; the next line is still scanned") + "a line at or past the parser's own bound is dropped whole, as parseCodexStream drops it, even when it names a child; the next line is still scanned") assert.Empty(t, c.line, "nothing pending after a newline") } @@ -285,7 +318,8 @@ func TestParseCodexStream_FailedCollabItem(t *testing.T) { // does), streams streamFixture for the codex launch, and executes the // child-usage read command for real under sh with the sandbox sessions path // rewritten to sessionsDir, so the command text is exercised, not stubbed. -// FULLSEND_TEST_CHILD_READ_FAIL makes that command exit 1; +// FULLSEND_TEST_CHILD_READ_FAIL makes that command exit 1, with +// FULLSEND_TEST_CHILD_READ_STDERR appended to its stderr; // FULLSEND_TEST_CODEX_EXIT sets the launch's exit status. func fakeOpenshellCodexChildren(t *testing.T, logPath, storeDir, streamFixture, sessionsDir string) { t.Helper() @@ -298,7 +332,7 @@ if [ "$2" = "exec" ]; then cat\ *) f=$(printf '%s' "${last#cat }" | tr -d "'" | tr '/' '_'); cat '` + storeDir + `'/"$f"; exit $? ;; *"exec --json"*) cat '` + streamFixture + `'; exit "${FULLSEND_TEST_CODEX_EXIT:-0}" ;; *` + codexChildUsageMarker + `*) - if [ -n "${FULLSEND_TEST_CHILD_READ_FAIL:-}" ]; then echo "fake openshell: refusing the rollout read" >&2; exit 1; fi + if [ -n "${FULLSEND_TEST_CHILD_READ_FAIL:-}" ]; then echo "fake openshell: refusing the rollout read${FULLSEND_TEST_CHILD_READ_STDERR:+ $FULLSEND_TEST_CHILD_READ_STDERR}" >&2; exit 1; fi sh -c "$(printf '%s' "$last" | sed 's#` + CodexRuntime{}.codexSessionsDir() + `#` + sessionsDir + `#g')"; exit $? ;; esac exit 0 @@ -422,13 +456,15 @@ func TestFoldCodexChildUsage_ClampsNegativeCounters(t *testing.T) { } // A read cut at the bound is a warning; the children before the cut stay -// folded and the ones past it are not counted. +// folded and the ones past it are not counted. Each planted line stays under +// the parser's own line limit, so only the head -c bound stops the third +// child. func TestFoldCodexChildUsage_CutReadIsAWarning(t *testing.T) { sessions := writeCodexChildRollouts(t, codexChildSameModelID) day := filepath.Join(sessions, "2026", "09", "29") - planted := `{"type":"turn_context","payload":{"model":"` + strings.Repeat("x", codexChildUsageMaxBytes) + `"}}` + "\n" - require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-2026-09-29T15-46-38-"+codexChildOtherModelID+".jsonl"), []byte(planted), 0o644)) - require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-2026-09-29T15-46-38-"+codexChildFailedID+".jsonl"), readCodexFixture(t, "child_usage_other_model.jsonl"), 0o644)) + big := `{"type":"turn_context","payload":{"model":"` + strings.Repeat("x", 600<<10) + `"}}` + "\n" + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-2026-09-29T15-46-38-"+codexChildOtherModelID+".jsonl"), []byte(big), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-2026-09-29T15-46-38-"+codexChildFailedID+".jsonl"), append([]byte(big), readCodexFixture(t, "child_usage_other_model.jsonl")...), 0o644)) fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) m := codexParentMetrics("gpt-5.6-luna") @@ -482,25 +518,52 @@ func TestFoldCodexChildUsage_UnreadableRolloutIsAWarning(t *testing.T) { } } -// A counter no real thread reaches is skipped: two planted rollouts whose -// input sums past MaxInt would otherwise wrap the run's 15 down to 5. -func TestFoldCodexChildUsage_SkipsImplausibleCounters(t *testing.T) { +// The child's model comes from an agent-writable rollout and becomes a +// metrics.json key, so a credential planted there is redacted. +func TestFoldCodexChildUsage_RedactsThePlantedModel(t *testing.T) { + token := "ghp_" + strings.Repeat("A", 36) sessions := writeCodexChildRollouts(t) - day := filepath.Join(sessions, "2026", "09", "29") - for name, input := range map[string]string{"a": "9223372036854775807", "b": "9223372036854775799"} { - rollout := `{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tokens":` + input + `}}}` + "\n" - require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-"+name+"-"+codexChildSameModelID+".jsonl"), []byte(rollout), 0o644)) - } + rollout := `{"type":"turn_context","payload":{"model":"` + token + `"}}` + "\n" + + `{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tokens":10,"output_tokens":2}}}` + "\n" + require.NoError(t, os.WriteFile(filepath.Join(sessions, "2026", "09", "29", "rollout-2026-09-29T15-46-38-"+codexChildSameModelID+".jsonl"), []byte(rollout), 0o644)) fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) m := codexParentMetrics("gpt-5.6-luna") n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID}, m) require.NoError(t, err) - assert.Zero(t, n) - assert.Equal(t, codexTokenTotals{15, 1140, 291, 13618, 40590}, codexTotalsOf(m)) + assert.Equal(t, 1, n) + assert.Len(t, m.PerModelUsage, 2) + for spec := range m.PerModelUsage { + assert.NotContains(t, spec, token) + } assertCodexUsageSumsToTotals(t, m) } +// A counter no real thread reaches is skipped, with a warning, whichever +// counter it is: two planted rollouts near MaxInt would otherwise wrap the +// run's figures. +func TestFoldCodexChildUsage_SkipsImplausibleCounters(t *testing.T) { + for _, field := range []string{"input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens"} { + t.Run(field, func(t *testing.T) { + sessions := writeCodexChildRollouts(t) + day := filepath.Join(sessions, "2026", "09", "29") + for name, value := range map[string]string{"a": "9223372036854775807", "b": "9223372036854775799"} { + rollout := `{"type":"token_usage_record","payload":{"thread_token_usage":{"` + field + `":` + value + `}}}` + "\n" + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-"+name+"-"+codexChildSameModelID+".jsonl"), []byte(rollout), 0o644)) + } + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + + m := codexParentMetrics("gpt-5.6-luna") + n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID}, m) + require.Error(t, err, "a skipped child is a warning, as a cut or unreadable read is") + assert.Contains(t, err.Error(), "2 child(ren) with a counter past") + assert.Zero(t, n) + assert.Equal(t, codexTokenTotals{15, 1140, 291, 13618, 40590}, codexTotalsOf(m)) + assertCodexUsageSumsToTotals(t, m) + }) + } +} + // No child id, no sandbox command: PATH holds no openshell, so any exec // would fail to start. The parent's entry still lands in the breakdown // (a delegating agent that dispatched nothing), and a parent without a @@ -560,6 +623,26 @@ func TestFoldCodexChildUsage_ReadFailuresKeepTheParentEntry(t *testing.T) { }) } +// sumCodexIterations adds iterations up as internal/cli aggregateRunMetrics +// does. +func sumCodexIterations(ms ...*RunMetrics) *RunMetrics { + sum := &RunMetrics{PerModelUsage: map[string]ModelUsage{}} + for _, m := range ms { + sum.InputTokens += m.InputTokens + sum.OutputTokens += m.OutputTokens + sum.ReasoningTokens += m.ReasoningTokens + sum.CacheCreationInputTokens += m.CacheCreationInputTokens + sum.CacheReadInputTokens += m.CacheReadInputTokens + sum.TotalCostUSD += m.TotalCostUSD + for spec, u := range m.PerModelUsage { + entry := sum.PerModelUsage[spec] + entry.Add(u) + sum.PerModelUsage[spec] = entry + } + } + return sum +} + func TestFoldCodexChildUsage_TwoIterationsSumToTotals(t *testing.T) { sessions := writeCodexChildRollouts(t, codexChildSameModelID, codexChildOtherModelID) fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) @@ -577,21 +660,7 @@ func TestFoldCodexChildUsage_TwoIterationsSumToTotals(t *testing.T) { require.NoError(t, err) assert.Zero(t, n) - // Summed as internal/cli aggregateRunMetrics sums iterations. - sum := &RunMetrics{PerModelUsage: map[string]ModelUsage{}} - for _, m := range []*RunMetrics{first, second} { - sum.InputTokens += m.InputTokens - sum.OutputTokens += m.OutputTokens - sum.ReasoningTokens += m.ReasoningTokens - sum.CacheCreationInputTokens += m.CacheCreationInputTokens - sum.CacheReadInputTokens += m.CacheReadInputTokens - sum.TotalCostUSD += m.TotalCostUSD - for spec, u := range m.PerModelUsage { - entry := sum.PerModelUsage[spec] - entry.Add(u) - sum.PerModelUsage[spec] = entry - } - } + sum := sumCodexIterations(first, second) assert.Equal(t, map[string]ModelUsage{ "gpt-5.6-luna": {Requests: 3, InputTokens: 118, OutputTokens: 1198, CacheCreationInputTokens: 21016, CacheReadInputTokens: 40620}, "gpt-5.6-terra": {Requests: 1, InputTokens: 1000, OutputTokens: 200, CacheCreationInputTokens: 2000, CacheReadInputTokens: 1000}, @@ -604,8 +673,7 @@ func TestFoldCodexChildUsage_TwoIterationsSumToTotals(t *testing.T) { // stream fixture and a sessions tree holding the rollouts of the three // children the stream spawns, and returns the metrics, the exit code, the // printer output and the fake's argv log. delegating sets RoleFiles on the -// runner-held digests (what Bootstrap records for an agent with the Agent -// tool). +// runner-held digests (what Bootstrap records for a delegating agent). func runCodexWithChildren(t *testing.T, streamFixture string, delegating bool) (*RunMetrics, int, string, string) { t.Helper() logPath := filepath.Join(t.TempDir(), "openshell.log") @@ -653,7 +721,7 @@ func TestCodexRun_FoldsChildUsage(t *testing.T) { assert.Contains(t, out, "2 sub-agent thread(s) folded into the run metrics") assert.Equal(t, 1, strings.Count(log, codexChildUsageMarker), "one read command, after the run") assert.Contains(t, log, shellQuote(codexChildFailedID), "the failed child's rollout is read too; it is its content that contributes nothing") - assert.NotContains(t, log, codexChildDeniedID, "the failed spawn's receiver is never looked up") + assert.NotContains(t, log, codexChildFailedSpawnID, "the failed spawn's receiver is never looked up") } // A delegating agent that dispatched nothing: the breakdown carries the @@ -685,11 +753,14 @@ func TestCodexRun_NoSpawnNoBreakdown(t *testing.T) { // A failed read is a warning; the iteration keeps its exit code and the // parent's numbers, and the breakdown keeps the parent's entry. func TestCodexRun_ChildReadFailureIsAWarning(t *testing.T) { + token := "ghp_" + strings.Repeat("B", 36) t.Setenv("FULLSEND_TEST_CHILD_READ_FAIL", "1") + t.Setenv("FULLSEND_TEST_CHILD_READ_STDERR", token) metrics, exit, out, _ := runCodexWithChildren(t, "collab_spawn.ndjson", false) - assert.Equal(t, 0, exit, "losing the breakdown must not fail an iteration that succeeded") - assert.Contains(t, out, "! Could not read the sub-agent usage: reading the child rollouts: exited 1: fake openshell: refusing the rollout read") + assert.Equal(t, 0, exit, "losing the children's tokens must not fail an iteration that succeeded") + assert.Contains(t, out, "! Sub-agent usage not fully counted: reading the child rollouts: exited 1: fake openshell: refusing the rollout read") + assert.NotContains(t, out, token, "the warning goes through the shared secret redactor") assert.NotContains(t, out, "folded into the run metrics") assert.Equal(t, codexTokenTotals{15, 1140, 291, 13618, 40590}, codexTotalsOf(metrics), "the parent's tokens only") assert.Equal(t, map[string]ModelUsage{ @@ -698,16 +769,27 @@ func TestCodexRun_ChildReadFailureIsAWarning(t *testing.T) { assertCodexUsageSumsToTotals(t, metrics) } -// A codex process that did not exit 0 (killed at the timeout, cancelled, or -// crashed) reports the parent's tokens only and runs no sandbox command: -// the rollouts of a killed run are not read (docs/cli/run.md). -func TestCodexRun_NonZeroExitSkipsTheChildRead(t *testing.T) { +// A codex process that did not exit 0 (a failed or interrupted turn, a +// timeout, a cancel) still has its children's rollouts read: codex writes a +// child's usage record as each response completes, so what the children +// recorded is kept, and the parent's entry is recorded too. With an exit-0 +// retry the breakdown still sums to the totals. +func TestCodexRun_NonZeroExitStillReadsTheChildren(t *testing.T) { t.Setenv("FULLSEND_TEST_CODEX_EXIT", "137") - metrics, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", true) + failed, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", true) assert.Equal(t, 137, exit) - assert.Nil(t, metrics.PerModelUsage) - assert.Equal(t, codexTokenTotals{15, 1140, 291, 13618, 40590}, codexTotalsOf(metrics)) - assert.NotContains(t, log, codexChildUsageMarker) - assert.NotContains(t, out, "sub-agent") + assert.Equal(t, map[string]ModelUsage{ + "gpt-5.6-luna": {Requests: 2, InputTokens: 18, OutputTokens: 1148, CacheCreationInputTokens: 20996, CacheReadInputTokens: 40590}, + "gpt-5.6-terra": {Requests: 1, InputTokens: 1000, OutputTokens: 200, CacheCreationInputTokens: 2000, CacheReadInputTokens: 1000}, + }, failed.PerModelUsage, "the parent's entry and the children it spawned") + assert.Equal(t, codexTokenTotals{1018, 1348, 391, 22996, 41590}, codexTotalsOf(failed)) + assert.Equal(t, 1, strings.Count(log, codexChildUsageMarker), "one read command, after the run") + assert.Contains(t, out, "2 sub-agent thread(s) folded into the run metrics") + assertCodexUsageSumsToTotals(t, failed) + + t.Setenv("FULLSEND_TEST_CODEX_EXIT", "0") + retry, exit, _, _ := runCodexWithChildren(t, "collab_spawn.ndjson", true) + require.Equal(t, 0, exit) + assertCodexUsageSumsToTotals(t, sumCodexIterations(failed, retry)) } From fdac47a9a361aae8228b7441977f920b079a75c2 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 20 Oct 2026 05:24:45 -0400 Subject: [PATCH 6/9] refactor(codex): name a child by its last turn_context A forked child's rollout starts with the parent's turn_context lines, so the first one named the parent's model. The read and the parser now take the last turn_context, the child's own. Signed-off-by: Dharit Shah --- internal/runtime/codex_subagents.go | 13 +++++----- internal/runtime/codex_subagents_test.go | 24 +++++++++++++++---- internal/runtime/testdata/codex/README.md | 3 ++- .../testdata/codex/child_usage_forked.jsonl | 6 +++++ 4 files changed, 33 insertions(+), 13 deletions(-) create mode 100644 internal/runtime/testdata/codex/child_usage_forked.jsonl diff --git a/internal/runtime/codex_subagents.go b/internal/runtime/codex_subagents.go index a8c73a7cb9..03a26ba1cc 100644 --- a/internal/runtime/codex_subagents.go +++ b/internal/runtime/codex_subagents.go @@ -64,8 +64,9 @@ var codexChildUsageThreadID = regexp.MustCompile(`^[0-9a-f-]{36}$`) // codexChildUsage is what one child's rollout reported. type codexChildUsage struct { ID string - // Model is turn_context.payload.model of the child's first turn; "" - // when the rollout has no turn_context. + // Model is turn_context.payload.model of the child's last turn, which is + // its own: a fork copies the parent's turn_context lines ahead of the + // child's. "" when the rollout has no turn_context. Model string // Usage is payload.thread_token_usage of the child's last // token_usage_record: codex adds every completed response to it, and a @@ -86,7 +87,7 @@ type codexChildUsage struct { // codexChildUsageReadCommand renders the one in-sandbox command that reads // the children's rollouts. For each id, sorted and once, it finds every // rollout named for the thread (codex writes one), prints a marker line, -// then the rollout's first turn_context line and its last token_usage_record +// then the rollout's last turn_context line and its last token_usage_record // line. The record and not the last token_count: codex writes a token_count // whose usage counters are zero when a request overflows the context window, // and writes it only after the response's tools finish, so a child cancelled @@ -112,7 +113,7 @@ func codexChildUsageReadCommand(sessionsDir string, ids []string) (string, error quoted = append(quoted, shellQuote(id)) } return fmt.Sprintf( - `for id in %s; do files=$(command -p find %s -type f -name "rollout-*-$id.jsonl" 2>/dev/null) || [ -n "$files" ] || printf '%%s %%s\n' %s "$id"; printf '%%s\n' "$files" | while IFS= read -r f; do case $f in %s/*) ;; *) continue ;; esac; if [ ! -r "$f" ]; then printf '%%s %%s\n' %s "$id"; continue; fi; printf '%%s %%s\n' %s "$id"; command -p grep -a -e '"type":"turn_context"' -- "$f" 2>/dev/null | command -p head -n 1; command -p grep -a -e '"type":"token_usage_record"' -- "$f" 2>/dev/null | command -p tail -n 1; done; done | command -p head -c %d`, + `for id in %s; do files=$(command -p find %s -type f -name "rollout-*-$id.jsonl" 2>/dev/null) || [ -n "$files" ] || printf '%%s %%s\n' %s "$id"; printf '%%s\n' "$files" | while IFS= read -r f; do case $f in %s/*) ;; *) continue ;; esac; if [ ! -r "$f" ]; then printf '%%s %%s\n' %s "$id"; continue; fi; printf '%%s %%s\n' %s "$id"; command -p grep -a -e '"type":"turn_context"' -- "$f" 2>/dev/null | command -p tail -n 1; command -p grep -a -e '"type":"token_usage_record"' -- "$f" 2>/dev/null | command -p tail -n 1; done; done | command -p head -c %d`, strings.Join(quoted, " "), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(codexChildUsageMarker), codexChildUsageMaxBytes), nil } @@ -156,9 +157,7 @@ func parseCodexChildUsage(data []byte) []codexChildUsage { cur := &out[len(out)-1] switch { case env.Type == "turn_context": - if cur.Model == "" { - cur.Model = strings.TrimSpace(env.Payload.Model) - } + cur.Model = strings.TrimSpace(env.Payload.Model) case env.Type == "token_usage_record": cur.Usage = env.Payload.Thread cur.HasUsage = true diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index 61517b56de..44b9c03356 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -49,6 +49,7 @@ const ( codexChildOtherModelID = "01a06300-0000-7000-8000-0000000000a2" codexChildFailedID = "01a06300-0000-7000-8000-0000000000a3" codexChildNoModelID = "01a06300-0000-7000-8000-0000000000a4" + codexChildForkedID = "01a06300-0000-7000-8000-0000000000a5" codexChildFailedSpawnID = "01a06300-0000-7000-8000-0000000000a9" ) @@ -58,6 +59,7 @@ var codexChildFixtures = map[string]string{ codexChildOtherModelID: "child_usage_other_model.jsonl", codexChildFailedID: "child_usage_failed.jsonl", codexChildNoModelID: "child_usage_no_model.jsonl", + codexChildForkedID: "child_usage_forked.jsonl", } // writeCodexChildRollouts lays the child fixtures out as codex would under a @@ -161,7 +163,6 @@ func TestCodexChildUsageReadCommand_ReadsTheThreadTotal(t *testing.T) { count(`null`), record(3000, 4), count(`{"total_token_usage":` + usage(3000, 4, 3004) + `}`), - `{"type":"turn_context","payload":{"model":"gpt-5.6-terra"}}`, record(90000, 20), count(`{"total_token_usage":` + usage(0, 0, 258400) + `,"last_token_usage":` + usage(0, 0, 168380) + `,"model_context_window":258400}`), }, "\n") + "\n" @@ -173,7 +174,20 @@ func TestCodexChildUsageReadCommand_ReadsTheThreadTotal(t *testing.T) { assert.Equal(t, codexChildUsage{ ID: codexChildSameModelID, Model: "gpt-5.6-luna", HasUsage: true, Usage: codexUsage{InputTokens: 90000, OutputTokens: 20}, - }, got[0], "the first turn_context's model; the last record's thread total, not the zeroed token_count after it") + }, got[0], "the last record's thread total, not the zeroed token_count after it") +} + +// A forked child's rollout starts with the parent's turn_context lines; the +// read names the child by its own, the last. +func TestCodexChildUsageReadCommand_NamesAForkedChildByItsOwnTurn(t *testing.T) { + t.Parallel() + + got := runCodexChildUsageRead(t, writeCodexChildRollouts(t, codexChildForkedID), []string{codexChildForkedID}) + require.Len(t, got, 1) + assert.Equal(t, codexChildUsage{ + ID: codexChildForkedID, Model: "gpt-5.6-terra", HasUsage: true, + Usage: codexUsage{InputTokens: 600, OutputTokens: 40, ReasoningOutputTokens: 10}, + }, got[0], "the child's model and record, not the parent's inherited turn_context or token_count") } // A planted rollout name with a newline in it splits into several "paths"; @@ -228,8 +242,8 @@ func TestParseCodexChildUsage(t *testing.T) { got := parseCodexChildUsage([]byte(data)) require.Len(t, got, 3) - assert.Equal(t, codexChildUsage{ID: codexChildSameModelID, Model: "gpt-5.6-terra", HasUsage: true, Usage: codexUsage{InputTokens: 20, OutputTokens: 2}}, - got[0], "first turn_context names the model, the last record wins, a malformed line is skipped") + assert.Equal(t, codexChildUsage{ID: codexChildSameModelID, Model: "gpt-5.6-sol", HasUsage: true, Usage: codexUsage{InputTokens: 20, OutputTokens: 2}}, + got[0], "the last turn_context names the model, the last record wins, a malformed line is skipped") assert.Equal(t, codexChildUsage{ID: codexChildOtherModelID, HasUsage: true, Usage: codexUsage{InputTokens: 5, OutputTokens: 5}}, got[1], "no turn_context: the model stays empty and the fold buckets it") assert.Equal(t, codexChildUsage{ID: codexChildFailedID, Model: "gpt-5.6-terra"}, @@ -464,7 +478,7 @@ func TestFoldCodexChildUsage_CutReadIsAWarning(t *testing.T) { day := filepath.Join(sessions, "2026", "09", "29") big := `{"type":"turn_context","payload":{"model":"` + strings.Repeat("x", 600<<10) + `"}}` + "\n" require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-2026-09-29T15-46-38-"+codexChildOtherModelID+".jsonl"), []byte(big), 0o644)) - require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-2026-09-29T15-46-38-"+codexChildFailedID+".jsonl"), append([]byte(big), readCodexFixture(t, "child_usage_other_model.jsonl")...), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-2026-09-29T15-46-38-"+codexChildFailedID+".jsonl"), append(readCodexFixture(t, "child_usage_other_model.jsonl"), big...), 0o644)) fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) m := codexParentMetrics("gpt-5.6-luna") diff --git a/internal/runtime/testdata/codex/README.md b/internal/runtime/testdata/codex/README.md index 9df1f051e2..665e0a47b4 100644 --- a/internal/runtime/testdata/codex/README.md +++ b/internal/runtime/testdata/codex/README.md @@ -34,7 +34,7 @@ Inputs for `foldCodexChildUsage` (`internal/runtime/codex_subagents.go`), not fo `parseCodexStream`: they are codex **rollouts** (`$CODEX_HOME/sessions/**/rollout-*.jsonl`, the underscored envelope of `codex_redact.go`), not the `exec --json` stream. Line types and fields were copied from the rollouts of the 0.157.0 paid probe of 2026-09-29, trimmed, with -synthetic ids. The fold reads two lines per rollout: the first `turn_context` (its +synthetic ids. The fold reads two lines per rollout: the last `turn_context` (its `payload.model`) and the last `token_usage_record` (its `payload.thread_token_usage`, cumulative for the thread and not reset when a request overflows the context window, unlike `token_count`). @@ -44,6 +44,7 @@ the thread and not reset when a request overflows the context window, unlike `to | `child_usage_other_model.jsonl` | A child on `gpt-5.6-terra`, every normalized counter non-zero. | | `child_usage_failed.jsonl` | A child whose model the provider rejected (404): `turn_context` names the model, `task_complete` carries `error`, and there is no `token_usage_record`, so it contributes nothing. | | `child_usage_no_model.jsonl` | A child with a `token_usage_record` and no `turn_context`: its usage is bucketed under `unknown`. | +| `child_usage_forked.jsonl` | A forked child (hand-authored from codex 0.159.3's fork rules): the parent's `turn_context` (`gpt-5.6-luna`) and `token_count` copied ahead of the child's own `turn_context` (`gpt-5.6-terra`) and `token_usage_record`; its usage lands under `gpt-5.6-terra`. | The tests lay the rollouts out under a temporary sessions tree as `2026/09/29/rollout-2026-09-29T15-46-38-.jsonl`, the name codex gives a rollout. diff --git a/internal/runtime/testdata/codex/child_usage_forked.jsonl b/internal/runtime/testdata/codex/child_usage_forked.jsonl new file mode 100644 index 0000000000..71222884ee --- /dev/null +++ b/internal/runtime/testdata/codex/child_usage_forked.jsonl @@ -0,0 +1,6 @@ +{"timestamp":"2026-09-29T19:46:20.000Z","ordinal":0,"type":"turn_context","payload":{"turn_id":"01a06300-0000-7000-8000-0000000000b0","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","cwd":"/sandbox/workspace/repo","approval_policy":"never","sandbox_policy":{"type":"danger-full-access"},"model":"gpt-5.6-luna","multi_agent_version":"v1","effort":"medium","summary":"auto"}} +{"timestamp":"2026-09-29T19:46:30.000Z","ordinal":1,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":54208,"cached_input_tokens":40590,"cache_write_input_tokens":13618,"output_tokens":1140,"reasoning_output_tokens":291,"total_tokens":55348},"last_token_usage":{"input_tokens":54208,"cached_input_tokens":40590,"cache_write_input_tokens":13618,"output_tokens":1140,"reasoning_output_tokens":291,"total_tokens":55348},"model_context_window":258400},"rate_limits":null}} +{"timestamp":"2026-09-29T19:46:38.900Z","ordinal":2,"type":"event_msg","payload":{"type":"task_started","turn_id":"01a06300-0000-7000-8000-0000000000b5","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","started_at":1790711198,"model_context_window":258400,"collaboration_mode_kind":"default"}} +{"timestamp":"2026-09-29T19:46:39.400Z","ordinal":3,"type":"turn_context","payload":{"turn_id":"01a06300-0000-7000-8000-0000000000b5","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","cwd":"/sandbox/workspace/repo","approval_policy":"never","sandbox_policy":{"type":"danger-full-access"},"model":"gpt-5.6-terra","multi_agent_version":"v1","effort":"low","summary":"auto"}} +{"timestamp":"2026-09-29T19:46:41.000Z","ordinal":4,"type":"token_usage_record","payload":{"thread_id":"01a06300-0000-7000-8000-0000000000a5","turn_id":"01a06300-0000-7000-8000-0000000000b5","session_id":"01a06300-0000-7000-8000-000000000050","root_turn_id":"01a06300-0000-7000-8000-0000000000b0","response_id":"resp_fixture_a5_1","usage":{"input_tokens":600,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":40,"reasoning_output_tokens":10,"total_tokens":640},"turn_token_usage":{"input_tokens":600,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":40,"reasoning_output_tokens":10,"total_tokens":640},"thread_token_usage":{"input_tokens":600,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":40,"reasoning_output_tokens":10,"total_tokens":640}}} +{"timestamp":"2026-09-29T19:46:41.010Z","ordinal":5,"type":"event_msg","payload":{"type":"task_complete","turn_id":"01a06300-0000-7000-8000-0000000000b5","last_agent_message":"Done.","started_at":1790711198,"completed_at":1790711201,"duration_ms":2100,"time_to_first_token_ms":900}} From 9517fa6517996d148a067b6aa9e2219b2f396af9 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 20 Oct 2026 05:27:12 -0400 Subject: [PATCH 7/9] refactor(codex): shorten the child-usage comments Each comment keeps what the code does not say; the codex background is in the earlier commit messages. The cap counter is now overMaxTokens. Signed-off-by: Dharit Shah --- internal/runtime/codex_run.go | 13 +- internal/runtime/codex_subagents.go | 173 +++++++--------------- internal/runtime/codex_subagents_test.go | 129 ++++++---------- internal/runtime/testdata/codex/README.md | 12 +- 4 files changed, 105 insertions(+), 222 deletions(-) diff --git a/internal/runtime/codex_run.go b/internal/runtime/codex_run.go index fa6e084b42..b04c24aa08 100644 --- a/internal/runtime/codex_run.go +++ b/internal/runtime/codex_run.go @@ -607,8 +607,6 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri } } - // Child thread ids come off a tee of the stream: the parser's events - // carry no thread id. childIDs := &codexChildIDs{} reader = io.TeeReader(reader, childIDs) @@ -659,14 +657,9 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri r.ConfigDir()) } - // The fold runs whatever the exit code. The parent's entry goes into the - // breakdown, so a retry keeps per_model_usage summing to the totals, and - // the children's rollouts are read: they are separate threads whose - // tokens never reached the stream just parsed, and codex writes a - // child's usage record as each response completes, so a failed, - // interrupted, cancelled or timed-out iteration keeps what its children - // recorded. A read failure costs the children's tokens, not the - // iteration. + // The fold runs whatever the exit code: codex writes a child's usage as + // each response completes, and the parent's entry keeps per_model_usage + // summing to the totals across a retry. A read failure is a warning. if digests.delegating() || len(childIDs.IDs) > 0 { n, ferr := r.foldCodexChildUsage(params.SandboxName, childIDs.IDs, metrics) if ferr != nil { diff --git a/internal/runtime/codex_subagents.go b/internal/runtime/codex_subagents.go index 03a26ba1cc..63cdc27d12 100644 --- a/internal/runtime/codex_subagents.go +++ b/internal/runtime/codex_subagents.go @@ -13,94 +13,54 @@ import ( "github.com/fullsend-ai/fullsend/internal/sandbox" ) -// Native child accounting for the Codex runtime. -// -// A Codex child is a separate thread. Its tokens never reach the parent's -// `exec --json` stream (turn.completed.usage excludes children — #6970, probe -// of 2026-09-03), and codex records them only in that thread's rollout under -// $CODEX_HOME/sessions/: the running total in `token_usage_record` lines -// (`payload.thread_token_usage`, the stream's five usage fields plus -// total_tokens), the model in the `turn_context` line, and the thread id in -// the file name (rollout--.jsonl). Run reads those -// lines back with one bounded command after codex exits and folds them into -// RunMetrics, so metrics.json carries the children (#6970, transcripts and -// usage). -// -// The fold covers the fields a per-model entry has: input, output, -// cache-creation and cache-read tokens, and cost, which is 0 on codex. Child -// reasoning tokens go to the run-level ReasoningTokens only, as on pi: -// RunMetrics has no per-model reasoning field. +// Native child accounting for the Codex runtime. A child's tokens never reach +// the parent's `exec --json` stream; codex records them only in the child's +// rollout under $CODEX_HOME/sessions/ (rollout--.jsonl). +// After codex exits, Run reads each child's model and usage from it and folds +// them into RunMetrics. Child reasoning goes to the run total only, as on pi. -// codexChildUsageMarker starts the line the read command prints before each -// child's rollout lines, so the parser knows where one child's lines end and -// the next child's begin. A rollout line that imitates it can only -// misattribute that child's own lines. +// codexChildUsageMarker starts the line printed before each child's rollout +// lines. A rollout line that imitates it can only misattribute its own child. const codexChildUsageMarker = "fullsend-child" -// codexChildUnreadableMarker starts the line the read command prints for a -// child whose rollout it could not read, or that a failed search of the -// sessions directory did not find. A rollout line that imitates it can only -// add a warning and misattribute that child's own lines. +// codexChildUnreadableMarker starts the line printed for a child whose +// rollout fails test -r, or that a failed search did not find. const codexChildUnreadableMarker = "fullsend-unreadable" -// codexChildUsageMaxBytes bounds the read. The sessions directory is -// agent-writable, so an unbounded read is an unbounded allocation in the -// runner (the reason piSubagentUsageMaxBytes exists). The command selects at -// most two lines per child, so a real read is a few kilobytes. +// codexChildUsageMaxBytes bounds the read: the sessions directory is +// agent-writable. A real read is a few kilobytes. const codexChildUsageMaxBytes = 1 << 20 -// codexChildUsageMaxTokens is far above any counter a real thread reports. A -// child whose record carries a counter past it is skipped, with a warning, -// so under the bounded read the sums of the counters left cannot wrap the -// run's figures. A counter past the int range does not decode, so its record -// counts nothing, as a malformed line does. +// codexChildUsageMaxTokens is far above any real counter. A child past it is +// skipped with a warning, so planted counters cannot wrap the run's sums. const codexChildUsageMaxTokens = 1 << 40 -// codexChildUsageThreadID is the shape of a codex thread id (UUID text). A -// child id comes off the stream and goes into a shell command, so nothing -// else is accepted; shellQuote wraps it as well. +// codexChildUsageThreadID is a codex thread id. Ids go into a shell command, +// so nothing else is accepted. var codexChildUsageThreadID = regexp.MustCompile(`^[0-9a-f-]{36}$`) // codexChildUsage is what one child's rollout reported. type codexChildUsage struct { ID string - // Model is turn_context.payload.model of the child's last turn, which is - // its own: a fork copies the parent's turn_context lines ahead of the - // child's. "" when the rollout has no turn_context. + // Model is from the last turn_context, the child's own (a fork copies + // the parent's ahead of it); "" when there is none. Model string - // Usage is payload.thread_token_usage of the child's last - // token_usage_record: codex adds every completed response to it, and a - // context-window overflow does not reset it, so one record is the whole - // child. + // Usage is the thread total of the last token_usage_record. Usage codexUsage - // HasUsage is false for a child with no token_usage_record, such as one - // that errored before its first response (the provider rejected its - // model in the 2026-09-29 paid probe); it contributes nothing, not even a - // request. + // HasUsage is false when the rollout has no record; such a child adds + // nothing, not even a request. HasUsage bool - // Unreadable is set when the child's rollout failed `test -r`, or a - // failed search of the sessions directory did not find it; the fold - // reports it. + // Unreadable marks a rollout that failed test -r or a failed search. Unreadable bool } -// codexChildUsageReadCommand renders the one in-sandbox command that reads -// the children's rollouts. For each id, sorted and once, it finds every -// rollout named for the thread (codex writes one), prints a marker line, -// then the rollout's last turn_context line and its last token_usage_record -// line. The record and not the last token_count: codex writes a token_count -// whose usage counters are zero when a request overflows the context window, -// and writes it only after the response's tools finish, so a child cancelled -// in between can lack one for its last response. A rollout that fails -// `test -r`, or one a failed search of the sessions directory did not find -// (a missing directory included), prints codexChildUnreadableMarker in its -// place; a rollout missing from a directory searched without error prints -// nothing, and a path outside the sessions directory (a planted file name -// with a newline in it) is skipped. Two greps rather than a cat: a review -// child's rollout is megabytes and the two lines are all the fold needs, so -// the head -c bound is a safety net, not the usual limit. `command -p` -// bypasses shell functions and uses the system PATH, as the launch guards -// do. +// codexChildUsageReadCommand renders the in-sandbox command that prints, per +// child, a marker line, the rollout's last turn_context and its last +// token_usage_record. The record, not token_count: codex zeroes token_count's +// counters when a request overflows the context window. A rollout it cannot +// read, or that a failed search cannot find, prints the unreadable marker; +// one a clean search misses prints nothing; a path outside sessionsDir is +// skipped; head -c bounds the output. func codexChildUsageReadCommand(sessionsDir string, ids []string) (string, error) { ids = slices.Clone(ids) slices.Sort(ids) @@ -117,11 +77,9 @@ func codexChildUsageReadCommand(sessionsDir string, ids []string) (string, error strings.Join(quoted, " "), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(codexChildUsageMarker), codexChildUsageMaxBytes), nil } -// parseCodexChildUsage decodes the read command's output: a marker line per -// child, then that child's turn_context and token_usage_record lines, or an -// unreadable marker line for a child it could not read. A line before the -// first marker belongs to nobody; a line that is not JSON (the head -c cut, -// or something planted in the agent-writable directory) is skipped. +// parseCodexChildUsage decodes the read command's output. Lines before the +// first marker, and lines that do not decode (a cut, planted text, a counter +// past the int range), are skipped. func parseCodexChildUsage(data []byte) []codexChildUsage { var out []codexChildUsage marker := []byte(codexChildUsageMarker + " ") @@ -166,15 +124,10 @@ func parseCodexChildUsage(data []byte) []codexChildUsage { return out } -// codexChildIDs collects the thread ids of the children the parent spawned. -// It is an io.Writer that Run feeds through a tee of the `exec --json` -// stream: the parser's events carry no thread id (ToolUseEvent is a name and -// a summary) and parseCodexStream's signature is shared with pi's, so the -// ids are read here, one line at a time, from the completed spawn_agent -// items (codexCollabToolCallItem). A spawn that failed made no thread. -// -// A final line with no newline is not scanned; in a codex stream the last -// line is the terminal event, never an item. +// codexChildIDs collects the thread ids of completed spawn_agent items from +// a tee of the `exec --json` stream: the parser's events carry no thread id. +// A final line without a newline is not scanned; in codex it is the terminal +// event. type codexChildIDs struct { IDs []string line []byte @@ -198,9 +151,8 @@ func (c *codexChildIDs) Write(p []byte) (int, error) { } } -// take appends to the pending line, dropping it once it reaches the -// parser's own line bound (streamBufSize): parseCodexStream skips such a -// line too. +// take appends to the pending line and drops a line that reaches +// streamBufSize, as parseCodexStream does. func (c *codexChildIDs) take(b []byte) { if c.overlong || len(c.line)+len(b) >= streamBufSize { c.overlong = true @@ -211,7 +163,7 @@ func (c *codexChildIDs) take(b []byte) { } func (c *codexChildIDs) scan(line []byte) { - // Cheap pre-filter: almost no line of a stream names the tool. + // Pre-filter: few lines name the tool. if !bytes.Contains(line, []byte("spawn_agent")) { return } @@ -229,32 +181,14 @@ func (c *codexChildIDs) scan(line []byte) { c.IDs = append(c.IDs, evt.Item.ReceiverThreadIDs...) } -// foldCodexChildUsage adds the parent's own entry to m.PerModelUsage and, -// when the parent spawned children, reads their rollouts with one bounded -// sandbox command and folds each child's cumulative usage into the totals -// and the breakdown. It returns how many child rollouts it folded (codex -// writes one per thread). An error names what was not counted: a read that -// did not happen or did not finish, a rollout that could not be read, or a -// child skipped for a counter past codexChildUsageMaxTokens; the children it -// did read stay folded. The caller reports it and keeps the run, because -// losing the children's tokens must not fail an iteration that succeeded. No -// sandbox command runs when childIDs is empty. -// -// The parent's entry is added first and always. Iterations are summed -// (internal/cli aggregateRunMetrics), so an iteration that dispatched -// nothing, or whose read failed, still has to be in the breakdown or the -// run's per_model_usage stops summing to its totals across a retry. -// -// Requests: one for the parent iteration, one per child rollout folded (the -// invocation-count semantics of the pi fold). A child with no -// token_usage_record, or whose rollout is missing, recorded nothing and -// contributes nothing. A child whose rollout names no model is bucketed -// under piSubagentUnknownModel, as pi does for a record without one. Child -// reasoning tokens go to the run-level total only. The figures come from an -// agent-writable directory, so every counter is floored at zero, as pi's -// fold clamps its records, and a child with a counter past -// codexChildUsageMaxTokens is skipped and reported; both happen before -// anything is added. +// foldCodexChildUsage adds the parent's entry to m.PerModelUsage, always, so +// the breakdown sums to the totals when iterations are summed. It then folds +// each child's usage into the totals and the breakdown, one request per +// rollout, and returns how many it folded. The error lists what was not +// counted; the caller warns and keeps the run. No sandbox command runs +// without child ids. A child with no model goes under piSubagentUnknownModel, +// as on pi. The figures are agent-written, so counters are floored at zero +// and a child past codexChildUsageMaxTokens is skipped. func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, m *RunMetrics) (folded int, err error) { per := m.PerModelUsage if per == nil { @@ -293,7 +227,7 @@ func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, if exitCode != 0 { return 0, fmt.Errorf("reading the child rollouts: exited %d: %s", exitCode, strings.TrimSpace(sanitizeOutput(stderr))) } - unreadable, implausible := 0, 0 + unreadable, overMaxTokens := 0, 0 for _, child := range parseCodexChildUsage([]byte(stdout)) { if child.Unreadable { unreadable++ @@ -301,16 +235,15 @@ func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, if !child.HasUsage { continue } - // counters() floors only its two subtractions; the three raw fields - // are floored here. + // counters() floors only its subtractions; the raw fields are + // floored here. c := child.Usage.counters() reasoning, cacheWrite, cacheRead := nonNegative(c.Reasoning), nonNegative(c.CacheWrite), nonNegative(c.CacheRead) if max(c.Input, c.Output, reasoning, cacheWrite, cacheRead) > codexChildUsageMaxTokens { - implausible++ + overMaxTokens++ continue } - // The model comes from an agent-writable rollout and becomes a - // metrics.json key, so it goes through the shared secret redactor. + // The model is agent-written and becomes a metrics.json key. key := redactSummary(child.Model) if key == "" { key = piSubagentUnknownModel @@ -333,8 +266,8 @@ func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, if unreadable > 0 { lost = append(lost, fmt.Sprintf("%d child rollout(s) could not be read", unreadable)) } - if implausible > 0 { - lost = append(lost, fmt.Sprintf("%d child(ren) with a counter past %d not counted", implausible, codexChildUsageMaxTokens)) + if overMaxTokens > 0 { + lost = append(lost, fmt.Sprintf("%d child(ren) with a counter past %d not counted", overMaxTokens, codexChildUsageMaxTokens)) } if len(stdout) >= codexChildUsageMaxBytes { lost = append(lost, fmt.Sprintf("cut at %d bytes; only the children before the cut are counted", codexChildUsageMaxBytes)) diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index 44b9c03356..9b68b5ba6f 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -18,9 +18,7 @@ import ( "github.com/fullsend-ai/fullsend/internal/ui" ) -// The gate Run uses to decide that a delegating agent's breakdown must carry -// the parent's entry even when it spawned nothing. It reads the runner-held -// record only: the manifest is agent-writable and never authority. +// delegating reads the runner-held role set only, never the manifest. func TestCodexRunnerHeldDigestSet_Delegating(t *testing.T) { t.Parallel() @@ -77,10 +75,8 @@ func writeCodexChildRollouts(t *testing.T, ids ...string) string { return sessions } -// runCodexChildUsageRead executes the read command under /bin/sh against a -// local sessions directory and parses what it printed. The command is run, -// not inspected: a Go-level assertion on its text would not catch a quoting -// slip (the same reason codex_run_test.go executes the guards). +// runCodexChildUsageRead runs the read command under /bin/sh, so a quoting +// slip fails the test, and parses what it printed. func runCodexChildUsageRead(t *testing.T, sessions string, ids []string) []codexChildUsage { t.Helper() cmd, err := codexChildUsageReadCommand(sessions, ids) @@ -142,10 +138,8 @@ func TestCodexChildUsageReadCommand_Executes(t *testing.T) { "a child that errored before its first response has a model and no usage") } -// The read takes the thread total of the last token_usage_record. The -// token_count codex writes after a context-window overflow has its usage -// counters at zero, and a rate-limit token_count before the first response -// has no usage; neither is read. +// The read takes the last record's thread total; a token_count is zeroed +// after a context-window overflow and empty before the first response. func TestCodexChildUsageReadCommand_ReadsTheThreadTotal(t *testing.T) { t.Parallel() @@ -190,9 +184,8 @@ func TestCodexChildUsageReadCommand_NamesAForkedChildByItsOwnTurn(t *testing.T) }, got[0], "the child's model and record, not the parent's inherited turn_context or token_count") } -// A planted rollout name with a newline in it splits into several "paths"; -// the read keeps only those under the sessions directory, so a file in the -// working directory is never opened. +// A planted file name with a newline splits into several paths; only those +// under the sessions directory are opened. func TestCodexChildUsageReadCommand_SkipsPathsOutsideTheSessionsDirectory(t *testing.T) { t.Parallel() @@ -277,12 +270,10 @@ func TestCodexChildIDs_SkipsOverlongLine(t *testing.T) { t.Parallel() spawn := `{"type":"item.completed","item":{"id":"item_1","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["` + codexChildSameModelID + `"],"prompt":null,"agents_states":{},"status":"completed"}}` - // A completed spawn naming another child, padded past the bound: if the - // line were scanned, its receiver would be collected. + // A completed spawn padded past the bound. overlong := `{"type":"item.completed","item":{"id":"item_0","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["` + codexChildOtherModelID + `"],"prompt":"` + strings.Repeat("a", streamBufSize) + `","agents_states":{},"status":"completed"}}` - // A line of exactly the bound is dropped too: parseCodexStream's reader - // cannot return it whole either. + // A line of exactly the bound is dropped too, as parseCodexStream drops it. head := `{"type":"item.completed","item":{"id":"item_2","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"01a06300-0000-7000-8000-000000000050","receiver_thread_ids":["` + codexChildFailedID + `"],"prompt":"` tail := `","agents_states":{},"status":"completed"}}` exact := head + strings.Repeat("a", streamBufSize-len(head)-len(tail)) + tail @@ -296,10 +287,8 @@ func TestCodexChildIDs_SkipsOverlongLine(t *testing.T) { assert.Empty(t, c.line, "nothing pending after a newline") } -// A failed child is visible in the stream and never fails the run: codex -// exits 0 and completes the turn (paid probe, 2026-09-29), so the wait and -// close items are the only trace. Pinned here because the delegation -// instructions given to the parent depend on it. +// A failed child shows only as failed wait and close items and never fails +// the run. func TestParseCodexStream_FailedCollabItem(t *testing.T) { t.Parallel() @@ -327,14 +316,11 @@ func TestParseCodexStream_FailedCollabItem(t *testing.T) { assert.Equal(t, 40590, result.CacheReadInputTokens) } -// fakeOpenshellCodexChildren is the fake openshell for the fold and run-level -// tests. It answers the manifest `cat` from storeDir (as fakeOpenshellCodex -// does), streams streamFixture for the codex launch, and executes the -// child-usage read command for real under sh with the sandbox sessions path -// rewritten to sessionsDir, so the command text is exercised, not stubbed. -// FULLSEND_TEST_CHILD_READ_FAIL makes that command exit 1, with -// FULLSEND_TEST_CHILD_READ_STDERR appended to its stderr; -// FULLSEND_TEST_CODEX_EXIT sets the launch's exit status. +// fakeOpenshellCodexChildren answers the manifest cat from storeDir, streams +// streamFixture for the launch, and runs the read command under sh against +// sessionsDir. FULLSEND_TEST_CHILD_READ_FAIL makes the read exit 1 (with +// FULLSEND_TEST_CHILD_READ_STDERR on stderr); FULLSEND_TEST_CODEX_EXIT sets +// the launch's exit status. func fakeOpenshellCodexChildren(t *testing.T, logPath, storeDir, streamFixture, sessionsDir string) { t.Helper() binDir := t.TempDir() @@ -357,8 +343,7 @@ exit 0 t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH")) } -// codexParentMetrics is the parent's own iteration as the stream fixture -// reports it (collab_spawn.ndjson, normalized). +// codexParentMetrics is the parent's iteration in collab_spawn.ndjson. func codexParentMetrics(model string) *RunMetrics { return &RunMetrics{Model: model, NumTurns: 1, InputTokens: 15, OutputTokens: 1140, ReasoningTokens: 291, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590} } @@ -371,9 +356,8 @@ func codexTotalsOf(m *RunMetrics) codexTokenTotals { return codexTokenTotals{m.InputTokens, m.OutputTokens, m.ReasoningTokens, m.CacheCreationInputTokens, m.CacheReadInputTokens} } -// assertCodexUsageSumsToTotals is the invariant docs/cli/run.md states for -// per_model_usage: the entries sum to the run totals for the five fields an -// entry has. Reasoning is run-level only and outside it. +// assertCodexUsageSumsToTotals checks that per_model_usage sums to the run +// totals (docs/cli/run.md); reasoning is run-level only. func assertCodexUsageSumsToTotals(t *testing.T, m *RunMetrics) { t.Helper() var sum ModelUsage @@ -387,12 +371,9 @@ func assertCodexUsageSumsToTotals(t *testing.T, m *RunMetrics) { assert.Equal(t, m.TotalCostUSD, sum.CostUSD, "cost (0 on codex)") } -// TestFoldCodexChildUsage is the arithmetic per fixture: the parent's entry, -// then each child's last cumulative snapshot through codexUsage.counters(), -// added exactly once. Numbers: parent 15/1140/291/13618/40590 (real, paid -// probe); luna child 3/8/0/7378/0 (real); terra child 1000/200/100/2000/1000 -// (synthetic); the no-model child 50/5/0/0/0 (synthetic) under unknown; the -// failed child nothing. +// Per fixture: parent 15/1140/291/13618/40590, luna child 3/8/0/7378/0, +// terra child 1000/200/100/2000/1000, no-model child 50/5/0/0/0 under +// unknown, failed child nothing. func TestFoldCodexChildUsage(t *testing.T) { r := CodexRuntime{} parentOnly := ModelUsage{Requests: 1, InputTokens: 15, OutputTokens: 1140, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590} @@ -447,9 +428,7 @@ func TestFoldCodexChildUsage(t *testing.T) { } } -// A planted negative counter cannot lower the run's figures: counters() -// floors only its two subtractions, so the fold floors the three raw fields -// (a wrap is TestFoldCodexChildUsage_SkipsImplausibleCounters). +// A planted negative counter cannot lower the run's figures. func TestFoldCodexChildUsage_ClampsNegativeCounters(t *testing.T) { sessions := writeCodexChildRollouts(t) rollout := `{"type":"turn_context","payload":{"model":"gpt-5.6-luna"}}` + "\n" + @@ -461,8 +440,7 @@ func TestFoldCodexChildUsage_ClampsNegativeCounters(t *testing.T) { n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID}, m) require.NoError(t, err) assert.Equal(t, 1, n) - // Input is 10 - (-5000) - (-7000) = 12010 and output 20 - (-900) = 920: - // inflation is accepted, as on pi; nothing drops below the parent's figures. + // Input 10+5000+7000 and output 20+900: inflation is accepted, as on pi. assert.Equal(t, codexTokenTotals{15 + 12010, 1140 + 920, 291, 13618, 40590}, codexTotalsOf(m)) assert.Equal(t, ModelUsage{Requests: 2, InputTokens: 15 + 12010, OutputTokens: 1140 + 920, CacheCreationInputTokens: 13618, CacheReadInputTokens: 40590}, m.PerModelUsage["gpt-5.6-luna"]) @@ -470,9 +448,7 @@ func TestFoldCodexChildUsage_ClampsNegativeCounters(t *testing.T) { } // A read cut at the bound is a warning; the children before the cut stay -// folded and the ones past it are not counted. Each planted line stays under -// the parser's own line limit, so only the head -c bound stops the third -// child. +// folded. func TestFoldCodexChildUsage_CutReadIsAWarning(t *testing.T) { sessions := writeCodexChildRollouts(t, codexChildSameModelID) day := filepath.Join(sessions, "2026", "09", "29") @@ -491,9 +467,8 @@ func TestFoldCodexChildUsage_CutReadIsAWarning(t *testing.T) { assertCodexUsageSumsToTotals(t, m) } -// A rollout the read cannot open, or one a failed search of the sessions -// directory does not find, is a warning; the children it did read stay -// folded. +// An unreadable rollout, or one a failed search misses, is a warning; +// readable children stay folded. func TestFoldCodexChildUsage_UnreadableRolloutIsAWarning(t *testing.T) { if os.Geteuid() == 0 { t.Skip("file modes do not stop root") @@ -532,8 +507,7 @@ func TestFoldCodexChildUsage_UnreadableRolloutIsAWarning(t *testing.T) { } } -// The child's model comes from an agent-writable rollout and becomes a -// metrics.json key, so a credential planted there is redacted. +// A credential planted as the child's model is redacted from the key. func TestFoldCodexChildUsage_RedactsThePlantedModel(t *testing.T) { token := "ghp_" + strings.Repeat("A", 36) sessions := writeCodexChildRollouts(t) @@ -553,10 +527,9 @@ func TestFoldCodexChildUsage_RedactsThePlantedModel(t *testing.T) { assertCodexUsageSumsToTotals(t, m) } -// A counter no real thread reaches is skipped, with a warning, whichever -// counter it is: two planted rollouts near MaxInt would otherwise wrap the -// run's figures. -func TestFoldCodexChildUsage_SkipsImplausibleCounters(t *testing.T) { +// A child with any counter past codexChildUsageMaxTokens is skipped with a +// warning. +func TestFoldCodexChildUsage_SkipsCountersOverMaxTokens(t *testing.T) { for _, field := range []string{"input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens"} { t.Run(field, func(t *testing.T) { sessions := writeCodexChildRollouts(t) @@ -578,10 +551,8 @@ func TestFoldCodexChildUsage_SkipsImplausibleCounters(t *testing.T) { } } -// No child id, no sandbox command: PATH holds no openshell, so any exec -// would fail to start. The parent's entry still lands in the breakdown -// (a delegating agent that dispatched nothing), and a parent without a -// model is bucketed as pi buckets a record without one. +// No child id, no sandbox command (PATH has no openshell); the parent's +// entry still lands, under unknown when it has no model. func TestFoldCodexChildUsage_NoChildrenNoSandbox(t *testing.T) { t.Setenv("PATH", t.TempDir()) @@ -637,8 +608,7 @@ func TestFoldCodexChildUsage_ReadFailuresKeepTheParentEntry(t *testing.T) { }) } -// sumCodexIterations adds iterations up as internal/cli aggregateRunMetrics -// does. +// sumCodexIterations sums iterations as internal/cli aggregateRunMetrics does. func sumCodexIterations(ms ...*RunMetrics) *RunMetrics { sum := &RunMetrics{PerModelUsage: map[string]ModelUsage{}} for _, m := range ms { @@ -667,8 +637,7 @@ func TestFoldCodexChildUsage_TwoIterationsSumToTotals(t *testing.T) { require.NoError(t, err) assert.Equal(t, 2, n) - // The retry dispatched nothing; a delegating agent still folds, so its - // parent entry is in the breakdown. + // The retry dispatched nothing; its parent entry still lands. second := &RunMetrics{Model: "gpt-5.6-luna", NumTurns: 1, InputTokens: 100, OutputTokens: 50, ReasoningTokens: 7, CacheCreationInputTokens: 20, CacheReadInputTokens: 30} n, err = r.foldCodexChildUsage("sb", nil, second) require.NoError(t, err) @@ -683,11 +652,9 @@ func TestFoldCodexChildUsage_TwoIterationsSumToTotals(t *testing.T) { assertCodexUsageSumsToTotals(t, sum) } -// runCodexWithChildren runs CodexRuntime.Run against the fake with the given -// stream fixture and a sessions tree holding the rollouts of the three -// children the stream spawns, and returns the metrics, the exit code, the -// printer output and the fake's argv log. delegating sets RoleFiles on the -// runner-held digests (what Bootstrap records for a delegating agent). +// runCodexWithChildren runs Run against the fake with the rollouts of the +// three children the stream spawns; delegating sets RoleFiles on the +// runner-held digests. It returns the metrics, exit code, output and argv log. func runCodexWithChildren(t *testing.T, streamFixture string, delegating bool) (*RunMetrics, int, string, string) { t.Helper() logPath := filepath.Join(t.TempDir(), "openshell.log") @@ -715,9 +682,7 @@ func runCodexWithChildren(t *testing.T, streamFixture string, delegating bool) ( return metrics, exit, out.String(), readFileString(t, logPath) } -// A run that spawned: metrics.json carries the children. Digests without -// RoleFiles here, so the spawn in the stream alone is what triggers the read -// (the second half of the gate). +// A spawn in the stream alone (no RoleFiles) triggers the read. func TestCodexRun_FoldsChildUsage(t *testing.T) { metrics, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", false) @@ -738,8 +703,8 @@ func TestCodexRun_FoldsChildUsage(t *testing.T) { assert.NotContains(t, log, codexChildFailedSpawnID, "the failed spawn's receiver is never looked up") } -// A delegating agent that dispatched nothing: the breakdown carries the -// parent's entry and no sandbox command runs (the first half of the gate). +// A delegating agent that spawned nothing gets the parent's entry and no +// sandbox command. func TestCodexRun_DelegatingWithoutSpawnHasParentEntry(t *testing.T) { metrics, exit, _, log := runCodexWithChildren(t, "basic_run.ndjson", true) @@ -751,8 +716,7 @@ func TestCodexRun_DelegatingWithoutSpawnHasParentEntry(t *testing.T) { assert.NotContains(t, log, codexChildUsageMarker, "no id, no sandbox command") } -// The byte-equal invariant: a non-delegating agent whose stream reports no -// spawn writes the same metrics.json as before. +// A non-delegating agent with no spawn writes the same metrics.json as before. func TestCodexRun_NoSpawnNoBreakdown(t *testing.T) { metrics, exit, _, log := runCodexWithChildren(t, "basic_run.ndjson", false) @@ -765,7 +729,7 @@ func TestCodexRun_NoSpawnNoBreakdown(t *testing.T) { } // A failed read is a warning; the iteration keeps its exit code and the -// parent's numbers, and the breakdown keeps the parent's entry. +// parent's entry. func TestCodexRun_ChildReadFailureIsAWarning(t *testing.T) { token := "ghp_" + strings.Repeat("B", 36) t.Setenv("FULLSEND_TEST_CHILD_READ_FAIL", "1") @@ -783,11 +747,8 @@ func TestCodexRun_ChildReadFailureIsAWarning(t *testing.T) { assertCodexUsageSumsToTotals(t, metrics) } -// A codex process that did not exit 0 (a failed or interrupted turn, a -// timeout, a cancel) still has its children's rollouts read: codex writes a -// child's usage record as each response completes, so what the children -// recorded is kept, and the parent's entry is recorded too. With an exit-0 -// retry the breakdown still sums to the totals. +// A non-zero codex exit still reads the children; with an exit-0 retry the +// breakdown still sums to the totals. func TestCodexRun_NonZeroExitStillReadsTheChildren(t *testing.T) { t.Setenv("FULLSEND_TEST_CODEX_EXIT", "137") failed, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", true) diff --git a/internal/runtime/testdata/codex/README.md b/internal/runtime/testdata/codex/README.md index 665e0a47b4..109f02247e 100644 --- a/internal/runtime/testdata/codex/README.md +++ b/internal/runtime/testdata/codex/README.md @@ -26,17 +26,13 @@ ARG exists run `CODEX_VERSION=0.152.1 ./regen.sh`. | `truncated.ndjson` | Killed mid-write — the last line stops mid-token and there is no terminal event. (The repo's `end-of-file-fixer` hook keeps a trailing newline after it; the line is still unparseable, which is what the fixture tests.) | | `unknown_types.ndjson` | An unknown top-level event type and an unknown item type: skipped, the run still completes. | | `second_turn_unfinished.ndjson` | A completed turn followed by a second `turn.started` that never finishes: the run is incomplete, not the first turn's success. | -| `collab_spawn.ndjson` | Three completed `spawn_agent` items (one child each), one **failed** `spawn_agent` item whose receiver must not be counted as a child, `wait` and `close_agent` items for the errored child with `status: failed` inside a completed turn, and the real parent usage of the 2026-09-29 paid probe. Note: a spawn a PreToolUse hook denied emits no `collab_tool_call` item at all (seen in a mock run); the failed item here is hand-authored to pin the collector's status filter. | +| `collab_spawn.ndjson` | Three completed `spawn_agent` items, one **failed** one whose receiver is not a child, failed `wait` and `close_agent` items for the errored child inside a completed turn, and the parent usage of the 2026-09-29 paid probe. A hook-denied spawn emits no item; the failed one is hand-authored to pin the status filter. | ## Child rollout fixtures (`child_usage_*.jsonl`) -Inputs for `foldCodexChildUsage` (`internal/runtime/codex_subagents.go`), not for -`parseCodexStream`: they are codex **rollouts** (`$CODEX_HOME/sessions/**/rollout-*.jsonl`, the -underscored envelope of `codex_redact.go`), not the `exec --json` stream. Line types and fields -were copied from the rollouts of the 0.157.0 paid probe of 2026-09-29, trimmed, with -synthetic ids. The fold reads two lines per rollout: the last `turn_context` (its -`payload.model`) and the last `token_usage_record` (its `payload.thread_token_usage`, cumulative for -the thread and not reset when a request overflows the context window, unlike `token_count`). +Codex **rollouts** (`$CODEX_HOME/sessions/**/rollout-*.jsonl`) for `foldCodexChildUsage`, not +`exec --json` streams, modelled on the 0.157.0 paid probe of 2026-09-29, with synthetic ids. The fold reads each rollout's last `turn_context` (`payload.model`) and last +`token_usage_record` (`payload.thread_token_usage`). | Fixture | Covers | |---|---| From 21b934dfaa7dc98139023703ebc4c5becc71b464 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 20 Oct 2026 11:01:13 -0400 Subject: [PATCH 8/9] refactor(codex): fold what a failed or torn child read returned A failed or timed-out read now folds the stdout that came back instead of discarding it, and the read keeps the last two record and turn_context lines so a torn last line falls back to the one before. A line that does not decode is reported, the cut warning says the child at the cut may be counted short, and a codex stopped at the budget or cancelled warns that its children can record more after the read. Signed-off-by: Dharit Shah --- docs/cli/run.md | 5 +- internal/runtime/codex_run.go | 5 ++ internal/runtime/codex_subagents.go | 38 ++++++++----- internal/runtime/codex_subagents_test.go | 68 ++++++++++++++++++++---- 4 files changed, 91 insertions(+), 25 deletions(-) diff --git a/docs/cli/run.md b/docs/cli/run.md index 6caf28e3f1..1a17173ba6 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -180,8 +180,9 @@ differences in the last bullet. there. `requests` counts one per child rollout that reported usage (codex writes one per thread); `wait`, `send_input` and `close_agent` calls add none, and a child that errored before its first response has no usage and adds no `requests`. A codex iteration that exits non-zero, after a - failed or interrupted turn, a cancel or a timeout, still counts what its children recorded: codex - writes a child's usage as each response completes. + failed or interrupted turn, a cancel or a timeout, still counts what its children had recorded + when the runner read them: codex writes a child's usage as each response completes. After a + cancel or a timeout the run warns that usage recorded after the read is not counted. ## Budget and deadline diff --git a/internal/runtime/codex_run.go b/internal/runtime/codex_run.go index 71b34a7bf4..b58ba0bac0 100644 --- a/internal/runtime/codex_run.go +++ b/internal/runtime/codex_run.go @@ -669,6 +669,11 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri if n > 0 { printer.StepInfo(fmt.Sprintf("%d sub-agent thread(s) folded into the run metrics", n)) } + // At the budget or on a cancel OpenShell kills nothing, so codex's + // children can record more after the read. + if len(childIDs.IDs) > 0 && (ctx.Err() != nil || exitCode == 124 || exitCode == -1) { + printer.StepWarn("Sub-agent usage may be undercounted: codex was stopped, and its children can record more after the read") + } } if exitCode == 0 && lastResult != nil && lastResult.IsError { diff --git a/internal/runtime/codex_subagents.go b/internal/runtime/codex_subagents.go index 63cdc27d12..a01436b411 100644 --- a/internal/runtime/codex_subagents.go +++ b/internal/runtime/codex_subagents.go @@ -42,21 +42,24 @@ var codexChildUsageThreadID = regexp.MustCompile(`^[0-9a-f-]{36}$`) // codexChildUsage is what one child's rollout reported. type codexChildUsage struct { ID string - // Model is from the last turn_context, the child's own (a fork copies - // the parent's ahead of it); "" when there is none. + // Model is from the last turn_context that decodes, the child's own (a + // fork copies the parent's ahead of it); "" when there is none. Model string - // Usage is the thread total of the last token_usage_record. + // Usage is the thread total of the last token_usage_record that decodes. Usage codexUsage // HasUsage is false when the rollout has no record; such a child adds // nothing, not even a request. HasUsage bool // Unreadable marks a rollout that failed test -r or a failed search. Unreadable bool + // BadLine marks a line that did not decode (torn, cut or planted). + BadLine bool } // codexChildUsageReadCommand renders the in-sandbox command that prints, per -// child, a marker line, the rollout's last turn_context and its last -// token_usage_record. The record, not token_count: codex zeroes token_count's +// child, a marker line, the rollout's last two turn_context and last two +// token_usage_record lines: the parser keeps the last that decodes, so a torn +// last line falls back to the one before it. The record, not token_count: codex zeroes token_count's // counters when a request overflows the context window. A rollout it cannot // read, or that a failed search cannot find, prints the unreadable marker; // one a clean search misses prints nothing; a path outside sessionsDir is @@ -73,7 +76,7 @@ func codexChildUsageReadCommand(sessionsDir string, ids []string) (string, error quoted = append(quoted, shellQuote(id)) } return fmt.Sprintf( - `for id in %s; do files=$(command -p find %s -type f -name "rollout-*-$id.jsonl" 2>/dev/null) || [ -n "$files" ] || printf '%%s %%s\n' %s "$id"; printf '%%s\n' "$files" | while IFS= read -r f; do case $f in %s/*) ;; *) continue ;; esac; if [ ! -r "$f" ]; then printf '%%s %%s\n' %s "$id"; continue; fi; printf '%%s %%s\n' %s "$id"; command -p grep -a -e '"type":"turn_context"' -- "$f" 2>/dev/null | command -p tail -n 1; command -p grep -a -e '"type":"token_usage_record"' -- "$f" 2>/dev/null | command -p tail -n 1; done; done | command -p head -c %d`, + `for id in %s; do files=$(command -p find %s -type f -name "rollout-*-$id.jsonl" 2>/dev/null) || [ -n "$files" ] || printf '%%s %%s\n' %s "$id"; printf '%%s\n' "$files" | while IFS= read -r f; do case $f in %s/*) ;; *) continue ;; esac; if [ ! -r "$f" ]; then printf '%%s %%s\n' %s "$id"; continue; fi; printf '%%s %%s\n' %s "$id"; command -p grep -a -e '"type":"turn_context"' -- "$f" 2>/dev/null | command -p tail -n 2; command -p grep -a -e '"type":"token_usage_record"' -- "$f" 2>/dev/null | command -p tail -n 2; done; done | command -p head -c %d`, strings.Join(quoted, " "), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(codexChildUsageMarker), codexChildUsageMaxBytes), nil } @@ -109,10 +112,11 @@ func parseCodexChildUsage(data []byte) []codexChildUsage { Thread codexUsage `json:"thread_token_usage"` } `json:"payload"` } + cur := &out[len(out)-1] if json.Unmarshal(line, &env) != nil { + cur.BadLine = true continue } - cur := &out[len(out)-1] switch { case env.Type == "turn_context": cur.Model = strings.TrimSpace(env.Payload.Model) @@ -220,18 +224,22 @@ func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, if err != nil { return 0, err } + // A read that fails still folds whatever stdout came back. + var lost []string stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, cmd, 10*time.Second) if err != nil { - return 0, fmt.Errorf("reading the child rollouts: %w", err) - } - if exitCode != 0 { - return 0, fmt.Errorf("reading the child rollouts: exited %d: %s", exitCode, strings.TrimSpace(sanitizeOutput(stderr))) + lost = append(lost, err.Error()) + } else if exitCode != 0 { + lost = append(lost, fmt.Sprintf("exited %d: %s", exitCode, strings.TrimSpace(sanitizeOutput(stderr)))) } - unreadable, overMaxTokens := 0, 0 + unreadable, overMaxTokens, badLines := 0, 0, 0 for _, child := range parseCodexChildUsage([]byte(stdout)) { if child.Unreadable { unreadable++ } + if child.BadLine { + badLines++ + } if !child.HasUsage { continue } @@ -262,15 +270,17 @@ func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, m.CacheReadInputTokens += cacheRead folded++ } - var lost []string if unreadable > 0 { lost = append(lost, fmt.Sprintf("%d child rollout(s) could not be read", unreadable)) } + if badLines > 0 { + lost = append(lost, fmt.Sprintf("%d child rollout(s) had a line that did not decode", badLines)) + } if overMaxTokens > 0 { lost = append(lost, fmt.Sprintf("%d child(ren) with a counter past %d not counted", overMaxTokens, codexChildUsageMaxTokens)) } if len(stdout) >= codexChildUsageMaxBytes { - lost = append(lost, fmt.Sprintf("cut at %d bytes; only the children before the cut are counted", codexChildUsageMaxBytes)) + lost = append(lost, fmt.Sprintf("cut at %d bytes; children at and past the cut are not fully counted", codexChildUsageMaxBytes)) } if len(lost) > 0 { return folded, fmt.Errorf("reading the child rollouts: %s", strings.Join(lost, "; ")) diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index 9b68b5ba6f..4fad9b195e 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -171,6 +171,22 @@ func TestCodexChildUsageReadCommand_ReadsTheThreadTotal(t *testing.T) { }, got[0], "the last record's thread total, not the zeroed token_count after it") } +// A codex killed mid-write leaves a torn last line; the record before it +// still counts. +func TestCodexChildUsageReadCommand_FallsBackPastATornRecord(t *testing.T) { + t.Parallel() + + rollout := `{"type":"turn_context","payload":{"model":"gpt-5.6-luna"}}` + "\n" + + `{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tokens":30,"output_tokens":3}}}` + "\n" + + `{"type":"token_usage_record","payload":{"thread_token_usage":{"input_tok` + sessions := writeCodexChildRollouts(t) + require.NoError(t, os.WriteFile(filepath.Join(sessions, "2026", "09", "29", "rollout-2026-09-29T15-46-38-"+codexChildSameModelID+".jsonl"), []byte(rollout), 0o644)) + + got := runCodexChildUsageRead(t, sessions, []string{codexChildSameModelID}) + require.Len(t, got, 1) + assert.Equal(t, codexChildUsage{ID: codexChildSameModelID, Model: "gpt-5.6-luna", HasUsage: true, Usage: codexUsage{InputTokens: 30, OutputTokens: 3}, BadLine: true}, got[0]) +} + // A forked child's rollout starts with the parent's turn_context lines; the // read names the child by its own, the last. func TestCodexChildUsageReadCommand_NamesAForkedChildByItsOwnTurn(t *testing.T) { @@ -235,11 +251,11 @@ func TestParseCodexChildUsage(t *testing.T) { got := parseCodexChildUsage([]byte(data)) require.Len(t, got, 3) - assert.Equal(t, codexChildUsage{ID: codexChildSameModelID, Model: "gpt-5.6-sol", HasUsage: true, Usage: codexUsage{InputTokens: 20, OutputTokens: 2}}, - got[0], "the last turn_context names the model, the last record wins, a malformed line is skipped") + assert.Equal(t, codexChildUsage{ID: codexChildSameModelID, Model: "gpt-5.6-sol", HasUsage: true, Usage: codexUsage{InputTokens: 20, OutputTokens: 2}, BadLine: true}, + got[0], "the last turn_context names the model, the last record wins, a malformed line is skipped and flagged") assert.Equal(t, codexChildUsage{ID: codexChildOtherModelID, HasUsage: true, Usage: codexUsage{InputTokens: 5, OutputTokens: 5}}, got[1], "no turn_context: the model stays empty and the fold buckets it") - assert.Equal(t, codexChildUsage{ID: codexChildFailedID, Model: "gpt-5.6-terra"}, + assert.Equal(t, codexChildUsage{ID: codexChildFailedID, Model: "gpt-5.6-terra", BadLine: true}, got[2], "a truncated last line (the head -c cut) is not usage") assert.Empty(t, parseCodexChildUsage(nil)) } @@ -318,9 +334,10 @@ func TestParseCodexStream_FailedCollabItem(t *testing.T) { // fakeOpenshellCodexChildren answers the manifest cat from storeDir, streams // streamFixture for the launch, and runs the read command under sh against -// sessionsDir. FULLSEND_TEST_CHILD_READ_FAIL makes the read exit 1 (with -// FULLSEND_TEST_CHILD_READ_STDERR on stderr); FULLSEND_TEST_CODEX_EXIT sets -// the launch's exit status. +// sessionsDir. FULLSEND_TEST_CHILD_READ_FAIL=1 makes the read exit 1 (with +// FULLSEND_TEST_CHILD_READ_STDERR on stderr), =after makes it time out after +// printing; FULLSEND_TEST_CODEX_EXIT sets the launch's exit status (killed: +// SIGKILL, as the budget's context kill ends it). func fakeOpenshellCodexChildren(t *testing.T, logPath, storeDir, streamFixture, sessionsDir string) { t.Helper() binDir := t.TempDir() @@ -330,10 +347,12 @@ if [ "$2" = "exec" ]; then for last; do :; done case "$last" in cat\ *) f=$(printf '%s' "${last#cat }" | tr -d "'" | tr '/' '_'); cat '` + storeDir + `'/"$f"; exit $? ;; - *"exec --json"*) cat '` + streamFixture + `'; exit "${FULLSEND_TEST_CODEX_EXIT:-0}" ;; + *"exec --json"*) cat '` + streamFixture + `'; [ "${FULLSEND_TEST_CODEX_EXIT:-}" = killed ] && kill -9 $$; exit "${FULLSEND_TEST_CODEX_EXIT:-0}" ;; *` + codexChildUsageMarker + `*) - if [ -n "${FULLSEND_TEST_CHILD_READ_FAIL:-}" ]; then echo "fake openshell: refusing the rollout read${FULLSEND_TEST_CHILD_READ_STDERR:+ $FULLSEND_TEST_CHILD_READ_STDERR}" >&2; exit 1; fi - sh -c "$(printf '%s' "$last" | sed 's#` + CodexRuntime{}.codexSessionsDir() + `#` + sessionsDir + `#g')"; exit $? ;; + if [ "${FULLSEND_TEST_CHILD_READ_FAIL:-}" = 1 ]; then echo "fake openshell: refusing the rollout read${FULLSEND_TEST_CHILD_READ_STDERR:+ $FULLSEND_TEST_CHILD_READ_STDERR}" >&2; exit 1; fi + sh -c "$(printf '%s' "$last" | sed 's#` + CodexRuntime{}.codexSessionsDir() + `#` + sessionsDir + `#g')"; rc=$? + if [ "${FULLSEND_TEST_CHILD_READ_FAIL:-}" = after ]; then exit 124; fi + exit $rc ;; esac exit 0 fi @@ -461,6 +480,7 @@ func TestFoldCodexChildUsage_CutReadIsAWarning(t *testing.T) { n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID, codexChildOtherModelID, codexChildFailedID}, m) require.Error(t, err) assert.Contains(t, err.Error(), "cut at") + assert.Contains(t, err.Error(), "had a line that did not decode", "the cut line is reported too") assert.Equal(t, 1, n, "the child before the cut") assert.NotContains(t, m.PerModelUsage, "gpt-5.6-terra", "the child past the cut") assert.Equal(t, 2, m.PerModelUsage["gpt-5.6-luna"].Requests) @@ -595,6 +615,19 @@ func TestFoldCodexChildUsage_ReadFailuresKeepTheParentEntry(t *testing.T) { assert.Equal(t, codexTokenTotals{15, 1140, 291, 13618, 40590}, codexTotalsOf(m), "totals untouched") }) + t.Run("a timed-out read folds the stdout that came back", func(t *testing.T) { + sessions := writeCodexChildRollouts(t, codexChildSameModelID) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + t.Setenv("FULLSEND_TEST_CHILD_READ_FAIL", "after") + m := codexParentMetrics("gpt-5.6-luna") + n, err := r.foldCodexChildUsage("sb", []string{codexChildSameModelID}, m) + require.Error(t, err) + assert.Contains(t, err.Error(), "timed out") + assert.Equal(t, 1, n) + assert.Equal(t, 2, m.PerModelUsage["gpt-5.6-luna"].Requests) + assertCodexUsageSumsToTotals(t, m) + }) + t.Run("the read command exits non-zero", func(t *testing.T) { fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", t.TempDir()) t.Setenv("FULLSEND_TEST_CHILD_READ_FAIL", "1") @@ -767,4 +800,21 @@ func TestCodexRun_NonZeroExitStillReadsTheChildren(t *testing.T) { retry, exit, _, _ := runCodexWithChildren(t, "collab_spawn.ndjson", true) require.Equal(t, 0, exit) assertCodexUsageSumsToTotals(t, sumCodexIterations(failed, retry)) + assert.NotContains(t, out, "may be undercounted", "codex exited on its own; its children were done") +} + +// A codex stopped at the budget (the context kill, -1, or openshell's own +// timeout, 124) may still be running; the run says the children's later +// usage is not counted. +func TestCodexRun_BudgetStopWarnsOfLaterChildUsage(t *testing.T) { + for exitEnv, want := range map[string]int{"killed": -1, "124": 124} { + t.Run(exitEnv, func(t *testing.T) { + t.Setenv("FULLSEND_TEST_CODEX_EXIT", exitEnv) + _, exit, out, _ := runCodexWithChildren(t, "collab_spawn.ndjson", false) + + assert.Equal(t, want, exit) + assert.Contains(t, out, "2 sub-agent thread(s) folded into the run metrics") + assert.Contains(t, out, "! Sub-agent usage may be undercounted: codex was stopped") + }) + } } From 949bd95b55b5d0f94c391f5f67e594a844e65343 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 20 Oct 2026 14:49:16 -0400 Subject: [PATCH 9/9] refactor(codex): count nothing for a child with more than one rollout Codex writes one rollout per thread, so a second file named for the same id is planted. Each copy was folded as its own child, multiplying the child's tokens and requests; such an id now prints the unreadable marker and none of its copies count. Signed-off-by: Dharit Shah --- internal/runtime/codex_subagents.go | 14 ++++++++----- internal/runtime/codex_subagents_test.go | 25 +++++++++++++++++++++--- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/internal/runtime/codex_subagents.go b/internal/runtime/codex_subagents.go index a01436b411..0e933cd217 100644 --- a/internal/runtime/codex_subagents.go +++ b/internal/runtime/codex_subagents.go @@ -24,7 +24,8 @@ import ( const codexChildUsageMarker = "fullsend-child" // codexChildUnreadableMarker starts the line printed for a child whose -// rollout fails test -r, or that a failed search did not find. +// rollout fails test -r, that a failed search did not find, or that has more +// than one rollout. const codexChildUnreadableMarker = "fullsend-unreadable" // codexChildUsageMaxBytes bounds the read: the sessions directory is @@ -50,7 +51,8 @@ type codexChildUsage struct { // HasUsage is false when the rollout has no record; such a child adds // nothing, not even a request. HasUsage bool - // Unreadable marks a rollout that failed test -r or a failed search. + // Unreadable marks a rollout that failed test -r, a failed search, or an + // id with more than one rollout. Unreadable bool // BadLine marks a line that did not decode (torn, cut or planted). BadLine bool @@ -61,7 +63,9 @@ type codexChildUsage struct { // token_usage_record lines: the parser keeps the last that decodes, so a torn // last line falls back to the one before it. The record, not token_count: codex zeroes token_count's // counters when a request overflows the context window. A rollout it cannot -// read, or that a failed search cannot find, prints the unreadable marker; +// read, or that a failed search cannot find, prints the unreadable marker, +// and so does an id with more than one rollout (codex writes one; copies are +// planted), whose copies all go uncounted; // one a clean search misses prints nothing; a path outside sessionsDir is // skipped; head -c bounds the output. func codexChildUsageReadCommand(sessionsDir string, ids []string) (string, error) { @@ -76,8 +80,8 @@ func codexChildUsageReadCommand(sessionsDir string, ids []string) (string, error quoted = append(quoted, shellQuote(id)) } return fmt.Sprintf( - `for id in %s; do files=$(command -p find %s -type f -name "rollout-*-$id.jsonl" 2>/dev/null) || [ -n "$files" ] || printf '%%s %%s\n' %s "$id"; printf '%%s\n' "$files" | while IFS= read -r f; do case $f in %s/*) ;; *) continue ;; esac; if [ ! -r "$f" ]; then printf '%%s %%s\n' %s "$id"; continue; fi; printf '%%s %%s\n' %s "$id"; command -p grep -a -e '"type":"turn_context"' -- "$f" 2>/dev/null | command -p tail -n 2; command -p grep -a -e '"type":"token_usage_record"' -- "$f" 2>/dev/null | command -p tail -n 2; done; done | command -p head -c %d`, - strings.Join(quoted, " "), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(codexChildUsageMarker), codexChildUsageMaxBytes), nil + `for id in %s; do files=$(command -p find %s -type f -name "rollout-*-$id.jsonl" 2>/dev/null) || [ -n "$files" ] || printf '%%s %%s\n' %s "$id"; if [ "$(printf '%%s\n' "$files" | command -p grep -c .)" -gt 1 ]; then printf '%%s %%s\n' %s "$id"; continue; fi; printf '%%s\n' "$files" | while IFS= read -r f; do case $f in %s/*) ;; *) continue ;; esac; if [ ! -r "$f" ]; then printf '%%s %%s\n' %s "$id"; continue; fi; printf '%%s %%s\n' %s "$id"; command -p grep -a -e '"type":"turn_context"' -- "$f" 2>/dev/null | command -p tail -n 2; command -p grep -a -e '"type":"token_usage_record"' -- "$f" 2>/dev/null | command -p tail -n 2; done; done | command -p head -c %d`, + strings.Join(quoted, " "), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(codexChildUnreadableMarker), shellQuote(sessionsDir), shellQuote(codexChildUnreadableMarker), shellQuote(codexChildUsageMarker), codexChildUsageMaxBytes), nil } // parseCodexChildUsage decodes the read command's output. Lines before the diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index 4fad9b195e..6d9e80b0a1 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -527,6 +527,25 @@ func TestFoldCodexChildUsage_UnreadableRolloutIsAWarning(t *testing.T) { } } +// Codex writes one rollout per thread, so a copy is planted: the id is +// reported and none of its copies count, while other children still do. +func TestFoldCodexChildUsage_DuplicateRolloutsCountNothing(t *testing.T) { + sessions := writeCodexChildRollouts(t, codexChildSameModelID, codexChildOtherModelID) + day := filepath.Join(sessions, "2026", "09", "29") + data, err := os.ReadFile(filepath.Join(day, "rollout-2026-09-29T15-46-38-"+codexChildOtherModelID+".jsonl")) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-copy-"+codexChildOtherModelID+".jsonl"), data, 0o644)) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) + + m := codexParentMetrics("gpt-5.6-luna") + n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID, codexChildOtherModelID}, m) + require.Error(t, err) + assert.Contains(t, err.Error(), "1 child rollout(s) could not be read") + assert.Equal(t, 1, n, "the luna child only") + assert.NotContains(t, m.PerModelUsage, "gpt-5.6-terra", "neither copy counts") + assertCodexUsageSumsToTotals(t, m) +} + // A credential planted as the child's model is redacted from the key. func TestFoldCodexChildUsage_RedactsThePlantedModel(t *testing.T) { token := "ghp_" + strings.Repeat("A", 36) @@ -554,14 +573,14 @@ func TestFoldCodexChildUsage_SkipsCountersOverMaxTokens(t *testing.T) { t.Run(field, func(t *testing.T) { sessions := writeCodexChildRollouts(t) day := filepath.Join(sessions, "2026", "09", "29") - for name, value := range map[string]string{"a": "9223372036854775807", "b": "9223372036854775799"} { + for id, value := range map[string]string{codexChildSameModelID: "9223372036854775807", codexChildOtherModelID: "9223372036854775799"} { rollout := `{"type":"token_usage_record","payload":{"thread_token_usage":{"` + field + `":` + value + `}}}` + "\n" - require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-"+name+"-"+codexChildSameModelID+".jsonl"), []byte(rollout), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-a-"+id+".jsonl"), []byte(rollout), 0o644)) } fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), t.TempDir(), "", sessions) m := codexParentMetrics("gpt-5.6-luna") - n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID}, m) + n, err := CodexRuntime{}.foldCodexChildUsage("sb", []string{codexChildSameModelID, codexChildOtherModelID}, m) require.Error(t, err, "a skipped child is a warning, as a cut or unreadable read is") assert.Contains(t, err.Error(), "2 child(ren) with a counter past") assert.Zero(t, n)