Commit Graph
7 Commits
Author SHA1 Message Date
yetone d56c14e953 gateway: a single provider's busy or briefly rate-limited reply is waited out, for its own Patience (zoecats)
zoecats on Discord: a request to one provider (not a group) got a local
relay's short 429 straight back in Claude Code once the few same-one
retries were spent. A group would have held the agent and asked again.

A plain provider now takes the group's replan path (patience.go: replan,
pauseAlive, the held writer) once passing's same-one retries are spent:
its accounts take turns as members do, each pause never shorter than the
Retry-After, and a streaming agent gets keepalives past keepHeldAfter.
- Zero-config: unset, it waits singlePatience, PatienceDefault (60s),
  counted from when the agent would have had the error.
- The user's value wins: Provider.Patience, the same values as a group's
  Patience, set with `magpie provider set <id> patience=2m|off|default`
  (at most 4m). The provider editor has no row for it (no new UI), and its
  save keeps it. A group the provider is in keeps the group's own.
- Not retried: a Retry-After past the budget, quota/credit/plan limits,
  401/403, refusals, response protection, didNotStream, and an agent
  that has gone (499, try marked Gone).
- The try is traced with Again alone, so the Routing page tells it as
  "tried again in …".
- codexReset (ChatGPT's 503 for a large request) is left out of the
  plain-provider replan, so Codex still gets its 503 with advice.
- Codex's own one-account relay (codexUpstreamOn) does not join. It is
  relayed outside the candidate loop, and its backend 429 is always the
  plan's usage limit (codexBusy never retries one), so the short rate
  limit this waits out doesn't arise there. Its overloads keep
  lastRetries and then fallbacks.

longestPause became a var so tests can scale it. Tests updated for the
new count (1 + retries + replanRounds when it never clears):
- TestLastOneLeftIsTriedAgain
- TestRateLimitIsWaitedOut
- TestQueuedStreamFailureIsTheStreamsError
- TestOverflowTheVendorDidntSay

New tests, through the server with a fake upstream and injected
durations, waiting on trace state, not a duration:
- TestSingleProviderWaitsOutAShortRateLimit (stream and whole: 200,
  keepalive before the answer, asked twice)
- TestSingleProviderPassesALongLimitThrough (an hour, quota, 401)
- TestSingleProviderAgentGoneInTheWait
- TestSingleProviderOwnPatienceWins (off, shorter and longer than the
  default)
- TestPatiencePair (cli)
- TestProviderSaveKeepsPatience (gui)

Broken by hand, each red, then restored:
- singlePatience fallback 0 for a plain provider: WaitsOut stream and
  whole got 429, and AgentGone never paused.
- replan's budget check off: PassesALongLimitThrough/an_hour, "magpie
  waits to ask again".
- pauseAlive's ctx.Done case removed: AgentGone, "route done false
  status 0".
- The gateway ignoring Provider.Patience: OwnPatienceWins off, shorter
  and longer all red.
- The GUI save not keeping Patience: TestProviderSaveKeepsPatience,
  "patience 0 … want -1 kept".

Run in this tree, before the rebase:
- go test ./internal/gateway ./internal/cli ./internal/gui: ok.
- ./internal/provider: ok with -skip TestUnreadLogins. That test crashes
  with "close of synctest channel from outside bubble", the known #3632,
  in filememo and not touched here.
- gofmt -l: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: all 0.
- go build for darwin, linux (nogui) and windows: ok.

Run again after rebasing on origin/main 39526c069 (17 commits, 22 files
in gateway/provider/cli): gofmt, go build, go vet on the four
packages, the replan, retry, overflow and Codex-reset tests, and every
new test: all ok. The whole gateway package was not run again there.

Not run:
- The full ./... suite: machine load ~150, other sessions' suites
  running.
- A real vendor's 429.
- The GUI suite: no GUI file changed.
2026-10-27 02:26:27 +08:00
yetone 198c7637a1 gateway tests: the queued-stream tests order the gateway's writes and the vendor's arrivals by a sequence, not a clock that ticks every ~0.5ms on Windows (#2249)
TestQueuedStreamKeptAliveForASlot checked heard.Before(asked) on
wall-clock times. On Windows time.Now() advances in ~0.5ms ticks, and
the keepalive, the slot being freed and the vendor being asked fit in
one, so heard == asked and the test failed with the right order.
Loosening it to !asked.Before(heard) would pass a broken keepalive: with
queued keepalives off, the first write (the reply) lands in the same ms
as the ask, seen below.

A shared counter (step) now gives each gateway write a place in order,
taken before the write so nothing the agent does on hearing it can come
earlier, and each vendor arrival and answer one too. The sibling checks
use it: TestQueuedStreamKeptAliveForTheMinute's same heard-before-asked
and TestQueuedStreamKeptAliveOnceSentToItsVendor's writeLog.within (its
"kept alive before the vendor was asked" is the same strict compare on
the one write that frees the slot).

Run:
- Reproduced by truncating both clocks to 100ms (forced equal ticks):
  old ForASlot FAIL 5/5 at queue_keepalive_test.go:387 with equal
  times, the issue's message; OnceSentToItsVendor FAIL 5/5 "the agent
  wasn't kept alive before the vendor was asked". With the fix and the
  same truncation, all TestQueuedStream* pass 3/3.
- Broke the guarded behaviour by hand (queuedAlive := func() {} in
  gateway.go): all three tests FAIL at the body check; with the body's
  ": keepalive" check also dropped, each FAILs at the new order check
  (ForASlot :433, ForTheMinute :304, OnceSentToItsVendor :368).
- go test -tags nogui -race -count=20 -run of these and
  TestTranslatedSilenceStillTimesOut: ok (358s). gofmt -l clean,
  go vet -tags nogui ./internal/gateway (darwin) clean.

Not run: the full go test ./..., GOOS=linux/windows vet, the Windows
box. Stopped because the disk dropped below 10G free.
2026-10-15 04:46:57 +08:00
yetone ee20a1511b gateway: the package's tests wait ~42s less for queues and OTel exports (#1654)
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.
2026-10-12 01:16:36 +08:00
yetone c0a13dee3c gateway: a queued stream's agent, kept alive while it waited, goes on hearing a keepalive every 15s once the request goes to its vendor, not up to 30s of nothing
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.
2026-10-11 06:19:16 +08:00
yetone 3f4287e674 gateway tests: the queued-keepalive tests ask that the gateway wrote to the agent before the vendor was asked, not for a client's idle timeout
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.
2026-10-11 03:49:34 +08:00
yetone 4caae1c8e0 gateway tests: the queued-stream tests count an agent's idle timeout only until the reply's last event, and time the minute from the first request's start
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.
2026-10-11 03:11:00 +08:00
yetone 24bef0f9be gateway: a streamed request waiting for its key's slot (Concurrency) or for room in its minute (Requests per minute) has its agent sent the stream's 200 and SSE keepalives after 15s, as a held try's stream is, instead of nothing until it is sent (coeo91 on Discord: WorkBuddy, Trae and Qoder said it timed out)
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.
2026-10-08 23:13:12 +08:00