gateway: a Codex turn that reasons after its preamble tells its speed (Archivemylife on X)

A Codex turn often goes: a one-line preamble, then reasoning (summary
or hidden), then a tool call. firstToken.see stopped looking for
reasoning once the first text had come, so such a turn was timed from
the preamble and its window held all of the thinking. The output then
read as a burst (flow*4 < window) and Usage showed "—" for its speed;
reasoning_hidden was missed for it too. Whether a turn shows a speed
depended on its shape, hence "sometimes there, sometimes not". Fast
(priority) makes the burst rule trip more often, but is not the cause.

Now reasoning seen after text marks the turn "again": the next content
restarts the text clock there, and hidden reasoning is noted. Both SSE
and WS reach the same see().

Fixture: testdata/codex-preamble-reasoning-tool.json is a real capture
(Codex gpt-6.1-sol, service_tier priority, effort high, through
/v1/responses in a sandbox HOME), encrypted_content cut short.

Run on mica. The full run was at this change on f9492fd8e; it was then
rebased onto b1d5912de (two commits, Gemini draw and Antigravity
discovery, no file in common). At the pushed head: go vet of gateway,
provider, usage and catalog; go test of internal/agent, usage and
catalog in full; gateway and provider -run Speed|Reasoning|TTFT|
FirstToken|Gemini|Draw|Tier: all ok.
At f9492fd8e:
- gofmt -l: clean
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows
  go build: ok
- go test -tags nogui -count=1 -timeout 45m ./...: 103 ok, no FAIL
  (gateway 1117s), log kept whole and grepped
- Broken by hand: TestCodexPreambleThenReasoningTellsSpeed is red on
  the old ttft.go, green on the new.
- Real use: a sandbox gateway built from this head, real Codex
  account, priority, preamble+reasoning+tool turns: before the fix 3 of
  4 such turns read burst-flow ("—"); after, 2 of 2 show a speed (147,
  125 tok/s) with reasoning_hidden set. Plain preamble+tool turns: 6 of
  6 OK.

Not changed / not tried:
- The preamble's few tokens (~27) count in the post-reasoning window,
  about a 4% overcount.
- Hidden reasoning then a tool call with no text at all stays on
  page.js's "≥" floor (2d3b33bb7).
- The GUI was not opened against the new rows; page.js is unchanged.
This commit is contained in:
yetone
2026-11-17 20:18:02 +08:00
parent b1d5912def
commit 52d527f7b2
3 changed files with 760 additions and 16 deletions
+52
View File
@@ -397,3 +397,55 @@ func TestLiveVisibleReasoningFixture(t *testing.T) {
t.Fatalf("live tool turn speed %d/%d; want 76/731", n, ms)
}
}
// A Codex turn that wrote a preamble, reasoned, then called a tool
// (Archivemylife on X, gpt-6.1-sol at service_tier priority): counted from
// the preamble, its window held the reasoning and its content read as one
// burst at the end, so it told no speed. Its answer is counted from what
// came after its last reasoning, the shell call's first bytes.
func TestCodexPreambleThenReasoningTellsSpeed(t *testing.T) {
var sample struct {
Record struct {
Out int `json:"out"`
Reasoning int `json:"reasoning"`
Ms int64 `json:"ms"`
} `json:"record"`
Events []struct {
At int64 `json:"at_ms"`
Data json.RawMessage `json:"data"`
} `json:"events"`
}
b, err := os.ReadFile("testdata/codex-preamble-reasoning-tool.json")
if err != nil {
t.Fatal(err)
}
if err = json.Unmarshal(b, &sample); err != nil {
t.Fatal(err)
}
f := firstToken{}
var called int64 // the shell call's start, as it came
for _, e := range sample.Events {
if called == 0 && strings.Contains(string(e.Data), `"type":"function_call"`) {
called = e.At
}
f.start = time.Now().Add(-time.Duration(e.At) * time.Millisecond)
f.see([]byte("data: " + string(e.Data) + "\n\n"))
}
rec := sample.Record
ttft, text := f.ms()
if !f.hidesReasoning(provider.Responses, rec.Reasoning) {
t.Fatal("the reasoning after the preamble was not seen")
}
if text < called || text > called+50 {
t.Fatalf("answer counted from %d ms; want the shell call's start, %d", text, called)
}
n, w := usage.DecodeOf(rec.Out, rec.Reasoning, rec.Ms, ttft, text, f.flowFor(rec.Reasoning))
if n != rec.Out-rec.Reasoning || w <= 0 {
t.Fatalf("no speed: %d/%d (ttft %d, text %d, flow %d)", n, w, ttft, text, f.flowFor(rec.Reasoning))
}
// 630 tokens in about 1.6 s: priority's pace, not the 30 tok/s the
// whole turn after the preamble would read
if s := float64(n) / (float64(w) / 1000); s < 200 || s > 600 {
t.Fatalf("speed %.0f tok/s", s)
}
}
File diff suppressed because one or more lines are too long
+65 -16
View File
@@ -28,10 +28,18 @@ type firstToken struct {
text time.Duration // to the first text
reasoning, lastReasoning time.Duration
hidden bool // redacted thinking cannot be timed by its visible portion
off bool // not a stream, or read as far as it is
began bool
read int
pend []byte
// again: the reply reasoned again after its first text (a Codex
// preamble, "I'll look at the tests", then its thinking, then a tool
// call: Archivemylife on X), and nothing has come after that
// reasoning yet. The answer the speed is counted over starts at what
// comes next, so text then moves to it: counted from the preamble, the
// window held the thinking, and the reply read as one burst at its
// end and told no speed
again bool
off bool // not a stream, or read as far as it is
began bool
read int
pend []byte
// flow: how many bytes of content events had come by each time, one
// mark a millisecond, from the first content on
flow []flowMark
@@ -74,9 +82,24 @@ func (f *firstToken) see(b []byte) {
f.pend = f.pend[end:]
if f.text > 0 {
// the first text is known: what is left to tell is when the
// rest came, which a quicker look tells
// rest came, which a quicker look tells, and whether the reply
// reasoned again after it (again)
if mayReason(ev) {
_, _, reasoning, hidden := timingKind(ev)
f.hidden = f.hidden || hidden
if reasoning || hidden || reasoningItem(ev) {
f.again, f.lastReasoning = true, d
if flowContent(ev) {
f.mark(d, len(ev))
}
continue
}
}
if flowContent(ev) {
f.mark(d, len(ev))
if f.again {
f.text, f.again = d, false
}
}
continue
}
@@ -107,6 +130,28 @@ func (f *firstToken) see(b []byte) {
}
}
// mayReason: an event that can carry reasoning, or a reasoning item's
// start or end, told by a look rather than a parse, so the events of an
// answer after its first text are still only looked at (see).
func mayReason(ev []byte) bool {
return bodyHas(ev, "reasoning") || bodyHas(ev, "thinking") || bodyHas(ev, "encrypted_content") || bodyHas(ev, `"thought"`)
}
// reasoningItem: a Responses reasoning item's start or end, which streams
// nothing of the thinking it holds when its summary is off.
func reasoningItem(ev []byte) bool {
if !bodyHas(ev, "output_item.") {
return false
}
_, data := eventParts(ev)
var v struct {
Item *struct {
Type string `json:"type"`
} `json:"item"`
}
return json.Unmarshal(data, &v) == nil && v.Item != nil && v.Item.Type == "reasoning"
}
// flowMost is the most marks kept: a reply that took longer than this many
// distinct milliseconds to come has its flow untold (flowMs).
const flowMost = 1 << 16
@@ -182,17 +227,7 @@ func firstKind(ev []byte) (content, text bool) {
}
func timingKind(ev []byte) (content, text, reasoning, hidden bool) {
var name string
var data []byte
for _, ln := range bytes.Split(ev, []byte("\n")) {
ln = bytes.TrimRight(ln, "\r")
switch {
case bytes.HasPrefix(ln, []byte("event:")):
name = string(bytes.TrimSpace(ln[6:]))
case bytes.HasPrefix(ln, []byte("data:")):
data = append(data, bytes.TrimSpace(ln[5:])...)
}
}
name, data := eventParts(ev)
// only deltas, a tool call's start and Gemini's parts carry any: the
// rest go by unread
if len(data) == 0 || !(bodyHas(data, "delta") || bodyHas(data, `"parts"`) ||
@@ -300,6 +335,20 @@ func timingKind(ev []byte) (content, text, reasoning, hidden bool) {
return content, false, reasoning, hidden
}
// eventParts are a server-sent event's name and its data lines joined.
func eventParts(ev []byte) (name string, data []byte) {
for _, ln := range bytes.Split(ev, []byte("\n")) {
ln = bytes.TrimRight(ln, "\r")
switch {
case bytes.HasPrefix(ln, []byte("event:")):
name = string(bytes.TrimSpace(ln[6:]))
case bytes.HasPrefix(ln, []byte("data:")):
data = append(data, bytes.TrimSpace(ln[5:])...)
}
}
return name, data
}
// filled is a JSON value with something in it.
func filled(raw json.RawMessage) bool {
switch string(bytes.TrimSpace(raw)) {