internal/gateway hit go test's default 10m timeout under a full ./... on
a loaded Mac. go test -json timed its 1583 top-level tests at ~306s
summed (they run one after another); the slowest few waited on real
clocks for things the tests don't check.
- TestQueuedStreamFailureIsTheStreamsError (27s -> 0.3s): it queued for
room in a 3s minute (MaxRPM 1), and each of the vendor's two retries
waited a minute more, 9s a protocol. It now queues for a slot
(MaxConcurrency 1, freed once the agent has heard a keepalive), which
goes through the same keepQueued, queuedAlive and watch around the
attempt, so its retries go at once. The assertions are unchanged.
- TestQueuedStreamKeptAliveOnceSentToItsVendor (15s -> 7.6s): the same
slot instead of a 4s minute; keepHeldAfter 1.5s, keepalive 100ms and
the vendor's 1s quiet stay. With the h.alive.sent clause in
holdWriter.watch removed by hand it goes red on all three protocols
("wrote nothing ... between the vendor being asked and its answer").
- TestQueuedStreamKeptAliveForTheMinute keeps the MaxRPM queue.
- A shared holdSlot helper holds the slot; it frees itself after 5s and
in cleanup, so a test that hears nothing fails instead of hanging.
- usage.OTelEvery / OTelSessionsEvery (5s / 2s, read once when StartOTel
starts an exporter) replace the hard-coded tickers; the gateway's OTel
tests set them to 200ms / 50ms through fastOTel.
TestOTelClaudeMainAndChildDedupRetainsHelper 10s -> 4.5s (the rest is
sessions' 2s settle before a Claude transcript counts as finished),
TestOTelSessionDedupOnlyUnkeyedLoopback 2.25s -> 0.4s. Production
intervals are unchanged.
Not cut: TestPluginStreamLargeReplies (22s, 24MB throttled at 3MB/s),
TestPluginStreamLongActiveReader (16s, sized to outlast a 10s stall
window the plugin host dropped in c38728145), TestLargeRequestEndpoints
(16s, a 64MB body the gateway parses many times over - product speed,
not test waits), and the many 1-3s tests.
Run: go test -count=3 -run 'TestQueued|TestOTel' ./internal/gateway (ok),
-race -count=2 of the same (ok), go test ./internal/usage (ok);
go test -count=1 -json ./internal/gateway: tests summed 305.9s before,
the changed ones ~41.6s less after; the whole run took 330.6s at load
average ~125 against 306.7s for the baseline, other tests slowing under
that load (e.g. TestWarmClaudeSaysWhyNot 0.26s -> 5.3s). gofmt -l clean;
GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway
./internal/usage clean.
keepQueued keeps a streaming agent alive while its request waits for a
slot (MaxConcurrency) or for room in its minute (MaxRPM): past
keepHeldAfter it sends the stream's 200 and a comment every
keepaliveEvery (15s each). When the wait ends, keepQueued stops and the
try's watch starts, and watch only called keepQuiet once keepHeldAfter
(15s) had passed since it began, as if the agent had heard nothing yet.
An agent sent its last keepalive just before the handoff then went up
to keepHeldAfter + keepaliveEvery, ~30s, with nothing while the vendor
was quiet, twice the cadence magpie promises. Found while fixing
TestQueuedStreamKeptAliveForTheMinute's flake (4caae1c8).
watch now calls keepQuiet at once when the request's agent has already
been sent the stream's 200 (h.alive.sent), as keepQueued does;
keepAlive still paces the comments by keepaliveEvery since the last
one (a.at), so nothing is sent more often. scan's keepalive for a held
stream of frames takes the same condition. The 200 is already out in
that case, so the wait keepHeldAfter gave (a refusal still going to
another account with nothing sent) buys nothing.
The scan change is for the same rule in the other place that waits
keepHeldAfter; it isn't observable by itself, since watch's tick
keeps a held stream alive too. pauseAlive counts keepHeldAfter from the
request's start, not from a handoff, so it has no such gap.
Test: TestQueuedStreamKeptAliveOnceSentToItsVendor (chat, responses,
messages). The timing is injected, not waited for: keepHeldAfter
1.5s, keepaliveEvery 100ms, a 4s minute so the queued request is kept
alive before its handoff even when it arrives late under load, and a
vendor that stays quiet 1s on every request after the first. As
3f4287e6's tests do, it checks the gateway's own writes in order rather
than gaps a client measures (they stretch under load): wroteConn now
also logs every write on the agent's connection, and the vendor notes
when it answers. The agent must have been written to before the vendor
was asked, and again between the vendor being asked and its answer:
10 keepalives are due in that second, and the old watch, begun before
the vendor was asked, writes none until keepHeldAfter after it began.
Run:
- watch's change reverted by hand: all 3 subtests fail with "the
gateway wrote nothing to the kept-alive agent in the 1.001s between
the vendor being asked and its answer, want a keepalive every
100ms"; with it, they pass.
- go test -race -count=5 -run TestQueued ./internal/gateway.
- gofmt -l internal/gateway; go vet, GOOS=linux and GOOS=windows go vet
-tags nogui ./internal/gateway.
- go test -tags nogui -timeout 40m ./... under the suite lock.
20582866a saw TestQueuedStreamKeptAliveForTheMinute red at machine
load ~130, passing alone, and didn't file it. The cause is CPU
starvation against wall-clock bounds, not a silent gap in the gateway:
- With 8 busy goroutines per core in the test process, the old test
failed 3/3 runs, its first, unqueued request's 400ms idle client
included. A gap probe of the reads showed every gap stretched, the
longest (1-1.9s) before the 200 itself.
- With no starvation, a vendor answering 700ms late (the try's watch
keeps the agent alive) left no gap over ~110ms: the hand-over from
keepQueued to watch.
- Under starvation a client's own clock is late too: its first byte
was stamped after the vendor was asked though the gateway had flushed
it long before. And the queued request itself arrived up to ~1.4s
late, so a 1.2s minute had nearly passed and nothing was due to it.
So the tests now check order as the gateway acted:
- askHeard records the gateway's first write on the agent's connection
(wroteListener, by the agent's address). keepQueued's stop() waits for
its goroutine, so that write precedes the try's request in program
order. The minute and slot tests ask that it came before the vendor
had the queued request.
- The minute is queueMinute (3s), so what is left of it when the
request arrives late stays far over keepHeldAfter; the vendor-side gap
check is half of it, the vendor seeing the first late too (rpmSlack
is zero here). TestQueuedBrieflyStill429's minute is 10s, far from
its 50ms longest.
- Fixed sleeps that let the first take the slot are waitSeen polls,
and the slot test frees the slot once the queued agent heard
something (5s at most), not at a fixed 1s.
4caae1c8e, made at the same time, kept the client idle timeout and
stopped counting it after the reply's last event (serve's bookkeeping
before the close). That is one late read; under the same starvation
it still failed (FailureIsTheStreamsError's first request, i/o
timeout). This replaces its idleConn: nothing here counts a client's
idle time, so the wait after the last event is not counted either.
Ran, on this commit rebased onto 4caae1c8e:
- origin/main (4caae1c8e) under the same starvation: -count=3 red.
- In-process starvation (8 x GOMAXPROCS spinning goroutines, a
temporary init in the package, not committed): old tests red 3/3;
new TestQueued* -count=5 green.
- keepQueued disabled by hand: the minute, slot, failure, waited-out
and unheld-try tests fail; restored, green.
- go test -race -count=3 -run TestQueued ./internal/gateway.
- go test -count=1 ./internal/gateway (285s, ok).
- gofmt -l clean; go vet darwin, GOOS=linux, GOOS=windows on the package.
TestQueuedStreamKeptAliveForTheMinute/responses failed in a full
go test ./... at load ~130: "the agent gave up after 1.496s of a queued
request: i/o timeout", with the stream read whole: 22 keepalives, then
response.created, the delta and response.completed. The keepalives
were fine. What timed out was the wait after the reply's last event:
serve's bookkeeping (usage ledger, the route's trace, affinity) runs
before the handler returns and net/http closes the stream, and the
test's idleConn still counted its 400ms idle timeout there. No agent's
idle timeout counts that wait (Codex hangs up on response.completed),
the same cause 8412a5d1 fixed in TestTranslatedStreamKeepsClientAlive.
The product isn't stalling the keepalive: keepQueued sends one every
keepaliveEvery while the request waits, and the failing body shows them
all.
Timing assumptions in the test and the code it covers:
- keepHeldAfter 80ms, watchEvery 10ms, keepaliveEvery 40ms: the first
keepalive by ~90ms after keepQueued starts, then every ~40-50ms,
against the client's 400ms. ~300ms of room; a stall there is what the
test is for, and it stays counted.
- the handoff from keepQueued to watch: next keepalive at most
max(last+40ms, watch start+80ms) later, in room too.
- after the reply's last event, until the close: was counted against
400ms; now closeAfterLast (5s), so a stream that never closes fails
instead of hanging.
- "answered after 1s" was measured from the end of the first request,
so a first request slow to close (the same bookkeeping) moved the
bound into the minute. It is now measured from before the first
request was sent, against rpmWindow (1.2s): the minute counts from
the first's start, which is after that, and rpmSlack is 0, so the
bound is exact with no room needed on that side.
idleConn now watches what it reads for the reply's last event in each
protocol (data: [DONE], response.completed/failed, message_stop, an
error event) and waits closeAfterLast after it. This covers every test
using askIdle: ForASlot, FailureIsTheStreamsError, WaitedOut and
Briefly429 too.
Run:
- Injected 500ms after the handler returns (a wrapper around the
gateway's handler): the old test failed ForTheMinute, Failure/messages
and WaitedOut with the same "whole reply, then i/o timeout" body as
the full run. With this change all TestQueued* pass with the delay.
- keepQueued made a no-op by hand: ForTheMinute (all 3) and ForASlot
fail with "gave up after ~400ms ... read \"\"", so the test still
guards the keepalive.
- go test -race -count=5 -run TestQueued ./internal/gateway; the whole
gateway package with -timeout 40m; gofmt -l; go vet, GOOS=linux and
GOOS=windows go vet -tags nogui ./internal/gateway.
serve's try took its lane slot and waited for the minute (04704111)
before holdWriter.watch started, so for up to 2 minutes (or QueueWait,
unbounded by default) the agent got no status, no headers, no byte.
keepQueued runs beside lanes.take and rpms.wait: past keepHeldAfter it
sends the stream's 200 and ": keepalive" comments every keepaliveEvery
(keepAlive, the mechanism held tries already use; none for Gemini, #934).
Once they are out the try is held, so the vendor's error, or the queue
turning it away, reaches the agent as its protocol's stream error
(failTo: Chat's error chunk, Responses' response.failed, Messages'
event: error), and the next candidate still answers in the same stream.
A wait shorter than keepHeldAfter sends nothing: its 429 keeps its
Retry-After. Non-streamed requests are unchanged.
What the agents do with it (read from their app bundles, not tried live):
- WorkBuddy 5.5.6 / WorkBuddy AI 5.6.2 (codebuddy-headless.js): no
header timeout, first-token timer 20 min, so a 2-minute queue alone
doesn't time it out there.
- Qoder 0.4.3: 60s to headers, then 60s more after them; its SSE parser
drops comment lines, so keepalives don't extend that. Headers at 15s
give it 75s instead of 60s; longer waits need firstPayloadTimeoutMs.
- Trae: its agent is downloaded at runtime and wasn't read.
Verified (Linux, golang:1.26.8 in Docker):
- queue_keepalive_test.go through lanGuard(New().Handler()), with an
agent whose connection gives up after 400ms of silence: a request
queued 1.2s for the minute (chat, responses, messages) and one queued
for a Concurrency slot get 200, keepalives, then the reply; a vendor
500 after keepalives is each protocol's stream error; a QueueWait
waited out is the stream's error naming the limit; a short wait is
still a plain 429. With keepQueued taken out, every one but the 429
test fails with "i/o timeout". TestQueuedUnheldTryHeldOnceKeptAlive
fails without the hold (": keepalive\n{\"error\":...}" in the stream).
- go test -tags nogui ./internal/gateway: ok (122s).
- go test -race on internal/gateway the way CI runs it (go test -race -c,
build/race-shards.sh over 14 processes, -test.timeout=20m): 1258 tests,
every shard ok. A single serial -race process passes 10m's default
timeout, which is why CI shards it (#923).
- go vet -tags nogui ./internal/gateway for linux, windows and darwin;
gofmt -l clean. After rebasing on 5e17a183: TestQueued, TestBurst,
RPM, TestQuiet and TestSilentHeld under -race, and linux vet, pass.