sessions: a Codex line's marks are read in one pass, not one bytes.Contains each (#3493)

callHead and codexCallLine asked of every rollout line, with a
bytes.Contains each, whether it held "type":"user_message",
"role":"user", "type":"function_call_output" and nine more: up to twelve
passes over the line in each, a line of megabytes of tool output
included. A CPU profile of a cold usage read on Windows (20,807 Codex
rollouts, 44GB, magpie web in a sandbox home on the Windows box) put 37%
of its 270s of samples in that bytes.Contains (indexbody).

cxMarksOf reads them all in one pass: it walks each `":"` that ends a key
(in a JSON string the quotes are escaped, so never one inside a string),
and records the "type" values and the user's role it finds. It finds
what each value's own pass found: the same line, anywhere in it.

Run:
- TestCxMarksAsContains: twelve lines (long escaped strings holding the
  values, a nested value past a long string, "subtype"/"xtype" keys,
  "role":"users", empty and cut lines) give the same marks as a
  bytes.Contains of each. Red when the role is not recorded (3 lines).
- Every line of the owner's real ~/.codex/sessions, read only: 619
  files, 20,059 lines, 4.3GB, 0 lines whose marks differ.
- BenchmarkCxMarks, a 1MB exec_command_end line: 0.36ms a line, from
  11.2ms.
- Windows box, cold (.cache\magpie removed), magpie web, 3 rounds each,
  alternating, origin/main 552e974f2 against this change:
    CPU in the first 70s:  214.3 / 214.1 / 216.0s  ->  127.2 / 123.4 / 124.5s
    peak working set:      318 / 297 / 311MB       ->  344 / 342 / 325MB
  The peak is ~25MB higher: the same work is done in less time. Not
  changed here.
- go test ./internal/sessions/ ./internal/usage/ ./internal/gui/: ok.
  gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/sessions/ clean.

Not changed: codexBody (codex.go) asks the same values with
bytes.Contains, but only of lines codexHead let through by their head
(1% of the profile's bytes.Contains was there, under 1s).
This commit is contained in:
yetone
2026-10-25 17:57:52 +08:00
parent d580537201
commit 120264a49f
2 changed files with 159 additions and 13 deletions
+91 -13
View File
@@ -452,11 +452,89 @@ func callHead(st *callFile, b []byte) bool {
return false
}
compacted := typeAfter(b[:min(len(b), 1024)], cxType) == "compacted"
if !compacted && (bytes.Contains(b, cxUserMsg) || bytes.Contains(b, cxUserRole) || bytes.Contains(b, cxToolOut) || bytes.Contains(b, cxCustomOut)) {
m := cxMarksOf(b)
if !compacted && m&cxInput != 0 {
codexCallLine(st, b)
return false
}
return bytes.Contains(b, cxMeta) || bytes.Contains(b, cxTurn) || bytes.Contains(b, cxRecord) || bytes.Contains(b, cxCompacted) || bytes.Contains(b, cxCount) || bytes.Contains(b, cxSettings) || bytes.Contains(b, cxStarted) || bytes.Contains(b, cxDone)
return m&cxFollowed != 0
}
// cxMarks are the "type" values a rollout line holds anywhere in it that
// codexCallLine follows, and whether an object in it has the user's role.
type cxMarks uint16
const (
cxMarkUserMsg cxMarks = 1 << iota
cxMarkUserRole
cxMarkToolOut
cxMarkMeta
cxMarkTurn
cxMarkRecord
cxMarkCompacted
cxMarkCount
cxMarkSettings
cxMarkStarted
cxMarkDone
// what the model is given: the prompt, a tool's output
cxInput = cxMarkUserMsg | cxMarkUserRole | cxMarkToolOut
// the lines codexCallLine reads whole
cxFollowed = cxMarkMeta | cxMarkTurn | cxMarkRecord | cxMarkCompacted | cxMarkCount | cxMarkSettings | cxMarkStarted | cxMarkDone
)
var (
cxKeyEnd = []byte(`":"`)
cxTypeKey = []byte(`"type`)
cxRoleKey = []byte(`"role`)
cxUserName = []byte(`user"`)
)
// cxMarksOf reads b's marks in one pass: every `"type":"<v>"` and
// `"role":"user"` that a bytes.Contains of each would find, as one each
// had been (up to twelve passes over a line of megabytes, most of a cold
// usage read's CPU on Windows, #3493). In a JSON string the quotes are
// escaped, so the `":"` ending a key is never inside one.
func cxMarksOf(b []byte) (m cxMarks) {
for {
i := bytes.Index(b, cxKeyEnd)
if i < 0 {
return m
}
key, val := b[:i], b[i+len(cxKeyEnd):]
b = val
switch {
case bytes.HasSuffix(key, cxTypeKey):
j := bytes.IndexByte(val, '"')
if j < 0 {
return m
}
switch string(val[:j]) {
case "user_message":
m |= cxMarkUserMsg
case "function_call_output", "custom_tool_call_output":
m |= cxMarkToolOut
case "session_meta":
m |= cxMarkMeta
case "turn_context":
m |= cxMarkTurn
case "token_usage_record":
m |= cxMarkRecord
case "compacted":
m |= cxMarkCompacted
case "token_count":
m |= cxMarkCount
case "thread_settings_applied":
m |= cxMarkSettings
case "task_started":
m |= cxMarkStarted
case "task_complete":
m |= cxMarkDone
}
case bytes.HasSuffix(key, cxRoleKey) && bytes.HasPrefix(val, cxUserName):
m |= cxMarkUserRole
}
}
}
// sessionOfPath is the session a Claude Code file belongs to by its name:
@@ -743,13 +821,10 @@ func firstChars(s string, n int) string {
}
var (
ccIdentity = []byte(`"identity":{"modelId":"`)
ccUserLine = []byte(`"type":"user"`)
ccCompact = []byte(`"subtype":"compact_boundary"`)
cxToolOut = []byte(`"type":"function_call_output"`)
cxCustomOut = []byte(`"type":"custom_tool_call_output"`)
cxStarted = []byte(`"type":"task_started"`)
cxDone = []byte(`"type":"task_complete"`)
ccIdentity = []byte(`"identity":{"modelId":"`)
ccUserLine = []byte(`"type":"user"`)
ccCompact = []byte(`"subtype":"compact_boundary"`)
cxStarted = []byte(`"type":"task_started"`)
)
// cxCall is a line of a Codex rollout that says something about calls.
@@ -807,18 +882,21 @@ func codexCallLine(st *callFile, b []byte) {
st.codexChanged(r.Usage.compacted(tsAt(b, false), r.Model, cxCompactionIn(b)))
return
}
if bytes.Contains(b, cxUserMsg) || bytes.Contains(b, cxUserRole) || bytes.Contains(b, cxToolOut) || bytes.Contains(b, cxCustomOut) {
m := cxMarksOf(b)
if m&cxInput != 0 {
if at := tsAt(b, false); !at.IsZero() {
r.LastIn = at
if bytes.Contains(b, cxUserMsg) || bytes.Contains(b, cxUserRole) {
if m&(cxMarkUserMsg|cxMarkUserRole) != 0 {
r.Usage.Pending = 0
}
r.saveContext()
}
return
}
if !(!r.Meta && bytes.Contains(b, cxMeta) || bytes.Contains(b, cxTurn) || bytes.Contains(b, cxRecord) || bytes.Contains(b, cxCompacted) || bytes.Contains(b, cxCount) ||
bytes.Contains(b, cxSettings) || bytes.Contains(b, cxStarted) || bytes.Contains(b, cxDone)) {
if r.Meta {
m &^= cxMarkMeta
}
if m&cxFollowed == 0 {
return
}
var l cxCall
+68
View File
@@ -0,0 +1,68 @@
package sessions
import (
"bytes"
"strings"
"testing"
)
// cxMarksByContains is what callHead and codexCallLine found with a
// bytes.Contains of each value, a pass over the line each.
func cxMarksByContains(b []byte) (m cxMarks) {
for v, mark := range map[string]cxMarks{
`"type":"user_message"`: cxMarkUserMsg, `"role":"user"`: cxMarkUserRole,
`"type":"function_call_output"`: cxMarkToolOut, `"type":"custom_tool_call_output"`: cxMarkToolOut,
`"type":"session_meta"`: cxMarkMeta, `"type":"turn_context"`: cxMarkTurn,
`"type":"token_usage_record"`: cxMarkRecord, `"type":"compacted"`: cxMarkCompacted,
`"type":"token_count"`: cxMarkCount, `"type":"thread_settings_applied"`: cxMarkSettings,
`"type":"task_started"`: cxMarkStarted, `"type":"task_complete"`: cxMarkDone,
} {
if bytes.Contains(b, []byte(v)) {
m |= mark
}
}
return m
}
// One pass finds what each value's own pass found, wherever it is in the
// line: the head, nested past a long string, a string's escaped copy (not
// found by either), a key whose name only ends in "type".
func TestCxMarksAsContains(t *testing.T) {
long := strings.Repeat(`x\":\"y \"type\":\"token_count\" `, 2000)
lines := []string{
`{"timestamp":"2026-10-25T08:00:00.000Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":1}}}}`,
`{"timestamp":"2026-10-25T08:00:00.000Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}}`,
`{"timestamp":"2026-10-25T08:00:00.000Z","type":"response_item","payload":{"type":"function_call_output","call_id":"c","output":"` + long + `"}}`,
`{"timestamp":"2026-10-25T08:00:00.000Z","type":"event_msg","payload":{"type":"exec_command_end","aggregated_output":"` + long + `"}}`,
`{"timestamp":"2026-10-25T08:00:00.000Z","type":"event_msg","payload":{"type":"agent_message","text":"` + long + `","inner":{"type":"task_complete"}}}`,
`{"timestamp":"2026-10-25T08:00:00.000Z","type":"compacted","payload":{"replacement_history":[{"type":"message","role":"user"},{"type":"message","role":"assistant"}]}}`,
`{"timestamp":"2026-10-25T08:00:00.000Z","type":"session_meta","payload":{"id":"s","base_instructions":{"text":"` + long + `"}}}`,
`{"timestamp":"2026-10-25T08:00:00.000Z","type":"turn_context","payload":{"model":"gpt-5.5","subtype":"user_message","xtype":"task_started"}}`,
`{"type":"token_usage_record","payload":{"type":"thread_settings_applied","role":"users","r":{"role":"user"}}}`,
`{"a":":","type":"custom_tool_call_output","b":"\"role\":\"user\""}`,
`"type":"task_started"`, `"type":"`, `"role":"`, `":"`, ``, `{"type":"user_message`,
}
for _, l := range lines {
b := []byte(l)
if got, want := cxMarksOf(b), cxMarksByContains(b); got != want {
t.Errorf("cxMarksOf(%.120q) = %b, the passes of each found %b", l, got, want)
}
}
}
// A line that names none of the values is passed over once: no more than
// a bytes.Index of `":"` would cost, not one pass a value.
func BenchmarkCxMarks(b *testing.B) {
line := []byte(`{"timestamp":"2026-10-25T08:00:00.000Z","type":"event_msg","payload":{"type":"exec_command_end","aggregated_output":"` + strings.Repeat(`line of output \"quoted\" `, 40000) + `"}}`)
b.SetBytes(int64(len(line)))
b.Run("one pass", func(b *testing.B) {
for range b.N {
cxMarksOf(line)
}
})
b.Run("a pass each", func(b *testing.B) {
for range b.N {
cxMarksByContains(line)
}
})
}