diff --git a/internal/sessions/codex.go b/internal/sessions/codex.go index 8be4f0b34..1f99fa6a5 100644 --- a/internal/sessions/codex.go +++ b/internal/sessions/codex.go @@ -8,6 +8,9 @@ import ( "strings" "sync" "time" + "unicode" + "unicode/utf8" + "unsafe" "github.com/tidwall/gjson" ) @@ -837,8 +840,7 @@ func cxFastPrompt(s *state, at time.Time, b []byte, main bool) bool { return false } found = true - text := strAt(rest[:len(cxText)+strEnd(rest[len(cxText):])], cxText) - p := cxPrompt(text) + p := cxTextPrompt(rest[len(cxText)-1 : len(cxText)+strEnd(rest[len(cxText):])]) typed = typed || p != "" if s.Title == "" { s.Title = p @@ -907,6 +909,136 @@ func cxFastCount(s *state, at time.Time, b []byte) bool { return true } +// cxTextPrompt is cxPrompt of the JSON string q, its quotes included, +// without the whole of a long one decoded: a prompt's title is its first +// 160 runes, and decoding all of every pasted log or file made ~half a +// GB on a cold read of a year of Codex history. Only a head is decoded +// when that settles the title, the rest only checked to be what +// json.Unmarshal takes; whatever it doesn't settle is decoded whole. +func cxTextPrompt(q []byte) string { + const head = 1024 + whole := func() string { + if len(q) >= 2 && q[len(q)-1] == '"' && plainJSON(q[1:len(q)-1]) { + // as json.Unmarshal reads it, and only read here: cxPrompt's + // title is a string of its own + return cxPrompt(unsafe.String(&q[1], len(q)-2)) + } + var v string + if json.Unmarshal(q, &v) != nil { + return "" + } + return cxPrompt(v) + } + if len(q) <= 2*head || q[len(q)-1] != '"' { + return whole() + } + k := jsonCut(q, head) + if k < 0 || !jsonBodyValid(q[k:len(q)-1]) { + return whole() + } + var v string + if plainJSON(q[1:k]) { + v = unsafe.String(&q[1], k-1) + } else if json.Unmarshal(append(append(make([]byte, 0, k+1), q[:k]...), '"'), &v) != nil { + return whole() + } + t := strings.TrimLeftFunc(v, unicode.IsSpace) + p, cut := titleCut(t) + if !cut { + return whole() // the head doesn't hold the whole title + } + if strings.HasPrefix(t, "<") || strings.HasPrefix(t, "# AGENTS.md") { + return "" + } + return p +} + +// plainJSON: b, a JSON string's body, is its own decoding: UTF-8 with no +// escape or control byte. +func plainJSON(b []byte) bool { + for _, c := range b { + if c < 0x20 || c == '\\' { + return false + } + } + return utf8.Valid(b) +} + +// jsonCut is where the JSON string q can be cut at or after at with its +// head decoded as the whole decodes it: before an ASCII byte, which ends +// any UTF-8 sequence, outside an escape and not between a surrogate +// pair's halves; -1 for none. +func jsonCut(q []byte, at int) int { + high := false + for j := 1; j < len(q)-1; { + if j >= at && q[j] < 0x80 && !high { + return j + } + high = false + if q[j] != '\\' { + j++ + continue + } + if j+6 <= len(q) && q[j+1] == 'u' { + r := 0 + for _, h := range q[j+2 : j+6] { + r = r<<4 | hexVal(h) + } + high = r >= 0xD800 && r < 0xDC00 + j += 6 + } else { + j += 2 + } + } + return -1 +} + +// jsonBodyValid: b, a JSON string's body without its quotes, is one +// json.Unmarshal takes: no control byte, and each escape one it knows. +func jsonBodyValid(b []byte) bool { + for j := 0; j < len(b); j++ { + c := b[j] + if c < 0x20 { + return false + } + if c != '\\' { + continue + } + if j++; j >= len(b) { + return false + } + switch b[j] { + case '"', '\\', '/', 'b', 'f', 'n', 'r', 't': + case 'u': + if j+5 > len(b) { + return false + } + for _, h := range b[j+1 : j+5] { + if hexVal(h) < 0 { + return false + } + } + j += 4 + default: + return false + } + } + return true +} + +// hexVal is a hex digit's value, or a large negative for another byte. +func hexVal(h byte) int { + switch { + case '0' <= h && h <= '9': + return int(h - '0') + case 'a' <= h && h <= 'f': + return int(h-'a') + 10 + case 'A' <= h && h <= 'F': + return int(h-'A') + 10 + } + return -1 << 20 +} + // cxPrompt is the words of a prompt, or "" for what Codex put in itself // (the environment, AGENTS.md, instructions). func cxPrompt(text string) string { diff --git a/internal/sessions/codex_prompt_head_test.go b/internal/sessions/codex_prompt_head_test.go new file mode 100644 index 000000000..15260d322 --- /dev/null +++ b/internal/sessions/codex_prompt_head_test.go @@ -0,0 +1,131 @@ +package sessions + +import ( + "encoding/json" + "math/rand" + "runtime" + "strings" + "testing" +) + +// oldTextPrompt is what a prompt's title was read as before: its whole +// text decoded, then cxPrompt. +func oldTextPrompt(q []byte) string { + return cxPrompt(strAt(append([]byte(`,"text":`), q...), cxText)) +} + +// TestCxTextPromptAsTheWholeText holds the head-only read of a prompt +// to the whole text's decoding, title for title, around and past the +// head's length, with escapes, surrogates, bytes not UTF-8, runs of +// space, Codex's own texts and what json.Unmarshal refuses late in it. +func TestCxTextPromptAsTheWholeText(t *testing.T) { + r := rand.New(rand.NewSource(7)) + pieces := []string{"a", "word ", " ", "\n", "\t\t", " ", " ", "é", "中文", "😀", "<", "#", "\"", "\\", "/", "…"} + raws := []string{`\n`, ` `, `
`, `😀`, `\ud83d`, `\ude00`, `\ud83dx`, "\xff", "\xe4\xb8", `\/`, `\"`, `\\`, `\t`, `A`} + bads := []string{`\x`, "\x01", `\u12`, `\uzzzz`, `\`} + make1 := func() []byte { + var b strings.Builder + switch r.Intn(6) { + case 0: + b.WriteString(strings.Repeat(" ", r.Intn(9000))) + case 1: + b.WriteString("# AGENTS.md") + case 2: + b.WriteString("") + case 3: + b.WriteString(strings.Repeat(`\n`, r.Intn(3000))) + } + n := []int{50, 1500, 2100, 4000, 9000, 20000}[r.Intn(6)] + q := []byte{'"'} + q = append(q, b.String()...) + for len(q) < n { + if r.Intn(3) == 0 { + q = append(q, raws[r.Intn(len(raws))]...) + continue + } + s, _ := json.Marshal(pieces[r.Intn(len(pieces))]) + if r.Intn(40) == 0 { + s, _ = json.Marshal(strings.Repeat(" ", r.Intn(5000))) + } + q = append(q, s[1:len(s)-1]...) + } + if r.Intn(8) == 0 { + at := 1 + r.Intn(len(q)-1) + q = append(q[:at], append([]byte(bads[r.Intn(len(bads))]), q[at:]...)...) + } + if r.Intn(20) > 0 { + q = append(q, '"') + } + return q + } + words := strings.Repeat("word ", 200) + short := strings.Repeat("word ", 20) // the title ends in what follows + hand := []string{ + words + strings.Repeat(`\u3000`, 3000), + words + strings.Repeat(`\u3000`, 3000) + "x", + words + strings.Repeat(" ", 3000), + short + strings.Repeat(" ", 3000), + short + strings.Repeat(" ", 3000), + short + strings.Repeat(`\u3000`, 3000), + words + strings.Repeat(" ", 3000) + " ", + words + strings.Repeat(" ", 3000) + "x", + words + strings.Repeat(" ", 9000), + words + strings.Repeat(" ", 9000) + `\x`, + words + strings.Repeat(" ", 9000) + `\`, + words + strings.Repeat(" ", 9000) + `\q`, + words + strings.Repeat(`\ud83d\ude00`, 2000), + words + strings.Repeat(" ", 9000) + `\ud83d`, + strings.Repeat(" ", 9000) + words, + strings.Repeat(`\n`, 9000) + "" + words, + } + cut := 0 + for i := range 4000 + len(hand) { + var q []byte + if i < len(hand) { + q = []byte(`"` + hand[i] + `"`) + } else { + q = make1() + } + // as the caller has it: up to its first closing quote + q = q[:1+strEnd(q[1:])] + want, got := oldTextPrompt(q), cxTextPrompt(q) + if got != want { + t.Fatalf("case %d (%d bytes): got %q, want %q", i, len(q), got, want) + } + if strings.HasSuffix(want, "…") { + cut++ + } + } + if cut < 500 { + t.Fatalf("only %d of the cases were titles cut short", cut) + } +} + +// TestCxTextPromptDecodesItsHead: a 5 MB prompt's title is read from +// its head, not from the whole of it decoded (~10 MB each time), and a +// short one with nothing to unescape is read where it is. +func TestCxTextPromptDecodesItsHead(t *testing.T) { + q, _ := json.Marshal("Fix the build: " + strings.Repeat("log line \"x\" é\n", 280000)) + if got, want := cxTextPrompt(q), oldTextPrompt(q); got != want || !strings.HasSuffix(got, "…") { + t.Fatalf("got %q, want %q", got, want) + } + var ms runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&ms) + before := ms.TotalAlloc + for range 10 { + cxTextPrompt(q) + } + runtime.ReadMemStats(&ms) + per := (ms.TotalAlloc - before) / 10 + t.Logf("%d bytes a read of %d", per, len(q)) + if per > 8<<10 { + t.Fatalf("a %d-byte prompt's title made %d bytes, want at most 8 KB", len(q), per) + } + short := []byte(`"` + strings.Repeat("plain words é ", 100) + `"`) + words := string(short[1 : len(short)-1]) + own := testing.AllocsPerRun(20, func() { title(words) }) + if n := testing.AllocsPerRun(20, func() { cxTextPrompt(short) }); n > own { + t.Fatalf("a plain prompt's title made %v allocations, want %v, its title's own", n, own) + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 091c7e837..e85859cc2 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -2522,6 +2522,12 @@ func untagged(s string) string { return title(tag.ReplaceAllString(s, " ")) } // as far as it keeps, and one past: a pasted file as a prompt went through // a regexp and into runes whole, 0.45 GB of a cold start's first 2 minutes. func title(s string) string { + t, _ := titleCut(s) + return t +} + +// titleCut is title(s), and whether words were left past what it kept. +func titleCut(s string) (string, bool) { const most = 160 s = strings.TrimLeftFunc(s, unicode.IsSpace) b := make([]byte, 0, min(len(s), 4*most)) @@ -2539,10 +2545,10 @@ func title(s string) string { } } if strings.IndexFunc(s[i:], func(r rune) bool { return !unicode.IsSpace(r) }) < 0 { - return strings.TrimRightFunc(string(b), unicode.IsSpace) + return strings.TrimRightFunc(string(b), unicode.IsSpace), false } // as []rune made it: each byte not UTF-8 one U+FFFD - return strings.TrimSpace(string([]rune(string(b)))) + "…" + return strings.TrimSpace(string([]rune(string(b)))) + "…", true } // ---- pricing ----------------------------------------------------------------